admin.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. "use strict";
  2. var toError = require('./utils').toError;
  3. /**
  4. * @fileOverview The **Admin** class is an internal class that allows convenient access to
  5. * the admin functionality and commands for MongoDB.
  6. *
  7. * **ADMIN Cannot directly be instantiated**
  8. * @example
  9. * var MongoClient = require('mongodb').MongoClient,
  10. * test = require('assert');
  11. * // Connection url
  12. * var url = 'mongodb://localhost:27017/test';
  13. * // Connect using MongoClient
  14. * MongoClient.connect(url, function(err, db) {
  15. * // Use the admin database for the operation
  16. * var adminDb = db.admin();
  17. *
  18. * // List all the available databases
  19. * adminDb.listDatabases(function(err, dbs) {
  20. * test.equal(null, err);
  21. * test.ok(dbs.databases.length > 0);
  22. * db.close();
  23. * });
  24. * });
  25. */
  26. /**
  27. * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly)
  28. * @class
  29. * @return {Admin} a collection instance.
  30. */
  31. var Admin = function(db, topology) {
  32. if(!(this instanceof Admin)) return new Admin(db, topology);
  33. var self = this;
  34. // Internal state
  35. this.s = {
  36. db: db
  37. , topology: topology
  38. }
  39. }
  40. /**
  41. * The callback format for results
  42. * @callback Admin~resultCallback
  43. * @param {MongoError} error An error instance representing the error during the execution.
  44. * @param {object} result The result object if the command was executed successfully.
  45. */
  46. /**
  47. * Execute a command
  48. * @method
  49. * @param {object} command The command hash
  50. * @param {object} [options=null] Optional settings.
  51. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  52. * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query.
  53. * @param {Admin~resultCallback} callback The command result callback
  54. * @return {null}
  55. */
  56. Admin.prototype.command = function(command, options, callback) {
  57. var args = Array.prototype.slice.call(arguments, 1);
  58. callback = args.pop();
  59. options = args.length ? args.shift() : {};
  60. // Execute a command
  61. this.s.db.executeDbAdminCommand(command, options, function(err, doc) {
  62. return callback != null ? callback(err, doc) : null;
  63. });
  64. }
  65. /**
  66. * Retrieve the server information for the current
  67. * instance of the db client
  68. *
  69. * @param {Admin~resultCallback} callback The command result callback
  70. * @return {null}
  71. */
  72. Admin.prototype.buildInfo = function(callback) {
  73. this.serverInfo(callback);
  74. }
  75. /**
  76. * Retrieve the server information for the current
  77. * instance of the db client
  78. *
  79. * @param {Admin~resultCallback} callback The command result callback
  80. * @return {null}
  81. */
  82. Admin.prototype.serverInfo = function(callback) {
  83. this.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) {
  84. if(err != null) return callback(err, null);
  85. return callback(null, doc);
  86. });
  87. }
  88. /**
  89. * Retrieve this db's server status.
  90. *
  91. * @param {Admin~resultCallback} callback The command result callback
  92. * @return {null}
  93. */
  94. Admin.prototype.serverStatus = function(callback) {
  95. var self = this;
  96. this.s.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) {
  97. if(err == null && doc.ok === 1) {
  98. callback(null, doc);
  99. } else {
  100. if(err) return callback(err, false);
  101. return callback(toError(doc), false);
  102. }
  103. });
  104. };
  105. /**
  106. * Retrieve the current profiling Level for MongoDB
  107. *
  108. * @param {Admin~resultCallback} callback The command result callback
  109. * @return {null}
  110. */
  111. Admin.prototype.profilingLevel = function(callback) {
  112. var self = this;
  113. this.s.db.executeDbAdminCommand({profile:-1}, function(err, doc) {
  114. doc = doc;
  115. if(err == null && doc.ok === 1) {
  116. var was = doc.was;
  117. if(was == 0) return callback(null, "off");
  118. if(was == 1) return callback(null, "slow_only");
  119. if(was == 2) return callback(null, "all");
  120. return callback(new Error("Error: illegal profiling level value " + was), null);
  121. } else {
  122. err != null ? callback(err, null) : callback(new Error("Error with profile command"), null);
  123. }
  124. });
  125. };
  126. /**
  127. * Ping the MongoDB server and retrieve results
  128. *
  129. * @param {Admin~resultCallback} callback The command result callback
  130. * @return {null}
  131. */
  132. Admin.prototype.ping = function(options, callback) {
  133. var args = Array.prototype.slice.call(arguments, 0);
  134. this.s.db.executeDbAdminCommand({ping: 1}, args.pop());
  135. }
  136. /**
  137. * Authenticate a user against the server.
  138. * @method
  139. * @param {string} username The username.
  140. * @param {string} [password] The password.
  141. * @param {Admin~resultCallback} callback The command result callback
  142. * @return {null}
  143. */
  144. Admin.prototype.authenticate = function(username, password, callback) {
  145. this.s.db.authenticate(username, password, {authdb: 'admin'}, function(err, doc) {
  146. return callback(err, doc);
  147. })
  148. }
  149. /**
  150. * Logout user from server, fire off on all connections and remove all auth info
  151. * @method
  152. * @param {Admin~resultCallback} callback The command result callback
  153. * @return {null}
  154. */
  155. Admin.prototype.logout = function(callback) {
  156. this.s.db.logout({authdb: 'admin'}, function(err, doc) {
  157. return callback(err, doc);
  158. })
  159. }
  160. /**
  161. * Add a user to the database.
  162. * @method
  163. * @param {string} username The username.
  164. * @param {string} password The password.
  165. * @param {object} [options=null] Optional settings.
  166. * @param {(number|string)} [options.w=null] The write concern.
  167. * @param {number} [options.wtimeout=null] The write concern timeout.
  168. * @param {boolean} [options.j=false] Specify a journal write concern.
  169. * @param {boolean} [options.fsync=false] Specify a file sync write concern.
  170. * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher)
  171. * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher)
  172. * @param {Admin~resultCallback} callback The command result callback
  173. * @return {null}
  174. */
  175. Admin.prototype.addUser = function(username, password, options, callback) {
  176. var args = Array.prototype.slice.call(arguments, 2);
  177. callback = args.pop();
  178. options = args.length ? args.shift() : {};
  179. // Set the db name to admin
  180. options.dbName = 'admin';
  181. // Add user
  182. this.s.db.addUser(username, password, options, function(err, doc) {
  183. return callback(err, doc);
  184. })
  185. }
  186. /**
  187. * Remove a user from a database
  188. * @method
  189. * @param {string} username The username.
  190. * @param {object} [options=null] Optional settings.
  191. * @param {(number|string)} [options.w=null] The write concern.
  192. * @param {number} [options.wtimeout=null] The write concern timeout.
  193. * @param {boolean} [options.j=false] Specify a journal write concern.
  194. * @param {boolean} [options.fsync=false] Specify a file sync write concern.
  195. * @param {Admin~resultCallback} callback The command result callback
  196. * @return {null}
  197. */
  198. Admin.prototype.removeUser = function(username, options, callback) {
  199. var self = this;
  200. var args = Array.prototype.slice.call(arguments, 1);
  201. callback = args.pop();
  202. options = args.length ? args.shift() : {};
  203. options.dbName = 'admin';
  204. this.s.db.removeUser(username, options, function(err, doc) {
  205. return callback(err, doc);
  206. })
  207. }
  208. /**
  209. * Set the current profiling level of MongoDB
  210. *
  211. * @param {string} level The new profiling level (off, slow_only, all).
  212. * @param {Admin~resultCallback} callback The command result callback.
  213. * @return {null}
  214. */
  215. Admin.prototype.setProfilingLevel = function(level, callback) {
  216. var self = this;
  217. var command = {};
  218. var profile = 0;
  219. if(level == "off") {
  220. profile = 0;
  221. } else if(level == "slow_only") {
  222. profile = 1;
  223. } else if(level == "all") {
  224. profile = 2;
  225. } else {
  226. return callback(new Error("Error: illegal profiling level value " + level));
  227. }
  228. // Set up the profile number
  229. command['profile'] = profile;
  230. this.s.db.executeDbAdminCommand(command, function(err, doc) {
  231. doc = doc;
  232. if(err == null && doc.ok === 1)
  233. return callback(null, level);
  234. return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null);
  235. });
  236. };
  237. /**
  238. * Retrive the current profiling information for MongoDB
  239. *
  240. * @param {Admin~resultCallback} callback The command result callback.
  241. * @return {null}
  242. */
  243. Admin.prototype.profilingInfo = function(callback) {
  244. try {
  245. this.s.topology.cursor("admin.system.profile", { find: 'system.profile', query: {}}, {}).toArray(callback);
  246. } catch (err) {
  247. return callback(err, null);
  248. }
  249. };
  250. /**
  251. * Validate an existing collection
  252. *
  253. * @param {string} collectionName The name of the collection to validate.
  254. * @param {object} [options=null] Optional settings.
  255. * @param {Admin~resultCallback} callback The command result callback.
  256. * @return {null}
  257. */
  258. Admin.prototype.validateCollection = function(collectionName, options, callback) {
  259. var args = Array.prototype.slice.call(arguments, 1);
  260. callback = args.pop();
  261. options = args.length ? args.shift() : {};
  262. var self = this;
  263. var command = {validate: collectionName};
  264. var keys = Object.keys(options);
  265. // Decorate command with extra options
  266. for(var i = 0; i < keys.length; i++) {
  267. if(options.hasOwnProperty(keys[i])) {
  268. command[keys[i]] = options[keys[i]];
  269. }
  270. }
  271. this.s.db.command(command, function(err, doc) {
  272. if(err != null) return callback(err, null);
  273. if(doc.ok === 0)
  274. return callback(new Error("Error with validate command"), null);
  275. if(doc.result != null && doc.result.constructor != String)
  276. return callback(new Error("Error with validation data"), null);
  277. if(doc.result != null && doc.result.match(/exception|corrupt/) != null)
  278. return callback(new Error("Error: invalid collection " + collectionName), null);
  279. if(doc.valid != null && !doc.valid)
  280. return callback(new Error("Error: invalid collection " + collectionName), null);
  281. return callback(null, doc);
  282. });
  283. };
  284. /**
  285. * List the available databases
  286. *
  287. * @param {Admin~resultCallback} callback The command result callback.
  288. * @return {null}
  289. */
  290. Admin.prototype.listDatabases = function(callback) {
  291. this.s.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, doc) {
  292. if(err != null) return callback(err, null);
  293. return callback(null, doc);
  294. });
  295. }
  296. /**
  297. * Get ReplicaSet status
  298. *
  299. * @param {Admin~resultCallback} callback The command result callback.
  300. * @return {null}
  301. */
  302. Admin.prototype.replSetGetStatus = function(callback) {
  303. var self = this;
  304. this.s.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) {
  305. if(err == null && doc.ok === 1)
  306. return callback(null, doc);
  307. if(err) return callback(err, false);
  308. return callback(toError(doc), false);
  309. });
  310. };
  311. module.exports = Admin;