admin.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. "use strict";
  2. var toError = require('./utils').toError,
  3. Define = require('./metadata'),
  4. shallowClone = require('./utils').shallowClone;
  5. /**
  6. * @fileOverview The **Admin** class is an internal class that allows convenient access to
  7. * the admin functionality and commands for MongoDB.
  8. *
  9. * **ADMIN Cannot directly be instantiated**
  10. * @example
  11. * var MongoClient = require('mongodb').MongoClient,
  12. * test = require('assert');
  13. * // Connection url
  14. * var url = 'mongodb://localhost:27017/test';
  15. * // Connect using MongoClient
  16. * MongoClient.connect(url, function(err, db) {
  17. * // Use the admin database for the operation
  18. * var adminDb = db.admin();
  19. *
  20. * // List all the available databases
  21. * adminDb.listDatabases(function(err, dbs) {
  22. * test.equal(null, err);
  23. * test.ok(dbs.databases.length > 0);
  24. * db.close();
  25. * });
  26. * });
  27. */
  28. /**
  29. * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly)
  30. * @class
  31. * @return {Admin} a collection instance.
  32. */
  33. var Admin = function(db, topology, promiseLibrary) {
  34. if(!(this instanceof Admin)) return new Admin(db, topology);
  35. var self = this;
  36. // Internal state
  37. this.s = {
  38. db: db
  39. , topology: topology
  40. , promiseLibrary: promiseLibrary
  41. }
  42. }
  43. var define = Admin.define = new Define('Admin', Admin, false);
  44. /**
  45. * The callback format for results
  46. * @callback Admin~resultCallback
  47. * @param {MongoError} error An error instance representing the error during the execution.
  48. * @param {object} result The result object if the command was executed successfully.
  49. */
  50. /**
  51. * Execute a command
  52. * @method
  53. * @param {object} command The command hash
  54. * @param {object} [options=null] Optional settings.
  55. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  56. * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query.
  57. * @param {Admin~resultCallback} [callback] The command result callback
  58. * @return {Promise} returns Promise if no callback passed
  59. */
  60. Admin.prototype.command = function(command, options, callback) {
  61. var self = this;
  62. var args = Array.prototype.slice.call(arguments, 1);
  63. callback = args.pop();
  64. if(typeof callback != 'function') args.push(callback);
  65. options = args.length ? args.shift() : {};
  66. // Execute using callback
  67. if(typeof callback == 'function') return this.s.db.executeDbAdminCommand(command, options, function(err, doc) {
  68. return callback != null ? callback(err, doc) : null;
  69. });
  70. // Return a Promise
  71. return new this.s.promiseLibrary(function(resolve, reject) {
  72. self.s.db.executeDbAdminCommand(command, options, function(err, doc) {
  73. if(err) return reject(err);
  74. resolve(doc);
  75. });
  76. });
  77. }
  78. define.classMethod('command', {callback: true, promise:true});
  79. /**
  80. * Retrieve the server information for the current
  81. * instance of the db client
  82. *
  83. * @param {Admin~resultCallback} [callback] The command result callback
  84. * @return {Promise} returns Promise if no callback passed
  85. */
  86. Admin.prototype.buildInfo = function(callback) {
  87. var self = this;
  88. // Execute using callback
  89. if(typeof callback == 'function') return this.serverInfo(callback);
  90. // Return a Promise
  91. return new this.s.promiseLibrary(function(resolve, reject) {
  92. self.serverInfo(function(err, r) {
  93. if(err) return reject(err);
  94. resolve(r);
  95. });
  96. });
  97. }
  98. define.classMethod('buildInfo', {callback: true, promise:true});
  99. /**
  100. * Retrieve the server information for the current
  101. * instance of the db client
  102. *
  103. * @param {Admin~resultCallback} [callback] The command result callback
  104. * @return {Promise} returns Promise if no callback passed
  105. */
  106. Admin.prototype.serverInfo = function(callback) {
  107. var self = this;
  108. // Execute using callback
  109. if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) {
  110. if(err != null) return callback(err, null);
  111. callback(null, doc);
  112. });
  113. // Return a Promise
  114. return new this.s.promiseLibrary(function(resolve, reject) {
  115. self.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) {
  116. if(err) return reject(err);
  117. resolve(doc);
  118. });
  119. });
  120. }
  121. define.classMethod('serverInfo', {callback: true, promise:true});
  122. /**
  123. * Retrieve this db's server status.
  124. *
  125. * @param {Admin~resultCallback} [callback] The command result callback
  126. * @return {Promise} returns Promise if no callback passed
  127. */
  128. Admin.prototype.serverStatus = function(callback) {
  129. var self = this;
  130. // Execute using callback
  131. if(typeof callback == 'function') return serverStatus(self, callback)
  132. // Return a Promise
  133. return new this.s.promiseLibrary(function(resolve, reject) {
  134. serverStatus(self, function(err, r) {
  135. if(err) return reject(err);
  136. resolve(r);
  137. });
  138. });
  139. };
  140. var serverStatus = function(self, callback) {
  141. self.s.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) {
  142. if(err == null && doc.ok === 1) {
  143. callback(null, doc);
  144. } else {
  145. if(err) return callback(err, false);
  146. return callback(toError(doc), false);
  147. }
  148. });
  149. }
  150. define.classMethod('serverStatus', {callback: true, promise:true});
  151. /**
  152. * Retrieve the current profiling Level for MongoDB
  153. *
  154. * @param {Admin~resultCallback} [callback] The command result callback
  155. * @return {Promise} returns Promise if no callback passed
  156. */
  157. Admin.prototype.profilingLevel = function(callback) {
  158. var self = this;
  159. // Execute using callback
  160. if(typeof callback == 'function') return profilingLevel(self, callback)
  161. // Return a Promise
  162. return new this.s.promiseLibrary(function(resolve, reject) {
  163. profilingLevel(self, function(err, r) {
  164. if(err) return reject(err);
  165. resolve(r);
  166. });
  167. });
  168. };
  169. var profilingLevel = function(self, callback) {
  170. self.s.db.executeDbAdminCommand({profile:-1}, function(err, doc) {
  171. doc = doc;
  172. if(err == null && doc.ok === 1) {
  173. var was = doc.was;
  174. if(was == 0) return callback(null, "off");
  175. if(was == 1) return callback(null, "slow_only");
  176. if(was == 2) return callback(null, "all");
  177. return callback(new Error("Error: illegal profiling level value " + was), null);
  178. } else {
  179. err != null ? callback(err, null) : callback(new Error("Error with profile command"), null);
  180. }
  181. });
  182. }
  183. define.classMethod('profilingLevel', {callback: true, promise:true});
  184. /**
  185. * Ping the MongoDB server and retrieve results
  186. *
  187. * @param {Admin~resultCallback} [callback] The command result callback
  188. * @return {Promise} returns Promise if no callback passed
  189. */
  190. Admin.prototype.ping = function(options, callback) {
  191. var self = this;
  192. var args = Array.prototype.slice.call(arguments, 0);
  193. callback = args.pop();
  194. if(typeof callback != 'function') args.push(callback);
  195. // Execute using callback
  196. if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({ping: 1}, callback);
  197. // Return a Promise
  198. return new this.s.promiseLibrary(function(resolve, reject) {
  199. self.s.db.executeDbAdminCommand({ping: 1}, function(err, r) {
  200. if(err) return reject(err);
  201. resolve(r);
  202. });
  203. });
  204. }
  205. define.classMethod('ping', {callback: true, promise:true});
  206. /**
  207. * Authenticate a user against the server.
  208. * @method
  209. * @param {string} username The username.
  210. * @param {string} [password] The password.
  211. * @param {Admin~resultCallback} [callback] The command result callback
  212. * @return {Promise} returns Promise if no callback passed
  213. */
  214. Admin.prototype.authenticate = function(username, password, options, callback) {
  215. var self = this;
  216. if(typeof options == 'function') callback = options, options = {};
  217. options = shallowClone(options);
  218. options.authdb = 'admin';
  219. // Execute using callback
  220. if(typeof callback == 'function') return this.s.db.authenticate(username, password, options, callback);
  221. // Return a Promise
  222. return new this.s.promiseLibrary(function(resolve, reject) {
  223. self.s.db.authenticate(username, password, options, function(err, r) {
  224. if(err) return reject(err);
  225. resolve(r);
  226. });
  227. });
  228. }
  229. define.classMethod('authenticate', {callback: true, promise:true});
  230. /**
  231. * Logout user from server, fire off on all connections and remove all auth info
  232. * @method
  233. * @param {Admin~resultCallback} [callback] The command result callback
  234. * @return {Promise} returns Promise if no callback passed
  235. */
  236. Admin.prototype.logout = function(callback) {
  237. var self = this;
  238. // Execute using callback
  239. if(typeof callback == 'function') return this.s.db.logout({authdb: 'admin'}, callback);
  240. // Return a Promise
  241. return new this.s.promiseLibrary(function(resolve, reject) {
  242. self.s.db.logout({authdb: 'admin'}, function(err, r) {
  243. if(err) return reject(err);
  244. resolve(r);
  245. });
  246. });
  247. }
  248. define.classMethod('logout', {callback: true, promise:true});
  249. // Get write concern
  250. var writeConcern = function(options, db) {
  251. options = shallowClone(options);
  252. // If options already contain write concerns return it
  253. if(options.w || options.wtimeout || options.j || options.fsync) {
  254. return options;
  255. }
  256. // Set db write concern if available
  257. if(db.writeConcern) {
  258. if(options.w) options.w = db.writeConcern.w;
  259. if(options.wtimeout) options.wtimeout = db.writeConcern.wtimeout;
  260. if(options.j) options.j = db.writeConcern.j;
  261. if(options.fsync) options.fsync = db.writeConcern.fsync;
  262. }
  263. // Return modified options
  264. return options;
  265. }
  266. /**
  267. * Add a user to the database.
  268. * @method
  269. * @param {string} username The username.
  270. * @param {string} password The password.
  271. * @param {object} [options=null] Optional settings.
  272. * @param {(number|string)} [options.w=null] The write concern.
  273. * @param {number} [options.wtimeout=null] The write concern timeout.
  274. * @param {boolean} [options.j=false] Specify a journal write concern.
  275. * @param {boolean} [options.fsync=false] Specify a file sync write concern.
  276. * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher)
  277. * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher)
  278. * @param {Admin~resultCallback} [callback] The command result callback
  279. * @return {Promise} returns Promise if no callback passed
  280. */
  281. Admin.prototype.addUser = function(username, password, options, callback) {
  282. var self = this;
  283. var args = Array.prototype.slice.call(arguments, 2);
  284. callback = args.pop();
  285. if(typeof callback != 'function') args.push(callback);
  286. options = args.length ? args.shift() : {};
  287. options = options || {};
  288. // Get the options
  289. options = writeConcern(options, self.s.db)
  290. // Set the db name to admin
  291. options.dbName = 'admin';
  292. // Execute using callback
  293. if(typeof callback == 'function')
  294. return self.s.db.addUser(username, password, options, callback);
  295. // Return a Promise
  296. return new this.s.promiseLibrary(function(resolve, reject) {
  297. self.s.db.addUser(username, password, options, function(err, r) {
  298. if(err) return reject(err);
  299. resolve(r);
  300. });
  301. });
  302. }
  303. define.classMethod('addUser', {callback: true, promise:true});
  304. /**
  305. * Remove a user from a database
  306. * @method
  307. * @param {string} username The username.
  308. * @param {object} [options=null] Optional settings.
  309. * @param {(number|string)} [options.w=null] The write concern.
  310. * @param {number} [options.wtimeout=null] The write concern timeout.
  311. * @param {boolean} [options.j=false] Specify a journal write concern.
  312. * @param {boolean} [options.fsync=false] Specify a file sync write concern.
  313. * @param {Admin~resultCallback} [callback] The command result callback
  314. * @return {Promise} returns Promise if no callback passed
  315. */
  316. Admin.prototype.removeUser = function(username, options, callback) {
  317. var self = this;
  318. var args = Array.prototype.slice.call(arguments, 1);
  319. callback = args.pop();
  320. if(typeof callback != 'function') args.push(callback);
  321. options = args.length ? args.shift() : {};
  322. options = options || {};
  323. // Get the options
  324. options = writeConcern(options, self.s.db)
  325. // Set the db name
  326. options.dbName = 'admin';
  327. // Execute using callback
  328. if(typeof callback == 'function')
  329. return self.s.db.removeUser(username, options, callback);
  330. // Return a Promise
  331. return new this.s.promiseLibrary(function(resolve, reject) {
  332. self.s.db.removeUser(username, options, function(err, r) {
  333. if(err) return reject(err);
  334. resolve(r);
  335. });
  336. });
  337. }
  338. define.classMethod('removeUser', {callback: true, promise:true});
  339. /**
  340. * Set the current profiling level of MongoDB
  341. *
  342. * @param {string} level The new profiling level (off, slow_only, all).
  343. * @param {Admin~resultCallback} [callback] The command result callback.
  344. * @return {Promise} returns Promise if no callback passed
  345. */
  346. Admin.prototype.setProfilingLevel = function(level, callback) {
  347. var self = this;
  348. // Execute using callback
  349. if(typeof callback == 'function') return setProfilingLevel(self, level, callback);
  350. // Return a Promise
  351. return new this.s.promiseLibrary(function(resolve, reject) {
  352. setProfilingLevel(self, level, function(err, r) {
  353. if(err) return reject(err);
  354. resolve(r);
  355. });
  356. });
  357. };
  358. var setProfilingLevel = function(self, level, callback) {
  359. var command = {};
  360. var profile = 0;
  361. if(level == "off") {
  362. profile = 0;
  363. } else if(level == "slow_only") {
  364. profile = 1;
  365. } else if(level == "all") {
  366. profile = 2;
  367. } else {
  368. return callback(new Error("Error: illegal profiling level value " + level));
  369. }
  370. // Set up the profile number
  371. command['profile'] = profile;
  372. self.s.db.executeDbAdminCommand(command, function(err, doc) {
  373. doc = doc;
  374. if(err == null && doc.ok === 1)
  375. return callback(null, level);
  376. return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null);
  377. });
  378. }
  379. define.classMethod('setProfilingLevel', {callback: true, promise:true});
  380. /**
  381. * Retrive the current profiling information for MongoDB
  382. *
  383. * @param {Admin~resultCallback} [callback] The command result callback.
  384. * @return {Promise} returns Promise if no callback passed
  385. */
  386. Admin.prototype.profilingInfo = function(callback) {
  387. var self = this;
  388. // Execute using callback
  389. if(typeof callback == 'function') return profilingInfo(self, callback);
  390. // Return a Promise
  391. return new this.s.promiseLibrary(function(resolve, reject) {
  392. profilingInfo(self, function(err, r) {
  393. if(err) return reject(err);
  394. resolve(r);
  395. });
  396. });
  397. };
  398. var profilingInfo = function(self, callback) {
  399. try {
  400. self.s.topology.cursor("admin.system.profile", { find: 'system.profile', query: {}}, {}).toArray(callback);
  401. } catch (err) {
  402. return callback(err, null);
  403. }
  404. }
  405. define.classMethod('profilingLevel', {callback: true, promise:true});
  406. /**
  407. * Validate an existing collection
  408. *
  409. * @param {string} collectionName The name of the collection to validate.
  410. * @param {object} [options=null] Optional settings.
  411. * @param {Admin~resultCallback} [callback] The command result callback.
  412. * @return {Promise} returns Promise if no callback passed
  413. */
  414. Admin.prototype.validateCollection = function(collectionName, options, callback) {
  415. var self = this;
  416. var args = Array.prototype.slice.call(arguments, 1);
  417. callback = args.pop();
  418. if(typeof callback != 'function') args.push(callback);
  419. options = args.length ? args.shift() : {};
  420. options = options || {};
  421. // Execute using callback
  422. if(typeof callback == 'function')
  423. return validateCollection(self, collectionName, options, callback);
  424. // Return a Promise
  425. return new this.s.promiseLibrary(function(resolve, reject) {
  426. validateCollection(self, collectionName, options, function(err, r) {
  427. if(err) return reject(err);
  428. resolve(r);
  429. });
  430. });
  431. };
  432. var validateCollection = function(self, collectionName, options, callback) {
  433. var command = {validate: collectionName};
  434. var keys = Object.keys(options);
  435. // Decorate command with extra options
  436. for(var i = 0; i < keys.length; i++) {
  437. if(options.hasOwnProperty(keys[i])) {
  438. command[keys[i]] = options[keys[i]];
  439. }
  440. }
  441. self.s.db.command(command, function(err, doc) {
  442. if(err != null) return callback(err, null);
  443. if(doc.ok === 0)
  444. return callback(new Error("Error with validate command"), null);
  445. if(doc.result != null && doc.result.constructor != String)
  446. return callback(new Error("Error with validation data"), null);
  447. if(doc.result != null && doc.result.match(/exception|corrupt/) != null)
  448. return callback(new Error("Error: invalid collection " + collectionName), null);
  449. if(doc.valid != null && !doc.valid)
  450. return callback(new Error("Error: invalid collection " + collectionName), null);
  451. return callback(null, doc);
  452. });
  453. }
  454. define.classMethod('validateCollection', {callback: true, promise:true});
  455. /**
  456. * List the available databases
  457. *
  458. * @param {Admin~resultCallback} [callback] The command result callback.
  459. * @return {Promise} returns Promise if no callback passed
  460. */
  461. Admin.prototype.listDatabases = function(callback) {
  462. var self = this;
  463. // Execute using callback
  464. if(typeof callback == 'function') return self.s.db.executeDbAdminCommand({listDatabases:1}, {}, callback);
  465. // Return a Promise
  466. return new this.s.promiseLibrary(function(resolve, reject) {
  467. self.s.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, r) {
  468. if(err) return reject(err);
  469. resolve(r);
  470. });
  471. });
  472. }
  473. define.classMethod('listDatabases', {callback: true, promise:true});
  474. /**
  475. * Get ReplicaSet status
  476. *
  477. * @param {Admin~resultCallback} [callback] The command result callback.
  478. * @return {Promise} returns Promise if no callback passed
  479. */
  480. Admin.prototype.replSetGetStatus = function(callback) {
  481. var self = this;
  482. // Execute using callback
  483. if(typeof callback == 'function') return replSetGetStatus(self, callback);
  484. // Return a Promise
  485. return new this.s.promiseLibrary(function(resolve, reject) {
  486. replSetGetStatus(self, function(err, r) {
  487. if(err) return reject(err);
  488. resolve(r);
  489. });
  490. });
  491. };
  492. var replSetGetStatus = function(self, callback) {
  493. self.s.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) {
  494. if(err == null && doc.ok === 1)
  495. return callback(null, doc);
  496. if(err) return callback(err, false);
  497. callback(toError(doc), false);
  498. });
  499. }
  500. define.classMethod('replSetGetStatus', {callback: true, promise:true});
  501. module.exports = Admin;