Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

server.js 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  1. 'use strict';
  2. var inherits = require('util').inherits,
  3. f = require('util').format,
  4. EventEmitter = require('events').EventEmitter,
  5. ReadPreference = require('./read_preference'),
  6. Logger = require('../connection/logger'),
  7. debugOptions = require('../connection/utils').debugOptions,
  8. retrieveBSON = require('../connection/utils').retrieveBSON,
  9. Pool = require('../connection/pool'),
  10. MongoError = require('../error').MongoError,
  11. MongoNetworkError = require('../error').MongoNetworkError,
  12. wireProtocol = require('../wireprotocol'),
  13. BasicCursor = require('../cursor'),
  14. sdam = require('./shared'),
  15. createClientInfo = require('./shared').createClientInfo,
  16. createCompressionInfo = require('./shared').createCompressionInfo,
  17. resolveClusterTime = require('./shared').resolveClusterTime,
  18. SessionMixins = require('./shared').SessionMixins,
  19. relayEvents = require('../utils').relayEvents;
  20. const collationNotSupported = require('../utils').collationNotSupported;
  21. // Used for filtering out fields for loggin
  22. var debugFields = [
  23. 'reconnect',
  24. 'reconnectTries',
  25. 'reconnectInterval',
  26. 'emitError',
  27. 'cursorFactory',
  28. 'host',
  29. 'port',
  30. 'size',
  31. 'keepAlive',
  32. 'keepAliveInitialDelay',
  33. 'noDelay',
  34. 'connectionTimeout',
  35. 'checkServerIdentity',
  36. 'socketTimeout',
  37. 'ssl',
  38. 'ca',
  39. 'crl',
  40. 'cert',
  41. 'key',
  42. 'rejectUnauthorized',
  43. 'promoteLongs',
  44. 'promoteValues',
  45. 'promoteBuffers',
  46. 'servername'
  47. ];
  48. // Server instance id
  49. var id = 0;
  50. var serverAccounting = false;
  51. var servers = {};
  52. var BSON = retrieveBSON();
  53. /**
  54. * Creates a new Server instance
  55. * @class
  56. * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection
  57. * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
  58. * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
  59. * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval)
  60. * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled.
  61. * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors
  62. * @param {string} options.host The server host
  63. * @param {number} options.port The server port
  64. * @param {number} [options.size=5] Server connection pool size
  65. * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled
  66. * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled
  67. * @param {boolean} [options.noDelay=true] TCP Connection no delay
  68. * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting
  69. * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting
  70. * @param {boolean} [options.ssl=false] Use SSL for connection
  71. * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function.
  72. * @param {Buffer} [options.ca] SSL Certificate store binary buffer
  73. * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer
  74. * @param {Buffer} [options.cert] SSL Certificate binary buffer
  75. * @param {Buffer} [options.key] SSL Key file binary buffer
  76. * @param {string} [options.passphrase] SSL Certificate pass phrase
  77. * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates
  78. * @param {string} [options.servername=null] String containing the server name requested via TLS SNI.
  79. * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits
  80. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
  81. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
  82. * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes.
  83. * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.
  84. * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology
  85. * @return {Server} A cursor instance
  86. * @fires Server#connect
  87. * @fires Server#close
  88. * @fires Server#error
  89. * @fires Server#timeout
  90. * @fires Server#parseError
  91. * @fires Server#reconnect
  92. * @fires Server#reconnectFailed
  93. * @fires Server#serverHeartbeatStarted
  94. * @fires Server#serverHeartbeatSucceeded
  95. * @fires Server#serverHeartbeatFailed
  96. * @fires Server#topologyOpening
  97. * @fires Server#topologyClosed
  98. * @fires Server#topologyDescriptionChanged
  99. * @property {string} type the topology type.
  100. * @property {string} parserType the parser type used (c++ or js).
  101. */
  102. var Server = function(options) {
  103. options = options || {};
  104. // Add event listener
  105. EventEmitter.call(this);
  106. // Server instance id
  107. this.id = id++;
  108. // Internal state
  109. this.s = {
  110. // Options
  111. options: options,
  112. // Logger
  113. logger: Logger('Server', options),
  114. // Factory overrides
  115. Cursor: options.cursorFactory || BasicCursor,
  116. // BSON instance
  117. bson:
  118. options.bson ||
  119. new BSON([
  120. BSON.Binary,
  121. BSON.Code,
  122. BSON.DBRef,
  123. BSON.Decimal128,
  124. BSON.Double,
  125. BSON.Int32,
  126. BSON.Long,
  127. BSON.Map,
  128. BSON.MaxKey,
  129. BSON.MinKey,
  130. BSON.ObjectId,
  131. BSON.BSONRegExp,
  132. BSON.Symbol,
  133. BSON.Timestamp
  134. ]),
  135. // Pool
  136. pool: null,
  137. // Disconnect handler
  138. disconnectHandler: options.disconnectHandler,
  139. // Monitor thread (keeps the connection alive)
  140. monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true,
  141. // Is the server in a topology
  142. inTopology: !!options.parent,
  143. // Monitoring timeout
  144. monitoringInterval:
  145. typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000,
  146. // Topology id
  147. topologyId: -1,
  148. compression: { compressors: createCompressionInfo(options) },
  149. // Optional parent topology
  150. parent: options.parent
  151. };
  152. // If this is a single deployment we need to track the clusterTime here
  153. if (!this.s.parent) {
  154. this.s.clusterTime = null;
  155. }
  156. // Curent ismaster
  157. this.ismaster = null;
  158. // Current ping time
  159. this.lastIsMasterMS = -1;
  160. // The monitoringProcessId
  161. this.monitoringProcessId = null;
  162. // Initial connection
  163. this.initialConnect = true;
  164. // Default type
  165. this._type = 'server';
  166. // Set the client info
  167. this.clientInfo = createClientInfo(options);
  168. // Max Stalleness values
  169. // last time we updated the ismaster state
  170. this.lastUpdateTime = 0;
  171. // Last write time
  172. this.lastWriteDate = 0;
  173. // Stalleness
  174. this.staleness = 0;
  175. };
  176. inherits(Server, EventEmitter);
  177. Object.assign(Server.prototype, SessionMixins);
  178. Object.defineProperty(Server.prototype, 'type', {
  179. enumerable: true,
  180. get: function() {
  181. return this._type;
  182. }
  183. });
  184. Object.defineProperty(Server.prototype, 'parserType', {
  185. enumerable: true,
  186. get: function() {
  187. return BSON.native ? 'c++' : 'js';
  188. }
  189. });
  190. Object.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', {
  191. enumerable: true,
  192. get: function() {
  193. if (!this.ismaster) return null;
  194. return this.ismaster.logicalSessionTimeoutMinutes || null;
  195. }
  196. });
  197. // In single server deployments we track the clusterTime directly on the topology, however
  198. // in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the
  199. // tracking objects so we can ensure we are gossiping the maximum time received from the
  200. // server.
  201. Object.defineProperty(Server.prototype, 'clusterTime', {
  202. enumerable: true,
  203. set: function(clusterTime) {
  204. const settings = this.s.parent ? this.s.parent : this.s;
  205. resolveClusterTime(settings, clusterTime);
  206. },
  207. get: function() {
  208. const settings = this.s.parent ? this.s.parent : this.s;
  209. return settings.clusterTime || null;
  210. }
  211. });
  212. Server.enableServerAccounting = function() {
  213. serverAccounting = true;
  214. servers = {};
  215. };
  216. Server.disableServerAccounting = function() {
  217. serverAccounting = false;
  218. };
  219. Server.servers = function() {
  220. return servers;
  221. };
  222. Object.defineProperty(Server.prototype, 'name', {
  223. enumerable: true,
  224. get: function() {
  225. return this.s.options.host + ':' + this.s.options.port;
  226. }
  227. });
  228. function disconnectHandler(self, type, ns, cmd, options, callback) {
  229. // Topology is not connected, save the call in the provided store to be
  230. // Executed at some point when the handler deems it's reconnected
  231. if (
  232. !self.s.pool.isConnected() &&
  233. self.s.options.reconnect &&
  234. self.s.disconnectHandler != null &&
  235. !options.monitoring
  236. ) {
  237. self.s.disconnectHandler.add(type, ns, cmd, options, callback);
  238. return true;
  239. }
  240. // If we have no connection error
  241. if (!self.s.pool.isConnected()) {
  242. callback(new MongoError(f('no connection available to server %s', self.name)));
  243. return true;
  244. }
  245. }
  246. function monitoringProcess(self) {
  247. return function() {
  248. // Pool was destroyed do not continue process
  249. if (self.s.pool.isDestroyed()) return;
  250. // Emit monitoring Process event
  251. self.emit('monitoring', self);
  252. // Perform ismaster call
  253. // Get start time
  254. var start = new Date().getTime();
  255. // Execute the ismaster query
  256. self.command(
  257. 'admin.$cmd',
  258. { ismaster: true },
  259. {
  260. socketTimeout:
  261. typeof self.s.options.connectionTimeout !== 'number'
  262. ? 2000
  263. : self.s.options.connectionTimeout,
  264. monitoring: true
  265. },
  266. (err, result) => {
  267. // Set initial lastIsMasterMS
  268. self.lastIsMasterMS = new Date().getTime() - start;
  269. if (self.s.pool.isDestroyed()) return;
  270. // Update the ismaster view if we have a result
  271. if (result) {
  272. self.ismaster = result.result;
  273. }
  274. // Re-schedule the monitoring process
  275. self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval);
  276. }
  277. );
  278. };
  279. }
  280. var eventHandler = function(self, event) {
  281. return function(err, conn) {
  282. // Log information of received information if in info mode
  283. if (self.s.logger.isInfo()) {
  284. var object = err instanceof MongoError ? JSON.stringify(err) : {};
  285. self.s.logger.info(
  286. f('server %s fired event %s out with message %s', self.name, event, object)
  287. );
  288. }
  289. // Handle connect event
  290. if (event === 'connect') {
  291. self.initialConnect = false;
  292. self.ismaster = conn.ismaster;
  293. self.lastIsMasterMS = conn.lastIsMasterMS;
  294. if (conn.agreedCompressor) {
  295. self.s.pool.options.agreedCompressor = conn.agreedCompressor;
  296. }
  297. if (conn.zlibCompressionLevel) {
  298. self.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel;
  299. }
  300. if (conn.ismaster.$clusterTime) {
  301. const $clusterTime = conn.ismaster.$clusterTime;
  302. self.clusterTime = $clusterTime;
  303. }
  304. // It's a proxy change the type so
  305. // the wireprotocol will send $readPreference
  306. if (self.ismaster.msg === 'isdbgrid') {
  307. self._type = 'mongos';
  308. }
  309. // Have we defined self monitoring
  310. if (self.s.monitoring) {
  311. self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval);
  312. }
  313. // Emit server description changed if something listening
  314. sdam.emitServerDescriptionChanged(self, {
  315. address: self.name,
  316. arbiters: [],
  317. hosts: [],
  318. passives: [],
  319. type: sdam.getTopologyType(self)
  320. });
  321. if (!self.s.inTopology) {
  322. // Emit topology description changed if something listening
  323. sdam.emitTopologyDescriptionChanged(self, {
  324. topologyType: 'Single',
  325. servers: [
  326. {
  327. address: self.name,
  328. arbiters: [],
  329. hosts: [],
  330. passives: [],
  331. type: sdam.getTopologyType(self)
  332. }
  333. ]
  334. });
  335. }
  336. // Log the ismaster if available
  337. if (self.s.logger.isInfo()) {
  338. self.s.logger.info(
  339. f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster))
  340. );
  341. }
  342. // Emit connect
  343. self.emit('connect', self);
  344. } else if (
  345. event === 'error' ||
  346. event === 'parseError' ||
  347. event === 'close' ||
  348. event === 'timeout' ||
  349. event === 'reconnect' ||
  350. event === 'attemptReconnect' ||
  351. 'reconnectFailed'
  352. ) {
  353. // Remove server instance from accounting
  354. if (
  355. serverAccounting &&
  356. ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1
  357. ) {
  358. // Emit toplogy opening event if not in topology
  359. if (!self.s.inTopology) {
  360. self.emit('topologyOpening', { topologyId: self.id });
  361. }
  362. delete servers[self.id];
  363. }
  364. if (event === 'close') {
  365. // Closing emits a server description changed event going to unknown.
  366. sdam.emitServerDescriptionChanged(self, {
  367. address: self.name,
  368. arbiters: [],
  369. hosts: [],
  370. passives: [],
  371. type: 'Unknown'
  372. });
  373. }
  374. // Reconnect failed return error
  375. if (event === 'reconnectFailed') {
  376. self.emit('reconnectFailed', err);
  377. // Emit error if any listeners
  378. if (self.listeners('error').length > 0) {
  379. self.emit('error', err);
  380. }
  381. // Terminate
  382. return;
  383. }
  384. // On first connect fail
  385. if (
  386. ['disconnected', 'connecting'].indexOf(self.s.pool.state) !== -1 &&
  387. self.initialConnect &&
  388. ['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1
  389. ) {
  390. self.initialConnect = false;
  391. return self.emit(
  392. 'error',
  393. new MongoNetworkError(
  394. f('failed to connect to server [%s] on first connect [%s]', self.name, err)
  395. )
  396. );
  397. }
  398. // Reconnect event, emit the server
  399. if (event === 'reconnect') {
  400. // Reconnecting emits a server description changed event going from unknown to the
  401. // current server type.
  402. sdam.emitServerDescriptionChanged(self, {
  403. address: self.name,
  404. arbiters: [],
  405. hosts: [],
  406. passives: [],
  407. type: sdam.getTopologyType(self)
  408. });
  409. return self.emit(event, self);
  410. }
  411. // Emit the event
  412. self.emit(event, err);
  413. }
  414. };
  415. };
  416. /**
  417. * Initiate server connect
  418. */
  419. Server.prototype.connect = function(options) {
  420. var self = this;
  421. options = options || {};
  422. // Set the connections
  423. if (serverAccounting) servers[this.id] = this;
  424. // Do not allow connect to be called on anything that's not disconnected
  425. if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) {
  426. throw new MongoError(f('server instance in invalid state %s', self.s.pool.state));
  427. }
  428. // Create a pool
  429. self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson }));
  430. // Set up listeners
  431. self.s.pool.on('close', eventHandler(self, 'close'));
  432. self.s.pool.on('error', eventHandler(self, 'error'));
  433. self.s.pool.on('timeout', eventHandler(self, 'timeout'));
  434. self.s.pool.on('parseError', eventHandler(self, 'parseError'));
  435. self.s.pool.on('connect', eventHandler(self, 'connect'));
  436. self.s.pool.on('reconnect', eventHandler(self, 'reconnect'));
  437. self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed'));
  438. // Set up listeners for command monitoring
  439. relayEvents(self.s.pool, self, ['commandStarted', 'commandSucceeded', 'commandFailed']);
  440. // Emit toplogy opening event if not in topology
  441. if (!self.s.inTopology) {
  442. this.emit('topologyOpening', { topologyId: self.id });
  443. }
  444. // Emit opening server event
  445. self.emit('serverOpening', {
  446. topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id,
  447. address: self.name
  448. });
  449. self.s.pool.connect();
  450. };
  451. /**
  452. * Authenticate the topology.
  453. * @method
  454. * @param {MongoCredentials} credentials The credentials for authentication we are using
  455. * @param {authResultCallback} callback A callback function
  456. */
  457. Server.prototype.auth = function(credentials, callback) {
  458. if (typeof callback === 'function') callback(null, null);
  459. };
  460. /**
  461. * Get the server description
  462. * @method
  463. * @return {object}
  464. */
  465. Server.prototype.getDescription = function() {
  466. var ismaster = this.ismaster || {};
  467. var description = {
  468. type: sdam.getTopologyType(this),
  469. address: this.name
  470. };
  471. // Add fields if available
  472. if (ismaster.hosts) description.hosts = ismaster.hosts;
  473. if (ismaster.arbiters) description.arbiters = ismaster.arbiters;
  474. if (ismaster.passives) description.passives = ismaster.passives;
  475. if (ismaster.setName) description.setName = ismaster.setName;
  476. return description;
  477. };
  478. /**
  479. * Returns the last known ismaster document for this server
  480. * @method
  481. * @return {object}
  482. */
  483. Server.prototype.lastIsMaster = function() {
  484. return this.ismaster;
  485. };
  486. /**
  487. * Unref all connections belong to this server
  488. * @method
  489. */
  490. Server.prototype.unref = function() {
  491. this.s.pool.unref();
  492. };
  493. /**
  494. * Figure out if the server is connected
  495. * @method
  496. * @return {boolean}
  497. */
  498. Server.prototype.isConnected = function() {
  499. if (!this.s.pool) return false;
  500. return this.s.pool.isConnected();
  501. };
  502. /**
  503. * Figure out if the server instance was destroyed by calling destroy
  504. * @method
  505. * @return {boolean}
  506. */
  507. Server.prototype.isDestroyed = function() {
  508. if (!this.s.pool) return false;
  509. return this.s.pool.isDestroyed();
  510. };
  511. function basicWriteValidations(self) {
  512. if (!self.s.pool) return new MongoError('server instance is not connected');
  513. if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed');
  514. }
  515. function basicReadValidations(self, options) {
  516. basicWriteValidations(self, options);
  517. if (options.readPreference && !(options.readPreference instanceof ReadPreference)) {
  518. throw new Error('readPreference must be an instance of ReadPreference');
  519. }
  520. }
  521. /**
  522. * Execute a command
  523. * @method
  524. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  525. * @param {object} cmd The command hash
  526. * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it
  527. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  528. * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys.
  529. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  530. * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document.
  531. * @param {ClientSession} [options.session=null] Session to use for the operation
  532. * @param {opResultCallback} callback A callback function
  533. */
  534. Server.prototype.command = function(ns, cmd, options, callback) {
  535. var self = this;
  536. if (typeof options === 'function') {
  537. (callback = options), (options = {}), (options = options || {});
  538. }
  539. var result = basicReadValidations(self, options);
  540. if (result) return callback(result);
  541. // Clone the options
  542. options = Object.assign({}, options, { wireProtocolCommand: false });
  543. // Debug log
  544. if (self.s.logger.isDebug())
  545. self.s.logger.debug(
  546. f(
  547. 'executing command [%s] against %s',
  548. JSON.stringify({
  549. ns: ns,
  550. cmd: cmd,
  551. options: debugOptions(debugFields, options)
  552. }),
  553. self.name
  554. )
  555. );
  556. // If we are not connected or have a disconnectHandler specified
  557. if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return;
  558. // error if collation not supported
  559. if (collationNotSupported(this, cmd)) {
  560. return callback(new MongoError(`server ${this.name} does not support collation`));
  561. }
  562. wireProtocol.command(self, ns, cmd, options, callback);
  563. };
  564. /**
  565. * Insert one or more documents
  566. * @method
  567. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  568. * @param {array} ops An array of documents to insert
  569. * @param {boolean} [options.ordered=true] Execute in order or out of order
  570. * @param {object} [options.writeConcern={}] Write concern for the operation
  571. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  572. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  573. * @param {ClientSession} [options.session=null] Session to use for the operation
  574. * @param {opResultCallback} callback A callback function
  575. */
  576. Server.prototype.insert = function(ns, ops, options, callback) {
  577. var self = this;
  578. if (typeof options === 'function') {
  579. (callback = options), (options = {}), (options = options || {});
  580. }
  581. var result = basicWriteValidations(self, options);
  582. if (result) return callback(result);
  583. // If we are not connected or have a disconnectHandler specified
  584. if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return;
  585. // Setup the docs as an array
  586. ops = Array.isArray(ops) ? ops : [ops];
  587. // Execute write
  588. return wireProtocol.insert(self, ns, ops, options, callback);
  589. };
  590. /**
  591. * Perform one or more update operations
  592. * @method
  593. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  594. * @param {array} ops An array of updates
  595. * @param {boolean} [options.ordered=true] Execute in order or out of order
  596. * @param {object} [options.writeConcern={}] Write concern for the operation
  597. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  598. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  599. * @param {ClientSession} [options.session=null] Session to use for the operation
  600. * @param {opResultCallback} callback A callback function
  601. */
  602. Server.prototype.update = function(ns, ops, options, callback) {
  603. var self = this;
  604. if (typeof options === 'function') {
  605. (callback = options), (options = {}), (options = options || {});
  606. }
  607. var result = basicWriteValidations(self, options);
  608. if (result) return callback(result);
  609. // If we are not connected or have a disconnectHandler specified
  610. if (disconnectHandler(self, 'update', ns, ops, options, callback)) return;
  611. // error if collation not supported
  612. if (collationNotSupported(this, options)) {
  613. return callback(new MongoError(`server ${this.name} does not support collation`));
  614. }
  615. // Setup the docs as an array
  616. ops = Array.isArray(ops) ? ops : [ops];
  617. // Execute write
  618. return wireProtocol.update(self, ns, ops, options, callback);
  619. };
  620. /**
  621. * Perform one or more remove operations
  622. * @method
  623. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  624. * @param {array} ops An array of removes
  625. * @param {boolean} [options.ordered=true] Execute in order or out of order
  626. * @param {object} [options.writeConcern={}] Write concern for the operation
  627. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  628. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  629. * @param {ClientSession} [options.session=null] Session to use for the operation
  630. * @param {opResultCallback} callback A callback function
  631. */
  632. Server.prototype.remove = function(ns, ops, options, callback) {
  633. var self = this;
  634. if (typeof options === 'function') {
  635. (callback = options), (options = {}), (options = options || {});
  636. }
  637. var result = basicWriteValidations(self, options);
  638. if (result) return callback(result);
  639. // If we are not connected or have a disconnectHandler specified
  640. if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return;
  641. // error if collation not supported
  642. if (collationNotSupported(this, options)) {
  643. return callback(new MongoError(`server ${this.name} does not support collation`));
  644. }
  645. // Setup the docs as an array
  646. ops = Array.isArray(ops) ? ops : [ops];
  647. // Execute write
  648. return wireProtocol.remove(self, ns, ops, options, callback);
  649. };
  650. /**
  651. * Get a new cursor
  652. * @method
  653. * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
  654. * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId
  655. * @param {object} [options] Options for the cursor
  656. * @param {object} [options.batchSize=0] Batchsize for the operation
  657. * @param {array} [options.documents=[]] Initial documents list for cursor
  658. * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it
  659. * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized.
  660. * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  661. * @param {ClientSession} [options.session=null] Session to use for the operation
  662. * @param {object} [options.topology] The internal topology of the created cursor
  663. * @returns {Cursor}
  664. */
  665. Server.prototype.cursor = function(ns, cmd, options) {
  666. options = options || {};
  667. const topology = options.topology || this;
  668. // Set up final cursor type
  669. var FinalCursor = options.cursorFactory || this.s.Cursor;
  670. // Return the cursor
  671. return new FinalCursor(this.s.bson, ns, cmd, options, topology, this.s.options);
  672. };
  673. /**
  674. * Compare two server instances
  675. * @method
  676. * @param {Server} server Server to compare equality against
  677. * @return {boolean}
  678. */
  679. Server.prototype.equals = function(server) {
  680. if (typeof server === 'string') return this.name.toLowerCase() === server.toLowerCase();
  681. if (server.name) return this.name.toLowerCase() === server.name.toLowerCase();
  682. return false;
  683. };
  684. /**
  685. * All raw connections
  686. * @method
  687. * @return {Connection[]}
  688. */
  689. Server.prototype.connections = function() {
  690. return this.s.pool.allConnections();
  691. };
  692. /**
  693. * Selects a server
  694. * @method
  695. * @param {function} selector Unused
  696. * @param {ReadPreference} [options.readPreference] Unused
  697. * @param {ClientSession} [options.session] Unused
  698. * @return {Server}
  699. */
  700. Server.prototype.selectServer = function(selector, options, callback) {
  701. if (typeof selector === 'function' && typeof callback === 'undefined')
  702. (callback = selector), (selector = undefined), (options = {});
  703. if (typeof options === 'function')
  704. (callback = options), (options = selector), (selector = undefined);
  705. callback(null, this);
  706. };
  707. var listeners = ['close', 'error', 'timeout', 'parseError', 'connect'];
  708. /**
  709. * Destroy the server connection
  710. * @method
  711. * @param {boolean} [options.emitClose=false] Emit close event on destroy
  712. * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy
  713. * @param {boolean} [options.force=false] Force destroy the pool
  714. */
  715. Server.prototype.destroy = function(options, callback) {
  716. if (this._destroyed) {
  717. if (typeof callback === 'function') callback(null, null);
  718. return;
  719. }
  720. options = options || {};
  721. var self = this;
  722. // Set the connections
  723. if (serverAccounting) delete servers[this.id];
  724. // Destroy the monitoring process if any
  725. if (this.monitoringProcessId) {
  726. clearTimeout(this.monitoringProcessId);
  727. }
  728. // No pool, return
  729. if (!self.s.pool) {
  730. this._destroyed = true;
  731. if (typeof callback === 'function') callback(null, null);
  732. return;
  733. }
  734. // Emit close event
  735. if (options.emitClose) {
  736. self.emit('close', self);
  737. }
  738. // Emit destroy event
  739. if (options.emitDestroy) {
  740. self.emit('destroy', self);
  741. }
  742. // Remove all listeners
  743. listeners.forEach(function(event) {
  744. self.s.pool.removeAllListeners(event);
  745. });
  746. // Emit opening server event
  747. if (self.listeners('serverClosed').length > 0)
  748. self.emit('serverClosed', {
  749. topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id,
  750. address: self.name
  751. });
  752. // Emit toplogy opening event if not in topology
  753. if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) {
  754. self.emit('topologyClosed', { topologyId: self.id });
  755. }
  756. if (self.s.logger.isDebug()) {
  757. self.s.logger.debug(f('destroy called on server %s', self.name));
  758. }
  759. // Destroy the pool
  760. this.s.pool.destroy(options.force, callback);
  761. this._destroyed = true;
  762. };
  763. /**
  764. * A server connect event, used to verify that the connection is up and running
  765. *
  766. * @event Server#connect
  767. * @type {Server}
  768. */
  769. /**
  770. * A server reconnect event, used to verify that the server topology has reconnected
  771. *
  772. * @event Server#reconnect
  773. * @type {Server}
  774. */
  775. /**
  776. * A server opening SDAM monitoring event
  777. *
  778. * @event Server#serverOpening
  779. * @type {object}
  780. */
  781. /**
  782. * A server closed SDAM monitoring event
  783. *
  784. * @event Server#serverClosed
  785. * @type {object}
  786. */
  787. /**
  788. * A server description SDAM change monitoring event
  789. *
  790. * @event Server#serverDescriptionChanged
  791. * @type {object}
  792. */
  793. /**
  794. * A topology open SDAM event
  795. *
  796. * @event Server#topologyOpening
  797. * @type {object}
  798. */
  799. /**
  800. * A topology closed SDAM event
  801. *
  802. * @event Server#topologyClosed
  803. * @type {object}
  804. */
  805. /**
  806. * A topology structure SDAM change event
  807. *
  808. * @event Server#topologyDescriptionChanged
  809. * @type {object}
  810. */
  811. /**
  812. * Server reconnect failed
  813. *
  814. * @event Server#reconnectFailed
  815. * @type {Error}
  816. */
  817. /**
  818. * Server connection pool closed
  819. *
  820. * @event Server#close
  821. * @type {object}
  822. */
  823. /**
  824. * Server connection pool caused an error
  825. *
  826. * @event Server#error
  827. * @type {Error}
  828. */
  829. /**
  830. * Server destroyed was called
  831. *
  832. * @event Server#destroy
  833. * @type {Server}
  834. */
  835. module.exports = Server;