common.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. # Copyright 2011-present MongoDB, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you
  4. # may not use this file except in compliance with the License. You
  5. # 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
  12. # implied. See the License for the specific language governing
  13. # permissions and limitations under the License.
  14. """Functions and classes common to multiple pymongo modules."""
  15. import datetime
  16. import warnings
  17. from bson import SON
  18. from bson.binary import UuidRepresentation
  19. from bson.codec_options import CodecOptions, TypeRegistry
  20. from bson.py3compat import abc, integer_types, iteritems, string_type, PY3
  21. from bson.raw_bson import RawBSONDocument
  22. from pymongo.auth import MECHANISMS
  23. from pymongo.compression_support import (validate_compressors,
  24. validate_zlib_compression_level)
  25. from pymongo.driver_info import DriverInfo
  26. from pymongo.server_api import ServerApi
  27. from pymongo.encryption_options import validate_auto_encryption_opts_or_none
  28. from pymongo.errors import ConfigurationError
  29. from pymongo.monitoring import _validate_event_listeners
  30. from pymongo.read_concern import ReadConcern
  31. from pymongo.read_preferences import _MONGOS_MODES, _ServerMode
  32. from pymongo.ssl_support import (validate_cert_reqs,
  33. validate_allow_invalid_certs)
  34. from pymongo.write_concern import DEFAULT_WRITE_CONCERN, WriteConcern
  35. try:
  36. from collections import OrderedDict
  37. ORDERED_TYPES = (SON, OrderedDict)
  38. except ImportError:
  39. ORDERED_TYPES = (SON,)
  40. if PY3:
  41. from urllib.parse import unquote_plus
  42. else:
  43. from urllib import unquote_plus
  44. # Defaults until we connect to a server and get updated limits.
  45. MAX_BSON_SIZE = 16 * (1024 ** 2)
  46. MAX_MESSAGE_SIZE = 2 * MAX_BSON_SIZE
  47. MIN_WIRE_VERSION = 0
  48. MAX_WIRE_VERSION = 0
  49. MAX_WRITE_BATCH_SIZE = 1000
  50. # What this version of PyMongo supports.
  51. MIN_SUPPORTED_SERVER_VERSION = "2.6"
  52. MIN_SUPPORTED_WIRE_VERSION = 2
  53. MAX_SUPPORTED_WIRE_VERSION = 13
  54. # Frequency to call hello on servers, in seconds.
  55. HEARTBEAT_FREQUENCY = 10
  56. # Frequency to process kill-cursors, in seconds. See MongoClient.close_cursor.
  57. KILL_CURSOR_FREQUENCY = 1
  58. # Frequency to process events queue, in seconds.
  59. EVENTS_QUEUE_FREQUENCY = 1
  60. # How long to wait, in seconds, for a suitable server to be found before
  61. # aborting an operation. For example, if the client attempts an insert
  62. # during a replica set election, SERVER_SELECTION_TIMEOUT governs the
  63. # longest it is willing to wait for a new primary to be found.
  64. SERVER_SELECTION_TIMEOUT = 30
  65. # Spec requires at least 500ms between hello calls.
  66. MIN_HEARTBEAT_INTERVAL = 0.5
  67. # Spec requires at least 60s between SRV rescans.
  68. MIN_SRV_RESCAN_INTERVAL = 60
  69. # Default connectTimeout in seconds.
  70. CONNECT_TIMEOUT = 20.0
  71. # Default value for maxPoolSize.
  72. MAX_POOL_SIZE = 100
  73. # Default value for minPoolSize.
  74. MIN_POOL_SIZE = 0
  75. # Default value for maxIdleTimeMS.
  76. MAX_IDLE_TIME_MS = None
  77. # Default value for maxIdleTimeMS in seconds.
  78. MAX_IDLE_TIME_SEC = None
  79. # Default value for waitQueueTimeoutMS in seconds.
  80. WAIT_QUEUE_TIMEOUT = None
  81. # Default value for localThresholdMS.
  82. LOCAL_THRESHOLD_MS = 15
  83. # Default value for retryWrites.
  84. RETRY_WRITES = True
  85. # Default value for retryReads.
  86. RETRY_READS = True
  87. # mongod/s 2.6 and above return code 59 when a command doesn't exist.
  88. COMMAND_NOT_FOUND_CODES = (59,)
  89. # Error codes to ignore if GridFS calls createIndex on a secondary
  90. UNAUTHORIZED_CODES = (13, 16547, 16548)
  91. # Maximum number of sessions to send in a single endSessions command.
  92. # From the driver sessions spec.
  93. _MAX_END_SESSIONS = 10000
  94. def partition_node(node):
  95. """Split a host:port string into (host, int(port)) pair."""
  96. host = node
  97. port = 27017
  98. idx = node.rfind(':')
  99. if idx != -1:
  100. host, port = node[:idx], int(node[idx + 1:])
  101. if host.startswith('['):
  102. host = host[1:-1]
  103. return host, port
  104. def clean_node(node):
  105. """Split and normalize a node name from a hello response."""
  106. host, port = partition_node(node)
  107. # Normalize hostname to lowercase, since DNS is case-insensitive:
  108. # http://tools.ietf.org/html/rfc4343
  109. # This prevents useless rediscovery if "foo.com" is in the seed list but
  110. # "FOO.com" is in the hello response.
  111. return host.lower(), port
  112. def raise_config_error(key, dummy):
  113. """Raise ConfigurationError with the given key name."""
  114. raise ConfigurationError("Unknown option %s" % (key,))
  115. # Mapping of URI uuid representation options to valid subtypes.
  116. _UUID_REPRESENTATIONS = {
  117. 'unspecified': UuidRepresentation.UNSPECIFIED,
  118. 'standard': UuidRepresentation.STANDARD,
  119. 'pythonLegacy': UuidRepresentation.PYTHON_LEGACY,
  120. 'javaLegacy': UuidRepresentation.JAVA_LEGACY,
  121. 'csharpLegacy': UuidRepresentation.CSHARP_LEGACY
  122. }
  123. def validate_boolean(option, value):
  124. """Validates that 'value' is True or False."""
  125. if isinstance(value, bool):
  126. return value
  127. raise TypeError("%s must be True or False" % (option,))
  128. def validate_boolean_or_string(option, value):
  129. """Validates that value is True, False, 'true', or 'false'."""
  130. if isinstance(value, string_type):
  131. if value not in ('true', 'false'):
  132. raise ValueError("The value of %s must be "
  133. "'true' or 'false'" % (option,))
  134. return value == 'true'
  135. return validate_boolean(option, value)
  136. def validate_integer(option, value):
  137. """Validates that 'value' is an integer (or basestring representation).
  138. """
  139. if isinstance(value, integer_types):
  140. return value
  141. elif isinstance(value, string_type):
  142. try:
  143. return int(value)
  144. except ValueError:
  145. raise ValueError("The value of %s must be "
  146. "an integer" % (option,))
  147. raise TypeError("Wrong type for %s, value must be an integer" % (option,))
  148. def validate_positive_integer(option, value):
  149. """Validate that 'value' is a positive integer, which does not include 0.
  150. """
  151. val = validate_integer(option, value)
  152. if val <= 0:
  153. raise ValueError("The value of %s must be "
  154. "a positive integer" % (option,))
  155. return val
  156. def validate_non_negative_integer(option, value):
  157. """Validate that 'value' is a positive integer or 0.
  158. """
  159. val = validate_integer(option, value)
  160. if val < 0:
  161. raise ValueError("The value of %s must be "
  162. "a non negative integer" % (option,))
  163. return val
  164. def validate_readable(option, value):
  165. """Validates that 'value' is file-like and readable.
  166. """
  167. if value is None:
  168. return value
  169. # First make sure its a string py3.3 open(True, 'r') succeeds
  170. # Used in ssl cert checking due to poor ssl module error reporting
  171. value = validate_string(option, value)
  172. open(value, 'r').close()
  173. return value
  174. def validate_positive_integer_or_none(option, value):
  175. """Validate that 'value' is a positive integer or None.
  176. """
  177. if value is None:
  178. return value
  179. return validate_positive_integer(option, value)
  180. def validate_non_negative_integer_or_none(option, value):
  181. """Validate that 'value' is a positive integer or 0 or None.
  182. """
  183. if value is None:
  184. return value
  185. return validate_non_negative_integer(option, value)
  186. def validate_string(option, value):
  187. """Validates that 'value' is an instance of `basestring` for Python 2
  188. or `str` for Python 3.
  189. """
  190. if isinstance(value, string_type):
  191. return value
  192. raise TypeError("Wrong type for %s, value must be "
  193. "an instance of %s" % (option, string_type.__name__))
  194. def validate_string_or_none(option, value):
  195. """Validates that 'value' is an instance of `basestring` or `None`.
  196. """
  197. if value is None:
  198. return value
  199. return validate_string(option, value)
  200. def validate_int_or_basestring(option, value):
  201. """Validates that 'value' is an integer or string.
  202. """
  203. if isinstance(value, integer_types):
  204. return value
  205. elif isinstance(value, string_type):
  206. try:
  207. return int(value)
  208. except ValueError:
  209. return value
  210. raise TypeError("Wrong type for %s, value must be an "
  211. "integer or a string" % (option,))
  212. def validate_non_negative_int_or_basestring(option, value):
  213. """Validates that 'value' is an integer or string.
  214. """
  215. if isinstance(value, integer_types):
  216. return value
  217. elif isinstance(value, string_type):
  218. try:
  219. val = int(value)
  220. except ValueError:
  221. return value
  222. return validate_non_negative_integer(option, val)
  223. raise TypeError("Wrong type for %s, value must be an "
  224. "non negative integer or a string" % (option,))
  225. def validate_positive_float(option, value):
  226. """Validates that 'value' is a float, or can be converted to one, and is
  227. positive.
  228. """
  229. errmsg = "%s must be an integer or float" % (option,)
  230. try:
  231. value = float(value)
  232. except ValueError:
  233. raise ValueError(errmsg)
  234. except TypeError:
  235. raise TypeError(errmsg)
  236. # float('inf') doesn't work in 2.4 or 2.5 on Windows, so just cap floats at
  237. # one billion - this is a reasonable approximation for infinity
  238. if not 0 < value < 1e9:
  239. raise ValueError("%s must be greater than 0 and "
  240. "less than one billion" % (option,))
  241. return value
  242. def validate_positive_float_or_zero(option, value):
  243. """Validates that 'value' is 0 or a positive float, or can be converted to
  244. 0 or a positive float.
  245. """
  246. if value == 0 or value == "0":
  247. return 0
  248. return validate_positive_float(option, value)
  249. def validate_timeout_or_none(option, value):
  250. """Validates a timeout specified in milliseconds returning
  251. a value in floating point seconds.
  252. """
  253. if value is None:
  254. return value
  255. return validate_positive_float(option, value) / 1000.0
  256. def validate_timeout_or_zero(option, value):
  257. """Validates a timeout specified in milliseconds returning
  258. a value in floating point seconds for the case where None is an error
  259. and 0 is valid. Setting the timeout to nothing in the URI string is a
  260. config error.
  261. """
  262. if value is None:
  263. raise ConfigurationError("%s cannot be None" % (option, ))
  264. if value == 0 or value == "0":
  265. return 0
  266. return validate_positive_float(option, value) / 1000.0
  267. def validate_timeout_or_none_or_zero(option, value):
  268. """Validates a timeout specified in milliseconds returning
  269. a value in floating point seconds. value=0 and value="0" are treated the
  270. same as value=None which means unlimited timeout.
  271. """
  272. if value is None or value == 0 or value == "0":
  273. return None
  274. return validate_positive_float(option, value) / 1000.0
  275. def validate_max_staleness(option, value):
  276. """Validates maxStalenessSeconds according to the Max Staleness Spec."""
  277. if value == -1 or value == "-1":
  278. # Default: No maximum staleness.
  279. return -1
  280. return validate_positive_integer(option, value)
  281. def validate_read_preference(dummy, value):
  282. """Validate a read preference.
  283. """
  284. if not isinstance(value, _ServerMode):
  285. raise TypeError("%r is not a read preference." % (value,))
  286. return value
  287. def validate_read_preference_mode(dummy, value):
  288. """Validate read preference mode for a MongoReplicaSetClient.
  289. .. versionchanged:: 3.5
  290. Returns the original ``value`` instead of the validated read preference
  291. mode.
  292. """
  293. if value not in _MONGOS_MODES:
  294. raise ValueError("%s is not a valid read preference" % (value,))
  295. return value
  296. def validate_auth_mechanism(option, value):
  297. """Validate the authMechanism URI option.
  298. """
  299. # CRAM-MD5 is for server testing only. Undocumented,
  300. # unsupported, may be removed at any time. You have
  301. # been warned.
  302. if value not in MECHANISMS and value != 'CRAM-MD5':
  303. raise ValueError("%s must be in %s" % (option, tuple(MECHANISMS)))
  304. return value
  305. def validate_uuid_representation(dummy, value):
  306. """Validate the uuid representation option selected in the URI.
  307. """
  308. try:
  309. return _UUID_REPRESENTATIONS[value]
  310. except KeyError:
  311. raise ValueError("%s is an invalid UUID representation. "
  312. "Must be one of "
  313. "%s" % (value, tuple(_UUID_REPRESENTATIONS)))
  314. def validate_read_preference_tags(name, value):
  315. """Parse readPreferenceTags if passed as a client kwarg.
  316. """
  317. if not isinstance(value, list):
  318. value = [value]
  319. tag_sets = []
  320. for tag_set in value:
  321. if tag_set == '':
  322. tag_sets.append({})
  323. continue
  324. try:
  325. tags = {}
  326. for tag in tag_set.split(","):
  327. key, val = tag.split(":")
  328. tags[unquote_plus(key)] = unquote_plus(val)
  329. tag_sets.append(tags)
  330. except Exception:
  331. raise ValueError("%r not a valid "
  332. "value for %s" % (tag_set, name))
  333. return tag_sets
  334. _MECHANISM_PROPS = frozenset(['SERVICE_NAME',
  335. 'CANONICALIZE_HOST_NAME',
  336. 'SERVICE_REALM',
  337. 'AWS_SESSION_TOKEN'])
  338. def validate_auth_mechanism_properties(option, value):
  339. """Validate authMechanismProperties."""
  340. value = validate_string(option, value)
  341. props = {}
  342. for opt in value.split(','):
  343. try:
  344. key, val = opt.split(':')
  345. except ValueError:
  346. # Try not to leak the token.
  347. if 'AWS_SESSION_TOKEN' in opt:
  348. opt = ('AWS_SESSION_TOKEN:<redacted token>, did you forget '
  349. 'to percent-escape the token with quote_plus?')
  350. raise ValueError("auth mechanism properties must be "
  351. "key:value pairs like SERVICE_NAME:"
  352. "mongodb, not %s." % (opt,))
  353. if key not in _MECHANISM_PROPS:
  354. raise ValueError("%s is not a supported auth "
  355. "mechanism property. Must be one of "
  356. "%s." % (key, tuple(_MECHANISM_PROPS)))
  357. if key == 'CANONICALIZE_HOST_NAME':
  358. props[key] = validate_boolean_or_string(key, val)
  359. else:
  360. props[key] = unquote_plus(val)
  361. return props
  362. def validate_document_class(option, value):
  363. """Validate the document_class option."""
  364. if not issubclass(value, (abc.MutableMapping, RawBSONDocument)):
  365. raise TypeError("%s must be dict, bson.son.SON, "
  366. "bson.raw_bson.RawBSONDocument, or a "
  367. "sublass of collections.MutableMapping" % (option,))
  368. return value
  369. def validate_type_registry(option, value):
  370. """Validate the type_registry option."""
  371. if value is not None and not isinstance(value, TypeRegistry):
  372. raise TypeError("%s must be an instance of %s" % (
  373. option, TypeRegistry))
  374. return value
  375. def validate_list(option, value):
  376. """Validates that 'value' is a list."""
  377. if not isinstance(value, list):
  378. raise TypeError("%s must be a list" % (option,))
  379. return value
  380. def validate_list_or_none(option, value):
  381. """Validates that 'value' is a list or None."""
  382. if value is None:
  383. return value
  384. return validate_list(option, value)
  385. def validate_list_or_mapping(option, value):
  386. """Validates that 'value' is a list or a document."""
  387. if not isinstance(value, (abc.Mapping, list)):
  388. raise TypeError("%s must either be a list or an instance of dict, "
  389. "bson.son.SON, or any other type that inherits from "
  390. "collections.Mapping" % (option,))
  391. def validate_is_mapping(option, value):
  392. """Validate the type of method arguments that expect a document."""
  393. if not isinstance(value, abc.Mapping):
  394. raise TypeError("%s must be an instance of dict, bson.son.SON, or "
  395. "any other type that inherits from "
  396. "collections.Mapping" % (option,))
  397. def validate_is_document_type(option, value):
  398. """Validate the type of method arguments that expect a MongoDB document."""
  399. if not isinstance(value, (abc.MutableMapping, RawBSONDocument)):
  400. raise TypeError("%s must be an instance of dict, bson.son.SON, "
  401. "bson.raw_bson.RawBSONDocument, or "
  402. "a type that inherits from "
  403. "collections.MutableMapping" % (option,))
  404. def validate_appname_or_none(option, value):
  405. """Validate the appname option."""
  406. if value is None:
  407. return value
  408. validate_string(option, value)
  409. # We need length in bytes, so encode utf8 first.
  410. if len(value.encode('utf-8')) > 128:
  411. raise ValueError("%s must be <= 128 bytes" % (option,))
  412. return value
  413. def validate_driver_or_none(option, value):
  414. """Validate the driver keyword arg."""
  415. if value is None:
  416. return value
  417. if not isinstance(value, DriverInfo):
  418. raise TypeError("%s must be an instance of DriverInfo" % (option,))
  419. return value
  420. def validate_server_api_or_none(option, value):
  421. """Validate the server_api keyword arg."""
  422. if value is None:
  423. return value
  424. if not isinstance(value, ServerApi):
  425. raise TypeError("%s must be an instance of ServerApi" % (option,))
  426. return value
  427. def validate_is_callable_or_none(option, value):
  428. """Validates that 'value' is a callable."""
  429. if value is None:
  430. return value
  431. if not callable(value):
  432. raise ValueError("%s must be a callable" % (option,))
  433. return value
  434. def validate_ok_for_replace(replacement):
  435. """Validate a replacement document."""
  436. validate_is_mapping("replacement", replacement)
  437. # Replacement can be {}
  438. if replacement and not isinstance(replacement, RawBSONDocument):
  439. first = next(iter(replacement))
  440. if first.startswith('$'):
  441. raise ValueError('replacement can not include $ operators')
  442. def validate_ok_for_update(update):
  443. """Validate an update document."""
  444. validate_list_or_mapping("update", update)
  445. # Update cannot be {}.
  446. if not update:
  447. raise ValueError('update cannot be empty')
  448. is_document = not isinstance(update, list)
  449. first = next(iter(update))
  450. if is_document and not first.startswith('$'):
  451. raise ValueError('update only works with $ operators')
  452. _UNICODE_DECODE_ERROR_HANDLERS = frozenset(['strict', 'replace', 'ignore'])
  453. def validate_unicode_decode_error_handler(dummy, value):
  454. """Validate the Unicode decode error handler option of CodecOptions.
  455. """
  456. if value not in _UNICODE_DECODE_ERROR_HANDLERS:
  457. raise ValueError("%s is an invalid Unicode decode error handler. "
  458. "Must be one of "
  459. "%s" % (value, tuple(_UNICODE_DECODE_ERROR_HANDLERS)))
  460. return value
  461. def validate_tzinfo(dummy, value):
  462. """Validate the tzinfo option
  463. """
  464. if value is not None and not isinstance(value, datetime.tzinfo):
  465. raise TypeError("%s must be an instance of datetime.tzinfo" % value)
  466. return value
  467. # Dictionary where keys are the names of public URI options, and values
  468. # are lists of aliases for that option. Aliases of option names are assumed
  469. # to have been deprecated.
  470. URI_OPTIONS_ALIAS_MAP = {
  471. 'journal': ['j'],
  472. 'wtimeoutms': ['wtimeout'],
  473. 'tls': ['ssl'],
  474. 'tlsallowinvalidcertificates': ['ssl_cert_reqs'],
  475. 'tlsallowinvalidhostnames': ['ssl_match_hostname'],
  476. 'tlscrlfile': ['ssl_crlfile'],
  477. 'tlscafile': ['ssl_ca_certs'],
  478. 'tlscertificatekeyfile': ['ssl_certfile'],
  479. 'tlscertificatekeyfilepassword': ['ssl_pem_passphrase'],
  480. }
  481. # Dictionary where keys are the names of URI options, and values
  482. # are functions that validate user-input values for that option. If an option
  483. # alias uses a different validator than its public counterpart, it should be
  484. # included here as a key, value pair.
  485. URI_OPTIONS_VALIDATOR_MAP = {
  486. 'appname': validate_appname_or_none,
  487. 'authmechanism': validate_auth_mechanism,
  488. 'authmechanismproperties': validate_auth_mechanism_properties,
  489. 'authsource': validate_string,
  490. 'compressors': validate_compressors,
  491. 'connecttimeoutms': validate_timeout_or_none_or_zero,
  492. 'directconnection': validate_boolean_or_string,
  493. 'heartbeatfrequencyms': validate_timeout_or_none,
  494. 'journal': validate_boolean_or_string,
  495. 'localthresholdms': validate_positive_float_or_zero,
  496. 'maxidletimems': validate_timeout_or_none,
  497. 'maxpoolsize': validate_positive_integer_or_none,
  498. 'maxstalenessseconds': validate_max_staleness,
  499. 'readconcernlevel': validate_string_or_none,
  500. 'readpreference': validate_read_preference_mode,
  501. 'readpreferencetags': validate_read_preference_tags,
  502. 'replicaset': validate_string_or_none,
  503. 'retryreads': validate_boolean_or_string,
  504. 'retrywrites': validate_boolean_or_string,
  505. 'loadbalanced': validate_boolean_or_string,
  506. 'serverselectiontimeoutms': validate_timeout_or_zero,
  507. 'sockettimeoutms': validate_timeout_or_none_or_zero,
  508. 'ssl_keyfile': validate_readable,
  509. 'tls': validate_boolean_or_string,
  510. 'tlsallowinvalidcertificates': validate_allow_invalid_certs,
  511. 'ssl_cert_reqs': validate_cert_reqs,
  512. 'tlsallowinvalidhostnames': lambda *x: not validate_boolean_or_string(*x),
  513. 'ssl_match_hostname': validate_boolean_or_string,
  514. 'tlscafile': validate_readable,
  515. 'tlscertificatekeyfile': validate_readable,
  516. 'tlscertificatekeyfilepassword': validate_string_or_none,
  517. 'tlsdisableocspendpointcheck': validate_boolean_or_string,
  518. 'tlsinsecure': validate_boolean_or_string,
  519. 'w': validate_non_negative_int_or_basestring,
  520. 'wtimeoutms': validate_non_negative_integer,
  521. 'zlibcompressionlevel': validate_zlib_compression_level,
  522. }
  523. # Dictionary where keys are the names of URI options specific to pymongo,
  524. # and values are functions that validate user-input values for those options.
  525. NONSPEC_OPTIONS_VALIDATOR_MAP = {
  526. 'connect': validate_boolean_or_string,
  527. 'driver': validate_driver_or_none,
  528. 'server_api': validate_server_api_or_none,
  529. 'fsync': validate_boolean_or_string,
  530. 'minpoolsize': validate_non_negative_integer,
  531. 'socketkeepalive': validate_boolean_or_string,
  532. 'tlscrlfile': validate_readable,
  533. 'tz_aware': validate_boolean_or_string,
  534. 'unicode_decode_error_handler': validate_unicode_decode_error_handler,
  535. 'uuidrepresentation': validate_uuid_representation,
  536. 'waitqueuemultiple': validate_non_negative_integer_or_none,
  537. 'waitqueuetimeoutms': validate_timeout_or_none,
  538. }
  539. # Dictionary where keys are the names of keyword-only options for the
  540. # MongoClient constructor, and values are functions that validate user-input
  541. # values for those options.
  542. KW_VALIDATORS = {
  543. 'document_class': validate_document_class,
  544. 'type_registry': validate_type_registry,
  545. 'read_preference': validate_read_preference,
  546. 'event_listeners': _validate_event_listeners,
  547. 'tzinfo': validate_tzinfo,
  548. 'username': validate_string_or_none,
  549. 'password': validate_string_or_none,
  550. 'server_selector': validate_is_callable_or_none,
  551. 'auto_encryption_opts': validate_auto_encryption_opts_or_none,
  552. }
  553. # Dictionary where keys are any URI option name, and values are the
  554. # internally-used names of that URI option. Options with only one name
  555. # variant need not be included here. Options whose public and internal
  556. # names are the same need not be included here.
  557. INTERNAL_URI_OPTION_NAME_MAP = {
  558. 'j': 'journal',
  559. 'wtimeout': 'wtimeoutms',
  560. 'tls': 'ssl',
  561. 'tlsallowinvalidcertificates': 'ssl_cert_reqs',
  562. 'tlsallowinvalidhostnames': 'ssl_match_hostname',
  563. 'tlscrlfile': 'ssl_crlfile',
  564. 'tlscafile': 'ssl_ca_certs',
  565. 'tlscertificatekeyfile': 'ssl_certfile',
  566. 'tlscertificatekeyfilepassword': 'ssl_pem_passphrase',
  567. 'tlsdisableocspendpointcheck': 'ssl_check_ocsp_endpoint',
  568. }
  569. # Map from deprecated URI option names to a tuple indicating the method of
  570. # their deprecation and any additional information that may be needed to
  571. # construct the warning message.
  572. URI_OPTIONS_DEPRECATION_MAP = {
  573. # format: <deprecated option name>: (<mode>, <message>),
  574. # Supported <mode> values:
  575. # - 'renamed': <message> should be the new option name. Note that case is
  576. # preserved for renamed options as they are part of user warnings.
  577. # - 'removed': <message> may suggest the rationale for deprecating the
  578. # option and/or recommend remedial action.
  579. 'j': ('renamed', 'journal'),
  580. 'wtimeout': ('renamed', 'wTimeoutMS'),
  581. 'ssl_cert_reqs': ('renamed', 'tlsAllowInvalidCertificates'),
  582. 'ssl_match_hostname': ('renamed', 'tlsAllowInvalidHostnames'),
  583. 'ssl_crlfile': ('renamed', 'tlsCRLFile'),
  584. 'ssl_ca_certs': ('renamed', 'tlsCAFile'),
  585. 'ssl_certfile': ('removed', (
  586. 'Instead of using ssl_certfile to specify the certificate file, '
  587. 'use tlsCertificateKeyFile to pass a single file containing both '
  588. 'the client certificate and the private key')),
  589. 'ssl_keyfile': ('removed', (
  590. 'Instead of using ssl_keyfile to specify the private keyfile, '
  591. 'use tlsCertificateKeyFile to pass a single file containing both '
  592. 'the client certificate and the private key')),
  593. 'ssl_pem_passphrase': ('renamed', 'tlsCertificateKeyFilePassword'),
  594. 'waitqueuemultiple': ('removed', (
  595. 'Instead of using waitQueueMultiple to bound queuing, limit the size '
  596. 'of the thread pool in your application server'))
  597. }
  598. # Augment the option validator map with pymongo-specific option information.
  599. URI_OPTIONS_VALIDATOR_MAP.update(NONSPEC_OPTIONS_VALIDATOR_MAP)
  600. for optname, aliases in iteritems(URI_OPTIONS_ALIAS_MAP):
  601. for alias in aliases:
  602. if alias not in URI_OPTIONS_VALIDATOR_MAP:
  603. URI_OPTIONS_VALIDATOR_MAP[alias] = (
  604. URI_OPTIONS_VALIDATOR_MAP[optname])
  605. # Map containing all URI option and keyword argument validators.
  606. VALIDATORS = URI_OPTIONS_VALIDATOR_MAP.copy()
  607. VALIDATORS.update(KW_VALIDATORS)
  608. # List of timeout-related options.
  609. TIMEOUT_OPTIONS = [
  610. 'connecttimeoutms',
  611. 'heartbeatfrequencyms',
  612. 'maxidletimems',
  613. 'maxstalenessseconds',
  614. 'serverselectiontimeoutms',
  615. 'sockettimeoutms',
  616. 'waitqueuetimeoutms',
  617. ]
  618. _AUTH_OPTIONS = frozenset(['authmechanismproperties'])
  619. def validate_auth_option(option, value):
  620. """Validate optional authentication parameters.
  621. """
  622. lower, value = validate(option, value)
  623. if lower not in _AUTH_OPTIONS:
  624. raise ConfigurationError('Unknown '
  625. 'authentication option: %s' % (option,))
  626. return option, value
  627. def validate(option, value):
  628. """Generic validation function.
  629. """
  630. lower = option.lower()
  631. validator = VALIDATORS.get(lower, raise_config_error)
  632. value = validator(option, value)
  633. return option, value
  634. def get_validated_options(options, warn=True):
  635. """Validate each entry in options and raise a warning if it is not valid.
  636. Returns a copy of options with invalid entries removed.
  637. :Parameters:
  638. - `opts`: A dict containing MongoDB URI options.
  639. - `warn` (optional): If ``True`` then warnings will be logged and
  640. invalid options will be ignored. Otherwise, invalid options will
  641. cause errors.
  642. """
  643. if isinstance(options, _CaseInsensitiveDictionary):
  644. validated_options = _CaseInsensitiveDictionary()
  645. get_normed_key = lambda x: x
  646. get_setter_key = lambda x: options.cased_key(x)
  647. else:
  648. validated_options = {}
  649. get_normed_key = lambda x: x.lower()
  650. get_setter_key = lambda x: x
  651. for opt, value in iteritems(options):
  652. normed_key = get_normed_key(opt)
  653. try:
  654. validator = URI_OPTIONS_VALIDATOR_MAP.get(
  655. normed_key, raise_config_error)
  656. value = validator(opt, value)
  657. except (ValueError, TypeError, ConfigurationError) as exc:
  658. if warn:
  659. warnings.warn(str(exc))
  660. else:
  661. raise
  662. else:
  663. validated_options[get_setter_key(normed_key)] = value
  664. return validated_options
  665. # List of write-concern-related options.
  666. WRITE_CONCERN_OPTIONS = frozenset([
  667. 'w',
  668. 'wtimeout',
  669. 'wtimeoutms',
  670. 'fsync',
  671. 'j',
  672. 'journal'
  673. ])
  674. class BaseObject(object):
  675. """A base class that provides attributes and methods common
  676. to multiple pymongo classes.
  677. SHOULD NOT BE USED BY DEVELOPERS EXTERNAL TO MONGODB.
  678. """
  679. def __init__(self, codec_options, read_preference, write_concern,
  680. read_concern):
  681. if not isinstance(codec_options, CodecOptions):
  682. raise TypeError("codec_options must be an instance of "
  683. "bson.codec_options.CodecOptions")
  684. self.__codec_options = codec_options
  685. if not isinstance(read_preference, _ServerMode):
  686. raise TypeError("%r is not valid for read_preference. See "
  687. "pymongo.read_preferences for valid "
  688. "options." % (read_preference,))
  689. self.__read_preference = read_preference
  690. if not isinstance(write_concern, WriteConcern):
  691. raise TypeError("write_concern must be an instance of "
  692. "pymongo.write_concern.WriteConcern")
  693. self.__write_concern = write_concern
  694. if not isinstance(read_concern, ReadConcern):
  695. raise TypeError("read_concern must be an instance of "
  696. "pymongo.read_concern.ReadConcern")
  697. self.__read_concern = read_concern
  698. @property
  699. def codec_options(self):
  700. """Read only access to the :class:`~bson.codec_options.CodecOptions`
  701. of this instance.
  702. """
  703. return self.__codec_options
  704. @property
  705. def write_concern(self):
  706. """Read only access to the :class:`~pymongo.write_concern.WriteConcern`
  707. of this instance.
  708. .. versionchanged:: 3.0
  709. The :attr:`write_concern` attribute is now read only.
  710. """
  711. return self.__write_concern
  712. def _write_concern_for(self, session):
  713. """Read only access to the write concern of this instance or session.
  714. """
  715. # Override this operation's write concern with the transaction's.
  716. if session and session.in_transaction:
  717. return DEFAULT_WRITE_CONCERN
  718. return self.write_concern
  719. @property
  720. def read_preference(self):
  721. """Read only access to the read preference of this instance.
  722. .. versionchanged:: 3.0
  723. The :attr:`read_preference` attribute is now read only.
  724. """
  725. return self.__read_preference
  726. def _read_preference_for(self, session):
  727. """Read only access to the read preference of this instance or session.
  728. """
  729. # Override this operation's read preference with the transaction's.
  730. if session:
  731. return session._txn_read_preference() or self.__read_preference
  732. return self.__read_preference
  733. @property
  734. def read_concern(self):
  735. """Read only access to the :class:`~pymongo.read_concern.ReadConcern`
  736. of this instance.
  737. .. versionadded:: 3.2
  738. """
  739. return self.__read_concern
  740. class _CaseInsensitiveDictionary(abc.MutableMapping):
  741. def __init__(self, *args, **kwargs):
  742. self.__casedkeys = {}
  743. self.__data = {}
  744. self.update(dict(*args, **kwargs))
  745. def __contains__(self, key):
  746. return key.lower() in self.__data
  747. def __len__(self):
  748. return len(self.__data)
  749. def __iter__(self):
  750. return (key for key in self.__casedkeys)
  751. def __repr__(self):
  752. return str({self.__casedkeys[k]: self.__data[k] for k in self})
  753. def __setitem__(self, key, value):
  754. lc_key = key.lower()
  755. self.__casedkeys[lc_key] = key
  756. self.__data[lc_key] = value
  757. def __getitem__(self, key):
  758. return self.__data[key.lower()]
  759. def __delitem__(self, key):
  760. lc_key = key.lower()
  761. del self.__casedkeys[lc_key]
  762. del self.__data[lc_key]
  763. def __eq__(self, other):
  764. if not isinstance(other, abc.Mapping):
  765. return NotImplemented
  766. if len(self) != len(other):
  767. return False
  768. for key in other:
  769. if self[key] != other[key]:
  770. return False
  771. return True
  772. def get(self, key, default=None):
  773. return self.__data.get(key.lower(), default)
  774. def pop(self, key, *args, **kwargs):
  775. lc_key = key.lower()
  776. self.__casedkeys.pop(lc_key, None)
  777. return self.__data.pop(lc_key, *args, **kwargs)
  778. def popitem(self):
  779. lc_key, cased_key = self.__casedkeys.popitem()
  780. value = self.__data.pop(lc_key)
  781. return cased_key, value
  782. def clear(self):
  783. self.__casedkeys.clear()
  784. self.__data.clear()
  785. def setdefault(self, key, default=None):
  786. lc_key = key.lower()
  787. if key in self:
  788. return self.__data[lc_key]
  789. else:
  790. self.__casedkeys[lc_key] = key
  791. self.__data[lc_key] = default
  792. return default
  793. def update(self, other):
  794. if isinstance(other, _CaseInsensitiveDictionary):
  795. for key in other:
  796. self[other.cased_key(key)] = other[key]
  797. else:
  798. for key in other:
  799. self[key] = other[key]
  800. def cased_key(self, key):
  801. return self.__casedkeys[key.lower()]