MongoUrl.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. /* Copyright 2010-2016 MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Linq;
  18. using MongoDB.Bson;
  19. namespace MongoDB.Driver
  20. {
  21. /// <summary>
  22. /// Represents an immutable URL style connection string. See also MongoUrlBuilder.
  23. /// </summary>
  24. #if NET45
  25. [Serializable]
  26. #endif
  27. public class MongoUrl : IEquatable<MongoUrl>
  28. {
  29. // private static fields
  30. private static object __staticLock = new object();
  31. private static Dictionary<string, MongoUrl> __cache = new Dictionary<string, MongoUrl>();
  32. // private fields
  33. private readonly string _applicationName;
  34. private readonly string _authenticationMechanism;
  35. private readonly IEnumerable<KeyValuePair<string, string>> _authenticationMechanismProperties;
  36. private readonly string _authenticationSource;
  37. private readonly ConnectionMode _connectionMode;
  38. private readonly TimeSpan _connectTimeout;
  39. private readonly string _databaseName;
  40. private readonly bool? _fsync;
  41. private readonly GuidRepresentation _guidRepresentation;
  42. private readonly TimeSpan _heartbeatInterval;
  43. private readonly TimeSpan _heartbeatTimeout;
  44. private readonly bool _ipv6;
  45. private readonly bool? _journal;
  46. private readonly TimeSpan _maxConnectionIdleTime;
  47. private readonly TimeSpan _maxConnectionLifeTime;
  48. private readonly int _maxConnectionPoolSize;
  49. private readonly int _minConnectionPoolSize;
  50. private readonly string _password;
  51. private readonly ReadConcernLevel? _readConcernLevel;
  52. private readonly ReadPreference _readPreference;
  53. private readonly string _replicaSetName;
  54. private readonly TimeSpan _localThreshold;
  55. private readonly IEnumerable<MongoServerAddress> _servers;
  56. private readonly TimeSpan _serverSelectionTimeout;
  57. private readonly TimeSpan _socketTimeout;
  58. private readonly string _username;
  59. private readonly bool _useSsl;
  60. private readonly bool _verifySslCertificate;
  61. private readonly WriteConcern.WValue _w;
  62. private readonly double _waitQueueMultiple;
  63. private readonly int _waitQueueSize;
  64. private readonly TimeSpan _waitQueueTimeout;
  65. private readonly TimeSpan? _wTimeout;
  66. private readonly string _url;
  67. // constructors
  68. /// <summary>
  69. /// Creates a new instance of MongoUrl.
  70. /// </summary>
  71. /// <param name="url">The URL containing the settings.</param>
  72. public MongoUrl(string url)
  73. {
  74. var builder = new MongoUrlBuilder(url); // parses url
  75. _applicationName = builder.ApplicationName;
  76. _authenticationMechanism = builder.AuthenticationMechanism;
  77. _authenticationMechanismProperties = builder.AuthenticationMechanismProperties;
  78. _authenticationSource = builder.AuthenticationSource;
  79. _connectionMode = builder.ConnectionMode;
  80. _connectTimeout = builder.ConnectTimeout;
  81. _databaseName = builder.DatabaseName;
  82. _fsync = builder.FSync;
  83. _guidRepresentation = builder.GuidRepresentation;
  84. _heartbeatInterval = builder.HeartbeatInterval;
  85. _heartbeatTimeout = builder.HeartbeatTimeout;
  86. _ipv6 = builder.IPv6;
  87. _journal = builder.Journal;
  88. _localThreshold = builder.LocalThreshold;
  89. _maxConnectionIdleTime = builder.MaxConnectionIdleTime;
  90. _maxConnectionLifeTime = builder.MaxConnectionLifeTime;
  91. _maxConnectionPoolSize = builder.MaxConnectionPoolSize;
  92. _minConnectionPoolSize = builder.MinConnectionPoolSize;
  93. _password = builder.Password;
  94. _readConcernLevel = builder.ReadConcernLevel;
  95. _readPreference = builder.ReadPreference;
  96. _replicaSetName = builder.ReplicaSetName;
  97. _servers = builder.Servers;
  98. _serverSelectionTimeout = builder.ServerSelectionTimeout;
  99. _socketTimeout = builder.SocketTimeout;
  100. _username = builder.Username;
  101. _useSsl = builder.UseSsl;
  102. _verifySslCertificate = builder.VerifySslCertificate;
  103. _w = builder.W;
  104. _waitQueueMultiple = builder.WaitQueueMultiple;
  105. _waitQueueSize = builder.WaitQueueSize;
  106. _waitQueueTimeout = builder.WaitQueueTimeout;
  107. _wTimeout = builder.WTimeout;
  108. _url = builder.ToString(); // keep canonical form
  109. }
  110. // public properties
  111. /// <summary>
  112. /// Gets the application name.
  113. /// </summary>
  114. public string ApplicationName
  115. {
  116. get { return _applicationName; }
  117. }
  118. /// <summary>
  119. /// Gets the authentication mechanism.
  120. /// </summary>
  121. public string AuthenticationMechanism
  122. {
  123. get { return _authenticationMechanism; }
  124. }
  125. /// <summary>
  126. /// Gets the authentication mechanism properties.
  127. /// </summary>
  128. public IEnumerable<KeyValuePair<string, string>> AuthenticationMechanismProperties
  129. {
  130. get { return _authenticationMechanismProperties; }
  131. }
  132. /// <summary>
  133. /// Gets the authentication source.
  134. /// </summary>
  135. public string AuthenticationSource
  136. {
  137. get { return _authenticationSource; }
  138. }
  139. /// <summary>
  140. /// Gets the actual wait queue size (either WaitQueueSize or WaitQueueMultiple x MaxConnectionPoolSize).
  141. /// </summary>
  142. public int ComputedWaitQueueSize
  143. {
  144. get
  145. {
  146. if (_waitQueueMultiple == 0.0)
  147. {
  148. return _waitQueueSize;
  149. }
  150. else
  151. {
  152. return (int)(_waitQueueMultiple * _maxConnectionPoolSize);
  153. }
  154. }
  155. }
  156. /// <summary>
  157. /// Gets the connection mode.
  158. /// </summary>
  159. public ConnectionMode ConnectionMode
  160. {
  161. get { return _connectionMode; }
  162. }
  163. /// <summary>
  164. /// Gets the connect timeout.
  165. /// </summary>
  166. public TimeSpan ConnectTimeout
  167. {
  168. get { return _connectTimeout; }
  169. }
  170. /// <summary>
  171. /// Gets the optional database name.
  172. /// </summary>
  173. public string DatabaseName
  174. {
  175. get { return _databaseName; }
  176. }
  177. /// <summary>
  178. /// Gets the FSync component of the write concern.
  179. /// </summary>
  180. public bool? FSync
  181. {
  182. get { return _fsync; }
  183. }
  184. /// <summary>
  185. /// Gets the representation to use for Guids.
  186. /// </summary>
  187. public GuidRepresentation GuidRepresentation
  188. {
  189. get { return _guidRepresentation; }
  190. }
  191. /// <summary>
  192. /// Gets a value indicating whether this instance has authentication settings.
  193. /// </summary>
  194. public bool HasAuthenticationSettings
  195. {
  196. get
  197. {
  198. return
  199. _username != null ||
  200. _password != null ||
  201. _authenticationMechanism != null ||
  202. _authenticationSource != null;
  203. }
  204. }
  205. /// <summary>
  206. /// Gets the heartbeat interval.
  207. /// </summary>
  208. public TimeSpan HeartbeatInterval
  209. {
  210. get { return _heartbeatInterval; }
  211. }
  212. /// <summary>
  213. /// Gets the heartbeat timeout.
  214. /// </summary>
  215. public TimeSpan HeartbeatTimeout
  216. {
  217. get { return _heartbeatTimeout; }
  218. }
  219. /// <summary>
  220. /// Gets a value indicating whether to use IPv6.
  221. /// </summary>
  222. public bool IPv6
  223. {
  224. get { return _ipv6; }
  225. }
  226. /// <summary>
  227. /// Gets the Journal component of the write concern.
  228. /// </summary>
  229. public bool? Journal
  230. {
  231. get { return _journal; }
  232. }
  233. /// <summary>
  234. /// Gets the local threshold.
  235. /// </summary>
  236. public TimeSpan LocalThreshold
  237. {
  238. get { return _localThreshold; }
  239. }
  240. /// <summary>
  241. /// Gets the max connection idle time.
  242. /// </summary>
  243. public TimeSpan MaxConnectionIdleTime
  244. {
  245. get { return _maxConnectionIdleTime; }
  246. }
  247. /// <summary>
  248. /// Gets the max connection life time.
  249. /// </summary>
  250. public TimeSpan MaxConnectionLifeTime
  251. {
  252. get { return _maxConnectionLifeTime; }
  253. }
  254. /// <summary>
  255. /// Gets the max connection pool size.
  256. /// </summary>
  257. public int MaxConnectionPoolSize
  258. {
  259. get { return _maxConnectionPoolSize; }
  260. }
  261. /// <summary>
  262. /// Gets the min connection pool size.
  263. /// </summary>
  264. public int MinConnectionPoolSize
  265. {
  266. get { return _minConnectionPoolSize; }
  267. }
  268. /// <summary>
  269. /// Gets the password.
  270. /// </summary>
  271. public string Password
  272. {
  273. get { return _password; }
  274. }
  275. /// <summary>
  276. /// Gets the read concern level.
  277. /// </summary>
  278. public ReadConcernLevel? ReadConcernLevel
  279. {
  280. get { return _readConcernLevel; }
  281. }
  282. /// <summary>
  283. /// Gets the read preference.
  284. /// </summary>
  285. public ReadPreference ReadPreference
  286. {
  287. get { return _readPreference; }
  288. }
  289. /// <summary>
  290. /// Gets the name of the replica set.
  291. /// </summary>
  292. public string ReplicaSetName
  293. {
  294. get { return _replicaSetName; }
  295. }
  296. /// <summary>
  297. /// Gets the address of the server (see also Servers if using more than one address).
  298. /// </summary>
  299. public MongoServerAddress Server
  300. {
  301. get { return (_servers == null) ? null : _servers.Single(); }
  302. }
  303. /// <summary>
  304. /// Gets the list of server addresses (see also Server if using only one address).
  305. /// </summary>
  306. public IEnumerable<MongoServerAddress> Servers
  307. {
  308. get { return _servers; }
  309. }
  310. /// <summary>
  311. /// Gets the server selection timeout.
  312. /// </summary>
  313. public TimeSpan ServerSelectionTimeout
  314. {
  315. get { return _serverSelectionTimeout; }
  316. }
  317. /// <summary>
  318. /// Gets the socket timeout.
  319. /// </summary>
  320. public TimeSpan SocketTimeout
  321. {
  322. get { return _socketTimeout; }
  323. }
  324. /// <summary>
  325. /// Gets the URL (in canonical form).
  326. /// </summary>
  327. public string Url
  328. {
  329. get { return _url; }
  330. }
  331. /// <summary>
  332. /// Gets the username.
  333. /// </summary>
  334. public string Username
  335. {
  336. get { return _username; }
  337. }
  338. /// <summary>
  339. /// Gets a value indicating whether to use SSL.
  340. /// </summary>
  341. public bool UseSsl
  342. {
  343. get { return _useSsl; }
  344. }
  345. /// <summary>
  346. /// Gets a value indicating whether to verify an SSL certificate.
  347. /// </summary>
  348. public bool VerifySslCertificate
  349. {
  350. get { return _verifySslCertificate; }
  351. }
  352. /// <summary>
  353. /// Gets the W component of the write concern.
  354. /// </summary>
  355. public WriteConcern.WValue W
  356. {
  357. get { return _w; }
  358. }
  359. /// <summary>
  360. /// Gets the wait queue multiple (the actual wait queue size will be WaitQueueMultiple x MaxConnectionPoolSize).
  361. /// </summary>
  362. public double WaitQueueMultiple
  363. {
  364. get { return _waitQueueMultiple; }
  365. }
  366. /// <summary>
  367. /// Gets the wait queue size.
  368. /// </summary>
  369. public int WaitQueueSize
  370. {
  371. get { return _waitQueueSize; }
  372. }
  373. /// <summary>
  374. /// Gets the wait queue timeout.
  375. /// </summary>
  376. public TimeSpan WaitQueueTimeout
  377. {
  378. get { return _waitQueueTimeout; }
  379. }
  380. /// <summary>
  381. /// Gets the WTimeout component of the write concern.
  382. /// </summary>
  383. public TimeSpan? WTimeout
  384. {
  385. get { return _wTimeout; }
  386. }
  387. // public operators
  388. /// <summary>
  389. /// Compares two MongoUrls.
  390. /// </summary>
  391. /// <param name="lhs">The first URL.</param>
  392. /// <param name="rhs">The other URL.</param>
  393. /// <returns>True if the two URLs are equal (or both null).</returns>
  394. public static bool operator ==(MongoUrl lhs, MongoUrl rhs)
  395. {
  396. return object.Equals(lhs, rhs);
  397. }
  398. /// <summary>
  399. /// Compares two MongoUrls.
  400. /// </summary>
  401. /// <param name="lhs">The first URL.</param>
  402. /// <param name="rhs">The other URL.</param>
  403. /// <returns>True if the two URLs are not equal (or one is null and the other is not).</returns>
  404. public static bool operator !=(MongoUrl lhs, MongoUrl rhs)
  405. {
  406. return !(lhs == rhs);
  407. }
  408. // public static methods
  409. /// <summary>
  410. /// Clears the URL cache. When a URL is parsed it is stored in the cache so that it doesn't have to be
  411. /// parsed again. There is rarely a need to call this method.
  412. /// </summary>
  413. public static void ClearCache()
  414. {
  415. __cache.Clear();
  416. }
  417. /// <summary>
  418. /// Creates an instance of MongoUrl (might be an existing existence if the same URL has been used before).
  419. /// </summary>
  420. /// <param name="url">The URL containing the settings.</param>
  421. /// <returns>An instance of MongoUrl.</returns>
  422. public static MongoUrl Create(string url)
  423. {
  424. // cache previously seen urls to avoid repeated parsing
  425. lock (__staticLock)
  426. {
  427. MongoUrl mongoUrl;
  428. if (!__cache.TryGetValue(url, out mongoUrl))
  429. {
  430. mongoUrl = new MongoUrl(url);
  431. var canonicalUrl = mongoUrl.ToString();
  432. if (canonicalUrl != url)
  433. {
  434. if (__cache.ContainsKey(canonicalUrl))
  435. {
  436. mongoUrl = __cache[canonicalUrl]; // use existing MongoUrl
  437. }
  438. else
  439. {
  440. __cache[canonicalUrl] = mongoUrl; // cache under canonicalUrl also
  441. }
  442. }
  443. __cache[url] = mongoUrl;
  444. }
  445. return mongoUrl;
  446. }
  447. }
  448. // public methods
  449. /// <summary>
  450. /// Compares two MongoUrls.
  451. /// </summary>
  452. /// <param name="rhs">The other URL.</param>
  453. /// <returns>True if the two URLs are equal.</returns>
  454. public bool Equals(MongoUrl rhs)
  455. {
  456. if (object.ReferenceEquals(rhs, null) || GetType() != rhs.GetType()) { return false; }
  457. return _url == rhs._url; // this works because URL is in canonical form
  458. }
  459. /// <summary>
  460. /// Compares two MongoUrls.
  461. /// </summary>
  462. /// <param name="obj">The other URL.</param>
  463. /// <returns>True if the two URLs are equal.</returns>
  464. public override bool Equals(object obj)
  465. {
  466. return Equals(obj as MongoUrl); // works even if obj is null or of a different type
  467. }
  468. /// <summary>
  469. /// Gets the credential.
  470. /// </summary>
  471. /// <returns>The credential (or null if the URL has not authentication settings).</returns>
  472. public MongoCredential GetCredential()
  473. {
  474. if (HasAuthenticationSettings)
  475. {
  476. return MongoCredential.FromComponents(
  477. _authenticationMechanism,
  478. _authenticationSource ?? _databaseName,
  479. _username,
  480. _password);
  481. }
  482. else
  483. {
  484. return null;
  485. }
  486. }
  487. /// <summary>
  488. /// Gets the hash code.
  489. /// </summary>
  490. /// <returns>The hash code.</returns>
  491. public override int GetHashCode()
  492. {
  493. return _url.GetHashCode(); // this works because URL is in canonical form
  494. }
  495. /// <summary>
  496. /// Returns a WriteConcern value based on this instance's settings and a default enabled value.
  497. /// </summary>
  498. /// <param name="enabledDefault">The default enabled value.</param>
  499. /// <returns>A WriteConcern.</returns>
  500. public WriteConcern GetWriteConcern(bool enabledDefault)
  501. {
  502. if (_w == null && !_wTimeout.HasValue && !_fsync.HasValue && !_journal.HasValue)
  503. {
  504. return enabledDefault ? WriteConcern.Acknowledged : WriteConcern.Unacknowledged;
  505. }
  506. return new WriteConcern(_w, _wTimeout, _fsync, _journal);
  507. }
  508. /// <summary>
  509. /// Returns the canonical URL based on the settings in this MongoUrlBuilder.
  510. /// </summary>
  511. /// <returns>The canonical URL.</returns>
  512. public override string ToString()
  513. {
  514. return _url;
  515. }
  516. // private methods
  517. private bool AnyWriteConcernSettingsAreSet()
  518. {
  519. return _fsync != null || _journal != null || _w != null || _wTimeout != null;
  520. }
  521. }
  522. }