def __init__(self, host=None, port=None, max_pool_size=10, document_class=dict, tz_aware=False, _connect=True, **kwargs): """Create a new connection to a single MongoDB instance at *host:port*. The resultant client object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, :class:`~pymongo.errors.ConnectionFailure` is raised. If auto-reconnection will be performed, :class:`~pymongo.errors.AutoReconnect` will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. Raises :class:`TypeError` if port is not an instance of ``int``. Raises :class:`~pymongo.errors.ConnectionFailure` if the connection cannot be made. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ':', '/', '+' and '@' must be escaped following RFC 2396. :Parameters: - `host` (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost) - `port` (optional): port number on which to connect - `max_pool_size` (optional): The maximum number of idle connections to keep open in the pool for future use - `document_class` (optional): default class to use for documents returned from queries on this client - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`MongoClient` will be timezone aware (otherwise they will be naive) | **Other optional parameters can be passed as keyword arguments:** - `socketTimeoutMS`: (integer) How long (in milliseconds) a send or receive on a socket can take before timing out. - `connectTimeoutMS`: (integer) How long (in milliseconds) a connection can take to be opened before timing out. - `auto_start_request`: If ``True``, each thread that accesses this :class:`MongoClient` has a socket allocated to it for the thread's lifetime. This ensures consistent reads, even if you read after an unacknowledged write. Defaults to ``False`` - `use_greenlets`: If ``True``, :meth:`start_request()` will ensure that the current greenlet uses the same socket for all operations until :meth:`end_request()` | **Write Concern options:** - `w`: (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. `w=<int>` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). Passing w=0 **disables write acknowledgement** and all other write concern options. - `wtimeout`: (integer) Used in conjunction with `w`. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised. - `j`: If ``True`` block until write operations have been committed to the journal. Ignored if the server is running without journaling. - `fsync`: If ``True`` force the database to fsync all files before returning. When used with `j` the server awaits the next group commit before returning. | **Replica set keyword arguments for connecting with a replica set - either directly or via a mongos:** | (ignored by standalone mongod instances) - `replicaSet`: (string) The name of the replica set to connect to. The driver will verify that the replica set it connects to matches this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. *Ignored by mongos*. - `read_preference`: The read preference for this client. If connecting to a secondary then a read preference mode *other* than PRIMARY is required - otherwise all queries will throw :class:`~pymongo.errors.AutoReconnect` "not master". See :class:`~pymongo.read_preferences.ReadPreference` for all available read preference options. - `tag_sets`: Ignored unless connecting to a replica set via mongos. Specify a priority-order for tag sets, provide a list of tag sets: ``[{'dc': 'ny'}, {'dc': 'la'}, {}]``. A final, empty tag set, ``{}``, means "read from any member that matches the mode, ignoring tags. | **SSL configuration:** - `ssl`: If ``True``, create the connection to the server using SSL. - `ssl_keyfile`: The private keyfile used to identify the local connection against mongod. If included with the ``certfile` then only the ``ssl_certfile`` is needed. Implies ``ssl=True``. - `ssl_certfile`: The certificate file used to identify the local connection against mongod. Implies ``ssl=True``. - `ssl_cert_reqs`: Specifies whether a certificate is required from the other side of the connection, and whether it will be validated if provided. It must be one of the three values ``ssl.CERT_NONE`` (certificates ignored), ``ssl.CERT_OPTIONAL`` (not required, but validated if provided), or ``ssl.CERT_REQUIRED`` (required and validated). If the value of this parameter is not ``ssl.CERT_NONE``, then the ``ssl_ca_certs`` parameter must point to a file of CA certificates. Implies ``ssl=True``. - `ssl_ca_certs`: The ca_certs file contains a set of concatenated "certification authority" certificates, which are used to validate certificates passed from the other end of the connection. Implies ``ssl=True``. .. seealso:: :meth:`end_request` .. mongodoc:: connections .. versionchanged:: 2.5 Added addtional ssl options .. versionadded:: 2.4 """ if host is None: host = self.HOST if isinstance(host, basestring): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") seeds = set() username = None password = None db_name = None opts = {} for entity in host: if "://" in entity: if entity.startswith("mongodb://"): res = uri_parser.parse_uri(entity, port) seeds.update(res["nodelist"]) username = res["username"] or username password = res["password"] or password db_name = res["database"] or db_name opts = res["options"] else: idx = entity.find("://") raise InvalidURI("Invalid URI scheme: " "%s" % (entity[:idx], )) else: seeds.update(uri_parser.split_hosts(entity, port)) if not seeds: raise ConfigurationError("need to specify at least one host") self.__nodes = seeds self.__host = None self.__port = None self.__is_primary = False self.__is_mongos = False # _pool_class option is for deep customization of PyMongo, e.g. Motor. # SHOULD NOT BE USED BY DEVELOPERS EXTERNAL TO 10GEN. pool_class = kwargs.pop('_pool_class', pool.Pool) options = {} for option, value in kwargs.iteritems(): option, value = common.validate(option, value) options[option] = value options.update(opts) self.__max_pool_size = common.validate_positive_integer( 'max_pool_size', max_pool_size) self.__cursor_manager = CursorManager(self) self.__repl = options.get('replicaset') if len(seeds) == 1 and not self.__repl: self.__direct = True else: self.__direct = False self.__nodes = set() self.__net_timeout = options.get('sockettimeoutms') self.__conn_timeout = options.get('connecttimeoutms') self.__use_ssl = options.get('ssl', None) self.__ssl_keyfile = options.get('ssl_keyfile', None) self.__ssl_certfile = options.get('ssl_certfile', None) self.__ssl_cert_reqs = options.get('ssl_cert_reqs', None) self.__ssl_ca_certs = options.get('ssl_ca_certs', None) ssl_kwarg_keys = [k for k in kwargs.keys() if k.startswith('ssl_')] if self.__use_ssl == False and ssl_kwarg_keys: raise ConfigurationError("ssl has not been enabled but the " "following ssl parameters have been set: " "%s. Please set `ssl=True` or remove." % ', '.join(ssl_kwarg_keys)) if self.__ssl_cert_reqs and not self.__ssl_ca_certs: raise ConfigurationError("If `ssl_cert_reqs` is not " "`ssl.CERT_NONE` then you must " "include `ssl_ca_certs` to be able " "to validate the server.") if ssl_kwarg_keys and self.__use_ssl is None: # ssl options imply ssl = True self.__use_ssl = True if self.__use_ssl and not HAS_SSL: raise ConfigurationError("The ssl module is not available. If you " "are using a python version previous to " "2.6 you must install the ssl package " "from PyPI.") self.__use_greenlets = options.get('use_greenlets', False) self.__pool = pool_class(None, self.__max_pool_size, self.__net_timeout, self.__conn_timeout, self.__use_ssl, use_greenlets=self.__use_greenlets, ssl_keyfile=self.__ssl_keyfile, ssl_certfile=self.__ssl_certfile, ssl_cert_reqs=self.__ssl_cert_reqs, ssl_ca_certs=self.__ssl_ca_certs) self.__document_class = document_class self.__tz_aware = common.validate_boolean('tz_aware', tz_aware) self.__auto_start_request = options.get('auto_start_request', False) # cache of existing indexes used by ensure_index ops self.__index_cache = {} self.__auth_credentials = {} super(MongoClient, self).__init__(**options) if self.slave_okay: warnings.warn( "slave_okay is deprecated. Please " "use read_preference instead.", DeprecationWarning, stacklevel=2) if _connect: try: self.__find_node(seeds) except AutoReconnect, e: # ConnectionFailure makes more sense here than AutoReconnect raise ConnectionFailure(str(e))
class MongoClient(common.BaseObject): HOST = "localhost" PORT = 27017 # Define order to retrieve options from ClientOptions for __repr__. # No host/port; these are retrieved from TopologySettings. _constructor_args = ('document_class', 'tz_aware', 'connect') def __init__(self, host=None, port=None, document_class=dict, tz_aware=False, connect=True, **kwargs): """Client for a MongoDB instance, a replica set, or a set of mongoses. The client object is thread-safe and has connection-pooling built in. If an operation fails because of a network error, :class:`~pymongo.errors.ConnectionFailure` is raised and the client reconnects in the background. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ':', '/', '+' and '@' must be escaped following RFC 2396. .. warning:: When using PyMongo in a multiprocessing context, please read :ref:`multiprocessing` first. :Parameters: - `host` (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost) - `port` (optional): port number on which to connect - `document_class` (optional): default class to use for documents returned from queries on this client - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`MongoClient` will be timezone aware (otherwise they will be naive) - `connect` (optional): if ``True`` (the default), immediately begin connecting to MongoDB in the background. Otherwise connect on the first operation. | **Other optional parameters can be passed as keyword arguments:** - `maxPoolSize` (optional): The maximum number of connections that the pool will open simultaneously. If this is set, operations will block if there are `maxPoolSize` outstanding connections from the pool. Defaults to 100. Cannot be 0. - `socketTimeoutMS`: (integer or None) Controls how long (in milliseconds) the driver will wait for a response after sending an ordinary (non-monitoring) database operation before concluding that a network error has occurred. Defaults to ``None`` (no timeout). - `connectTimeoutMS`: (integer or None) Controls how long (in milliseconds) the driver will wait during server monitoring when connecting a new socket to a server before concluding the server is unavailable. Defaults to ``20000`` (20 seconds). - `serverSelectionTimeoutMS`: (integer) Controls how long (in milliseconds) the driver will wait to find an available, appropriate server to carry out a database operation; while it is waiting, multiple server monitoring operations may be carried out, each controlled by `connectTimeoutMS`. Defaults to ``30000`` (30 seconds). - `waitQueueTimeoutMS`: (integer or None) How long (in milliseconds) a thread will wait for a socket from the pool if the pool has no free sockets. Defaults to ``None`` (no timeout). - `waitQueueMultiple`: (integer or None) Multiplied by maxPoolSize to give the number of threads allowed to wait for a socket at one time. Defaults to ``None`` (no limit). - `socketKeepAlive`: (boolean) Whether to send periodic keep-alive packets on connected sockets. Defaults to ``False`` (do not send keep-alive packets). | **Write Concern options:** | (Only set if passed. No default values.) - `w`: (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. `w=<int>` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). Passing w=0 **disables write acknowledgement** and all other write concern options. - `wtimeout`: (integer) Used in conjunction with `w`. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised. - `j`: If ``True`` block until write operations have been committed to the journal. Cannot be used in combination with `fsync`. Prior to MongoDB 2.6 this option was ignored if the server was running without journaling. Starting with MongoDB 2.6 write operations will fail with an exception if this option is used when the server is running without journaling. - `fsync`: If ``True`` and the server is running without journaling, blocks until the server has synced all data files to disk. If the server is running with journaling, this acts the same as the `j` option, blocking until write operations have been committed to the journal. Cannot be used in combination with `j`. | **Replica set keyword arguments for connecting with a replica set - either directly or via a mongos:** - `replicaSet`: (string or None) The name of the replica set to connect to. The driver will verify that all servers it connects to match this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. Defaults to ``None``. - `read_preference`: The read preference for this client. If connecting directly to a secondary then a read preference mode *other* than PRIMARY is required - otherwise all queries will throw :class:`~pymongo.errors.AutoReconnect` "not master". See :class:`~pymongo.read_preferences.ReadPreference` for all available read preference options. Defaults to ``PRIMARY``. | **SSL configuration:** - `ssl`: If ``True``, create the connection to the server using SSL. Defaults to ``False``. - `ssl_keyfile`: The private keyfile used to identify the local connection against mongod. If included with the ``certfile`` then only the ``ssl_certfile`` is needed. Implies ``ssl=True``. Defaults to ``None``. - `ssl_certfile`: The certificate file used to identify the local connection against mongod. Implies ``ssl=True``. Defaults to ``None``. - `ssl_cert_reqs`: Specifies whether a certificate is required from the other side of the connection, and whether it will be validated if provided. It must be one of the three values ``ssl.CERT_NONE`` (certificates ignored), ``ssl.CERT_OPTIONAL`` (not required, but validated if provided), or ``ssl.CERT_REQUIRED`` (required and validated). If the value of this parameter is not ``ssl.CERT_NONE`` and a value is not provided for ``ssl_ca_certs`` PyMongo will attempt to load system provided CA certificates. If the python version in use does not support loading system CA certificates then the ``ssl_ca_certs`` parameter must point to a file of CA certificates. Implies ``ssl=True``. Defaults to ``ssl.CERT_REQUIRED`` if not provided and ``ssl=True``. - `ssl_ca_certs`: The ca_certs file contains a set of concatenated "certification authority" certificates, which are used to validate certificates passed from the other end of the connection. Implies ``ssl=True``. Defaults to ``None``. - `ssl_match_hostname`: If ``True`` (the default), and `ssl_cert_reqs` is not ``ssl.CERT_NONE``, enables hostname verification using the :func:`~ssl.match_hostname` function from python's :mod:`~ssl` module. Think very carefully before setting this to ``False`` as that could make your application vulnerable to man-in-the-middle attacks. .. mongodoc:: connections .. versionchanged:: 3.0 :class:`~pymongo.mongo_client.MongoClient` is now the one and only client class for a standalone server, mongos, or replica set. It includes the functionality that had been split into :class:`~pymongo.mongo_client.MongoReplicaSetClient`: it can connect to a replica set, discover all its members, and monitor the set for stepdowns, elections, and reconfigs. The :class:`~pymongo.mongo_client.MongoClient` constructor no longer blocks while connecting to the server or servers, and it no longer raises :class:`~pymongo.errors.ConnectionFailure` if they are unavailable, nor :class:`~pymongo.errors.ConfigurationError` if the user's credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads. Therefore the ``alive`` method is removed since it no longer provides meaningful information; even if the client is disconnected, it may discover a server in time to fulfill the next operation. In PyMongo 2.x, :class:`~pymongo.MongoClient` accepted a list of standalone MongoDB servers and used the first it could connect to:: MongoClient(['host1.com:27017', 'host2.com:27017']) A list of multiple standalones is no longer supported; if multiple servers are listed they must be members of the same replica set, or mongoses in the same sharded cluster. The behavior for a list of mongoses is changed from "high availability" to "load balancing". Before, the client connected to the lowest-latency mongos in the list, and used it until a network error prompted it to re-evaluate all mongoses' latencies and reconnect to one of them. In PyMongo 3, the client monitors its network latency to all the mongoses continuously, and distributes operations evenly among those with the lowest latency. See :ref:`mongos-load-balancing` for more information. The ``connect`` option is added. The ``start_request``, ``in_request``, and ``end_request`` methods are removed, as well as the ``auto_start_request`` option. The ``copy_database`` method is removed, see the :doc:`copy_database examples </examples/copydb>` for alternatives. The :meth:`MongoClient.disconnect` method is removed; it was a synonym for :meth:`~pymongo.MongoClient.close`. :class:`~pymongo.mongo_client.MongoClient` no longer returns an instance of :class:`~pymongo.database.Database` for attribute names with leading underscores. You must use dict-style lookups instead:: client['__my_database__'] Not:: client.__my_database__ """ if host is None: host = self.HOST if isinstance(host, string_type): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") seeds = set() username = None password = None dbase = None opts = {} for entity in host: if "://" in entity: if entity.startswith("mongodb://"): res = uri_parser.parse_uri(entity, port, warn=True) seeds.update(res["nodelist"]) username = res["username"] or username password = res["password"] or password dbase = res["database"] or dbase opts = res["options"] else: idx = entity.find("://") raise InvalidURI("Invalid URI scheme: " "%s" % (entity[:idx], )) else: seeds.update(uri_parser.split_hosts(entity, port)) if not seeds: raise ConfigurationError("need to specify at least one host") # _pool_class, _monitor_class, and _condition_class are for deep # customization of PyMongo, e.g. Motor. pool_class = kwargs.pop('_pool_class', None) monitor_class = kwargs.pop('_monitor_class', None) condition_class = kwargs.pop('_condition_class', None) keyword_opts = kwargs keyword_opts['document_class'] = document_class keyword_opts['tz_aware'] = tz_aware keyword_opts['connect'] = connect # Validate all keyword options. keyword_opts = dict( common.validate(k, v) for k, v in keyword_opts.items()) opts.update(keyword_opts) self.__options = options = ClientOptions(username, password, dbase, opts) self.__default_database_name = dbase self.__lock = threading.Lock() self.__cursor_manager = CursorManager(self) self.__kill_cursors_queue = [] # Cache of existing indexes used by ensure_index ops. self.__index_cache = {} super(MongoClient, self).__init__(options.codec_options, options.read_preference, options.write_concern) self.__all_credentials = {} creds = options.credentials if creds: self._cache_credentials(creds.source, creds) self._topology_settings = TopologySettings( seeds=seeds, replica_set_name=options.replica_set_name, pool_class=pool_class, pool_options=options.pool_options, monitor_class=monitor_class, condition_class=condition_class, local_threshold_ms=options.local_threshold_ms, server_selection_timeout=options.server_selection_timeout) self._topology = Topology(self._topology_settings) if connect: self._topology.open() def target(): client = self_ref() if client is None: return False # Stop the executor. MongoClient._process_kill_cursors_queue(client) return True executor = periodic_executor.PeriodicExecutor( condition_class=self._topology_settings.condition_class, interval=common.KILL_CURSOR_FREQUENCY, min_interval=0, target=target, name="pymongo_kill_cursors_thread") # We strongly reference the executor and it weakly references us via # this closure. When the client is freed, stop the executor soon. self_ref = weakref.ref(self, executor.close) self._kill_cursors_executor = executor executor.open() def _cache_credentials(self, source, credentials, connect=False): """Save a set of authentication credentials. The credentials are used to login a socket whenever one is created. If `connect` is True, verify the credentials on the server first. """ # Don't let other threads affect this call's data. all_credentials = self.__all_credentials.copy() if source in all_credentials: # Nothing to do if we already have these credentials. if credentials == all_credentials[source]: return raise OperationFailure('Another user is already authenticated ' 'to this database. You must logout first.') if connect: server = self._get_topology().select_server( writable_preferred_server_selector) # get_socket() logs out of the database if logged in with old # credentials, and logs in with new ones. with server.get_socket(all_credentials) as sock_info: sock_info.authenticate(credentials) # If several threads run _cache_credentials at once, last one wins. self.__all_credentials[source] = credentials def _purge_credentials(self, source): """Purge credentials from the authentication cache.""" self.__all_credentials.pop(source, None) def _cached(self, dbname, coll, index): """Test if `index` is cached.""" cache = self.__index_cache now = datetime.datetime.utcnow() return (dbname in cache and coll in cache[dbname] and index in cache[dbname][coll] and now < cache[dbname][coll][index]) def _cache_index(self, dbname, collection, index, cache_for): """Add an index to the index cache for ensure_index operations.""" now = datetime.datetime.utcnow() expire = datetime.timedelta(seconds=cache_for) + now if database not in self.__index_cache: self.__index_cache[dbname] = {} self.__index_cache[dbname][collection] = {} self.__index_cache[dbname][collection][index] = expire elif collection not in self.__index_cache[dbname]: self.__index_cache[dbname][collection] = {} self.__index_cache[dbname][collection][index] = expire else: self.__index_cache[dbname][collection][index] = expire def _purge_index(self, database_name, collection_name=None, index_name=None): """Purge an index from the index cache. If `index_name` is None purge an entire collection. If `collection_name` is None purge an entire database. """ if not database_name in self.__index_cache: return if collection_name is None: del self.__index_cache[database_name] return if not collection_name in self.__index_cache[database_name]: return if index_name is None: del self.__index_cache[database_name][collection_name] return if index_name in self.__index_cache[database_name][collection_name]: del self.__index_cache[database_name][collection_name][index_name] def _server_property(self, attr_name, default=None): """An attribute of the current server's description. Returns "default" while there is no current server, primary, or mongos. Not threadsafe if used multiple times in a single method, since the server may change. In such cases, store a local reference to a ServerDescription first, then use its properties. """ try: server = self._topology.select_server(writable_server_selector, server_selection_timeout=0) return getattr(server.description, attr_name) except ConnectionFailure: return default @property def address(self): """(host, port) of the current standalone, primary, or mongos, or None. Accessing :attr:`address` raises :exc:`~.errors.InvalidOperation` if the client is load-balancing among mongoses, since there is no single address. Use :attr:`nodes` instead. .. versionadded:: 3.0 """ try: return self._topology.get_direct_or_primary() except InvalidOperation: # Only one case where Topology throws InvalidOperation. raise InvalidOperation( 'Cannot use "address" property when load balancing among' ' mongoses, use "nodes" instead.') @property def primary(self): """The (host, port) of the current primary of the replica set. Returns ``None`` if this client is not connected to a replica set, there is no primary, or this client was created without the `replicaSet` option. .. versionadded:: 3.0 MongoClient gained this property in version 3.0 when MongoReplicaSetClient's functionality was merged in. """ return self._topology.get_primary() @property def secondaries(self): """The secondary members known to this client. A sequence of (host, port) pairs. Empty if this client is not connected to a replica set, there are no visible secondaries, or this client was created without the `replicaSet` option. .. versionadded:: 3.0 MongoClient gained this property in version 3.0 when MongoReplicaSetClient's functionality was merged in. """ return self._topology.get_secondaries() @property def arbiters(self): """Arbiters in the replica set. A sequence of (host, port) pairs. Empty if this client is not connected to a replica set, there are no arbiters, or this client was created without the `replicaSet` option. """ return self._topology.get_arbiters() @property def is_primary(self): """If this client if connected to a server that can accept writes. True if the current server is a standalone, mongos, or the primary of a replica set. """ return self._server_property('is_writable', False) @property def is_mongos(self): """If this client is connected to mongos. """ return self._server_property('server_type') == SERVER_TYPE.Mongos @property def max_pool_size(self): """The maximum number of sockets the pool will open concurrently. When the pool has reached `max_pool_size`, operations block waiting for a socket to be returned to the pool. If ``waitQueueTimeoutMS`` is set, a blocked operation will raise :exc:`~pymongo.errors.ConnectionFailure` after a timeout. By default ``waitQueueTimeoutMS`` is not set. """ return self.__options.pool_options.max_pool_size @property def nodes(self): """Set of all currently connected servers. .. warning:: When connected to a replica set the value of :attr:`nodes` can change over time as :class:`MongoClient`'s view of the replica set changes. :attr:`nodes` can also be an empty set when :class:`MongoClient` is first instantiated and hasn't yet connected to any servers, or a network partition causes it to lose connection to all servers. """ description = self._topology.description return frozenset(s.address for s in description.known_servers) @property def max_bson_size(self): """The largest BSON object the connected server accepts in bytes. Defaults to 16MB if not connected to a server. """ return self._server_property('max_bson_size', common.MAX_BSON_SIZE) @property def max_message_size(self): """The largest message the connected server accepts in bytes. Defaults to 32MB if not connected to a server. """ return self._server_property('max_message_size', common.MAX_MESSAGE_SIZE) @property def max_write_batch_size(self): """The maxWriteBatchSize reported by the server. Returns a default value when connected to server versions prior to MongoDB 2.6. """ return self._server_property('max_write_batch_size', common.MAX_WRITE_BATCH_SIZE) @property def local_threshold_ms(self): """The local threshold for this instance.""" return self.__options.local_threshold_ms @property def server_selection_timeout(self): """The server selection timeout for this instance in seconds.""" return self.__options.server_selection_timeout def _is_writable(self): """Attempt to connect to a writable server, or return False. """ topology = self._get_topology() # Starts monitors if necessary. try: svr = topology.select_server(writable_server_selector) # When directly connected to a secondary, arbiter, etc., # select_server returns it, whatever the selector. Check # again if the server is writable. return svr.description.is_writable except ConnectionFailure: return False def close(self): """Disconnect from MongoDB. Close all sockets in the connection pools and stop the monitor threads. If this instance is used again it will be automatically re-opened and the threads restarted. """ self._topology.close() def set_cursor_manager(self, manager_class): """Set this client's cursor manager. Raises :class:`TypeError` if `manager_class` is not a subclass of :class:`~pymongo.cursor_manager.CursorManager`. A cursor manager handles closing cursors. Different managers can implement different policies in terms of when to actually kill a cursor that has been closed. :Parameters: - `manager_class`: cursor manager to use .. versionchanged:: 3.0 Undeprecated. """ manager = manager_class(self) if not isinstance(manager, CursorManager): raise TypeError("manager_class must be a subclass of " "CursorManager") self.__cursor_manager = manager def _get_topology(self): """Get the internal :class:`~pymongo.topology.Topology` object. If this client was created with "connect=False", calling _get_topology launches the connection process in the background. """ self._topology.open() return self._topology @contextlib.contextmanager def _get_socket(self, selector): server = self._get_topology().select_server(selector) try: with server.get_socket(self.__all_credentials) as sock_info: yield sock_info except NetworkTimeout: # The socket has been closed. Don't reset the server. # Server Discovery And Monitoring Spec: "When an application # operation fails because of any network error besides a socket # timeout...." raise except NotMasterError: # "When the client sees a "not master" error it MUST replace the # server's description with type Unknown. It MUST request an # immediate check of the server." self._reset_server_and_request_check(server.description.address) raise except ConnectionFailure: # "Client MUST replace the server's description with type Unknown # ... MUST NOT request an immediate check of the server." self.__reset_server(server.description.address) raise def _socket_for_writes(self): return self._get_socket(writable_server_selector) @contextlib.contextmanager def _socket_for_reads(self, read_preference): preference = read_preference or ReadPreference.PRIMARY # Get a socket for a server matching the read preference, and yield # sock_info, slave_ok. Server Selection Spec: "slaveOK must be sent to # mongods with topology type Single. If the server type is Mongos, # follow the rules for passing read preference to mongos, even for # topology type Single." # Thread safe: if the type is single it cannot change. topology = self._get_topology() single = topology.description.topology_type == TOPOLOGY_TYPE.Single with self._get_socket(read_preference) as sock_info: slave_ok = (single and not sock_info.is_mongos) or ( preference != ReadPreference.PRIMARY) yield sock_info, slave_ok def _send_message_with_response(self, operation, read_preference=None, exhaust=False, address=None): """Send a message to MongoDB and return a Response. :Parameters: - `operation`: a _Query or _GetMore object. - `read_preference` (optional): A ReadPreference. - `exhaust` (optional): If True, the socket used stays checked out. It is returned along with its Pool in the Response. - `address` (optional): Optional address when sending a message to a specific server, used for getMore. """ with self.__lock: # If needed, restart kill-cursors thread after a fork. self._kill_cursors_executor.open() topology = self._get_topology() if address: server = topology.select_server_by_address(address) if not server: raise AutoReconnect('server %s:%d no longer available' % address) else: selector = read_preference or writable_server_selector server = topology.select_server(selector) # A _Query's slaveOk bit is already set for queries with non-primary # read preference. If this is a direct connection to a mongod, override # and *always* set the slaveOk bit. See bullet point 2 in # server-selection.rst#topology-type-single. set_slave_ok = ( topology.description.topology_type == TOPOLOGY_TYPE.Single and server.description.server_type != SERVER_TYPE.Mongos) return self._reset_on_error(server, server.send_message_with_response, operation, set_slave_ok, self.__all_credentials, exhaust) def _reset_on_error(self, server, func, *args, **kwargs): """Execute an operation. Reset the server on network error. Returns fn()'s return value on success. On error, clears the server's pool and marks the server Unknown. Re-raises any exception thrown by fn(). """ try: return func(*args, **kwargs) except NetworkTimeout: # The socket has been closed. Don't reset the server. raise except ConnectionFailure: self.__reset_server(server.description.address) raise def __reset_server(self, address): """Clear our connection pool for a server and mark it Unknown.""" self._topology.reset_server(address) def _reset_server_and_request_check(self, address): """Clear our pool for a server, mark it Unknown, and check it soon.""" self._topology.reset_server_and_request_check(address) def __eq__(self, other): if isinstance(other, self.__class__): return self.address == other.address return NotImplemented def __ne__(self, other): return not self == other def _repr_helper(self): def option_repr(option, value): """Fix options whose __repr__ isn't usable in a constructor.""" if option == 'document_class': if value is dict: return 'document_class=dict' else: return 'document_class=%s.%s' % (value.__module__, value.__name__) if "ms" in option: return "%s='%s'" % (option, int(value * 1000)) return '%s=%r' % (option, value) # Host first... options = [ 'host=%r' % [ '%s:%d' % (host, port) for host, port in self._topology_settings.seeds ] ] # ... then everything in self._constructor_args... options.extend( option_repr(key, self.__options._options[key]) for key in self._constructor_args) # ... then everything else. options.extend( option_repr(key, self.__options._options[key]) for key in self.__options._options if key not in set(self._constructor_args)) return ', '.join(options) def __repr__(self): return ("MongoClient(%s)" % (self._repr_helper(), )) def __getattr__(self, name): """Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get """ if name.startswith('_'): raise AttributeError( "MongoClient has no attribute %r. To access the %s" " database, use client[%r]." % (name, name, name)) return self.__getitem__(name) def __getitem__(self, name): """Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get """ return database.Database(self, name) def close_cursor(self, cursor_id, address=None): """Close a single database cursor. Raises :class:`TypeError` if `cursor_id` is not an instance of ``(int, long)``. What closing the cursor actually means depends on this client's cursor manager. :Parameters: - `cursor_id`: id of cursor to close - `address` (optional): (host, port) pair of the cursor's server. If it is not provided, the client attempts to close the cursor on the primary or standalone, or a mongos server. .. versionchanged:: 3.0 Added ``address`` parameter. """ if not isinstance(cursor_id, integer_types): raise TypeError("cursor_id must be an instance of (int, long)") self.__cursor_manager.close(cursor_id, address) def kill_cursors(self, cursor_ids, address=None): """Send a kill cursors message soon with the given ids. Raises :class:`TypeError` if `cursor_ids` is not an instance of ``list``. This method may be called from a :class:`~pymongo.cursor.Cursor` destructor during garbage collection, so it isn't safe to take a lock or do network I/O. Instead, we schedule the cursor to be closed soon on a background thread. :Parameters: - `cursor_ids`: list of cursor ids to kill - `address` (optional): (host, port) pair of the cursor's server. If it is not provided, the client attempts to close the cursor on the primary or standalone, or a mongos server. .. versionchanged:: 3.0 Now accepts an `address` argument. Schedules the cursors to be closed on a background thread instead of sending the message immediately. """ if not isinstance(cursor_ids, list): raise TypeError("cursor_ids must be a list") # "Atomic", needs no lock. self.__kill_cursors_queue.append((address, cursor_ids)) # This method is run periodically by a background thread. def _process_kill_cursors_queue(self): """Process any pending kill cursors requests.""" address_to_cursor_ids = defaultdict(list) # Other threads or the GC may append to the queue concurrently. while True: try: address, cursor_ids = self.__kill_cursors_queue.pop() except IndexError: break address_to_cursor_ids[address].extend(cursor_ids) # Don't re-open topology if it's closed and there's no pending cursors. if address_to_cursor_ids: publish = monitoring.enabled() topology = self._get_topology() for address, cursor_ids in address_to_cursor_ids.items(): try: if address: # address could be a tuple or _CursorAddress, but # select_server_by_address needs (host, port). server = topology.select_server_by_address( tuple(address)) else: # Application called close_cursor() with no address. server = topology.select_server( writable_server_selector) if publish: start = datetime.datetime.now() data = message.kill_cursors(cursor_ids) if publish: duration = datetime.datetime.now() - start try: dbname, collname = address.namespace.split(".", 1) except AttributeError: dbname = collname = 'OP_KILL_CURSORS' command = SON([('killCursors', collname), ('cursors', cursor_ids)]) monitoring.publish_command_start( command, dbname, data[0], address) start = datetime.datetime.now() server.send_message(data, self.__all_credentials) if publish: duration = (datetime.datetime.now() - start) + duration # OP_KILL_CURSORS returns no reply, fake one. reply = {'cursorsUnknown': cursor_ids, 'ok': 1} monitoring.publish_command_success( duration, reply, 'killCursors', data[0], address) except ConnectionFailure as exc: warnings.warn("couldn't close cursor on %s: %s" % (address, exc)) def server_info(self): """Get information about the MongoDB server we're connected to.""" return self.admin.command("buildinfo", read_preference=ReadPreference.PRIMARY) def database_names(self): """Get a list of the names of all databases on the connected server.""" return [ db["name"] for db in self.admin.command( "listDatabases", read_preference=ReadPreference.PRIMARY) ["databases"] ] def drop_database(self, name_or_database): """Drop a database. Raises :class:`TypeError` if `name_or_database` is not an instance of :class:`basestring` (:class:`str` in python 3) or :class:`~pymongo.database.Database`. :Parameters: - `name_or_database`: the name of a database to drop, or a :class:`~pymongo.database.Database` instance representing the database to drop """ name = name_or_database if isinstance(name, database.Database): name = name.name if not isinstance(name, string_type): raise TypeError("name_or_database must be an instance " "of %s or a Database" % (string_type.__name__, )) self._purge_index(name) self[name].command("dropDatabase", read_preference=ReadPreference.PRIMARY) def get_default_database(self): """Get the database named in the MongoDB connection URI. >>> uri = 'mongodb://host/my_database' >>> client = MongoClient(uri) >>> db = client.get_default_database() >>> assert db.name == 'my_database' Useful in scripts where you want to choose which database to use based only on the URI in a configuration file. """ if self.__default_database_name is None: raise ConfigurationError('No default database defined') return self[self.__default_database_name] def get_database(self, name, codec_options=None, read_preference=None, write_concern=None): """Get a :class:`~pymongo.database.Database` with the given name and options. Useful for creating a :class:`~pymongo.database.Database` with different codec options, read preference, and/or write concern from this :class:`MongoClient`. >>> client.read_preference Primary() >>> db1 = client.test >>> db1.read_preference Primary() >>> from pymongo import ReadPreference >>> db2 = client.get_database( ... 'test', read_preference=ReadPreference.SECONDARY) >>> db2.read_preference Secondary(tag_sets=None) :Parameters: - `name`: The name of the database - a string. - `codec_options` (optional): An instance of :class:`~bson.codec_options.CodecOptions`. If ``None`` (the default) the :attr:`codec_options` of this :class:`MongoClient` is used. - `read_preference` (optional): The read preference to use. If ``None`` (the default) the :attr:`read_preference` of this :class:`MongoClient` is used. See :mod:`~pymongo.read_preferences` for options. - `write_concern` (optional): An instance of :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the default) the :attr:`write_concern` of this :class:`MongoClient` is used. """ return database.Database(self, name, codec_options, read_preference, write_concern) @property def is_locked(self): """Is this server locked? While locked, all write operations are blocked, although read operations may still be allowed. Use :meth:`unlock` to unlock. """ ops = self.admin.current_op() return bool(ops.get('fsyncLock', 0)) def fsync(self, **kwargs): """Flush all pending writes to datafiles. :Parameters: Optional parameters can be passed as keyword arguments: - `lock`: If True lock the server to disallow writes. - `async`: If True don't block while synchronizing. .. warning:: `async` and `lock` can not be used together. .. warning:: MongoDB does not support the `async` option on Windows and will raise an exception on that platform. """ self.admin.command("fsync", read_preference=ReadPreference.PRIMARY, **kwargs) def unlock(self): """Unlock a previously locked server. """ coll = self.admin.get_collection( "$cmd.sys.unlock", read_preference=ReadPreference.PRIMARY) coll.find_one() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def __iter__(self): return self def __next__(self): raise TypeError("'MongoClient' object is not iterable") next = __next__
def __init__(self, host=None, port=None, document_class=dict, tz_aware=False, connect=True, **kwargs): """Client for a MongoDB instance, a replica set, or a set of mongoses. The client object is thread-safe and has connection-pooling built in. If an operation fails because of a network error, :class:`~pymongo.errors.ConnectionFailure` is raised and the client reconnects in the background. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ':', '/', '+' and '@' must be escaped following RFC 2396. .. warning:: When using PyMongo in a multiprocessing context, please read :ref:`multiprocessing` first. :Parameters: - `host` (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost) - `port` (optional): port number on which to connect - `document_class` (optional): default class to use for documents returned from queries on this client - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`MongoClient` will be timezone aware (otherwise they will be naive) - `connect` (optional): if ``True`` (the default), immediately begin connecting to MongoDB in the background. Otherwise connect on the first operation. | **Other optional parameters can be passed as keyword arguments:** - `maxPoolSize` (optional): The maximum number of connections that the pool will open simultaneously. If this is set, operations will block if there are `maxPoolSize` outstanding connections from the pool. Defaults to 100. Cannot be 0. - `socketTimeoutMS`: (integer or None) Controls how long (in milliseconds) the driver will wait for a response after sending an ordinary (non-monitoring) database operation before concluding that a network error has occurred. Defaults to ``None`` (no timeout). - `connectTimeoutMS`: (integer or None) Controls how long (in milliseconds) the driver will wait during server monitoring when connecting a new socket to a server before concluding the server is unavailable. Defaults to ``20000`` (20 seconds). - `serverSelectionTimeoutMS`: (integer) Controls how long (in milliseconds) the driver will wait to find an available, appropriate server to carry out a database operation; while it is waiting, multiple server monitoring operations may be carried out, each controlled by `connectTimeoutMS`. Defaults to ``30000`` (30 seconds). - `waitQueueTimeoutMS`: (integer or None) How long (in milliseconds) a thread will wait for a socket from the pool if the pool has no free sockets. Defaults to ``None`` (no timeout). - `waitQueueMultiple`: (integer or None) Multiplied by maxPoolSize to give the number of threads allowed to wait for a socket at one time. Defaults to ``None`` (no limit). - `socketKeepAlive`: (boolean) Whether to send periodic keep-alive packets on connected sockets. Defaults to ``False`` (do not send keep-alive packets). | **Write Concern options:** | (Only set if passed. No default values.) - `w`: (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. `w=<int>` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). Passing w=0 **disables write acknowledgement** and all other write concern options. - `wtimeout`: (integer) Used in conjunction with `w`. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised. - `j`: If ``True`` block until write operations have been committed to the journal. Cannot be used in combination with `fsync`. Prior to MongoDB 2.6 this option was ignored if the server was running without journaling. Starting with MongoDB 2.6 write operations will fail with an exception if this option is used when the server is running without journaling. - `fsync`: If ``True`` and the server is running without journaling, blocks until the server has synced all data files to disk. If the server is running with journaling, this acts the same as the `j` option, blocking until write operations have been committed to the journal. Cannot be used in combination with `j`. | **Replica set keyword arguments for connecting with a replica set - either directly or via a mongos:** - `replicaSet`: (string or None) The name of the replica set to connect to. The driver will verify that all servers it connects to match this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. Defaults to ``None``. - `read_preference`: The read preference for this client. If connecting directly to a secondary then a read preference mode *other* than PRIMARY is required - otherwise all queries will throw :class:`~pymongo.errors.AutoReconnect` "not master". See :class:`~pymongo.read_preferences.ReadPreference` for all available read preference options. Defaults to ``PRIMARY``. | **SSL configuration:** - `ssl`: If ``True``, create the connection to the server using SSL. Defaults to ``False``. - `ssl_keyfile`: The private keyfile used to identify the local connection against mongod. If included with the ``certfile`` then only the ``ssl_certfile`` is needed. Implies ``ssl=True``. Defaults to ``None``. - `ssl_certfile`: The certificate file used to identify the local connection against mongod. Implies ``ssl=True``. Defaults to ``None``. - `ssl_cert_reqs`: Specifies whether a certificate is required from the other side of the connection, and whether it will be validated if provided. It must be one of the three values ``ssl.CERT_NONE`` (certificates ignored), ``ssl.CERT_OPTIONAL`` (not required, but validated if provided), or ``ssl.CERT_REQUIRED`` (required and validated). If the value of this parameter is not ``ssl.CERT_NONE`` and a value is not provided for ``ssl_ca_certs`` PyMongo will attempt to load system provided CA certificates. If the python version in use does not support loading system CA certificates then the ``ssl_ca_certs`` parameter must point to a file of CA certificates. Implies ``ssl=True``. Defaults to ``ssl.CERT_REQUIRED`` if not provided and ``ssl=True``. - `ssl_ca_certs`: The ca_certs file contains a set of concatenated "certification authority" certificates, which are used to validate certificates passed from the other end of the connection. Implies ``ssl=True``. Defaults to ``None``. - `ssl_match_hostname`: If ``True`` (the default), and `ssl_cert_reqs` is not ``ssl.CERT_NONE``, enables hostname verification using the :func:`~ssl.match_hostname` function from python's :mod:`~ssl` module. Think very carefully before setting this to ``False`` as that could make your application vulnerable to man-in-the-middle attacks. .. mongodoc:: connections .. versionchanged:: 3.0 :class:`~pymongo.mongo_client.MongoClient` is now the one and only client class for a standalone server, mongos, or replica set. It includes the functionality that had been split into :class:`~pymongo.mongo_client.MongoReplicaSetClient`: it can connect to a replica set, discover all its members, and monitor the set for stepdowns, elections, and reconfigs. The :class:`~pymongo.mongo_client.MongoClient` constructor no longer blocks while connecting to the server or servers, and it no longer raises :class:`~pymongo.errors.ConnectionFailure` if they are unavailable, nor :class:`~pymongo.errors.ConfigurationError` if the user's credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads. Therefore the ``alive`` method is removed since it no longer provides meaningful information; even if the client is disconnected, it may discover a server in time to fulfill the next operation. In PyMongo 2.x, :class:`~pymongo.MongoClient` accepted a list of standalone MongoDB servers and used the first it could connect to:: MongoClient(['host1.com:27017', 'host2.com:27017']) A list of multiple standalones is no longer supported; if multiple servers are listed they must be members of the same replica set, or mongoses in the same sharded cluster. The behavior for a list of mongoses is changed from "high availability" to "load balancing". Before, the client connected to the lowest-latency mongos in the list, and used it until a network error prompted it to re-evaluate all mongoses' latencies and reconnect to one of them. In PyMongo 3, the client monitors its network latency to all the mongoses continuously, and distributes operations evenly among those with the lowest latency. See :ref:`mongos-load-balancing` for more information. The ``connect`` option is added. The ``start_request``, ``in_request``, and ``end_request`` methods are removed, as well as the ``auto_start_request`` option. The ``copy_database`` method is removed, see the :doc:`copy_database examples </examples/copydb>` for alternatives. The :meth:`MongoClient.disconnect` method is removed; it was a synonym for :meth:`~pymongo.MongoClient.close`. :class:`~pymongo.mongo_client.MongoClient` no longer returns an instance of :class:`~pymongo.database.Database` for attribute names with leading underscores. You must use dict-style lookups instead:: client['__my_database__'] Not:: client.__my_database__ """ if host is None: host = self.HOST if isinstance(host, string_type): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") seeds = set() username = None password = None dbase = None opts = {} for entity in host: if "://" in entity: if entity.startswith("mongodb://"): res = uri_parser.parse_uri(entity, port, warn=True) seeds.update(res["nodelist"]) username = res["username"] or username password = res["password"] or password dbase = res["database"] or dbase opts = res["options"] else: idx = entity.find("://") raise InvalidURI("Invalid URI scheme: " "%s" % (entity[:idx], )) else: seeds.update(uri_parser.split_hosts(entity, port)) if not seeds: raise ConfigurationError("need to specify at least one host") # _pool_class, _monitor_class, and _condition_class are for deep # customization of PyMongo, e.g. Motor. pool_class = kwargs.pop('_pool_class', None) monitor_class = kwargs.pop('_monitor_class', None) condition_class = kwargs.pop('_condition_class', None) keyword_opts = kwargs keyword_opts['document_class'] = document_class keyword_opts['tz_aware'] = tz_aware keyword_opts['connect'] = connect # Validate all keyword options. keyword_opts = dict( common.validate(k, v) for k, v in keyword_opts.items()) opts.update(keyword_opts) self.__options = options = ClientOptions(username, password, dbase, opts) self.__default_database_name = dbase self.__lock = threading.Lock() self.__cursor_manager = CursorManager(self) self.__kill_cursors_queue = [] # Cache of existing indexes used by ensure_index ops. self.__index_cache = {} super(MongoClient, self).__init__(options.codec_options, options.read_preference, options.write_concern) self.__all_credentials = {} creds = options.credentials if creds: self._cache_credentials(creds.source, creds) self._topology_settings = TopologySettings( seeds=seeds, replica_set_name=options.replica_set_name, pool_class=pool_class, pool_options=options.pool_options, monitor_class=monitor_class, condition_class=condition_class, local_threshold_ms=options.local_threshold_ms, server_selection_timeout=options.server_selection_timeout) self._topology = Topology(self._topology_settings) if connect: self._topology.open() def target(): client = self_ref() if client is None: return False # Stop the executor. MongoClient._process_kill_cursors_queue(client) return True executor = periodic_executor.PeriodicExecutor( condition_class=self._topology_settings.condition_class, interval=common.KILL_CURSOR_FREQUENCY, min_interval=0, target=target, name="pymongo_kill_cursors_thread") # We strongly reference the executor and it weakly references us via # this closure. When the client is freed, stop the executor soon. self_ref = weakref.ref(self, executor.close) self._kill_cursors_executor = executor executor.open()
def __init__(self, host=None, port=None, pool_size=None, auto_start_request=None, timeout=None, slave_okay=False, network_timeout=None, _connect=True): """Create a new connection to a single MongoDB instance at *host:port*. The resultant connection object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, :class:`~pymongo.errors.ConnectionFailure` is raised. If auto-reconnection will be performed, :class:`~pymongo.errors.AutoReconnect` will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. Raises :class:`TypeError` if host is not an instance of string or port is not an instance of ``int``. Raises :class:`~pymongo.errors.ConnectionFailure` if the connection cannot be made. :Parameters: - `host` (optional): hostname or IPv4 address of the instance to connect to - `port` (optional): port number on which to connect - `pool_size` (optional): DEPRECATED - `auto_start_request` (optional): DEPRECATED - `slave_okay` (optional): is it okay to connect directly to and perform queries on a slave instance - `timeout` (optional): DEPRECATED - `network_timeout` (optional): timeout (in seconds) to use for socket operations - default is no timeout .. seealso:: :meth:`end_request` .. versionchanged:: 1.4 DEPRECATED The `pool_size`, `auto_start_request`, and `timeout` parameters. .. versionadded:: 1.1 The `network_timeout` parameter. .. mongodoc:: connections """ if host is None: host = self.HOST if port is None: port = self.PORT if pool_size is not None: warnings.warn( "The pool_size parameter to Connection is " "deprecated", DeprecationWarning) if auto_start_request is not None: warnings.warn( "The auto_start_request parameter to Connection " "is deprecated", DeprecationWarning) if timeout is not None: warnings.warn("The timeout parameter to Connection is deprecated", DeprecationWarning) if not isinstance(host, basestring): raise TypeError("host must be an instance of basestring") if not isinstance(port, int): raise TypeError("port must be an instance of int") self.__host = None self.__port = None self.__nodes = [(host, port)] self.__slave_okay = slave_okay self.__cursor_manager = CursorManager(self) self.__pool = Pool(self.__connect) self.__network_timeout = network_timeout # cache of existing indexes used by ensure_index ops self.__index_cache = {} if _connect: self.__find_master()
def __init__(self, host=None, port=None, max_pool_size=10, network_timeout=None, document_class=dict, tz_aware=False, _connect=True, **kwargs): """Create a new connection to a single MongoDB instance at *host:port*. The resultant connection object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, :class:`~pymongo.errors.ConnectionFailure` is raised. If auto-reconnection will be performed, :class:`~pymongo.errors.AutoReconnect` will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. Raises :class:`TypeError` if port is not an instance of ``int``. Raises :class:`~pymongo.errors.ConnectionFailure` if the connection cannot be made. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ':', '/', '+' and '@' must be escaped following RFC 2396. :Parameters: - `host` (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost) - `port` (optional): port number on which to connect - `max_pool_size` (optional): The maximum size limit for the connection pool. - `network_timeout` (optional): timeout (in seconds) to use for socket operations - default is no timeout - `document_class` (optional): default class to use for documents returned from queries on this connection - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`Connection` will be timezone aware (otherwise they will be naive) Other optional parameters can be passed as keyword arguments: - `safe`: Use getlasterror for each write operation? - `j` or `journal`: Block until write operations have been committed to the journal. Ignored if the server is running without journaling. Implies safe=True. - `w`: (integer or string) If this is a replica set write operations won't return until they have been replicated to the specified number or tagged set of servers. Implies safe=True. - `wtimeout`: Used in conjunction with `j` and/or `w`. Wait this many milliseconds for journal acknowledgement and/or write replication. Implies safe=True. - `fsync`: Force the database to fsync all files before returning When used with `j` the server awaits the next group commit before returning. Implies safe=True. - `replicaSet`: The name of the replica set to connect to. The driver will verify that the replica set it connects to matches this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. - `socketTimeoutMS`: How long a send or receive on a socket can take before timing out. - `connectTimeoutMS`: How long a connection can take to be opened before timing out. - `ssl`: If True, create the connection to the server using SSL. - `read_preference`: The read preference for this connection. See :class:`~pymongo.read_preferences.ReadPreference` for available options. - `auto_start_request`: If True (the default), each thread that accesses this Connection has a socket allocated to it for the thread's lifetime. This ensures consistent reads, even if you read after an unsafe write. - `use_greenlets` (optional): if ``True``, :meth:`start_request()` will ensure that the current greenlet uses the same socket for all operations until :meth:`end_request()` - `slave_okay` or `slaveOk` (deprecated): Use `read_preference` instead. .. seealso:: :meth:`end_request` .. versionchanged:: 2.3 Added support for failover between mongos seed list members. .. versionchanged:: 2.2 Added `auto_start_request` option back. Added `use_greenlets` option. .. versionchanged:: 2.1 Support `w` = integer or string. Added `ssl` option. DEPRECATED slave_okay/slaveOk. .. versionchanged:: 2.0 `slave_okay` is a pure keyword argument. Added support for safe, and getlasterror options as keyword arguments. .. versionchanged:: 1.11 Added `max_pool_size`. Completely removed previously deprecated `pool_size`, `auto_start_request` and `timeout` parameters. .. versionchanged:: 1.8 The `host` parameter can now be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. .. versionadded:: 1.8 The `tz_aware` parameter. .. versionadded:: 1.7 The `document_class` parameter. .. versionadded:: 1.1 The `network_timeout` parameter. .. mongodoc:: connections """ if host is None: host = self.HOST if isinstance(host, basestring): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") seeds = set() username = None password = None db = None options = {} for entity in host: if "://" in entity: if entity.startswith("mongodb://"): res = uri_parser.parse_uri(entity, port) seeds.update(res["nodelist"]) username = res["username"] or username password = res["password"] or password db = res["database"] or db options = res["options"] else: idx = entity.find("://") raise InvalidURI("Invalid URI scheme: " "%s" % (entity[:idx], )) else: seeds.update(uri_parser.split_hosts(entity, port)) if not seeds: raise ConfigurationError("need to specify at least one host") self.__nodes = seeds self.__host = None self.__port = None self.__is_primary = False self.__is_mongos = False for option, value in kwargs.iteritems(): option, value = common.validate(option, value) options[option] = value self.__max_pool_size = common.validate_positive_integer( 'max_pool_size', max_pool_size) self.__cursor_manager = CursorManager(self) self.__repl = options.get('replicaset') if len(seeds) == 1 and not self.__repl: self.__direct = True else: self.__direct = False self.__nodes = set() if network_timeout is not None: if (not isinstance(network_timeout, (int, float)) or network_timeout <= 0): raise ConfigurationError("network_timeout must " "be a positive integer") self.__net_timeout = (network_timeout or options.get('sockettimeoutms')) self.__conn_timeout = options.get('connecttimeoutms') self.__use_ssl = options.get('ssl', False) if self.__use_ssl and not pool.have_ssl: raise ConfigurationError("The ssl module is not available. If you " "are using a python version previous to " "2.6 you must install the ssl package " "from PyPI.") if options.get('use_greenlets', False): if not pool.have_greenlet: raise ConfigurationError( "The greenlet module is not available. " "Install the greenlet package from PyPI.") self.pool_class = pool.GreenletPool else: self.pool_class = pool.Pool self.__pool = self.pool_class(None, self.__max_pool_size, self.__net_timeout, self.__conn_timeout, self.__use_ssl) self.__document_class = document_class self.__tz_aware = common.validate_boolean('tz_aware', tz_aware) self.__auto_start_request = options.get('auto_start_request', True) # cache of existing indexes used by ensure_index ops self.__index_cache = {} self.__auth_credentials = {} super(Connection, self).__init__(**options) if self.slave_okay: warnings.warn( "slave_okay is deprecated. Please " "use read_preference instead.", DeprecationWarning) if _connect: self.__find_node(seeds) if db and username is None: warnings.warn("must provide a username and password " "to authenticate to %s" % (db, )) if username: db = db or "admin" if not self[db].authenticate(username, password): raise ConfigurationError("authentication failed")
def __init__(self, host=None, port=None, pool_size=None, auto_start_request=None, timeout=None, slave_okay=False, network_timeout=None, document_class=dict, tz_aware=False, _connect=True): """Create a new connection to a single MongoDB instance at *host:port*. The resultant connection object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, :class:`~pymongo.errors.ConnectionFailure` is raised. If auto-reconnection will be performed, :class:`~pymongo.errors.AutoReconnect` will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. Raises :class:`TypeError` if port is not an instance of ``int``. Raises :class:`~pymongo.errors.ConnectionFailure` if the connection cannot be made. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. :Parameters: - `host` (optional): hostname or IPv4 address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs - `port` (optional): port number on which to connect - `pool_size` (optional): DEPRECATED - `auto_start_request` (optional): DEPRECATED - `slave_okay` (optional): is it okay to connect directly to and perform queries on a slave instance - `timeout` (optional): DEPRECATED - `network_timeout` (optional): timeout (in seconds) to use for socket operations - default is no timeout - `document_class` (optional): default class to use for documents returned from queries on this connection - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`Connection` will be timezone aware (otherwise they will be naive) .. seealso:: :meth:`end_request` .. versionchanged:: 1.8 The `host` parameter can now be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. .. versionadded:: 1.8 The `tz_aware` parameter. .. versionadded:: 1.7 The `document_class` parameter. .. versionchanged:: 1.4 DEPRECATED The `pool_size`, `auto_start_request`, and `timeout` parameters. .. versionadded:: 1.1 The `network_timeout` parameter. .. mongodoc:: connections """ if host is None: host = self.HOST if isinstance(host, str): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") nodes = set() database = None username = None password = None for uri in host: (n, db, u, p) = _parse_uri(uri, port) nodes.update(n) database = db or database username = u or username password = p or password if not nodes: raise ConfigurationError("need to specify at least one host") self.__nodes = nodes if database and username is None: raise InvalidURI("cannot specify database without " "a username and password") if pool_size is not None: warnings.warn("The pool_size parameter to Connection is " "deprecated", DeprecationWarning) if auto_start_request is not None: warnings.warn("The auto_start_request parameter to Connection " "is deprecated", DeprecationWarning) if timeout is not None: warnings.warn("The timeout parameter to Connection is deprecated", DeprecationWarning) self.__host = None self.__port = None self.__slave_okay = slave_okay if slave_okay and len(self.__nodes) > 1: raise ConfigurationError("cannot specify slave_okay for a paired " "or replica set connection") self.__cursor_manager = CursorManager(self) self.__pool = _Pool(self.__connect) self.__last_checkout = time.time() self.__network_timeout = network_timeout self.__document_class = document_class self.__tz_aware = tz_aware # cache of existing indexes used by ensure_index ops self.__index_cache = {} if _connect: self.__find_master() if username: database = database or "admin" if not self[database].authenticate(username, password): raise ConfigurationError("authentication failed")
def __init__(self, host=None, port=None, max_pool_size=10, document_class=dict, tz_aware=False, _connect=True, **kwargs): """Create a new connection to a single MongoDB instance at *host:port*. The resultant client object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, :class:`~pymongo.errors.ConnectionFailure` is raised. If auto-reconnection will be performed, :class:`~pymongo.errors.AutoReconnect` will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. Raises :class:`TypeError` if port is not an instance of ``int``. Raises :class:`~pymongo.errors.ConnectionFailure` if the connection cannot be made. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ':', '/', '+' and '@' must be escaped following RFC 2396. :Parameters: - `host` (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost) - `port` (optional): port number on which to connect - `max_pool_size` (optional): The maximum number of idle connections to keep open in the pool for future use - `document_class` (optional): default class to use for documents returned from queries on this client - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`MongoClient` will be timezone aware (otherwise they will be naive) | **Other optional parameters can be passed as keyword arguments:** - `socketTimeoutMS`: (integer) How long (in milliseconds) a send or receive on a socket can take before timing out. - `connectTimeoutMS`: (integer) How long (in milliseconds) a connection can take to be opened before timing out. - `auto_start_request`: If ``True``, each thread that accesses this :class:`MongoClient` has a socket allocated to it for the thread's lifetime. This ensures consistent reads, even if you read after an unacknowledged write. Defaults to ``False`` - `use_greenlets`: If ``True``, :meth:`start_request()` will ensure that the current greenlet uses the same socket for all operations until :meth:`end_request()` | **Write Concern options:** - `w`: (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. `w=<int>` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). Passing w=0 **disables write acknowledgement** and all other write concern options. - `wtimeout`: (integer) Used in conjunction with `w`. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised. - `j`: If ``True`` block until write operations have been committed to the journal. Ignored if the server is running without journaling. - `fsync`: If ``True`` force the database to fsync all files before returning. When used with `j` the server awaits the next group commit before returning. | **Replica set keyword arguments for connecting with a replica set - either directly or via a mongos:** | (ignored by standalone mongod instances) - `replicaSet`: (string) The name of the replica set to connect to. The driver will verify that the replica set it connects to matches this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. *Ignored by mongos*. - `read_preference`: The read preference for this client. If connecting to a secondary then a read preference mode *other* than PRIMARY is required - otherwise all queries will throw :class:`~pymongo.errors.AutoReconnect` "not master". See :class:`~pymongo.read_preferences.ReadPreference` for all available read preference options. - `tag_sets`: Ignored unless connecting to a replica set via mongos. Specify a priority-order for tag sets, provide a list of tag sets: ``[{'dc': 'ny'}, {'dc': 'la'}, {}]``. A final, empty tag set, ``{}``, means "read from any member that matches the mode, ignoring tags. | **SSL configuration:** - `ssl`: If ``True``, create the connection to the server using SSL. - `ssl_keyfile`: The private keyfile used to identify the local connection against mongod. If included with the ``certfile` then only the ``ssl_certfile`` is needed. Implies ``ssl=True``. - `ssl_certfile`: The certificate file used to identify the local connection against mongod. Implies ``ssl=True``. - `ssl_cert_reqs`: Specifies whether a certificate is required from the other side of the connection, and whether it will be validated if provided. It must be one of the three values ``ssl.CERT_NONE`` (certificates ignored), ``ssl.CERT_OPTIONAL`` (not required, but validated if provided), or ``ssl.CERT_REQUIRED`` (required and validated). If the value of this parameter is not ``ssl.CERT_NONE``, then the ``ssl_ca_certs`` parameter must point to a file of CA certificates. Implies ``ssl=True``. - `ssl_ca_certs`: The ca_certs file contains a set of concatenated "certification authority" certificates, which are used to validate certificates passed from the other end of the connection. Implies ``ssl=True``. .. seealso:: :meth:`end_request` .. mongodoc:: connections .. versionchanged:: 2.5 Added additional ssl options .. versionadded:: 2.4 """ if host is None: host = self.HOST if isinstance(host, str): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") seeds = set() username = None password = None db_name = None opts = {} for entity in host: if "://" in entity: if entity.startswith("mongodb://"): res = uri_parser.parse_uri(entity, port) seeds.update(res["nodelist"]) username = res["username"] or username password = res["password"] or password db_name = res["database"] or db_name opts = res["options"] else: idx = entity.find("://") raise InvalidURI("Invalid URI scheme: " "%s" % (entity[:idx],)) else: seeds.update(uri_parser.split_hosts(entity, port)) if not seeds: raise ConfigurationError("need to specify at least one host") self.__nodes = seeds self.__host = None self.__port = None self.__is_primary = False self.__is_mongos = False # _pool_class option is for deep customization of PyMongo, e.g. Motor. # SHOULD NOT BE USED BY DEVELOPERS EXTERNAL TO 10GEN. pool_class = kwargs.pop('_pool_class', pool.Pool) options = {} for option, value in kwargs.items(): option, value = common.validate(option, value) options[option] = value options.update(opts) self.__max_pool_size = common.validate_positive_integer( 'max_pool_size', max_pool_size) self.__cursor_manager = CursorManager(self) self.__repl = options.get('replicaset') if len(seeds) == 1 and not self.__repl: self.__direct = True else: self.__direct = False self.__nodes = set() self.__net_timeout = options.get('sockettimeoutms') self.__conn_timeout = options.get('connecttimeoutms') self.__use_ssl = options.get('ssl', None) self.__ssl_keyfile = options.get('ssl_keyfile', None) self.__ssl_certfile = options.get('ssl_certfile', None) self.__ssl_cert_reqs = options.get('ssl_cert_reqs', None) self.__ssl_ca_certs = options.get('ssl_ca_certs', None) ssl_kwarg_keys = [k for k in list(kwargs.keys()) if k.startswith('ssl_')] if self.__use_ssl == False and ssl_kwarg_keys: raise ConfigurationError("ssl has not been enabled but the " "following ssl parameters have been set: " "%s. Please set `ssl=True` or remove." % ', '.join(ssl_kwarg_keys)) if self.__ssl_cert_reqs and not self.__ssl_ca_certs: raise ConfigurationError("If `ssl_cert_reqs` is not " "`ssl.CERT_NONE` then you must " "include `ssl_ca_certs` to be able " "to validate the server.") if ssl_kwarg_keys and self.__use_ssl is None: # ssl options imply ssl = True self.__use_ssl = True if self.__use_ssl and not HAS_SSL: raise ConfigurationError("The ssl module is not available. If you " "are using a python version previous to " "2.6 you must install the ssl package " "from PyPI.") self.__use_greenlets = options.get('use_greenlets', False) self.__pool = pool_class( None, self.__max_pool_size, self.__net_timeout, self.__conn_timeout, self.__use_ssl, use_greenlets=self.__use_greenlets, ssl_keyfile=self.__ssl_keyfile, ssl_certfile=self.__ssl_certfile, ssl_cert_reqs=self.__ssl_cert_reqs, ssl_ca_certs=self.__ssl_ca_certs) self.__document_class = document_class self.__tz_aware = common.validate_boolean('tz_aware', tz_aware) self.__auto_start_request = options.get('auto_start_request', False) # cache of existing indexes used by ensure_index ops self.__index_cache = {} self.__auth_credentials = {} super(MongoClient, self).__init__(**options) if self.slave_okay: warnings.warn("slave_okay is deprecated. Please " "use read_preference instead.", DeprecationWarning, stacklevel=2) if _connect: try: self.__find_node(seeds) except AutoReconnect as e: # ConnectionFailure makes more sense here than AutoReconnect raise ConnectionFailure(str(e)) db_name = options.get('authsource', db_name) if db_name and username is None: warnings.warn("database name or authSource in URI is being " "ignored. If you wish to authenticate to %s, you " "must provide a username and password." % (db_name,)) if username: mechanism = options.get('authmechanism', 'MONGODB-CR') if mechanism == 'GSSAPI': source = '$external' else: source = db_name or 'admin' credentials = (source, str(username), str(password), mechanism) try: self._cache_credentials(source, credentials, _connect) except OperationFailure as exc: raise ConfigurationError(str(exc))
def __init__(self, host=None, port=None, max_pool_size=10, network_timeout=None, document_class=dict, tz_aware=False, _connect=True, **kwargs): """Create a new connection to a single MongoDB instance at *host:port*. The resultant connection object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, :class:`~pymongo.errors.ConnectionFailure` is raised. If auto-reconnection will be performed, :class:`~pymongo.errors.AutoReconnect` will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. Raises :class:`TypeError` if port is not an instance of ``int``. Raises :class:`~pymongo.errors.ConnectionFailure` if the connection cannot be made. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. :Parameters: - `host` (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost) - `port` (optional): port number on which to connect - `max_pool_size` (optional): The maximum size limit for the connection pool. - `network_timeout` (optional): timeout (in seconds) to use for socket operations - default is no timeout - `document_class` (optional): default class to use for documents returned from queries on this connection - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`Connection` will be timezone aware (otherwise they will be naive) Other optional parameters can be passed as keyword arguments: - `slave_okay` or `slaveok`: Is it OK to perform queries if this connection is to a secondary? - `safe`: Use getlasterror for each write operation? - `j`: Block until write operations have been commited to the journal. Ignored if the server is running without journaling. Implies safe=True. - `w`: If this is a replica set the server won't return until write operations have replicated to this many set members. Implies safe=True. - `wtimeout`: Used in conjunction with `j` and/or `w`. Wait this many milliseconds for journal acknowledgement and/or write replication. Implies safe=True. - `fsync`: Force the database to fsync all files before returning When used with `j` the server awaits the next group commit before returning. Implies safe=True. .. seealso:: :meth:`end_request` .. versionchanged:: 1.11+ `slave_okay` is a pure keyword argument. Added support for safe, and getlasterror options as keyword arguments. .. versionchanged:: 1.11 Added `max_pool_size`. Completely removed previously deprecated `pool_size`, `auto_start_request` and `timeout` parameters. .. versionchanged:: 1.8 The `host` parameter can now be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. .. versionadded:: 1.8 The `tz_aware` parameter. .. versionadded:: 1.7 The `document_class` parameter. .. versionchanged:: 1.4 DEPRECATED The `pool_size`, `auto_start_request`, and `timeout` parameters. .. versionadded:: 1.1 The `network_timeout` parameter. .. mongodoc:: connections """ super(Connection, self).__init__(**kwargs) if host is None: host = self.HOST if isinstance(host, basestring): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") nodes = set() username = None password = None db = None coll = None options = {} for entity in host: if "://" in entity: if entity.startswith("mongodb://"): res = uri_parser.parse_uri(entity, port) nodes.update(res["nodelist"]) username = res["username"] or username password = res["password"] or password db = res["database"] or db coll = res["collection"] or coll options = res["options"] else: idx = entity.find("://") raise InvalidURI("Invalid URI scheme: " "%s" % (entity[:idx], )) else: nodes.update(uri_parser.split_hosts(entity, port)) if not nodes: raise ConfigurationError("need to specify at least one host") self.__nodes = nodes self.__host = None self.__port = None if options: super(Connection, self)._set_options(**options) assert isinstance(max_pool_size, int), "max_pool_size must be an int" self.__max_pool_size = options.get("maxpoolsize") or max_pool_size if self.__max_pool_size < 0: raise ValueError("the maximum pool size must be >= 0") # TODO - Support using other options like w and fsync from URI self.__options = options # TODO - Support setting the collection from URI like the Java driver self.__collection = coll self.__cursor_manager = CursorManager(self) self.__network_timeout = network_timeout self.__pool = _Pool(self.__max_pool_size, self.__network_timeout) self.__last_checkout = time.time() self.__document_class = document_class self.__tz_aware = tz_aware # cache of existing indexes used by ensure_index ops self.__index_cache = {} if _connect: self.__find_node() if db and username is None: warnings.warn("must provide a username and password " "to authenticate to %s" % (db, )) if username: db = db or "admin" if not self[db].authenticate(username, password): raise ConfigurationError("authentication failed")
def __init__(self, host=None, port=None, max_pool_size=10, document_class=dict, tz_aware=False, _connect=True, **kwargs): """Create a new connection to a single MongoDB instance at *host:port*. The resultant connection object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, :class:`~pymongo.errors.ConnectionFailure` is raised. If auto-reconnection will be performed, :class:`~pymongo.errors.AutoReconnect` will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. Raises :class:`TypeError` if port is not an instance of ``int``. Raises :class:`~pymongo.errors.ConnectionFailure` if the connection cannot be made. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ':', '/', '+' and '@' must be escaped following RFC 2396. :Parameters: - `host` (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost) - `port` (optional): port number on which to connect - `max_pool_size` (optional): The maximum number of idle connections to keep open in the pool for future use - `document_class` (optional): default class to use for documents returned from queries on this connection - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`MongoClient` will be timezone aware (otherwise they will be naive) **Other optional parameters can be passed as keyword arguments:** - `w`: (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. `w=<int>` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). **Passing w=0 disables write acknowledgement and all other write concern options.** - `wtimeout`: (integer) Used in conjunction with `w`. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised. - `j`: If ``True`` block until write operations have been committed to the journal. Ignored if the server is running without journaling. - `fsync`: If ``True`` force the database to fsync all files before returning. When used with `j` the server awaits the next group commit before returning. - `replicaSet`: (string) The name of the replica set to connect to. The driver will verify that the replica set it connects to matches this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. - `socketTimeoutMS`: (integer) How long (in milliseconds) a send or receive on a socket can take before timing out. - `connectTimeoutMS`: (integer) How long (in milliseconds) a connection can take to be opened before timing out. - `ssl`: If ``True``, create the connection to the server using SSL. - `read_preference`: The read preference for this connection. See :class:`~pymongo.read_preferences.ReadPreference` for available options. - `auto_start_request`: If ``True``, each thread that accesses this :class:`MongoClient` has a socket allocated to it for the thread's lifetime. This ensures consistent reads, even if you read after an unacknowledged write. Defaults to ``False`` - `use_greenlets`: If ``True``, :meth:`start_request()` will ensure that the current greenlet uses the same socket for all operations until :meth:`end_request()` .. seealso:: :meth:`end_request` .. mongodoc:: connections .. versionadded:: 2.4 """ if host is None: host = self.HOST if isinstance(host, str): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") seeds = set() username = None password = None db = None opts = {} for entity in host: if "://" in entity: if entity.startswith("mongodb://"): res = uri_parser.parse_uri(entity, port) seeds.update(res["nodelist"]) username = res["username"] or username password = res["password"] or password db = res["database"] or db opts = res["options"] else: idx = entity.find("://") raise InvalidURI("Invalid URI scheme: " "%s" % (entity[:idx],)) else: seeds.update(uri_parser.split_hosts(entity, port)) if not seeds: raise ConfigurationError("need to specify at least one host") self.__nodes = seeds self.__host = None self.__port = None self.__is_primary = False self.__is_mongos = False # _pool_class option is for deep customization of PyMongo, e.g. Motor. # SHOULD NOT BE USED BY DEVELOPERS EXTERNAL TO 10GEN. pool_class = kwargs.pop('_pool_class', pool.Pool) options = {} for option, value in kwargs.items(): option, value = common.validate(option, value) options[option] = value options.update(opts) self.__max_pool_size = common.validate_positive_integer( 'max_pool_size', max_pool_size) self.__cursor_manager = CursorManager(self) self.__repl = options.get('replicaset') if len(seeds) == 1 and not self.__repl: self.__direct = True else: self.__direct = False self.__nodes = set() self.__net_timeout = options.get('sockettimeoutms') self.__conn_timeout = options.get('connecttimeoutms') self.__use_ssl = options.get('ssl', False) if self.__use_ssl and not pool.have_ssl: raise ConfigurationError("The ssl module is not available. If you " "are using a python version previous to " "2.6 you must install the ssl package " "from PyPI.") self.__use_greenlets = options.get('use_greenlets', False) self.__pool = pool_class( None, self.__max_pool_size, self.__net_timeout, self.__conn_timeout, self.__use_ssl, use_greenlets=self.__use_greenlets) self.__document_class = document_class self.__tz_aware = common.validate_boolean('tz_aware', tz_aware) self.__auto_start_request = options.get('auto_start_request', False) # cache of existing indexes used by ensure_index ops self.__index_cache = {} self.__auth_credentials = {} super(MongoClient, self).__init__(**options) if self.slave_okay: warnings.warn("slave_okay is deprecated. Please " "use read_preference instead.", DeprecationWarning) if _connect: try: self.__find_node(seeds) except AutoReconnect as e: # ConnectionFailure makes more sense here than AutoReconnect raise ConnectionFailure(str(e)) if db and username is None: warnings.warn("database name in URI is being ignored. If you wish " "to authenticate to %s, you must provide a username " "and password." % (db,)) if username: db = db or "admin" if not self[db].authenticate(username, password): raise ConfigurationError("authentication failed")
def __init__(self, host=None, port=None, pool_size=None, auto_start_request=None, timeout=None, slave_okay=False, network_timeout=None, document_class=dict, tz_aware=False, _connect=True): """Create a new connection to a single MongoDB instance at *host:port*. The resultant connection object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, :class:`~pymongo.errors.ConnectionFailure` is raised. If auto-reconnection will be performed, :class:`~pymongo.errors.AutoReconnect` will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. Raises :class:`TypeError` if port is not an instance of ``int``. Raises :class:`~pymongo.errors.ConnectionFailure` if the connection cannot be made. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. :Parameters: - `host` (optional): hostname or IPv4 address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs - `port` (optional): port number on which to connect - `pool_size` (optional): DEPRECATED - `auto_start_request` (optional): DEPRECATED - `slave_okay` (optional): is it okay to connect directly to and perform queries on a slave instance - `timeout` (optional): DEPRECATED - `network_timeout` (optional): timeout (in seconds) to use for socket operations - default is no timeout - `document_class` (optional): default class to use for documents returned from queries on this connection - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`Connection` will be timezone aware (otherwise they will be naive) .. seealso:: :meth:`end_request` .. versionchanged:: 1.8 The `host` parameter can now be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. .. versionadded:: 1.8 The `tz_aware` parameter. .. versionadded:: 1.7 The `document_class` parameter. .. versionchanged:: 1.4 DEPRECATED The `pool_size`, `auto_start_request`, and `timeout` parameters. .. versionadded:: 1.1 The `network_timeout` parameter. .. mongodoc:: connections """ if host is None: host = self.HOST if isinstance(host, basestring): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") nodes = set() database = None username = None password = None collection = None options = {} for uri in host: (n, db, u, p, coll, opts) = _parse_uri(uri, port) nodes.update(n) database = db or database username = u or username password = p or password collection = coll or collection options = opts or options if not nodes: raise ConfigurationError("need to specify at least one host") self.__nodes = nodes if database and username is None: raise InvalidURI("cannot specify database without " "a username and password") if pool_size is not None: warnings.warn( "The pool_size parameter to Connection is " "deprecated", DeprecationWarning) if auto_start_request is not None: warnings.warn( "The auto_start_request parameter to Connection " "is deprecated", DeprecationWarning) if timeout is not None: warnings.warn("The timeout parameter to Connection is deprecated", DeprecationWarning) self.__host = None self.__port = None for k in options.iterkeys(): # PYTHON-205 - Lets not break existing client code. if k in ("slaveOk", "slaveok"): self.__slave_okay = (options[k][0].upper() == 'T') break else: self.__slave_okay = slave_okay if slave_okay and len(self.__nodes) > 1: raise ConfigurationError("cannot specify slave_okay for a paired " "or replica set connection") # TODO - Support using other options like w and fsync from URI self.__options = options # TODO - Support setting the collection from URI as the Java driver does self.__collection = collection self.__cursor_manager = CursorManager(self) self.__pool = _Pool(self.__connect) self.__last_checkout = time.time() self.__network_timeout = network_timeout self.__document_class = document_class self.__tz_aware = tz_aware # cache of existing indexes used by ensure_index ops self.__index_cache = {} if _connect: self.__find_master() if username: database = database or "admin" if not self[database].authenticate(username, password): raise ConfigurationError("authentication failed")
def __init__(self, host=None, port=None, max_pool_size=10, document_class=dict, tz_aware=False, _connect=True, **kwargs): """Create a new connection to a single MongoDB instance at *host:port*. The resultant connection object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, :class:`~pymongo.errors.ConnectionFailure` is raised. If auto-reconnection will be performed, :class:`~pymongo.errors.AutoReconnect` will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. Raises :class:`TypeError` if port is not an instance of ``int``. Raises :class:`~pymongo.errors.ConnectionFailure` if the connection cannot be made. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ':', '/', '+' and '@' must be escaped following RFC 2396. :Parameters: - `host` (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost) - `port` (optional): port number on which to connect - `max_pool_size` (optional): The maximum number of idle connections to keep open in the pool for future use - `document_class` (optional): default class to use for documents returned from queries on this connection - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`MongoClient` will be timezone aware (otherwise they will be naive) **Other optional parameters can be passed as keyword arguments:** - `w`: (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. `w=<int>` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). **Passing w=0 disables write acknowledgement and all other write concern options.** - `wtimeout`: (integer) Used in conjunction with `w`. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised. - `j`: If ``True`` block until write operations have been committed to the journal. Ignored if the server is running without journaling. - `fsync`: If ``True`` force the database to fsync all files before returning. When used with `j` the server awaits the next group commit before returning. - `replicaSet`: (string) The name of the replica set to connect to. The driver will verify that the replica set it connects to matches this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. - `socketTimeoutMS`: (integer) How long (in milliseconds) a send or receive on a socket can take before timing out. - `connectTimeoutMS`: (integer) How long (in milliseconds) a connection can take to be opened before timing out. - `ssl`: If ``True``, create the connection to the server using SSL. - `read_preference`: The read preference for this connection. See :class:`~pymongo.read_preferences.ReadPreference` for available options. - `auto_start_request`: If ``True``, each thread that accesses this :class:`MongoClient` has a socket allocated to it for the thread's lifetime. This ensures consistent reads, even if you read after an unacknowledged write. Defaults to ``False`` - `use_greenlets`: If ``True``, :meth:`start_request()` will ensure that the current greenlet uses the same socket for all operations until :meth:`end_request()` .. seealso:: :meth:`end_request` .. mongodoc:: connections .. versionadded:: 2.4 """ if host is None: host = self.HOST if isinstance(host, basestring): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") seeds = set() username = None password = None db = None opts = {} for entity in host: if "://" in entity: if entity.startswith("mongodb://"): res = uri_parser.parse_uri(entity, port) seeds.update(res["nodelist"]) username = res["username"] or username password = res["password"] or password db = res["database"] or db opts = res["options"] else: idx = entity.find("://") raise InvalidURI("Invalid URI scheme: " "%s" % (entity[:idx], )) else: seeds.update(uri_parser.split_hosts(entity, port)) if not seeds: raise ConfigurationError("need to specify at least one host") self.__nodes = seeds self.__host = None self.__port = None self.__is_primary = False self.__is_mongos = False options = {} for option, value in kwargs.iteritems(): option, value = common.validate(option, value) options[option] = value options.update(opts) self.__max_pool_size = common.validate_positive_integer( 'max_pool_size', max_pool_size) self.__cursor_manager = CursorManager(self) self.__repl = options.get('replicaset') if len(seeds) == 1 and not self.__repl: self.__direct = True else: self.__direct = False self.__nodes = set() self.__net_timeout = options.get('sockettimeoutms') self.__conn_timeout = options.get('connecttimeoutms') self.__use_ssl = options.get('ssl', False) if self.__use_ssl and not pool.have_ssl: raise ConfigurationError("The ssl module is not available. If you " "are using a python version previous to " "2.6 you must install the ssl package " "from PyPI.") if options.get('use_greenlets', False): if not pool.have_greenlet: raise ConfigurationError( "The greenlet module is not available. " "Install the greenlet package from PyPI.") self.pool_class = pool.GreenletPool else: self.pool_class = pool.Pool self.__pool = self.pool_class(None, self.__max_pool_size, self.__net_timeout, self.__conn_timeout, self.__use_ssl) self.__document_class = document_class self.__tz_aware = common.validate_boolean('tz_aware', tz_aware) self.__auto_start_request = options.get('auto_start_request', False) # cache of existing indexes used by ensure_index ops self.__index_cache = {} self.__auth_credentials = {} super(MongoClient, self).__init__(**options) if self.slave_okay: warnings.warn( "slave_okay is deprecated. Please " "use read_preference instead.", DeprecationWarning) if _connect: try: self.__find_node(seeds) except AutoReconnect, e: # ConnectionFailure makes more sense here than AutoReconnect raise ConnectionFailure(str(e))
def __init__(self, host=None, port=None, max_pool_size=10, network_timeout=None, document_class=dict, tz_aware=False, _connect=True, **kwargs): """Create a new connection to a single MongoDB instance at *host:port*. The resultant connection object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, :class:`~pymongo.errors.ConnectionFailure` is raised. If auto-reconnection will be performed, :class:`~pymongo.errors.AutoReconnect` will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. Raises :class:`TypeError` if port is not an instance of ``int``. Raises :class:`~pymongo.errors.ConnectionFailure` if the connection cannot be made. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ':', '/', '+' and '@' must be escaped following RFC 2396. :Parameters: - `host` (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost) - `port` (optional): port number on which to connect - `max_pool_size` (optional): The maximum size limit for the connection pool. - `network_timeout` (optional): timeout (in seconds) to use for socket operations - default is no timeout - `document_class` (optional): default class to use for documents returned from queries on this connection - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`Connection` will be timezone aware (otherwise they will be naive) Other optional parameters can be passed as keyword arguments: - `safe`: Use getlasterror for each write operation? - `j` or `journal`: Block until write operations have been committed to the journal. Ignored if the server is running without journaling. Implies safe=True. - `w`: (integer or string) If this is a replica set write operations won't return until they have been replicated to the specified number or tagged set of servers. `w` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). Implies safe=True. - `wtimeout`: Used in conjunction with `j` and/or `w`. Wait this many milliseconds for journal acknowledgement and/or write replication. Implies safe=True. - `fsync`: Force the database to fsync all files before returning When used with `j` the server awaits the next group commit before returning. Implies safe=True. - `replicaSet`: The name of the replica set to connect to. The driver will verify that the replica set it connects to matches this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. - `socketTimeoutMS`: How long a send or receive on a socket can take before timing out. - `connectTimeoutMS`: How long a connection can take to be opened before timing out. - `ssl`: If True, create the connection to the server using SSL. - `read_preference`: The read preference for this connection. See :class:`~pymongo.read_preferences.ReadPreference` for available options. - `auto_start_request`: If True (the default), each thread that accesses this Connection has a socket allocated to it for the thread's lifetime. This ensures consistent reads, even if you read after an unsafe write. - `use_greenlets` (optional): if ``True``, :meth:`start_request()` will ensure that the current greenlet uses the same socket for all operations until :meth:`end_request()` - `slave_okay` or `slaveOk` (deprecated): Use `read_preference` instead. .. seealso:: :meth:`end_request` .. versionchanged:: 2.3 Added support for failover between mongos seed list members. .. versionchanged:: 2.2 Added `auto_start_request` option back. Added `use_greenlets` option. .. versionchanged:: 2.1 Support `w` = integer or string. Added `ssl` option. DEPRECATED slave_okay/slaveOk. .. versionchanged:: 2.0 `slave_okay` is a pure keyword argument. Added support for safe, and getlasterror options as keyword arguments. .. versionchanged:: 1.11 Added `max_pool_size`. Completely removed previously deprecated `pool_size`, `auto_start_request` and `timeout` parameters. .. versionchanged:: 1.8 The `host` parameter can now be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. .. versionadded:: 1.8 The `tz_aware` parameter. .. versionadded:: 1.7 The `document_class` parameter. .. versionadded:: 1.1 The `network_timeout` parameter. .. mongodoc:: connections """ if host is None: host = self.HOST if isinstance(host, str): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") seeds = set() username = None password = None db = None options = {} for entity in host: if "://" in entity: if entity.startswith("mongodb://"): res = uri_parser.parse_uri(entity, port) seeds.update(res["nodelist"]) username = res["username"] or username password = res["password"] or password db = res["database"] or db options = res["options"] else: idx = entity.find("://") raise InvalidURI("Invalid URI scheme: " "%s" % (entity[:idx],)) else: seeds.update(uri_parser.split_hosts(entity, port)) if not seeds: raise ConfigurationError("need to specify at least one host") self.__nodes = seeds self.__host = None self.__port = None self.__is_primary = False self.__is_mongos = False for option, value in kwargs.items(): option, value = common.validate(option, value) options[option] = value self.__max_pool_size = common.validate_positive_integer( 'max_pool_size', max_pool_size) self.__cursor_manager = CursorManager(self) self.__repl = options.get('replicaset') if len(seeds) == 1 and not self.__repl: self.__direct = True else: self.__direct = False self.__nodes = set() if network_timeout is not None: if (not isinstance(network_timeout, (int, float)) or network_timeout <= 0): raise ConfigurationError("network_timeout must " "be a positive integer") self.__net_timeout = (network_timeout or options.get('sockettimeoutms')) self.__conn_timeout = options.get('connecttimeoutms') self.__use_ssl = options.get('ssl', False) if self.__use_ssl and not pool.have_ssl: raise ConfigurationError("The ssl module is not available. If you " "are using a python version previous to " "2.6 you must install the ssl package " "from PyPI.") if options.get('use_greenlets', False): if not pool.have_greenlet: raise ConfigurationError( "The greenlet module is not available. " "Install the greenlet package from PyPI." ) self.pool_class = pool.GreenletPool else: self.pool_class = pool.Pool self.__pool = self.pool_class( None, self.__max_pool_size, self.__net_timeout, self.__conn_timeout, self.__use_ssl ) self.__document_class = document_class self.__tz_aware = common.validate_boolean('tz_aware', tz_aware) self.__auto_start_request = options.get('auto_start_request', True) # cache of existing indexes used by ensure_index ops self.__index_cache = {} self.__auth_credentials = {} super(Connection, self).__init__(**options) if self.slave_okay: warnings.warn("slave_okay is deprecated. Please " "use read_preference instead.", DeprecationWarning) if _connect: self.__find_node(seeds) if db and username is None: warnings.warn("must provide a username and password " "to authenticate to %s" % (db,)) if username: db = db or "admin" if not self[db].authenticate(username, password): raise ConfigurationError("authentication failed")
class Connection(common.BaseObject): """Connection to MongoDB. """ HOST = "localhost" PORT = 27017 __max_bson_size = 4 * 1024 * 1024 def __init__(self, host=None, port=None, max_pool_size=10, network_timeout=None, document_class=dict, tz_aware=False, _connect=True, **kwargs): """Create a new connection to a single MongoDB instance at *host:port*. The resultant connection object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, :class:`~pymongo.errors.ConnectionFailure` is raised. If auto-reconnection will be performed, :class:`~pymongo.errors.AutoReconnect` will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. Raises :class:`TypeError` if port is not an instance of ``int``. Raises :class:`~pymongo.errors.ConnectionFailure` if the connection cannot be made. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ':', '/', '+' and '@' must be escaped following RFC 2396. :Parameters: - `host` (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost) - `port` (optional): port number on which to connect - `max_pool_size` (optional): The maximum size limit for the connection pool. - `network_timeout` (optional): timeout (in seconds) to use for socket operations - default is no timeout - `document_class` (optional): default class to use for documents returned from queries on this connection - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`Connection` will be timezone aware (otherwise they will be naive) Other optional parameters can be passed as keyword arguments: - `safe`: Use getlasterror for each write operation? - `j` or `journal`: Block until write operations have been committed to the journal. Ignored if the server is running without journaling. Implies safe=True. - `w`: (integer or string) If this is a replica set write operations won't return until they have been replicated to the specified number or tagged set of servers. `w` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). Implies safe=True. - `wtimeout`: Used in conjunction with `j` and/or `w`. Wait this many milliseconds for journal acknowledgement and/or write replication. Implies safe=True. - `fsync`: Force the database to fsync all files before returning When used with `j` the server awaits the next group commit before returning. Implies safe=True. - `replicaSet`: The name of the replica set to connect to. The driver will verify that the replica set it connects to matches this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. - `socketTimeoutMS`: How long a send or receive on a socket can take before timing out. - `connectTimeoutMS`: How long a connection can take to be opened before timing out. - `ssl`: If True, create the connection to the server using SSL. - `read_preference`: The read preference for this connection. See :class:`~pymongo.read_preferences.ReadPreference` for available options. - `auto_start_request`: If True (the default), each thread that accesses this Connection has a socket allocated to it for the thread's lifetime. This ensures consistent reads, even if you read after an unsafe write. - `use_greenlets` (optional): if ``True``, :meth:`start_request()` will ensure that the current greenlet uses the same socket for all operations until :meth:`end_request()` - `slave_okay` or `slaveOk` (deprecated): Use `read_preference` instead. .. seealso:: :meth:`end_request` .. versionchanged:: 2.3 Added support for failover between mongos seed list members. .. versionchanged:: 2.2 Added `auto_start_request` option back. Added `use_greenlets` option. .. versionchanged:: 2.1 Support `w` = integer or string. Added `ssl` option. DEPRECATED slave_okay/slaveOk. .. versionchanged:: 2.0 `slave_okay` is a pure keyword argument. Added support for safe, and getlasterror options as keyword arguments. .. versionchanged:: 1.11 Added `max_pool_size`. Completely removed previously deprecated `pool_size`, `auto_start_request` and `timeout` parameters. .. versionchanged:: 1.8 The `host` parameter can now be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. .. versionadded:: 1.8 The `tz_aware` parameter. .. versionadded:: 1.7 The `document_class` parameter. .. versionadded:: 1.1 The `network_timeout` parameter. .. mongodoc:: connections """ if host is None: host = self.HOST if isinstance(host, str): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") seeds = set() username = None password = None db = None options = {} for entity in host: if "://" in entity: if entity.startswith("mongodb://"): res = uri_parser.parse_uri(entity, port) seeds.update(res["nodelist"]) username = res["username"] or username password = res["password"] or password db = res["database"] or db options = res["options"] else: idx = entity.find("://") raise InvalidURI("Invalid URI scheme: " "%s" % (entity[:idx],)) else: seeds.update(uri_parser.split_hosts(entity, port)) if not seeds: raise ConfigurationError("need to specify at least one host") self.__nodes = seeds self.__host = None self.__port = None self.__is_primary = False self.__is_mongos = False for option, value in kwargs.items(): option, value = common.validate(option, value) options[option] = value self.__max_pool_size = common.validate_positive_integer( 'max_pool_size', max_pool_size) self.__cursor_manager = CursorManager(self) self.__repl = options.get('replicaset') if len(seeds) == 1 and not self.__repl: self.__direct = True else: self.__direct = False self.__nodes = set() if network_timeout is not None: if (not isinstance(network_timeout, (int, float)) or network_timeout <= 0): raise ConfigurationError("network_timeout must " "be a positive integer") self.__net_timeout = (network_timeout or options.get('sockettimeoutms')) self.__conn_timeout = options.get('connecttimeoutms') self.__use_ssl = options.get('ssl', False) if self.__use_ssl and not pool.have_ssl: raise ConfigurationError("The ssl module is not available. If you " "are using a python version previous to " "2.6 you must install the ssl package " "from PyPI.") if options.get('use_greenlets', False): if not pool.have_greenlet: raise ConfigurationError( "The greenlet module is not available. " "Install the greenlet package from PyPI." ) self.pool_class = pool.GreenletPool else: self.pool_class = pool.Pool self.__pool = self.pool_class( None, self.__max_pool_size, self.__net_timeout, self.__conn_timeout, self.__use_ssl ) self.__document_class = document_class self.__tz_aware = common.validate_boolean('tz_aware', tz_aware) self.__auto_start_request = options.get('auto_start_request', True) # cache of existing indexes used by ensure_index ops self.__index_cache = {} self.__auth_credentials = {} super(Connection, self).__init__(**options) if self.slave_okay: warnings.warn("slave_okay is deprecated. Please " "use read_preference instead.", DeprecationWarning) if _connect: self.__find_node(seeds) if db and username is None: warnings.warn("must provide a username and password " "to authenticate to %s" % (db,)) if username: db = db or "admin" if not self[db].authenticate(username, password): raise ConfigurationError("authentication failed") def _cached(self, dbname, coll, index): """Test if `index` is cached. """ cache = self.__index_cache now = datetime.datetime.utcnow() return (dbname in cache and coll in cache[dbname] and index in cache[dbname][coll] and now < cache[dbname][coll][index]) def _cache_index(self, database, collection, index, cache_for): """Add an index to the index cache for ensure_index operations. """ now = datetime.datetime.utcnow() expire = datetime.timedelta(seconds=cache_for) + now if database not in self.__index_cache: self.__index_cache[database] = {} self.__index_cache[database][collection] = {} self.__index_cache[database][collection][index] = expire elif collection not in self.__index_cache[database]: self.__index_cache[database][collection] = {} self.__index_cache[database][collection][index] = expire else: self.__index_cache[database][collection][index] = expire def _purge_index(self, database_name, collection_name=None, index_name=None): """Purge an index from the index cache. If `index_name` is None purge an entire collection. If `collection_name` is None purge an entire database. """ if not database_name in self.__index_cache: return if collection_name is None: del self.__index_cache[database_name] return if not collection_name in self.__index_cache[database_name]: return if index_name is None: del self.__index_cache[database_name][collection_name] return if index_name in self.__index_cache[database_name][collection_name]: del self.__index_cache[database_name][collection_name][index_name] def _cache_credentials(self, db_name, username, password): """Add credentials to the database authentication cache for automatic login when a socket is created. If credentials are already cached for `db_name` they will be replaced. """ self.__auth_credentials[db_name] = (username, password) def _purge_credentials(self, db_name=None): """Purge credentials from the database authentication cache. If `db_name` is None purge credentials for all databases. """ if db_name is None: self.__auth_credentials.clear() elif db_name in self.__auth_credentials: del self.__auth_credentials[db_name] def __check_auth(self, sock_info): """Authenticate using cached database credentials. If credentials for the 'admin' database are available only this database is authenticated, since this gives global access. """ authset = sock_info.authset names = set(self.__auth_credentials.keys()) # Logout from any databases no longer listed in the credentials cache. for dbname in authset - names: try: self.__simple_command(sock_info, dbname, {'logout': 1}) # TODO: We used this socket to logout. Fix logout so we don't # have to catch this. except OperationFailure: pass authset.discard(dbname) # Once logged into the admin database we can access anything. if "admin" in authset: return if "admin" in self.__auth_credentials: username, password = self.__auth_credentials["admin"] self.__auth(sock_info, 'admin', username, password) authset.add('admin') else: for db_name in names - authset: user, pwd = self.__auth_credentials[db_name] self.__auth(sock_info, db_name, user, pwd) authset.add(db_name) @property def host(self): """Current connected host. .. versionchanged:: 1.3 ``host`` is now a property rather than a method. """ return self.__host @property def port(self): """Current connected port. .. versionchanged:: 1.3 ``port`` is now a property rather than a method. """ return self.__port @property def is_primary(self): """If this Connection is connected to a standalone, a replica-set primary, or the master of a master-slave set. .. versionadded:: 2.3 """ return self.__is_primary @property def is_mongos(self): """If this Connection is connected to mongos. .. versionadded:: 2.3 """ return self.__is_mongos @property def max_pool_size(self): """The maximum pool size limit set for this connection. .. versionadded:: 1.11 """ return self.__max_pool_size @property def nodes(self): """List of all known nodes. Includes both nodes specified when the :class:`Connection` was created, as well as nodes discovered through the replica set discovery mechanism. .. versionadded:: 1.8 """ return self.__nodes @property def auto_start_request(self): return self.__auto_start_request def get_document_class(self): return self.__document_class def set_document_class(self, klass): self.__document_class = klass document_class = property(get_document_class, set_document_class, doc="""Default class to use for documents returned on this connection. .. versionadded:: 1.7 """) @property def tz_aware(self): """Does this connection return timezone-aware datetimes? See the `tz_aware` parameter to :meth:`Connection`. .. versionadded:: 1.8 """ return self.__tz_aware @property def max_bson_size(self): """Return the maximum size BSON object the connected server accepts in bytes. Defaults to 4MB in server < 1.7.4. .. versionadded:: 1.10 """ return self.__max_bson_size def __simple_command(self, sock_info, dbname, spec): """Send a command to the server. """ rqst_id, msg, _ = message.query(0, dbname + '.$cmd', 0, -1, spec) start = time.time() try: sock_info.sock.sendall(msg) response = self.__receive_message_on_socket(1, rqst_id, sock_info) except: sock_info.close() raise end = time.time() response = helpers._unpack_response(response)['data'][0] msg = "command %r failed: %%s" % spec helpers._check_command_response(response, None, msg) return response, end - start def __auth(self, sock_info, dbname, user, passwd): """Authenticate socket against database `dbname`. """ # Get a nonce response, _ = self.__simple_command(sock_info, dbname, {'getnonce': 1}) nonce = response['nonce'] key = helpers._auth_key(nonce, user, passwd) # Actually authenticate query = SON([('authenticate', 1), ('user', user), ('nonce', nonce), ('key', key)]) self.__simple_command(sock_info, dbname, query) def __try_node(self, node): """Try to connect to this node and see if it works for our connection type. Returns ((host, port), ismaster, isdbgrid, res_time). :Parameters: - `node`: The (host, port) pair to try. """ self.disconnect() self.__host, self.__port = node # Call 'ismaster' directly so we can get a response time. sock_info = self.__socket() response, res_time = self.__simple_command(sock_info, 'admin', {'ismaster': 1}) self.__pool.maybe_return_socket(sock_info) # Are we talking to a mongos? isdbgrid = response.get('msg', '') == 'isdbgrid' if "maxBsonObjectSize" in response: self.__max_bson_size = response["maxBsonObjectSize"] # Replica Set? if not self.__direct: # Check that this host is part of the given replica set. if self.__repl: set_name = response.get('setName') # The 'setName' field isn't returned by mongod before 1.6.2 # so we can't assume that if it's missing this host isn't in # the specified set. if set_name and set_name != self.__repl: raise ConfigurationError("%s:%d is not a member of " "replica set %s" % (node[0], node[1], self.__repl)) if "hosts" in response: self.__nodes = set([_partition_node(h) for h in response["hosts"]]) else: # The user passed a seed list of standalone or # mongos instances. self.__nodes.add(node) if response["ismaster"]: return node, True, isdbgrid, res_time elif "primary" in response: candidate = _partition_node(response["primary"]) return self.__try_node(candidate) # Explain why we aren't using this connection. raise AutoReconnect('%s:%d is not primary or master' % node) # Direct connection if response.get("arbiterOnly", False) and not self.__direct: raise ConfigurationError("%s:%d is an arbiter" % node) return node, response['ismaster'], isdbgrid, res_time def __pick_nearest(self, candidates): """Return the 'nearest' candidate based on response time. """ latency = self.secondary_acceptable_latency_ms # Only used for mongos high availability, res_time is in seconds. fastest = min([res_time for candidate, res_time in candidates]) near_candidates = [ candidate for candidate, res_time in candidates if res_time - fastest < latency / 1000.0 ] node = random.choice(near_candidates) # Clear the pool from the last choice. self.disconnect() self.__host, self.__port = node return node def __find_node(self, seeds=None): """Find a host, port pair suitable for our connection type. If only one host was supplied to __init__ see if we can connect to it. Don't check if the host is a master/primary so we can make a direct connection to read from a secondary or send commands to an arbiter. If more than one host was supplied treat them as a seed list for connecting to a replica set or to support high availability for mongos. If connecting to a replica set try to find the primary and fail if we can't, possibly updating any replSet information on success. If a mongos seed list was provided find the "nearest" mongos and return it. Otherwise we iterate through the list trying to find a host we can send write operations to. Sets __host and __port so that :attr:`host` and :attr:`port` will return the address of the connected host. Sets __is_primary to True if this is a primary or master, else False. Sets __is_mongos to True if the connection is to a mongos. """ errors = [] mongos_candidates = [] candidates = seeds or self.__nodes.copy() for candidate in candidates: try: node, ismaster, isdbgrid, res_time = self.__try_node(candidate) self.__is_primary = ismaster self.__is_mongos = isdbgrid # No need to calculate nearest if we only have one mongos. if isdbgrid and not self.__direct: mongos_candidates.append((node, res_time)) continue elif len(mongos_candidates): raise ConfigurationError("Seed list cannot contain a mix " "of mongod and mongos instances.") return node except Exception as why: errors.append(str(why)) # If we have a mongos seed list, pick the "nearest" member. if len(mongos_candidates): self.__is_mongos = True return self.__pick_nearest(mongos_candidates) # Otherwise, try any hosts we discovered that were not in the seed list. for candidate in self.__nodes - candidates: try: node, ismaster, isdbgrid, _ = self.__try_node(candidate) self.__is_primary = ismaster self.__is_mongos = isdbgrid return node except Exception as why: errors.append(str(why)) # Couldn't find a suitable host. self.disconnect() raise AutoReconnect(', '.join(errors)) def __socket(self): """Get a SocketInfo from the pool. """ host, port = (self.__host, self.__port) if host is None or port is None: host, port = self.__find_node() try: if self.__auto_start_request: # No effect if a request already started self.start_request() sock_info = self.__pool.get_socket((host, port)) except socket.error as why: self.disconnect() raise AutoReconnect("could not connect to " "%s:%d: %s" % (host, port, str(why))) if self.__auth_credentials: self.__check_auth(sock_info) return sock_info def disconnect(self): """Disconnect from MongoDB. Disconnecting will close all underlying sockets in the connection pool. If the :class:`Connection` is used again it will be automatically re-opened. Care should be taken to make sure that :meth:`disconnect` is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results. .. seealso:: :meth:`end_request` .. versionadded:: 1.3 """ self.__pool.reset() self.__host = None self.__port = None def close(self): """Alias for :meth:`disconnect` Disconnecting will close all underlying sockets in the connection pool. If the :class:`Connection` is used again it will be automatically re-opened. Care should be taken to make sure that :meth:`disconnect` is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results. .. seealso:: :meth:`end_request` .. versionadded:: 2.1 """ self.disconnect() def set_cursor_manager(self, manager_class): """Set this connection's cursor manager. Raises :class:`TypeError` if `manager_class` is not a subclass of :class:`~pymongo.cursor_manager.CursorManager`. A cursor manager handles closing cursors. Different managers can implement different policies in terms of when to actually kill a cursor that has been closed. :Parameters: - `manager_class`: cursor manager to use .. versionchanged:: 2.1+ Deprecated support for external cursor managers. """ warnings.warn("Support for external cursor managers is deprecated " "and will be removed in PyMongo 3.0.", DeprecationWarning) manager = manager_class(self) if not isinstance(manager, CursorManager): raise TypeError("manager_class must be a subclass of " "CursorManager") self.__cursor_manager = manager def __check_response_to_last_error(self, response): """Check a response to a lastError message for errors. `response` is a byte string representing a response to the message. If it represents an error response we raise OperationFailure. Return the response as a document. """ response = helpers._unpack_response(response) assert response["number_returned"] == 1 error = response["data"][0] helpers._check_command_response(error, self.disconnect) error_msg = error.get("err", "") if error_msg is None: return error if error_msg.startswith("not master"): self.disconnect() raise AutoReconnect(error_msg) details = error # mongos returns the error code in an error object # for some errors. if "errObjects" in error: for errobj in error["errObjects"]: if errobj["err"] == error_msg: details = errobj break if "code" in details: if details["code"] in [11000, 11001, 12582]: raise DuplicateKeyError(details["err"]) else: raise OperationFailure(details["err"], details["code"]) else: raise OperationFailure(details["err"]) def __check_bson_size(self, message): """Make sure the message doesn't include BSON documents larger than the connected server will accept. :Parameters: - `message`: message to check """ if len(message) == 3: (request_id, data, max_doc_size) = message if max_doc_size > self.__max_bson_size: raise InvalidDocument("BSON document too large (%d bytes)" " - the connected server supports" " BSON document sizes up to %d" " bytes." % (max_doc_size, self.__max_bson_size)) return (request_id, data) else: # get_more and kill_cursors messages # don't include BSON documents. return message def _send_message(self, message, with_last_error=False): """Say something to Mongo. Raises ConnectionFailure if the message cannot be sent. Raises OperationFailure if `with_last_error` is ``True`` and the response to the getLastError call returns an error. Return the response from lastError, or ``None`` if `with_last_error` is ``False``. :Parameters: - `message`: message to send - `with_last_error`: check getLastError status after sending the message """ sock_info = self.__socket() try: (request_id, data) = self.__check_bson_size(message) sock_info.sock.sendall(data) # Safe mode. We pack the message together with a lastError # message and send both. We then get the response (to the # lastError) and raise OperationFailure if it is an error # response. rv = None if with_last_error: response = self.__receive_message_on_socket(1, request_id, sock_info) rv = self.__check_response_to_last_error(response) self.__pool.maybe_return_socket(sock_info) return rv except OperationFailure: self.__pool.maybe_return_socket(sock_info) raise except (ConnectionFailure, socket.error) as e: self.disconnect() raise AutoReconnect(str(e)) except: sock_info.close() raise def __receive_data_on_socket(self, length, sock_info): """Lowest level receive operation. Takes length to receive and repeatedly calls recv until able to return a buffer of that length, raising ConnectionFailure on error. """ chunks = [] while length: chunk = sock_info.sock.recv(length) if chunk == EMPTY: raise ConnectionFailure("connection closed") length -= len(chunk) chunks.append(chunk) return EMPTY.join(chunks) def __receive_message_on_socket(self, operation, request_id, sock_info): """Receive a message in response to `request_id` on `sock`. Returns the response data with the header removed. """ header = self.__receive_data_on_socket(16, sock_info) length = struct.unpack("<i", header[:4])[0] assert request_id == struct.unpack("<i", header[8:12])[0], \ "ids don't match %r %r" % (request_id, struct.unpack("<i", header[8:12])[0]) assert operation == struct.unpack("<i", header[12:])[0] return self.__receive_data_on_socket(length - 16, sock_info) def __send_and_receive(self, message, sock_info): """Send a message on the given socket and return the response data. """ (request_id, data) = self.__check_bson_size(message) try: sock_info.sock.sendall(data) return self.__receive_message_on_socket(1, request_id, sock_info) except: sock_info.close() raise # we just ignore _must_use_master here: it's only relevant for # MasterSlaveConnection instances. def _send_message_with_response(self, message, _must_use_master=False, **kwargs): """Send a message to Mongo and return the response. Sends the given message and returns the response. :Parameters: - `message`: (request_id, data) pair making up the message to send """ sock_info = self.__socket() try: try: if "network_timeout" in kwargs: sock_info.sock.settimeout(kwargs["network_timeout"]) return self.__send_and_receive(message, sock_info) except (ConnectionFailure, socket.error) as e: self.disconnect() raise AutoReconnect(str(e)) finally: if "network_timeout" in kwargs: try: # Restore the socket's original timeout and return it to # the pool sock_info.sock.settimeout(self.__net_timeout) self.__pool.maybe_return_socket(sock_info) except socket.error: # There was an exception and we've closed the socket pass else: self.__pool.maybe_return_socket(sock_info) def start_request(self): """Ensure the current thread or greenlet always uses the same socket until it calls :meth:`end_request`. This ensures consistent reads, even if you read after an unsafe write. In Python 2.6 and above, or in Python 2.5 with "from __future__ import with_statement", :meth:`start_request` can be used as a context manager: >>> connection = pymongo.Connection(auto_start_request=False) >>> db = connection.test >>> _id = db.test_collection.insert({}, safe=True) >>> with connection.start_request(): ... for i in range(100): ... db.test_collection.update({'_id': _id}, {'$set': {'i':i}}) ... ... # Definitely read the document after the final update completes ... print db.test_collection.find({'_id': _id}) .. versionadded:: 2.2 The :class:`~pymongo.pool.Request` return value. :meth:`start_request` previously returned None """ self.__pool.start_request() return pool.Request(self) def in_request(self): """True if :meth:`start_request` has been called, but not :meth:`end_request`, or if `auto_start_request` is True and :meth:`end_request` has not been called in this thread or greenlet. """ return self.__pool.in_request() def end_request(self): """Undo :meth:`start_request` and allow this thread's connection to return to the pool. Calling :meth:`end_request` allows the :class:`~socket.socket` that has been reserved for this thread by :meth:`start_request` to be returned to the pool. Other threads will then be able to re-use that :class:`~socket.socket`. If your application uses many threads, or has long-running threads that infrequently perform MongoDB operations, then judicious use of this method can lead to performance gains. Care should be taken, however, to make sure that :meth:`end_request` is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results. """ self.__pool.end_request() def __eq__(self, other): if isinstance(other, Connection): us = (self.__host, self.__port) them = (other.__host, other.__port) return us == them return NotImplemented def __repr__(self): if len(self.__nodes) == 1: return "Connection(%r, %r)" % (self.__host, self.__port) else: return "Connection(%r)" % ["%s:%d" % n for n in self.__nodes] def __getattr__(self, name): """Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get """ return database.Database(self, name) def __getitem__(self, name): """Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get """ return self.__getattr__(name) def close_cursor(self, cursor_id): """Close a single database cursor. Raises :class:`TypeError` if `cursor_id` is not an instance of ``(int, long)``. What closing the cursor actually means depends on this connection's cursor manager. :Parameters: - `cursor_id`: id of cursor to close .. seealso:: :meth:`set_cursor_manager` and the :mod:`~pymongo.cursor_manager` module """ if not isinstance(cursor_id, int): raise TypeError("cursor_id must be an instance of (int, long)") self.__cursor_manager.close(cursor_id) def kill_cursors(self, cursor_ids): """Send a kill cursors message with the given ids. Raises :class:`TypeError` if `cursor_ids` is not an instance of ``list``. :Parameters: - `cursor_ids`: list of cursor ids to kill """ if not isinstance(cursor_ids, list): raise TypeError("cursor_ids must be a list") return self._send_message(message.kill_cursors(cursor_ids)) def server_info(self): """Get information about the MongoDB server we're connected to. """ return self.admin.command("buildinfo") def database_names(self): """Get a list of the names of all databases on the connected server. """ return [db["name"] for db in self.admin.command("listDatabases")["databases"]] def drop_database(self, name_or_database): """Drop a database. Raises :class:`TypeError` if `name_or_database` is not an instance of :class:`basestring` (:class:`str` in python 3) or Database. :Parameters: - `name_or_database`: the name of a database to drop, or a :class:`~pymongo.database.Database` instance representing the database to drop """ name = name_or_database if isinstance(name, database.Database): name = name.name if not isinstance(name, str): raise TypeError("name_or_database must be an instance of " "%s or Database" % (str.__name__,)) self._purge_index(name) self[name].command("dropDatabase") def copy_database(self, from_name, to_name, from_host=None, username=None, password=None): """Copy a database, potentially from another host. Raises :class:`TypeError` if `from_name` or `to_name` is not an instance of :class:`basestring` (:class:`str` in python 3). Raises :class:`~pymongo.errors.InvalidName` if `to_name` is not a valid database name. If `from_host` is ``None`` the current host is used as the source. Otherwise the database is copied from `from_host`. If the source database requires authentication, `username` and `password` must be specified. :Parameters: - `from_name`: the name of the source database - `to_name`: the name of the target database - `from_host` (optional): host name to copy from - `username` (optional): username for source database - `password` (optional): password for source database .. note:: Specifying `username` and `password` requires server version **>= 1.3.3+**. .. versionadded:: 1.5 """ if not isinstance(from_name, str): raise TypeError("from_name must be an instance " "of %s" % (str.__name__,)) if not isinstance(to_name, str): raise TypeError("to_name must be an instance " "of %s" % (str.__name__,)) database._check_name(to_name) command = {"fromdb": from_name, "todb": to_name} if from_host is not None: command["fromhost"] = from_host in_request = self.in_request() try: if not in_request: self.start_request() if username is not None: nonce = self.admin.command("copydbgetnonce", fromhost=from_host)["nonce"] command["username"] = username command["nonce"] = nonce command["key"] = helpers._auth_key(nonce, username, password) return self.admin.command("copydb", **command) finally: if not in_request: self.end_request() @property def is_locked(self): """Is this server locked? While locked, all write operations are blocked, although read operations may still be allowed. Use :meth:`~pymongo.connection.Connection.unlock` to unlock. .. versionadded:: 2.0 """ ops = self.admin.current_op() return bool(ops.get('fsyncLock', 0)) def fsync(self, **kwargs): """Flush all pending writes to datafiles. :Parameters: Optional parameters can be passed as keyword arguments: - `lock`: If True lock the server to disallow writes. - `async`: If True don't block while synchronizing. .. warning:: `async` and `lock` can not be used together. .. warning:: MongoDB does not support the `async` option on Windows and will raise an exception on that platform. .. versionadded:: 2.0 """ self.admin.command("fsync", **kwargs) def unlock(self): """Unlock a previously locked server. .. versionadded:: 2.0 """ self.admin['$cmd'].sys.unlock.find_one() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.disconnect() def __iter__(self): return self def __next__(self): raise TypeError("'Connection' object is not iterable")
class Connection(common.BaseObject): """Connection to MongoDB. """ HOST = "localhost" PORT = 27017 __max_bson_size = 4 * 1024 * 1024 def __init__(self, host=None, port=None, max_pool_size=10, network_timeout=None, document_class=dict, tz_aware=False, _connect=True, **kwargs): """Create a new connection to a single MongoDB instance at *host:port*. The resultant connection object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, :class:`~pymongo.errors.ConnectionFailure` is raised. If auto-reconnection will be performed, :class:`~pymongo.errors.AutoReconnect` will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. Raises :class:`TypeError` if port is not an instance of ``int``. Raises :class:`~pymongo.errors.ConnectionFailure` if the connection cannot be made. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ':', '/', '+' and '@' must be escaped following RFC 2396. :Parameters: - `host` (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost) - `port` (optional): port number on which to connect - `max_pool_size` (optional): The maximum size limit for the connection pool. - `network_timeout` (optional): timeout (in seconds) to use for socket operations - default is no timeout - `document_class` (optional): default class to use for documents returned from queries on this connection - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`Connection` will be timezone aware (otherwise they will be naive) Other optional parameters can be passed as keyword arguments: - `safe`: Use getlasterror for each write operation? - `j` or `journal`: Block until write operations have been committed to the journal. Ignored if the server is running without journaling. Implies safe=True. - `w`: (integer or string) If this is a replica set write operations won't return until they have been replicated to the specified number or tagged set of servers. `w` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). Implies safe=True. - `wtimeout`: Used in conjunction with `j` and/or `w`. Wait this many milliseconds for journal acknowledgement and/or write replication. Implies safe=True. - `fsync`: Force the database to fsync all files before returning When used with `j` the server awaits the next group commit before returning. Implies safe=True. - `replicaSet`: The name of the replica set to connect to. The driver will verify that the replica set it connects to matches this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. - `socketTimeoutMS`: How long a send or receive on a socket can take before timing out. - `connectTimeoutMS`: How long a connection can take to be opened before timing out. - `ssl`: If True, create the connection to the server using SSL. - `read_preference`: The read preference for this connection. See :class:`~pymongo.read_preferences.ReadPreference` for available options. - `auto_start_request`: If True (the default), each thread that accesses this Connection has a socket allocated to it for the thread's lifetime. This ensures consistent reads, even if you read after an unsafe write. - `use_greenlets` (optional): if ``True``, :meth:`start_request()` will ensure that the current greenlet uses the same socket for all operations until :meth:`end_request()` - `slave_okay` or `slaveOk` (deprecated): Use `read_preference` instead. .. seealso:: :meth:`end_request` .. versionchanged:: 2.3 Added support for failover between mongos seed list members. .. versionchanged:: 2.2 Added `auto_start_request` option back. Added `use_greenlets` option. .. versionchanged:: 2.1 Support `w` = integer or string. Added `ssl` option. DEPRECATED slave_okay/slaveOk. .. versionchanged:: 2.0 `slave_okay` is a pure keyword argument. Added support for safe, and getlasterror options as keyword arguments. .. versionchanged:: 1.11 Added `max_pool_size`. Completely removed previously deprecated `pool_size`, `auto_start_request` and `timeout` parameters. .. versionchanged:: 1.8 The `host` parameter can now be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. .. versionadded:: 1.8 The `tz_aware` parameter. .. versionadded:: 1.7 The `document_class` parameter. .. versionadded:: 1.1 The `network_timeout` parameter. .. mongodoc:: connections """ if host is None: host = self.HOST if isinstance(host, str): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") seeds = set() username = None password = None db = None options = {} for entity in host: if "://" in entity: if entity.startswith("mongodb://"): res = uri_parser.parse_uri(entity, port) seeds.update(res["nodelist"]) username = res["username"] or username password = res["password"] or password db = res["database"] or db options = res["options"] else: idx = entity.find("://") raise InvalidURI("Invalid URI scheme: " "%s" % (entity[:idx], )) else: seeds.update(uri_parser.split_hosts(entity, port)) if not seeds: raise ConfigurationError("need to specify at least one host") self.__nodes = seeds self.__host = None self.__port = None self.__is_primary = False self.__is_mongos = False for option, value in kwargs.items(): option, value = common.validate(option, value) options[option] = value self.__max_pool_size = common.validate_positive_integer( 'max_pool_size', max_pool_size) self.__cursor_manager = CursorManager(self) self.__repl = options.get('replicaset') if len(seeds) == 1 and not self.__repl: self.__direct = True else: self.__direct = False self.__nodes = set() if network_timeout is not None: if (not isinstance(network_timeout, (int, float)) or network_timeout <= 0): raise ConfigurationError("network_timeout must " "be a positive integer") self.__net_timeout = (network_timeout or options.get('sockettimeoutms')) self.__conn_timeout = options.get('connecttimeoutms') self.__use_ssl = options.get('ssl', False) if self.__use_ssl and not pool.have_ssl: raise ConfigurationError("The ssl module is not available. If you " "are using a python version previous to " "2.6 you must install the ssl package " "from PyPI.") if options.get('use_greenlets', False): if not pool.have_greenlet: raise ConfigurationError( "The greenlet module is not available. " "Install the greenlet package from PyPI.") self.pool_class = pool.GreenletPool else: self.pool_class = pool.Pool self.__pool = self.pool_class(None, self.__max_pool_size, self.__net_timeout, self.__conn_timeout, self.__use_ssl) self.__document_class = document_class self.__tz_aware = common.validate_boolean('tz_aware', tz_aware) self.__auto_start_request = options.get('auto_start_request', True) # cache of existing indexes used by ensure_index ops self.__index_cache = {} self.__auth_credentials = {} super(Connection, self).__init__(**options) if self.slave_okay: warnings.warn( "slave_okay is deprecated. Please " "use read_preference instead.", DeprecationWarning) if _connect: self.__find_node(seeds) if db and username is None: warnings.warn("must provide a username and password " "to authenticate to %s" % (db, )) if username: db = db or "admin" if not self[db].authenticate(username, password): raise ConfigurationError("authentication failed") def _cached(self, dbname, coll, index): """Test if `index` is cached. """ cache = self.__index_cache now = datetime.datetime.utcnow() return (dbname in cache and coll in cache[dbname] and index in cache[dbname][coll] and now < cache[dbname][coll][index]) def _cache_index(self, database, collection, index, cache_for): """Add an index to the index cache for ensure_index operations. """ now = datetime.datetime.utcnow() expire = datetime.timedelta(seconds=cache_for) + now if database not in self.__index_cache: self.__index_cache[database] = {} self.__index_cache[database][collection] = {} self.__index_cache[database][collection][index] = expire elif collection not in self.__index_cache[database]: self.__index_cache[database][collection] = {} self.__index_cache[database][collection][index] = expire else: self.__index_cache[database][collection][index] = expire def _purge_index(self, database_name, collection_name=None, index_name=None): """Purge an index from the index cache. If `index_name` is None purge an entire collection. If `collection_name` is None purge an entire database. """ if not database_name in self.__index_cache: return if collection_name is None: del self.__index_cache[database_name] return if not collection_name in self.__index_cache[database_name]: return if index_name is None: del self.__index_cache[database_name][collection_name] return if index_name in self.__index_cache[database_name][collection_name]: del self.__index_cache[database_name][collection_name][index_name] def _cache_credentials(self, db_name, username, password): """Add credentials to the database authentication cache for automatic login when a socket is created. If credentials are already cached for `db_name` they will be replaced. """ self.__auth_credentials[db_name] = (username, password) def _purge_credentials(self, db_name=None): """Purge credentials from the database authentication cache. If `db_name` is None purge credentials for all databases. """ if db_name is None: self.__auth_credentials.clear() elif db_name in self.__auth_credentials: del self.__auth_credentials[db_name] def __check_auth(self, sock_info): """Authenticate using cached database credentials. If credentials for the 'admin' database are available only this database is authenticated, since this gives global access. """ authset = sock_info.authset names = set(self.__auth_credentials.keys()) # Logout from any databases no longer listed in the credentials cache. for dbname in authset - names: try: self.__simple_command(sock_info, dbname, {'logout': 1}) # TODO: We used this socket to logout. Fix logout so we don't # have to catch this. except OperationFailure: pass authset.discard(dbname) # Once logged into the admin database we can access anything. if "admin" in authset: return if "admin" in self.__auth_credentials: username, password = self.__auth_credentials["admin"] self.__auth(sock_info, 'admin', username, password) authset.add('admin') else: for db_name in names - authset: user, pwd = self.__auth_credentials[db_name] self.__auth(sock_info, db_name, user, pwd) authset.add(db_name) @property def host(self): """Current connected host. .. versionchanged:: 1.3 ``host`` is now a property rather than a method. """ return self.__host @property def port(self): """Current connected port. .. versionchanged:: 1.3 ``port`` is now a property rather than a method. """ return self.__port @property def is_primary(self): """If this Connection is connected to a standalone, a replica-set primary, or the master of a master-slave set. .. versionadded:: 2.3 """ return self.__is_primary @property def is_mongos(self): """If this Connection is connected to mongos. .. versionadded:: 2.3 """ return self.__is_mongos @property def max_pool_size(self): """The maximum pool size limit set for this connection. .. versionadded:: 1.11 """ return self.__max_pool_size @property def nodes(self): """List of all known nodes. Includes both nodes specified when the :class:`Connection` was created, as well as nodes discovered through the replica set discovery mechanism. .. versionadded:: 1.8 """ return self.__nodes @property def auto_start_request(self): return self.__auto_start_request def get_document_class(self): return self.__document_class def set_document_class(self, klass): self.__document_class = klass document_class = property(get_document_class, set_document_class, doc="""Default class to use for documents returned on this connection. .. versionadded:: 1.7 """) @property def tz_aware(self): """Does this connection return timezone-aware datetimes? See the `tz_aware` parameter to :meth:`Connection`. .. versionadded:: 1.8 """ return self.__tz_aware @property def max_bson_size(self): """Return the maximum size BSON object the connected server accepts in bytes. Defaults to 4MB in server < 1.7.4. .. versionadded:: 1.10 """ return self.__max_bson_size def __simple_command(self, sock_info, dbname, spec): """Send a command to the server. """ rqst_id, msg, _ = message.query(0, dbname + '.$cmd', 0, -1, spec) start = time.time() try: sock_info.sock.sendall(msg) response = self.__receive_message_on_socket(1, rqst_id, sock_info) except: sock_info.close() raise end = time.time() response = helpers._unpack_response(response)['data'][0] msg = "command %r failed: %%s" % spec helpers._check_command_response(response, None, msg) return response, end - start def __auth(self, sock_info, dbname, user, passwd): """Authenticate socket against database `dbname`. """ # Get a nonce response, _ = self.__simple_command(sock_info, dbname, {'getnonce': 1}) nonce = response['nonce'] key = helpers._auth_key(nonce, user, passwd) # Actually authenticate query = SON([('authenticate', 1), ('user', user), ('nonce', nonce), ('key', key)]) self.__simple_command(sock_info, dbname, query) def __try_node(self, node): """Try to connect to this node and see if it works for our connection type. Returns ((host, port), ismaster, isdbgrid, res_time). :Parameters: - `node`: The (host, port) pair to try. """ self.disconnect() self.__host, self.__port = node # Call 'ismaster' directly so we can get a response time. sock_info = self.__socket() response, res_time = self.__simple_command(sock_info, 'admin', {'ismaster': 1}) self.__pool.maybe_return_socket(sock_info) # Are we talking to a mongos? isdbgrid = response.get('msg', '') == 'isdbgrid' if "maxBsonObjectSize" in response: self.__max_bson_size = response["maxBsonObjectSize"] # Replica Set? if not self.__direct: # Check that this host is part of the given replica set. if self.__repl: set_name = response.get('setName') # The 'setName' field isn't returned by mongod before 1.6.2 # so we can't assume that if it's missing this host isn't in # the specified set. if set_name and set_name != self.__repl: raise ConfigurationError("%s:%d is not a member of " "replica set %s" % (node[0], node[1], self.__repl)) if "hosts" in response: self.__nodes = set( [_partition_node(h) for h in response["hosts"]]) else: # The user passed a seed list of standalone or # mongos instances. self.__nodes.add(node) if response["ismaster"]: return node, True, isdbgrid, res_time elif "primary" in response: candidate = _partition_node(response["primary"]) return self.__try_node(candidate) # Explain why we aren't using this connection. raise AutoReconnect('%s:%d is not primary or master' % node) # Direct connection if response.get("arbiterOnly", False) and not self.__direct: raise ConfigurationError("%s:%d is an arbiter" % node) return node, response['ismaster'], isdbgrid, res_time def __pick_nearest(self, candidates): """Return the 'nearest' candidate based on response time. """ latency = self.secondary_acceptable_latency_ms # Only used for mongos high availability, res_time is in seconds. fastest = min([res_time for candidate, res_time in candidates]) near_candidates = [ candidate for candidate, res_time in candidates if res_time - fastest < latency / 1000.0 ] node = random.choice(near_candidates) # Clear the pool from the last choice. self.disconnect() self.__host, self.__port = node return node def __find_node(self, seeds=None): """Find a host, port pair suitable for our connection type. If only one host was supplied to __init__ see if we can connect to it. Don't check if the host is a master/primary so we can make a direct connection to read from a secondary or send commands to an arbiter. If more than one host was supplied treat them as a seed list for connecting to a replica set or to support high availability for mongos. If connecting to a replica set try to find the primary and fail if we can't, possibly updating any replSet information on success. If a mongos seed list was provided find the "nearest" mongos and return it. Otherwise we iterate through the list trying to find a host we can send write operations to. Sets __host and __port so that :attr:`host` and :attr:`port` will return the address of the connected host. Sets __is_primary to True if this is a primary or master, else False. Sets __is_mongos to True if the connection is to a mongos. """ errors = [] mongos_candidates = [] candidates = seeds or self.__nodes.copy() for candidate in candidates: try: node, ismaster, isdbgrid, res_time = self.__try_node(candidate) self.__is_primary = ismaster self.__is_mongos = isdbgrid # No need to calculate nearest if we only have one mongos. if isdbgrid and not self.__direct: mongos_candidates.append((node, res_time)) continue elif len(mongos_candidates): raise ConfigurationError("Seed list cannot contain a mix " "of mongod and mongos instances.") return node except Exception as why: errors.append(str(why)) # If we have a mongos seed list, pick the "nearest" member. if len(mongos_candidates): self.__is_mongos = True return self.__pick_nearest(mongos_candidates) # Otherwise, try any hosts we discovered that were not in the seed list. for candidate in self.__nodes - candidates: try: node, ismaster, isdbgrid, _ = self.__try_node(candidate) self.__is_primary = ismaster self.__is_mongos = isdbgrid return node except Exception as why: errors.append(str(why)) # Couldn't find a suitable host. self.disconnect() raise AutoReconnect(', '.join(errors)) def __socket(self): """Get a SocketInfo from the pool. """ host, port = (self.__host, self.__port) if host is None or port is None: host, port = self.__find_node() try: if self.__auto_start_request: # No effect if a request already started self.start_request() sock_info = self.__pool.get_socket((host, port)) except socket.error as why: self.disconnect() raise AutoReconnect("could not connect to " "%s:%d: %s" % (host, port, str(why))) if self.__auth_credentials: self.__check_auth(sock_info) return sock_info def disconnect(self): """Disconnect from MongoDB. Disconnecting will close all underlying sockets in the connection pool. If the :class:`Connection` is used again it will be automatically re-opened. Care should be taken to make sure that :meth:`disconnect` is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results. .. seealso:: :meth:`end_request` .. versionadded:: 1.3 """ self.__pool.reset() self.__host = None self.__port = None def close(self): """Alias for :meth:`disconnect` Disconnecting will close all underlying sockets in the connection pool. If the :class:`Connection` is used again it will be automatically re-opened. Care should be taken to make sure that :meth:`disconnect` is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results. .. seealso:: :meth:`end_request` .. versionadded:: 2.1 """ self.disconnect() def set_cursor_manager(self, manager_class): """Set this connection's cursor manager. Raises :class:`TypeError` if `manager_class` is not a subclass of :class:`~pymongo.cursor_manager.CursorManager`. A cursor manager handles closing cursors. Different managers can implement different policies in terms of when to actually kill a cursor that has been closed. :Parameters: - `manager_class`: cursor manager to use .. versionchanged:: 2.1+ Deprecated support for external cursor managers. """ warnings.warn( "Support for external cursor managers is deprecated " "and will be removed in PyMongo 3.0.", DeprecationWarning) manager = manager_class(self) if not isinstance(manager, CursorManager): raise TypeError("manager_class must be a subclass of " "CursorManager") self.__cursor_manager = manager def __check_response_to_last_error(self, response): """Check a response to a lastError message for errors. `response` is a byte string representing a response to the message. If it represents an error response we raise OperationFailure. Return the response as a document. """ response = helpers._unpack_response(response) assert response["number_returned"] == 1 error = response["data"][0] helpers._check_command_response(error, self.disconnect) error_msg = error.get("err", "") if error_msg is None: return error if error_msg.startswith("not master"): self.disconnect() raise AutoReconnect(error_msg) details = error # mongos returns the error code in an error object # for some errors. if "errObjects" in error: for errobj in error["errObjects"]: if errobj["err"] == error_msg: details = errobj break if "code" in details: if details["code"] in [11000, 11001, 12582]: raise DuplicateKeyError(details["err"]) else: raise OperationFailure(details["err"], details["code"]) else: raise OperationFailure(details["err"]) def __check_bson_size(self, message): """Make sure the message doesn't include BSON documents larger than the connected server will accept. :Parameters: - `message`: message to check """ if len(message) == 3: (request_id, data, max_doc_size) = message if max_doc_size > self.__max_bson_size: raise InvalidDocument("BSON document too large (%d bytes)" " - the connected server supports" " BSON document sizes up to %d" " bytes." % (max_doc_size, self.__max_bson_size)) return (request_id, data) else: # get_more and kill_cursors messages # don't include BSON documents. return message def _send_message(self, message, with_last_error=False): """Say something to Mongo. Raises ConnectionFailure if the message cannot be sent. Raises OperationFailure if `with_last_error` is ``True`` and the response to the getLastError call returns an error. Return the response from lastError, or ``None`` if `with_last_error` is ``False``. :Parameters: - `message`: message to send - `with_last_error`: check getLastError status after sending the message """ sock_info = self.__socket() try: (request_id, data) = self.__check_bson_size(message) sock_info.sock.sendall(data) # Safe mode. We pack the message together with a lastError # message and send both. We then get the response (to the # lastError) and raise OperationFailure if it is an error # response. rv = None if with_last_error: response = self.__receive_message_on_socket( 1, request_id, sock_info) rv = self.__check_response_to_last_error(response) self.__pool.maybe_return_socket(sock_info) return rv except OperationFailure: self.__pool.maybe_return_socket(sock_info) raise except (ConnectionFailure, socket.error) as e: self.disconnect() raise AutoReconnect(str(e)) except: sock_info.close() raise def __receive_data_on_socket(self, length, sock_info): """Lowest level receive operation. Takes length to receive and repeatedly calls recv until able to return a buffer of that length, raising ConnectionFailure on error. """ chunks = [] while length: chunk = sock_info.sock.recv(length) if chunk == EMPTY: raise ConnectionFailure("connection closed") length -= len(chunk) chunks.append(chunk) return EMPTY.join(chunks) def __receive_message_on_socket(self, operation, request_id, sock_info): """Receive a message in response to `request_id` on `sock`. Returns the response data with the header removed. """ header = self.__receive_data_on_socket(16, sock_info) length = struct.unpack("<i", header[:4])[0] assert request_id == struct.unpack("<i", header[8:12])[0], \ "ids don't match %r %r" % (request_id, struct.unpack("<i", header[8:12])[0]) assert operation == struct.unpack("<i", header[12:])[0] return self.__receive_data_on_socket(length - 16, sock_info) def __send_and_receive(self, message, sock_info): """Send a message on the given socket and return the response data. """ (request_id, data) = self.__check_bson_size(message) try: sock_info.sock.sendall(data) return self.__receive_message_on_socket(1, request_id, sock_info) except: sock_info.close() raise # we just ignore _must_use_master here: it's only relevant for # MasterSlaveConnection instances. def _send_message_with_response(self, message, _must_use_master=False, **kwargs): """Send a message to Mongo and return the response. Sends the given message and returns the response. :Parameters: - `message`: (request_id, data) pair making up the message to send """ sock_info = self.__socket() try: try: if "network_timeout" in kwargs: sock_info.sock.settimeout(kwargs["network_timeout"]) return self.__send_and_receive(message, sock_info) except (ConnectionFailure, socket.error) as e: self.disconnect() raise AutoReconnect(str(e)) finally: if "network_timeout" in kwargs: try: # Restore the socket's original timeout and return it to # the pool sock_info.sock.settimeout(self.__net_timeout) self.__pool.maybe_return_socket(sock_info) except socket.error: # There was an exception and we've closed the socket pass else: self.__pool.maybe_return_socket(sock_info) def start_request(self): """Ensure the current thread or greenlet always uses the same socket until it calls :meth:`end_request`. This ensures consistent reads, even if you read after an unsafe write. In Python 2.6 and above, or in Python 2.5 with "from __future__ import with_statement", :meth:`start_request` can be used as a context manager: >>> connection = pymongo.Connection(auto_start_request=False) >>> db = connection.test >>> _id = db.test_collection.insert({}, safe=True) >>> with connection.start_request(): ... for i in range(100): ... db.test_collection.update({'_id': _id}, {'$set': {'i':i}}) ... ... # Definitely read the document after the final update completes ... print db.test_collection.find({'_id': _id}) .. versionadded:: 2.2 The :class:`~pymongo.pool.Request` return value. :meth:`start_request` previously returned None """ self.__pool.start_request() return pool.Request(self) def in_request(self): """True if :meth:`start_request` has been called, but not :meth:`end_request`, or if `auto_start_request` is True and :meth:`end_request` has not been called in this thread or greenlet. """ return self.__pool.in_request() def end_request(self): """Undo :meth:`start_request` and allow this thread's connection to return to the pool. Calling :meth:`end_request` allows the :class:`~socket.socket` that has been reserved for this thread by :meth:`start_request` to be returned to the pool. Other threads will then be able to re-use that :class:`~socket.socket`. If your application uses many threads, or has long-running threads that infrequently perform MongoDB operations, then judicious use of this method can lead to performance gains. Care should be taken, however, to make sure that :meth:`end_request` is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results. """ self.__pool.end_request() def __eq__(self, other): if isinstance(other, Connection): us = (self.__host, self.__port) them = (other.__host, other.__port) return us == them return NotImplemented def __repr__(self): if len(self.__nodes) == 1: return "Connection(%r, %r)" % (self.__host, self.__port) else: return "Connection(%r)" % ["%s:%d" % n for n in self.__nodes] def __getattr__(self, name): """Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get """ return database.Database(self, name) def __getitem__(self, name): """Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get """ return self.__getattr__(name) def close_cursor(self, cursor_id): """Close a single database cursor. Raises :class:`TypeError` if `cursor_id` is not an instance of ``(int, long)``. What closing the cursor actually means depends on this connection's cursor manager. :Parameters: - `cursor_id`: id of cursor to close .. seealso:: :meth:`set_cursor_manager` and the :mod:`~pymongo.cursor_manager` module """ if not isinstance(cursor_id, int): raise TypeError("cursor_id must be an instance of (int, long)") self.__cursor_manager.close(cursor_id) def kill_cursors(self, cursor_ids): """Send a kill cursors message with the given ids. Raises :class:`TypeError` if `cursor_ids` is not an instance of ``list``. :Parameters: - `cursor_ids`: list of cursor ids to kill """ if not isinstance(cursor_ids, list): raise TypeError("cursor_ids must be a list") return self._send_message(message.kill_cursors(cursor_ids)) def server_info(self): """Get information about the MongoDB server we're connected to. """ return self.admin.command("buildinfo") def database_names(self): """Get a list of the names of all databases on the connected server. """ return [ db["name"] for db in self.admin.command("listDatabases")["databases"] ] def drop_database(self, name_or_database): """Drop a database. Raises :class:`TypeError` if `name_or_database` is not an instance of :class:`basestring` (:class:`str` in python 3) or Database. :Parameters: - `name_or_database`: the name of a database to drop, or a :class:`~pymongo.database.Database` instance representing the database to drop """ name = name_or_database if isinstance(name, database.Database): name = name.name if not isinstance(name, str): raise TypeError("name_or_database must be an instance of " "%s or Database" % (str.__name__, )) self._purge_index(name) self[name].command("dropDatabase") def copy_database(self, from_name, to_name, from_host=None, username=None, password=None): """Copy a database, potentially from another host. Raises :class:`TypeError` if `from_name` or `to_name` is not an instance of :class:`basestring` (:class:`str` in python 3). Raises :class:`~pymongo.errors.InvalidName` if `to_name` is not a valid database name. If `from_host` is ``None`` the current host is used as the source. Otherwise the database is copied from `from_host`. If the source database requires authentication, `username` and `password` must be specified. :Parameters: - `from_name`: the name of the source database - `to_name`: the name of the target database - `from_host` (optional): host name to copy from - `username` (optional): username for source database - `password` (optional): password for source database .. note:: Specifying `username` and `password` requires server version **>= 1.3.3+**. .. versionadded:: 1.5 """ if not isinstance(from_name, str): raise TypeError("from_name must be an instance " "of %s" % (str.__name__, )) if not isinstance(to_name, str): raise TypeError("to_name must be an instance " "of %s" % (str.__name__, )) database._check_name(to_name) command = {"fromdb": from_name, "todb": to_name} if from_host is not None: command["fromhost"] = from_host in_request = self.in_request() try: if not in_request: self.start_request() if username is not None: nonce = self.admin.command("copydbgetnonce", fromhost=from_host)["nonce"] command["username"] = username command["nonce"] = nonce command["key"] = helpers._auth_key(nonce, username, password) return self.admin.command("copydb", **command) finally: if not in_request: self.end_request() @property def is_locked(self): """Is this server locked? While locked, all write operations are blocked, although read operations may still be allowed. Use :meth:`~pymongo.connection.Connection.unlock` to unlock. .. versionadded:: 2.0 """ ops = self.admin.current_op() return bool(ops.get('fsyncLock', 0)) def fsync(self, **kwargs): """Flush all pending writes to datafiles. :Parameters: Optional parameters can be passed as keyword arguments: - `lock`: If True lock the server to disallow writes. - `async`: If True don't block while synchronizing. .. warning:: `async` and `lock` can not be used together. .. warning:: MongoDB does not support the `async` option on Windows and will raise an exception on that platform. .. versionadded:: 2.0 """ self.admin.command("fsync", **kwargs) def unlock(self): """Unlock a previously locked server. .. versionadded:: 2.0 """ self.admin['$cmd'].sys.unlock.find_one() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.disconnect() def __iter__(self): return self def __next__(self): raise TypeError("'Connection' object is not iterable")
class MongoClient(common.BaseObject): HOST = "localhost" PORT = 27017 def __init__( self, host=None, port=None, document_class=dict, tz_aware=False, connect=True, **kwargs): """Client for a MongoDB instance, a replica set, or a set of mongoses. The client object is thread-safe and has connection-pooling built in. If an operation fails because of a network error, :class:`~pymongo.errors.ConnectionFailure` is raised and the client reconnects in the background. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ':', '/', '+' and '@' must be escaped following RFC 2396. :Parameters: - `host` (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost) - `port` (optional): port number on which to connect - `document_class` (optional): default class to use for documents returned from queries on this client - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`MongoClient` will be timezone aware (otherwise they will be naive) - `connect` (optional): if ``True`` (the default), immediately begin connecting to MongoDB in the background. Otherwise connect on the first operation. | **Other optional parameters can be passed as keyword arguments:** - `maxPoolSize` (optional): The maximum number of connections that the pool will open simultaneously. If this is set, operations will block if there are `maxPoolSize` outstanding connections from the pool. Defaults to 100. Cannot be 0. - `socketTimeoutMS`: (integer or None) Controls how long (in milliseconds) the driver will wait for a response after sending an ordinary (non-monitoring) database operation before concluding that a network error has occurred. Defaults to ``None`` (no timeout). - `connectTimeoutMS`: (integer or None) Controls how long (in milliseconds) the driver will wait during server monitoring when connecting a new socket to a server before concluding the server is unavailable. Defaults to ``20000`` (20 seconds). - `serverSelectionTimeoutMS`: (integer) Controls how long (in milliseconds) the driver will wait to find an available, appropriate server to carry out a database operation; while it is waiting, multiple server monitoring operations may be carried out, each controlled by `connectTimeoutMS`. Defaults to ``30000`` (30 seconds). - `waitQueueTimeoutMS`: (integer or None) How long (in milliseconds) a thread will wait for a socket from the pool if the pool has no free sockets. Defaults to ``None`` (no timeout). - `waitQueueMultiple`: (integer or None) Multiplied by maxPoolSize to give the number of threads allowed to wait for a socket at one time. Defaults to ``None`` (no limit). - `socketKeepAlive`: (boolean) Whether to send periodic keep-alive packets on connected sockets. Defaults to ``False`` (do not send keep-alive packets). | **Write Concern options:** | (Only set if passed. No default values.) - `w`: (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. `w=<int>` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). Passing w=0 **disables write acknowledgement** and all other write concern options. - `wtimeout`: (integer) Used in conjunction with `w`. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised. - `j`: If ``True`` block until write operations have been committed to the journal. Cannot be used in combination with `fsync`. Prior to MongoDB 2.6 this option was ignored if the server was running without journaling. Starting with MongoDB 2.6 write operations will fail with an exception if this option is used when the server is running without journaling. - `fsync`: If ``True`` and the server is running without journaling, blocks until the server has synced all data files to disk. If the server is running with journaling, this acts the same as the `j` option, blocking until write operations have been committed to the journal. Cannot be used in combination with `j`. | **Replica set keyword arguments for connecting with a replica set - either directly or via a mongos:** - `replicaSet`: (string or None) The name of the replica set to connect to. The driver will verify that all servers it connects to match this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. Defaults to ``None``. - `read_preference`: The read preference for this client. If connecting directly to a secondary then a read preference mode *other* than PRIMARY is required - otherwise all queries will throw :class:`~pymongo.errors.AutoReconnect` "not master". See :class:`~pymongo.read_preferences.ReadPreference` for all available read preference options. Defaults to ``PRIMARY``. | **SSL configuration:** - `ssl`: If ``True``, create the connection to the server using SSL. Defaults to ``False``. - `ssl_keyfile`: The private keyfile used to identify the local connection against mongod. If included with the ``certfile`` then only the ``ssl_certfile`` is needed. Implies ``ssl=True``. Defaults to ``None``. - `ssl_certfile`: The certificate file used to identify the local connection against mongod. Implies ``ssl=True``. Defaults to ``None``. - `ssl_cert_reqs`: Specifies whether a certificate is required from the other side of the connection, and whether it will be validated if provided. It must be one of the three values ``ssl.CERT_NONE`` (certificates ignored), ``ssl.CERT_OPTIONAL`` (not required, but validated if provided), or ``ssl.CERT_REQUIRED`` (required and validated). If the value of this parameter is not ``ssl.CERT_NONE`` and a value is not provided for ``ssl_ca_certs`` PyMongo will attempt to load system provided CA certificates. If the python version in use does not support loading system CA certificates then the ``ssl_ca_certs`` parameter must point to a file of CA certificates. Implies ``ssl=True``. Defaults to ``ssl.CERT_REQUIRED`` if not provided and ``ssl=True``. - `ssl_ca_certs`: The ca_certs file contains a set of concatenated "certification authority" certificates, which are used to validate certificates passed from the other end of the connection. Implies ``ssl=True``. Defaults to ``None``. - `ssl_match_hostname`: If ``True`` (the default), and `ssl_cert_reqs` is not ``ssl.CERT_NONE``, enables hostname verification using the :func:`~ssl.match_hostname` function from python's :mod:`~ssl` module. Think very carefully before setting this to ``False`` as that could make your application vulnerable to man-in-the-middle attacks. .. mongodoc:: connections .. versionchanged:: 3.0 :class:`~pymongo.mongo_client.MongoClient` is now the one and only client class for a standalone server, mongos, or replica set. It includes the functionality that had been split into :class:`~pymongo.mongo_client.MongoReplicaSetClient`: it can connect to a replica set, discover all its members, and monitor the set for stepdowns, elections, and reconfigs. The :class:`~pymongo.mongo_client.MongoClient` constructor no longer blocks while connecting to the server or servers, and it no longer raises :class:`~pymongo.errors.ConnectionFailure` if they are unavailable, nor :class:`~pymongo.errors.ConfigurationError` if the user's credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads. Therefore the ``alive`` method is removed since it no longer provides meaningful information; even if the client is disconnected, it may discover a server in time to fulfill the next operation. In PyMongo 2.x, :class:`~pymongo.MongoClient` accepted a list of standalone MongoDB servers and used the first it could connect to:: MongoClient(['host1.com:27017', 'host2.com:27017']) A list of multiple standalones is no longer supported; if multiple servers are listed they must be members of the same replica set, or mongoses in the same sharded cluster. The behavior for a list of mongoses is changed from "high availability" to "load balancing". Before, the client connected to the lowest-latency mongos in the list, and used it until a network error prompted it to re-evaluate all mongoses' latencies and reconnect to one of them. In PyMongo 3, the client monitors its network latency to all the mongoses continuously, and distributes operations evenly among those with the lowest latency. See :ref:`mongos-load-balancing` for more information. The ``connect`` option is added. The ``start_request``, ``in_request``, and ``end_request`` methods are removed, as well as the ``auto_start_request`` option. The ``copy_database`` method is removed, see the :doc:`copy_database examples </examples/copydb>` for alternatives. The :meth:`MongoClient.disconnect` method is removed; it was a synonym for :meth:`~pymongo.MongoClient.close`. :class:`~pymongo.mongo_client.MongoClient` no longer returns an instance of :class:`~pymongo.database.Database` for attribute names with leading underscores. You must use dict-style lookups instead:: client['__my_database__'] Not:: client.__my_database__ """ if host is None: host = self.HOST if isinstance(host, string_type): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") seeds = set() username = None password = None dbase = None opts = {} for entity in host: if "://" in entity: if entity.startswith("mongodb://"): res = uri_parser.parse_uri(entity, port, False) seeds.update(res["nodelist"]) username = res["username"] or username password = res["password"] or password dbase = res["database"] or dbase opts = res["options"] else: idx = entity.find("://") raise InvalidURI("Invalid URI scheme: " "%s" % (entity[:idx],)) else: seeds.update(uri_parser.split_hosts(entity, port)) if not seeds: raise ConfigurationError("need to specify at least one host") # _pool_class, _monitor_class, and _condition_class are for deep # customization of PyMongo, e.g. Motor. pool_class = kwargs.pop('_pool_class', None) monitor_class = kwargs.pop('_monitor_class', None) condition_class = kwargs.pop('_condition_class', None) kwargs['document_class'] = document_class kwargs['tz_aware'] = tz_aware opts.update(kwargs) self.__options = options = ClientOptions( username, password, dbase, opts) self.__default_database_name = dbase self.__lock = threading.Lock() self.__cursor_manager = CursorManager(self) self.__kill_cursors_queue = [] # Cache of existing indexes used by ensure_index ops. self.__index_cache = {} super(MongoClient, self).__init__(options.codec_options, options.read_preference, options.write_concern) self.__all_credentials = {} creds = options.credentials if creds: self._cache_credentials(creds.source, creds) self._topology_settings = TopologySettings( seeds=seeds, replica_set_name=options.replica_set_name, pool_class=pool_class, pool_options=options.pool_options, monitor_class=monitor_class, condition_class=condition_class, local_threshold_ms=options.local_threshold_ms, server_selection_timeout=options.server_selection_timeout) self._topology = Topology(self._topology_settings) if connect: self._topology.open() def target(): client = self_ref() if client is None: return False # Stop the executor. MongoClient._process_kill_cursors_queue(client) return True executor = periodic_executor.PeriodicExecutor( condition_class=self._topology_settings.condition_class, interval=common.KILL_CURSOR_FREQUENCY, min_interval=0, target=target) # We strongly reference the executor and it weakly references us via # this closure. When the client is freed, stop the executor soon. self_ref = weakref.ref(self, executor.close) self._kill_cursors_executor = executor executor.open() def _cache_credentials(self, source, credentials, connect=False): """Save a set of authentication credentials. The credentials are used to login a socket whenever one is created. If `connect` is True, verify the credentials on the server first. """ # Don't let other threads affect this call's data. all_credentials = self.__all_credentials.copy() if source in all_credentials: # Nothing to do if we already have these credentials. if credentials == all_credentials[source]: return raise OperationFailure('Another user is already authenticated ' 'to this database. You must logout first.') if connect: server = self._get_topology().select_server( writable_preferred_server_selector) # get_socket() logs out of the database if logged in with old # credentials, and logs in with new ones. with server.get_socket(all_credentials) as sock_info: sock_info.authenticate(credentials) # If several threads run _cache_credentials at once, last one wins. self.__all_credentials[source] = credentials def _purge_credentials(self, source): """Purge credentials from the authentication cache.""" self.__all_credentials.pop(source, None) def _cached(self, dbname, coll, index): """Test if `index` is cached.""" cache = self.__index_cache now = datetime.datetime.utcnow() return (dbname in cache and coll in cache[dbname] and index in cache[dbname][coll] and now < cache[dbname][coll][index]) def _cache_index(self, dbname, collection, index, cache_for): """Add an index to the index cache for ensure_index operations.""" now = datetime.datetime.utcnow() expire = datetime.timedelta(seconds=cache_for) + now if database not in self.__index_cache: self.__index_cache[dbname] = {} self.__index_cache[dbname][collection] = {} self.__index_cache[dbname][collection][index] = expire elif collection not in self.__index_cache[dbname]: self.__index_cache[dbname][collection] = {} self.__index_cache[dbname][collection][index] = expire else: self.__index_cache[dbname][collection][index] = expire def _purge_index(self, database_name, collection_name=None, index_name=None): """Purge an index from the index cache. If `index_name` is None purge an entire collection. If `collection_name` is None purge an entire database. """ if not database_name in self.__index_cache: return if collection_name is None: del self.__index_cache[database_name] return if not collection_name in self.__index_cache[database_name]: return if index_name is None: del self.__index_cache[database_name][collection_name] return if index_name in self.__index_cache[database_name][collection_name]: del self.__index_cache[database_name][collection_name][index_name] def _server_property(self, attr_name, default=None): """An attribute of the current server's description. Returns "default" while there is no current server, primary, or mongos. Not threadsafe if used multiple times in a single method, since the server may change. In such cases, store a local reference to a ServerDescription first, then use its properties. """ try: server = self._topology.select_server( writable_server_selector, server_selection_timeout=0) return getattr(server.description, attr_name) except ConnectionFailure: return default @property def address(self): """(host, port) of the current standalone, primary, or mongos, or None. Accessing :attr:`address` raises :exc:`~.errors.InvalidOperation` if the client is load-balancing among mongoses, since there is no single address. Use :attr:`nodes` instead. .. versionadded:: 3.0 """ try: return self._topology.get_direct_or_primary() except InvalidOperation: # Only one case where Topology throws InvalidOperation. raise InvalidOperation( 'Cannot use "address" property when load balancing among' ' mongoses, use "nodes" instead.') @property def primary(self): """The (host, port) of the current primary of the replica set. Returns ``None`` if this client is not connected to a replica set, there is no primary, or this client was created without the `replicaSet` option. .. versionadded:: 3.0 MongoClient gained this property in version 3.0 when MongoReplicaSetClient's functionality was merged in. """ return self._topology.get_primary() @property def secondaries(self): """The secondary members known to this client. A sequence of (host, port) pairs. Empty if this client is not connected to a replica set, there are no visible secondaries, or this client was created without the `replicaSet` option. .. versionadded:: 3.0 MongoClient gained this property in version 3.0 when MongoReplicaSetClient's functionality was merged in. """ return self._topology.get_secondaries() @property def arbiters(self): """Arbiters in the replica set. A sequence of (host, port) pairs. Empty if this client is not connected to a replica set, there are no arbiters, or this client was created without the `replicaSet` option. """ return self._topology.get_arbiters() @property def is_primary(self): """If this client if connected to a server that can accept writes. True if the current server is a standalone, mongos, or the primary of a replica set. """ return self._server_property('is_writable', False) @property def is_mongos(self): """If this client is connected to mongos. """ return self._server_property('server_type') == SERVER_TYPE.Mongos @property def max_pool_size(self): """The maximum number of sockets the pool will open concurrently. When the pool has reached `max_pool_size`, operations block waiting for a socket to be returned to the pool. If ``waitQueueTimeoutMS`` is set, a blocked operation will raise :exc:`~pymongo.errors.ConnectionFailure` after a timeout. By default ``waitQueueTimeoutMS`` is not set. """ return self.__options.pool_options.max_pool_size @property def nodes(self): """Set of all currently connected servers. .. warning:: When connected to a replica set the value of :attr:`nodes` can change over time as :class:`MongoClient`'s view of the replica set changes. :attr:`nodes` can also be an empty set when :class:`MongoClient` is first instantiated and hasn't yet connected to any servers, or a network partition causes it to lose connection to all servers. """ description = self._topology.description return frozenset(s.address for s in description.known_servers) @property def max_bson_size(self): """The largest BSON object the connected server accepts in bytes. Defaults to 16MB if not connected to a server. """ return self._server_property('max_bson_size', common.MAX_BSON_SIZE) @property def max_message_size(self): """The largest message the connected server accepts in bytes. Defaults to 32MB if not connected to a server. """ return self._server_property( 'max_message_size', common.MAX_MESSAGE_SIZE) @property def max_write_batch_size(self): """The maxWriteBatchSize reported by the server. Returns a default value when connected to server versions prior to MongoDB 2.6. """ return self._server_property( 'max_write_batch_size', common.MAX_WRITE_BATCH_SIZE) @property def local_threshold_ms(self): """The local threshold for this instance.""" return self.__options.local_threshold_ms @property def server_selection_timeout(self): """The server selection timeout for this instance in seconds.""" return self.__options.server_selection_timeout def _is_writable(self): """Attempt to connect to a writable server, or return False. """ topology = self._get_topology() # Starts monitors if necessary. try: svr = topology.select_server(writable_server_selector) # When directly connected to a secondary, arbiter, etc., # select_server returns it, whatever the selector. Check # again if the server is writable. return svr.description.is_writable except ConnectionFailure: return False def close(self): """Disconnect from MongoDB. Close all sockets in the connection pools and stop the monitor threads. If this instance is used again it will be automatically re-opened and the threads restarted. """ self._topology.close() def set_cursor_manager(self, manager_class): """Set this client's cursor manager. Raises :class:`TypeError` if `manager_class` is not a subclass of :class:`~pymongo.cursor_manager.CursorManager`. A cursor manager handles closing cursors. Different managers can implement different policies in terms of when to actually kill a cursor that has been closed. :Parameters: - `manager_class`: cursor manager to use .. versionchanged:: 3.0 Undeprecated. """ manager = manager_class(self) if not isinstance(manager, CursorManager): raise TypeError("manager_class must be a subclass of " "CursorManager") self.__cursor_manager = manager def _get_topology(self): """Get the internal :class:`~pymongo.topology.Topology` object. If this client was created with "connect=False", calling _get_topology launches the connection process in the background. """ self._topology.open() return self._topology @contextlib.contextmanager def _get_socket(self, selector): server = self._get_topology().select_server(selector) try: with server.get_socket(self.__all_credentials) as sock_info: yield sock_info except NetworkTimeout: # The socket has been closed. Don't reset the server. # Server Discovery And Monitoring Spec: "When an application # operation fails because of any network error besides a socket # timeout...." raise except NotMasterError: # "When the client sees a "not master" error it MUST replace the # server's description with type Unknown. It MUST request an # immediate check of the server." self._reset_server_and_request_check(server.description.address) raise except ConnectionFailure: # "Client MUST replace the server's description with type Unknown # ... MUST NOT request an immediate check of the server." self.__reset_server(server.description.address) raise def _socket_for_writes(self): return self._get_socket(writable_server_selector) @contextlib.contextmanager def _socket_for_reads(self, read_preference): preference = read_preference or ReadPreference.PRIMARY # Get a socket for a server matching the read preference, and yield # sock_info, slave_ok. Server Selection Spec: "slaveOK must be sent to # mongods with topology type Single. If the server type is Mongos, # follow the rules for passing read preference to mongos, even for # topology type Single." # Thread safe: if the type is single it cannot change. topology = self._get_topology() single = topology.description.topology_type == TOPOLOGY_TYPE.Single with self._get_socket(read_preference) as sock_info: slave_ok = (single and not sock_info.is_mongos) or ( preference != ReadPreference.PRIMARY) yield sock_info, slave_ok def _send_message_with_response(self, operation, read_preference=None, exhaust=False, address=None): """Send a message to MongoDB and return a Response. :Parameters: - `operation`: a _Query or _GetMore object. - `read_preference` (optional): A ReadPreference. - `exhaust` (optional): If True, the socket used stays checked out. It is returned along with its Pool in the Response. - `address` (optional): Optional address when sending a message to a specific server, used for getMore. """ with self.__lock: # If needed, restart kill-cursors thread after a fork. self._kill_cursors_executor.open() topology = self._get_topology() if address: server = topology.select_server_by_address(address) if not server: raise AutoReconnect('server %s:%d no longer available' % address) else: selector = read_preference or writable_server_selector server = topology.select_server(selector) # A _Query's slaveOk bit is already set for queries with non-primary # read preference. If this is a direct connection to a mongod, override # and *always* set the slaveOk bit. See bullet point 2 in # server-selection.rst#topology-type-single. set_slave_ok = ( topology.description.topology_type == TOPOLOGY_TYPE.Single and server.description.server_type != SERVER_TYPE.Mongos) return self._reset_on_error( server, server.send_message_with_response, operation, set_slave_ok, self.__all_credentials, exhaust) def _reset_on_error(self, server, func, *args, **kwargs): """Execute an operation. Reset the server on network error. Returns fn()'s return value on success. On error, clears the server's pool and marks the server Unknown. Re-raises any exception thrown by fn(). """ try: return func(*args, **kwargs) except NetworkTimeout: # The socket has been closed. Don't reset the server. raise except ConnectionFailure: self.__reset_server(server.description.address) raise def __reset_server(self, address): """Clear our connection pool for a server and mark it Unknown.""" self._topology.reset_server(address) def _reset_server_and_request_check(self, address): """Clear our pool for a server, mark it Unknown, and check it soon.""" self._topology.reset_server_and_request_check(address) def __eq__(self, other): if isinstance(other, self.__class__): return self.address == other.address return NotImplemented def __ne__(self, other): return not self == other def __repr__(self): server_descriptions = self._topology.description.server_descriptions() if len(server_descriptions) == 1: description, = server_descriptions.values() return "MongoClient(%r, %r)" % description.address else: return "MongoClient(%r)" % [ "%s:%d" % address for address in server_descriptions] def __getattr__(self, name): """Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get """ if name.startswith('_'): raise AttributeError( "MongoClient has no attribute %r. To access the %s" " database, use client[%r]." % (name, name, name)) return self.__getitem__(name) def __getitem__(self, name): """Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get """ return database.Database(self, name) def close_cursor(self, cursor_id, address=None): """Close a single database cursor. Raises :class:`TypeError` if `cursor_id` is not an instance of ``(int, long)``. What closing the cursor actually means depends on this client's cursor manager. :Parameters: - `cursor_id`: id of cursor to close - `address` (optional): (host, port) pair of the cursor's server. If it is not provided, the client attempts to close the cursor on the primary or standalone, or a mongos server. .. versionchanged:: 3.0 Added ``address`` parameter. """ if not isinstance(cursor_id, integer_types): raise TypeError("cursor_id must be an instance of (int, long)") self.__cursor_manager.close(cursor_id, address) def kill_cursors(self, cursor_ids, address=None): """Send a kill cursors message soon with the given ids. Raises :class:`TypeError` if `cursor_ids` is not an instance of ``list``. This method may be called from a :class:`~pymongo.cursor.Cursor` destructor during garbage collection, so it isn't safe to take a lock or do network I/O. Instead, we schedule the cursor to be closed soon on a background thread. :Parameters: - `cursor_ids`: list of cursor ids to kill - `address` (optional): (host, port) pair of the cursor's server. If it is not provided, the client attempts to close the cursor on the primary or standalone, or a mongos server. .. versionchanged:: 3.0 Now accepts an `address` argument. Schedules the cursors to be closed on a background thread instead of sending the message immediately. """ if not isinstance(cursor_ids, list): raise TypeError("cursor_ids must be a list") # "Atomic", needs no lock. self.__kill_cursors_queue.append((address, cursor_ids)) # This method is run periodically by a background thread. def _process_kill_cursors_queue(self): """Process any pending kill cursors requests.""" address_to_cursor_ids = defaultdict(list) # Other threads or the GC may append to the queue concurrently. while True: try: address, cursor_ids = self.__kill_cursors_queue.pop() except IndexError: break address_to_cursor_ids[address].extend(cursor_ids) # Don't re-open topology if it's closed and there's no pending cursors. if address_to_cursor_ids: topology = self._get_topology() for address, cursor_ids in address_to_cursor_ids.items(): try: if address: server = topology.select_server_by_address(address) else: # Application called close_cursor() with no address. server = topology.select_server( writable_server_selector) server.send_message(message.kill_cursors(cursor_ids), self.__all_credentials) except ConnectionFailure as exc: warnings.warn("couldn't close cursor on %s: %s" % (address, exc)) def server_info(self): """Get information about the MongoDB server we're connected to.""" return self.admin.command("buildinfo", read_preference=ReadPreference.PRIMARY) def database_names(self): """Get a list of the names of all databases on the connected server.""" return [db["name"] for db in self.admin.command( "listDatabases", read_preference=ReadPreference.PRIMARY)["databases"]] def drop_database(self, name_or_database): """Drop a database. Raises :class:`TypeError` if `name_or_database` is not an instance of :class:`basestring` (:class:`str` in python 3) or :class:`~pymongo.database.Database`. :Parameters: - `name_or_database`: the name of a database to drop, or a :class:`~pymongo.database.Database` instance representing the database to drop """ name = name_or_database if isinstance(name, database.Database): name = name.name if not isinstance(name, string_type): raise TypeError("name_or_database must be an instance " "of %s or a Database" % (string_type.__name__,)) self._purge_index(name) self[name].command("dropDatabase", read_preference=ReadPreference.PRIMARY) def get_default_database(self): """Get the database named in the MongoDB connection URI. >>> uri = 'mongodb://host/my_database' >>> client = MongoClient(uri) >>> db = client.get_default_database() >>> assert db.name == 'my_database' Useful in scripts where you want to choose which database to use based only on the URI in a configuration file. """ if self.__default_database_name is None: raise ConfigurationError('No default database defined') return self[self.__default_database_name] def get_database(self, name, codec_options=None, read_preference=None, write_concern=None): """Get a :class:`~pymongo.database.Database` with the given name and options. Useful for creating a :class:`~pymongo.database.Database` with different codec options, read preference, and/or write concern from this :class:`MongoClient`. >>> client.read_preference Primary() >>> db1 = client.test >>> db1.read_preference Primary() >>> from pymongo import ReadPreference >>> db2 = client.get_database( ... 'test', read_preference=ReadPreference.SECONDARY) >>> db2.read_preference Secondary(tag_sets=None) :Parameters: - `name`: The name of the database - a string. - `codec_options` (optional): An instance of :class:`~bson.codec_options.CodecOptions`. If ``None`` (the default) the :attr:`codec_options` of this :class:`MongoClient` is used. - `read_preference` (optional): The read preference to use. If ``None`` (the default) the :attr:`read_preference` of this :class:`MongoClient` is used. See :mod:`~pymongo.read_preferences` for options. - `write_concern` (optional): An instance of :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the default) the :attr:`write_concern` of this :class:`MongoClient` is used. """ return database.Database( self, name, codec_options, read_preference, write_concern) @property def is_locked(self): """Is this server locked? While locked, all write operations are blocked, although read operations may still be allowed. Use :meth:`unlock` to unlock. """ ops = self.admin.current_op() return bool(ops.get('fsyncLock', 0)) def fsync(self, **kwargs): """Flush all pending writes to datafiles. :Parameters: Optional parameters can be passed as keyword arguments: - `lock`: If True lock the server to disallow writes. - `async`: If True don't block while synchronizing. .. warning:: `async` and `lock` can not be used together. .. warning:: MongoDB does not support the `async` option on Windows and will raise an exception on that platform. """ self.admin.command("fsync", read_preference=ReadPreference.PRIMARY, **kwargs) def unlock(self): """Unlock a previously locked server. """ coll = self.admin.get_collection( "$cmd.sys.unlock", read_preference=ReadPreference.PRIMARY) coll.find_one() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def __iter__(self): return self def __next__(self): raise TypeError("'MongoClient' object is not iterable") next = __next__
class MongoClient(common.BaseObject): """Connection to MongoDB. """ HOST = "localhost" PORT = 27017 __max_bson_size = 4 * 1024 * 1024 def __init__(self, host=None, port=None, max_pool_size=10, document_class=dict, tz_aware=False, _connect=True, **kwargs): """Create a new connection to a single MongoDB instance at *host:port*. The resultant client object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, :class:`~pymongo.errors.ConnectionFailure` is raised. If auto-reconnection will be performed, :class:`~pymongo.errors.AutoReconnect` will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. Raises :class:`TypeError` if port is not an instance of ``int``. Raises :class:`~pymongo.errors.ConnectionFailure` if the connection cannot be made. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ':', '/', '+' and '@' must be escaped following RFC 2396. :Parameters: - `host` (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost) - `port` (optional): port number on which to connect - `max_pool_size` (optional): The maximum number of idle connections to keep open in the pool for future use - `document_class` (optional): default class to use for documents returned from queries on this client - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`MongoClient` will be timezone aware (otherwise they will be naive) | **Other optional parameters can be passed as keyword arguments:** - `socketTimeoutMS`: (integer) How long (in milliseconds) a send or receive on a socket can take before timing out. - `connectTimeoutMS`: (integer) How long (in milliseconds) a connection can take to be opened before timing out. - `auto_start_request`: If ``True``, each thread that accesses this :class:`MongoClient` has a socket allocated to it for the thread's lifetime. This ensures consistent reads, even if you read after an unacknowledged write. Defaults to ``False`` - `use_greenlets`: If ``True``, :meth:`start_request()` will ensure that the current greenlet uses the same socket for all operations until :meth:`end_request()` | **Write Concern options:** - `w`: (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. `w=<int>` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). Passing w=0 **disables write acknowledgement** and all other write concern options. - `wtimeout`: (integer) Used in conjunction with `w`. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised. - `j`: If ``True`` block until write operations have been committed to the journal. Ignored if the server is running without journaling. - `fsync`: If ``True`` force the database to fsync all files before returning. When used with `j` the server awaits the next group commit before returning. | **Replica set keyword arguments for connecting with a replica set - either directly or via a mongos:** | (ignored by standalone mongod instances) - `replicaSet`: (string) The name of the replica set to connect to. The driver will verify that the replica set it connects to matches this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. *Ignored by mongos*. - `read_preference`: The read preference for this client. If connecting to a secondary then a read preference mode *other* than PRIMARY is required - otherwise all queries will throw :class:`~pymongo.errors.AutoReconnect` "not master". See :class:`~pymongo.read_preferences.ReadPreference` for all available read preference options. - `tag_sets`: Ignored unless connecting to a replica set via mongos. Specify a priority-order for tag sets, provide a list of tag sets: ``[{'dc': 'ny'}, {'dc': 'la'}, {}]``. A final, empty tag set, ``{}``, means "read from any member that matches the mode, ignoring tags. | **SSL configuration:** - `ssl`: If ``True``, create the connection to the server using SSL. - `ssl_keyfile`: The private keyfile used to identify the local connection against mongod. If included with the ``certfile` then only the ``ssl_certfile`` is needed. Implies ``ssl=True``. - `ssl_certfile`: The certificate file used to identify the local connection against mongod. Implies ``ssl=True``. - `ssl_cert_reqs`: Specifies whether a certificate is required from the other side of the connection, and whether it will be validated if provided. It must be one of the three values ``ssl.CERT_NONE`` (certificates ignored), ``ssl.CERT_OPTIONAL`` (not required, but validated if provided), or ``ssl.CERT_REQUIRED`` (required and validated). If the value of this parameter is not ``ssl.CERT_NONE``, then the ``ssl_ca_certs`` parameter must point to a file of CA certificates. Implies ``ssl=True``. - `ssl_ca_certs`: The ca_certs file contains a set of concatenated "certification authority" certificates, which are used to validate certificates passed from the other end of the connection. Implies ``ssl=True``. .. seealso:: :meth:`end_request` .. mongodoc:: connections .. versionchanged:: 2.5 Added additional ssl options .. versionadded:: 2.4 """ if host is None: host = self.HOST if isinstance(host, str): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") seeds = set() username = None password = None db_name = None opts = {} for entity in host: if "://" in entity: if entity.startswith("mongodb://"): res = uri_parser.parse_uri(entity, port) seeds.update(res["nodelist"]) username = res["username"] or username password = res["password"] or password db_name = res["database"] or db_name opts = res["options"] else: idx = entity.find("://") raise InvalidURI("Invalid URI scheme: " "%s" % (entity[:idx],)) else: seeds.update(uri_parser.split_hosts(entity, port)) if not seeds: raise ConfigurationError("need to specify at least one host") self.__nodes = seeds self.__host = None self.__port = None self.__is_primary = False self.__is_mongos = False # _pool_class option is for deep customization of PyMongo, e.g. Motor. # SHOULD NOT BE USED BY DEVELOPERS EXTERNAL TO 10GEN. pool_class = kwargs.pop('_pool_class', pool.Pool) options = {} for option, value in kwargs.items(): option, value = common.validate(option, value) options[option] = value options.update(opts) self.__max_pool_size = common.validate_positive_integer( 'max_pool_size', max_pool_size) self.__cursor_manager = CursorManager(self) self.__repl = options.get('replicaset') if len(seeds) == 1 and not self.__repl: self.__direct = True else: self.__direct = False self.__nodes = set() self.__net_timeout = options.get('sockettimeoutms') self.__conn_timeout = options.get('connecttimeoutms') self.__use_ssl = options.get('ssl', None) self.__ssl_keyfile = options.get('ssl_keyfile', None) self.__ssl_certfile = options.get('ssl_certfile', None) self.__ssl_cert_reqs = options.get('ssl_cert_reqs', None) self.__ssl_ca_certs = options.get('ssl_ca_certs', None) ssl_kwarg_keys = [k for k in list(kwargs.keys()) if k.startswith('ssl_')] if self.__use_ssl == False and ssl_kwarg_keys: raise ConfigurationError("ssl has not been enabled but the " "following ssl parameters have been set: " "%s. Please set `ssl=True` or remove." % ', '.join(ssl_kwarg_keys)) if self.__ssl_cert_reqs and not self.__ssl_ca_certs: raise ConfigurationError("If `ssl_cert_reqs` is not " "`ssl.CERT_NONE` then you must " "include `ssl_ca_certs` to be able " "to validate the server.") if ssl_kwarg_keys and self.__use_ssl is None: # ssl options imply ssl = True self.__use_ssl = True if self.__use_ssl and not HAS_SSL: raise ConfigurationError("The ssl module is not available. If you " "are using a python version previous to " "2.6 you must install the ssl package " "from PyPI.") self.__use_greenlets = options.get('use_greenlets', False) self.__pool = pool_class( None, self.__max_pool_size, self.__net_timeout, self.__conn_timeout, self.__use_ssl, use_greenlets=self.__use_greenlets, ssl_keyfile=self.__ssl_keyfile, ssl_certfile=self.__ssl_certfile, ssl_cert_reqs=self.__ssl_cert_reqs, ssl_ca_certs=self.__ssl_ca_certs) self.__document_class = document_class self.__tz_aware = common.validate_boolean('tz_aware', tz_aware) self.__auto_start_request = options.get('auto_start_request', False) # cache of existing indexes used by ensure_index ops self.__index_cache = {} self.__auth_credentials = {} super(MongoClient, self).__init__(**options) if self.slave_okay: warnings.warn("slave_okay is deprecated. Please " "use read_preference instead.", DeprecationWarning, stacklevel=2) if _connect: try: self.__find_node(seeds) except AutoReconnect as e: # ConnectionFailure makes more sense here than AutoReconnect raise ConnectionFailure(str(e)) db_name = options.get('authsource', db_name) if db_name and username is None: warnings.warn("database name or authSource in URI is being " "ignored. If you wish to authenticate to %s, you " "must provide a username and password." % (db_name,)) if username: mechanism = options.get('authmechanism', 'MONGODB-CR') if mechanism == 'GSSAPI': source = '$external' else: source = db_name or 'admin' credentials = (source, str(username), str(password), mechanism) try: self._cache_credentials(source, credentials, _connect) except OperationFailure as exc: raise ConfigurationError(str(exc)) def _cached(self, dbname, coll, index): """Test if `index` is cached. """ cache = self.__index_cache now = datetime.datetime.utcnow() return (dbname in cache and coll in cache[dbname] and index in cache[dbname][coll] and now < cache[dbname][coll][index]) def _cache_index(self, database, collection, index, cache_for): """Add an index to the index cache for ensure_index operations. """ now = datetime.datetime.utcnow() expire = datetime.timedelta(seconds=cache_for) + now if database not in self.__index_cache: self.__index_cache[database] = {} self.__index_cache[database][collection] = {} self.__index_cache[database][collection][index] = expire elif collection not in self.__index_cache[database]: self.__index_cache[database][collection] = {} self.__index_cache[database][collection][index] = expire else: self.__index_cache[database][collection][index] = expire def _purge_index(self, database_name, collection_name=None, index_name=None): """Purge an index from the index cache. If `index_name` is None purge an entire collection. If `collection_name` is None purge an entire database. """ if not database_name in self.__index_cache: return if collection_name is None: del self.__index_cache[database_name] return if not collection_name in self.__index_cache[database_name]: return if index_name is None: del self.__index_cache[database_name][collection_name] return if index_name in self.__index_cache[database_name][collection_name]: del self.__index_cache[database_name][collection_name][index_name] def _cache_credentials(self, source, credentials, connect=True): """Add credentials to the database authentication cache for automatic login when a socket is created. If `connect` is True, verify the credentials on the server first. """ if source in self.__auth_credentials: # Nothing to do if we already have these credentials. if credentials == self.__auth_credentials[source]: return raise OperationFailure('Another user is already authenticated ' 'to this database. You must logout first.') if connect: sock_info = self.__socket() try: # Since __check_auth was called in __socket # there is no need to call it here. auth.authenticate(credentials, sock_info, self.__simple_command) sock_info.authset.add(credentials) finally: self.__pool.maybe_return_socket(sock_info) self.__auth_credentials[source] = credentials def _purge_credentials(self, source): """Purge credentials from the database authentication cache. """ if source in self.__auth_credentials: del self.__auth_credentials[source] def __check_auth(self, sock_info): """Authenticate using cached database credentials. """ if self.__auth_credentials or sock_info.authset: cached = set(self.__auth_credentials.values()) authset = sock_info.authset.copy() # Logout any credentials that no longer exist in the cache. for credentials in authset - cached: self.__simple_command(sock_info, credentials[0], {'logout': 1}) sock_info.authset.discard(credentials) for credentials in cached - authset: auth.authenticate(credentials, sock_info, self.__simple_command) sock_info.authset.add(credentials) @property def host(self): """Current connected host. .. versionchanged:: 1.3 ``host`` is now a property rather than a method. """ return self.__host @property def port(self): """Current connected port. .. versionchanged:: 1.3 ``port`` is now a property rather than a method. """ return self.__port @property def is_primary(self): """If this instance is connected to a standalone, a replica set primary, or the master of a master-slave set. .. versionadded:: 2.3 """ return self.__is_primary @property def is_mongos(self): """If this instance is connected to mongos. .. versionadded:: 2.3 """ return self.__is_mongos @property def max_pool_size(self): """The maximum number of idle connections kept open in the pool for future use. .. note:: ``max_pool_size`` does not cap the number of concurrent connections to the server; there is currently no way to limit the number of connections. ``max_pool_size`` only limits the number of **idle** connections kept open when they are returned to the pool. .. versionadded:: 1.11 """ return self.__max_pool_size @property def use_greenlets(self): """Whether calling :meth:`start_request` assigns greenlet-local, rather than thread-local, sockets. .. versionadded:: 2.4.2 """ return self.__use_greenlets @property def nodes(self): """List of all known nodes. Includes both nodes specified when this instance was created, as well as nodes discovered through the replica set discovery mechanism. .. versionadded:: 1.8 """ return self.__nodes @property def auto_start_request(self): """Is auto_start_request enabled? """ return self.__auto_start_request def get_document_class(self): return self.__document_class def set_document_class(self, klass): self.__document_class = klass document_class = property(get_document_class, set_document_class, doc="""Default class to use for documents returned from this client. .. versionadded:: 1.7 """) @property def tz_aware(self): """Does this client return timezone-aware datetimes? .. versionadded:: 1.8 """ return self.__tz_aware @property def max_bson_size(self): """Return the maximum size BSON object the connected server accepts in bytes. Defaults to 4MB in server < 1.7.4. .. versionadded:: 1.10 """ return self.__max_bson_size def __simple_command(self, sock_info, dbname, spec): """Send a command to the server. """ rqst_id, msg, _ = message.query(0, dbname + '.$cmd', 0, -1, spec) start = time.time() try: sock_info.sock.sendall(msg) response = self.__receive_message_on_socket(1, rqst_id, sock_info) except: sock_info.close() raise end = time.time() response = helpers._unpack_response(response)['data'][0] msg = "command %r failed: %%s" % spec helpers._check_command_response(response, None, msg) return response, end - start def __try_node(self, node): """Try to connect to this node and see if it works for our connection type. Returns ((host, port), ismaster, isdbgrid, res_time). :Parameters: - `node`: The (host, port) pair to try. """ self.disconnect() self.__host, self.__port = node # Call 'ismaster' directly so we can get a response time. sock_info = self.__socket() response, res_time = self.__simple_command(sock_info, 'admin', {'ismaster': 1}) self.__pool.maybe_return_socket(sock_info) # Are we talking to a mongos? isdbgrid = response.get('msg', '') == 'isdbgrid' if "maxBsonObjectSize" in response: self.__max_bson_size = response["maxBsonObjectSize"] # Replica Set? if not self.__direct: # Check that this host is part of the given replica set. if self.__repl: set_name = response.get('setName') # The 'setName' field isn't returned by mongod before 1.6.2 # so we can't assume that if it's missing this host isn't in # the specified set. if set_name and set_name != self.__repl: raise ConfigurationError("%s:%d is not a member of " "replica set %s" % (node[0], node[1], self.__repl)) if "hosts" in response: self.__nodes = set([_partition_node(h) for h in response["hosts"]]) else: # The user passed a seed list of standalone or # mongos instances. self.__nodes.add(node) if response["ismaster"]: return node, True, isdbgrid, res_time elif "primary" in response: candidate = _partition_node(response["primary"]) return self.__try_node(candidate) # Explain why we aren't using this connection. raise AutoReconnect('%s:%d is not primary or master' % node) # Direct connection if response.get("arbiterOnly", False) and not self.__direct: raise ConfigurationError("%s:%d is an arbiter" % node) return node, response['ismaster'], isdbgrid, res_time def __pick_nearest(self, candidates): """Return the 'nearest' candidate based on response time. """ latency = self.secondary_acceptable_latency_ms # Only used for mongos high availability, res_time is in seconds. fastest = min([res_time for candidate, res_time in candidates]) near_candidates = [ candidate for candidate, res_time in candidates if res_time - fastest < latency / 1000.0 ] node = random.choice(near_candidates) # Clear the pool from the last choice. self.disconnect() self.__host, self.__port = node return node def __find_node(self, seeds=None): """Find a host, port pair suitable for our connection type. If only one host was supplied to __init__ see if we can connect to it. Don't check if the host is a master/primary so we can make a direct connection to read from a secondary or send commands to an arbiter. If more than one host was supplied treat them as a seed list for connecting to a replica set or to support high availability for mongos. If connecting to a replica set try to find the primary and fail if we can't, possibly updating any replSet information on success. If a mongos seed list was provided find the "nearest" mongos and return it. Otherwise we iterate through the list trying to find a host we can send write operations to. Sets __host and __port so that :attr:`host` and :attr:`port` will return the address of the connected host. Sets __is_primary to True if this is a primary or master, else False. Sets __is_mongos to True if the connection is to a mongos. """ errors = [] mongos_candidates = [] candidates = seeds or self.__nodes.copy() for candidate in candidates: try: node, ismaster, isdbgrid, res_time = self.__try_node(candidate) self.__is_primary = ismaster self.__is_mongos = isdbgrid # No need to calculate nearest if we only have one mongos. if isdbgrid and not self.__direct: mongos_candidates.append((node, res_time)) continue elif len(mongos_candidates): raise ConfigurationError("Seed list cannot contain a mix " "of mongod and mongos instances.") return node except Exception as why: errors.append(str(why)) # If we have a mongos seed list, pick the "nearest" member. if len(mongos_candidates): self.__is_mongos = True return self.__pick_nearest(mongos_candidates) # Otherwise, try any hosts we discovered that were not in the seed list. for candidate in self.__nodes - candidates: try: node, ismaster, isdbgrid, _ = self.__try_node(candidate) self.__is_primary = ismaster self.__is_mongos = isdbgrid return node except Exception as why: errors.append(str(why)) # Couldn't find a suitable host. self.disconnect() raise AutoReconnect(', '.join(errors)) def __socket(self): """Get a SocketInfo from the pool. """ host, port = (self.__host, self.__port) if host is None or (port is None and '/' not in host): host, port = self.__find_node() try: if self.auto_start_request and not self.in_request(): self.start_request() sock_info = self.__pool.get_socket((host, port)) except socket.error as why: self.disconnect() # Check if a unix domain socket if host.endswith('.sock'): host_details = "%s:" % host else: host_details = "%s:%d:" % (host, port) raise AutoReconnect("could not connect to " "%s %s" % (host_details, str(why))) try: self.__check_auth(sock_info) except OperationFailure: self.__pool.maybe_return_socket(sock_info) raise return sock_info def disconnect(self): """Disconnect from MongoDB. Disconnecting will close all underlying sockets in the connection pool. If this instance is used again it will be automatically re-opened. Care should be taken to make sure that :meth:`disconnect` is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results. .. seealso:: :meth:`end_request` .. versionadded:: 1.3 """ self.__pool.reset() self.__host = None self.__port = None def close(self): """Alias for :meth:`disconnect` Disconnecting will close all underlying sockets in the connection pool. If this instance is used again it will be automatically re-opened. Care should be taken to make sure that :meth:`disconnect` is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results. .. seealso:: :meth:`end_request` .. versionadded:: 2.1 """ self.disconnect() def alive(self): """Return ``False`` if there has been an error communicating with the server, else ``True``. This method attempts to check the status of the server with minimal I/O. The current thread / greenlet retrieves a socket from the pool (its request socket if it's in a request, or a random idle socket if it's not in a request) and checks whether calling `select`_ on it raises an error. If there are currently no idle sockets, :meth:`alive` will attempt to actually connect to the server. A more certain way to determine server availability is:: client.admin.command('ping') .. _select: http://docs.python.org/2/library/select.html#select.select """ # In the common case, a socket is available and was used recently, so # calling select() on it is a reasonable attempt to see if the OS has # reported an error. Note this can be wasteful: __socket implicitly # calls select() if the socket hasn't been checked in the last second, # or it may create a new socket, in which case calling select() is # redundant. try: sock_info = self.__socket() return not pool._closed(sock_info.sock) except (socket.error, ConnectionFailure): return False def set_cursor_manager(self, manager_class): """Set this client's cursor manager. Raises :class:`TypeError` if `manager_class` is not a subclass of :class:`~pymongo.cursor_manager.CursorManager`. A cursor manager handles closing cursors. Different managers can implement different policies in terms of when to actually kill a cursor that has been closed. :Parameters: - `manager_class`: cursor manager to use .. versionchanged:: 2.1+ Deprecated support for external cursor managers. """ warnings.warn("Support for external cursor managers is deprecated " "and will be removed in PyMongo 3.0.", DeprecationWarning, stacklevel=2) manager = manager_class(self) if not isinstance(manager, CursorManager): raise TypeError("manager_class must be a subclass of " "CursorManager") self.__cursor_manager = manager def __check_response_to_last_error(self, response): """Check a response to a lastError message for errors. `response` is a byte string representing a response to the message. If it represents an error response we raise OperationFailure. Return the response as a document. """ response = helpers._unpack_response(response) assert response["number_returned"] == 1 error = response["data"][0] helpers._check_command_response(error, self.disconnect) error_msg = error.get("err", "") if error_msg is None: return error if error_msg.startswith("not master"): self.disconnect() raise AutoReconnect(error_msg) details = error # mongos returns the error code in an error object # for some errors. if "errObjects" in error: for errobj in error["errObjects"]: if errobj["err"] == error_msg: details = errobj break if "code" in details: if details["code"] in (11000, 11001, 12582): raise DuplicateKeyError(details["err"], details["code"]) else: raise OperationFailure(details["err"], details["code"]) else: raise OperationFailure(details["err"]) def __check_bson_size(self, message): """Make sure the message doesn't include BSON documents larger than the connected server will accept. :Parameters: - `message`: message to check """ if len(message) == 3: (request_id, data, max_doc_size) = message if max_doc_size > self.__max_bson_size: raise InvalidDocument("BSON document too large (%d bytes)" " - the connected server supports" " BSON document sizes up to %d" " bytes." % (max_doc_size, self.__max_bson_size)) return (request_id, data) else: # get_more and kill_cursors messages # don't include BSON documents. return message def _send_message(self, message, with_last_error=False, check_primary=True): """Say something to Mongo. Raises ConnectionFailure if the message cannot be sent. Raises OperationFailure if `with_last_error` is ``True`` and the response to the getLastError call returns an error. Return the response from lastError, or ``None`` if `with_last_error` is ``False``. :Parameters: - `message`: message to send - `with_last_error`: check getLastError status after sending the message - `check_primary`: don't try to write to a non-primary; see kill_cursors for an exception to this rule """ if check_primary and not with_last_error and not self.is_primary: # The write won't succeed, bail as if we'd done a getLastError raise AutoReconnect("not master") sock_info = self.__socket() try: (request_id, data) = self.__check_bson_size(message) sock_info.sock.sendall(data) # Safe mode. We pack the message together with a lastError # message and send both. We then get the response (to the # lastError) and raise OperationFailure if it is an error # response. rv = None if with_last_error: response = self.__receive_message_on_socket(1, request_id, sock_info) rv = self.__check_response_to_last_error(response) self.__pool.maybe_return_socket(sock_info) return rv except OperationFailure: self.__pool.maybe_return_socket(sock_info) raise except (ConnectionFailure, socket.error) as e: self.disconnect() raise AutoReconnect(str(e)) except: sock_info.close() raise def __receive_data_on_socket(self, length, sock_info): """Lowest level receive operation. Takes length to receive and repeatedly calls recv until able to return a buffer of that length, raising ConnectionFailure on error. """ message = EMPTY while length: chunk = sock_info.sock.recv(length) if chunk == EMPTY: raise ConnectionFailure("connection closed") length -= len(chunk) message += chunk return message def __receive_message_on_socket(self, operation, request_id, sock_info): """Receive a message in response to `request_id` on `sock`. Returns the response data with the header removed. """ header = self.__receive_data_on_socket(16, sock_info) length = struct.unpack("<i", header[:4])[0] assert request_id == struct.unpack("<i", header[8:12])[0], \ "ids don't match %r %r" % (request_id, struct.unpack("<i", header[8:12])[0]) assert operation == struct.unpack("<i", header[12:])[0] return self.__receive_data_on_socket(length - 16, sock_info) def __send_and_receive(self, message, sock_info): """Send a message on the given socket and return the response data. """ (request_id, data) = self.__check_bson_size(message) try: sock_info.sock.sendall(data) return self.__receive_message_on_socket(1, request_id, sock_info) except: sock_info.close() raise # we just ignore _must_use_master here: it's only relevant for # MasterSlaveConnection instances. def _send_message_with_response(self, message, _must_use_master=False, **kwargs): """Send a message to Mongo and return the response. Sends the given message and returns the response. :Parameters: - `message`: (request_id, data) pair making up the message to send """ sock_info = self.__socket() try: try: if "network_timeout" in kwargs: sock_info.sock.settimeout(kwargs["network_timeout"]) return self.__send_and_receive(message, sock_info) except (ConnectionFailure, socket.error) as e: self.disconnect() raise AutoReconnect(str(e)) finally: if "network_timeout" in kwargs: try: # Restore the socket's original timeout and return it to # the pool sock_info.sock.settimeout(self.__net_timeout) self.__pool.maybe_return_socket(sock_info) except socket.error: # There was an exception and we've closed the socket pass else: self.__pool.maybe_return_socket(sock_info) def start_request(self): """Ensure the current thread or greenlet always uses the same socket until it calls :meth:`end_request`. This ensures consistent reads, even if you read after an unacknowledged write. In Python 2.6 and above, or in Python 2.5 with "from __future__ import with_statement", :meth:`start_request` can be used as a context manager: >>> client = pymongo.MongoClient(auto_start_request=False) >>> db = client.test >>> _id = db.test_collection.insert({}) >>> with client.start_request(): ... for i in range(100): ... db.test_collection.update({'_id': _id}, {'$set': {'i':i}}) ... ... # Definitely read the document after the final update completes ... print(db.test_collection.find({'_id': _id})) If a thread or greenlet calls start_request multiple times, an equal number of calls to :meth:`end_request` is required to end the request. .. versionchanged:: 2.4 Now counts the number of calls to start_request and doesn't end request until an equal number of calls to end_request. .. versionadded:: 2.2 The :class:`~pymongo.pool.Request` return value. :meth:`start_request` previously returned None """ self.__pool.start_request() return pool.Request(self) def in_request(self): """True if this thread is in a request, meaning it has a socket reserved for its exclusive use. """ return self.__pool.in_request() def end_request(self): """Undo :meth:`start_request`. If :meth:`end_request` is called as many times as :meth:`start_request`, the request is over and this thread's connection returns to the pool. Extra calls to :meth:`end_request` have no effect. Ending a request allows the :class:`~socket.socket` that has been reserved for this thread by :meth:`start_request` to be returned to the pool. Other threads will then be able to re-use that :class:`~socket.socket`. If your application uses many threads, or has long-running threads that infrequently perform MongoDB operations, then judicious use of this method can lead to performance gains. Care should be taken, however, to make sure that :meth:`end_request` is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results. """ self.__pool.end_request() def __eq__(self, other): if isinstance(other, self.__class__): us = (self.__host, self.__port) them = (other.__host, other.__port) return us == them return NotImplemented def __ne__(self, other): return not self == other def __repr__(self): if len(self.__nodes) == 1: return "MongoClient(%r, %r)" % (self.__host, self.__port) else: return "MongoClient(%r)" % ["%s:%d" % n for n in self.__nodes] def __getattr__(self, name): """Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get """ return database.Database(self, name) def __getitem__(self, name): """Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get """ return self.__getattr__(name) def close_cursor(self, cursor_id): """Close a single database cursor. Raises :class:`TypeError` if `cursor_id` is not an instance of ``(int, long)``. What closing the cursor actually means depends on this client's cursor manager. :Parameters: - `cursor_id`: id of cursor to close """ if not isinstance(cursor_id, int): raise TypeError("cursor_id must be an instance of (int, long)") self.__cursor_manager.close(cursor_id) def kill_cursors(self, cursor_ids): """Send a kill cursors message with the given ids. Raises :class:`TypeError` if `cursor_ids` is not an instance of ``list``. :Parameters: - `cursor_ids`: list of cursor ids to kill """ if not isinstance(cursor_ids, list): raise TypeError("cursor_ids must be a list") return self._send_message( message.kill_cursors(cursor_ids), check_primary=False) def server_info(self): """Get information about the MongoDB server we're connected to. """ return self.admin.command("buildinfo") def database_names(self): """Get a list of the names of all databases on the connected server. """ return [db["name"] for db in self.admin.command("listDatabases")["databases"]] def drop_database(self, name_or_database): """Drop a database. Raises :class:`TypeError` if `name_or_database` is not an instance of :class:`basestring` (:class:`str` in python 3) or Database. :Parameters: - `name_or_database`: the name of a database to drop, or a :class:`~pymongo.database.Database` instance representing the database to drop """ name = name_or_database if isinstance(name, database.Database): name = name.name if not isinstance(name, str): raise TypeError("name_or_database must be an instance of " "%s or Database" % (str.__name__,)) self._purge_index(name) self[name].command("dropDatabase") def copy_database(self, from_name, to_name, from_host=None, username=None, password=None): """Copy a database, potentially from another host. Raises :class:`TypeError` if `from_name` or `to_name` is not an instance of :class:`basestring` (:class:`str` in python 3). Raises :class:`~pymongo.errors.InvalidName` if `to_name` is not a valid database name. If `from_host` is ``None`` the current host is used as the source. Otherwise the database is copied from `from_host`. If the source database requires authentication, `username` and `password` must be specified. :Parameters: - `from_name`: the name of the source database - `to_name`: the name of the target database - `from_host` (optional): host name to copy from - `username` (optional): username for source database - `password` (optional): password for source database .. note:: Specifying `username` and `password` requires server version **>= 1.3.3+**. .. versionadded:: 1.5 """ if not isinstance(from_name, str): raise TypeError("from_name must be an instance " "of %s" % (str.__name__,)) if not isinstance(to_name, str): raise TypeError("to_name must be an instance " "of %s" % (str.__name__,)) database._check_name(to_name) command = {"fromdb": from_name, "todb": to_name} if from_host is not None: command["fromhost"] = from_host try: self.start_request() if username is not None: nonce = self.admin.command("copydbgetnonce", fromhost=from_host)["nonce"] command["username"] = username command["nonce"] = nonce command["key"] = auth._auth_key(nonce, username, password) return self.admin.command("copydb", **command) finally: self.end_request() @property def is_locked(self): """Is this server locked? While locked, all write operations are blocked, although read operations may still be allowed. Use :meth:`unlock` to unlock. .. versionadded:: 2.0 """ ops = self.admin.current_op() return bool(ops.get('fsyncLock', 0)) def fsync(self, **kwargs): """Flush all pending writes to datafiles. :Parameters: Optional parameters can be passed as keyword arguments: - `lock`: If True lock the server to disallow writes. - `async`: If True don't block while synchronizing. .. warning:: `async` and `lock` can not be used together. .. warning:: MongoDB does not support the `async` option on Windows and will raise an exception on that platform. .. versionadded:: 2.0 """ self.admin.command("fsync", **kwargs) def unlock(self): """Unlock a previously locked server. .. versionadded:: 2.0 """ self.admin['$cmd'].sys.unlock.find_one() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.disconnect() def __iter__(self): return self def __next__(self): raise TypeError("'MongoClient' object is not iterable")
def __init__( self, host=None, port=None, document_class=dict, tz_aware=False, connect=True, **kwargs): """Client for a MongoDB instance, a replica set, or a set of mongoses. The client object is thread-safe and has connection-pooling built in. If an operation fails because of a network error, :class:`~pymongo.errors.ConnectionFailure` is raised and the client reconnects in the background. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ':', '/', '+' and '@' must be escaped following RFC 2396. :Parameters: - `host` (optional): hostname or IP address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs. If `host` is an IPv6 literal it must be enclosed in '[' and ']' characters following the RFC2732 URL syntax (e.g. '[::1]' for localhost) - `port` (optional): port number on which to connect - `document_class` (optional): default class to use for documents returned from queries on this client - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`MongoClient` will be timezone aware (otherwise they will be naive) - `connect` (optional): if ``True`` (the default), immediately begin connecting to MongoDB in the background. Otherwise connect on the first operation. | **Other optional parameters can be passed as keyword arguments:** - `maxPoolSize` (optional): The maximum number of connections that the pool will open simultaneously. If this is set, operations will block if there are `maxPoolSize` outstanding connections from the pool. Defaults to 100. Cannot be 0. - `socketTimeoutMS`: (integer or None) Controls how long (in milliseconds) the driver will wait for a response after sending an ordinary (non-monitoring) database operation before concluding that a network error has occurred. Defaults to ``None`` (no timeout). - `connectTimeoutMS`: (integer or None) Controls how long (in milliseconds) the driver will wait during server monitoring when connecting a new socket to a server before concluding the server is unavailable. Defaults to ``20000`` (20 seconds). - `serverSelectionTimeoutMS`: (integer) Controls how long (in milliseconds) the driver will wait to find an available, appropriate server to carry out a database operation; while it is waiting, multiple server monitoring operations may be carried out, each controlled by `connectTimeoutMS`. Defaults to ``30000`` (30 seconds). - `waitQueueTimeoutMS`: (integer or None) How long (in milliseconds) a thread will wait for a socket from the pool if the pool has no free sockets. Defaults to ``None`` (no timeout). - `waitQueueMultiple`: (integer or None) Multiplied by maxPoolSize to give the number of threads allowed to wait for a socket at one time. Defaults to ``None`` (no limit). - `socketKeepAlive`: (boolean) Whether to send periodic keep-alive packets on connected sockets. Defaults to ``False`` (do not send keep-alive packets). | **Write Concern options:** | (Only set if passed. No default values.) - `w`: (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. `w=<int>` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). Passing w=0 **disables write acknowledgement** and all other write concern options. - `wtimeout`: (integer) Used in conjunction with `w`. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised. - `j`: If ``True`` block until write operations have been committed to the journal. Cannot be used in combination with `fsync`. Prior to MongoDB 2.6 this option was ignored if the server was running without journaling. Starting with MongoDB 2.6 write operations will fail with an exception if this option is used when the server is running without journaling. - `fsync`: If ``True`` and the server is running without journaling, blocks until the server has synced all data files to disk. If the server is running with journaling, this acts the same as the `j` option, blocking until write operations have been committed to the journal. Cannot be used in combination with `j`. | **Replica set keyword arguments for connecting with a replica set - either directly or via a mongos:** - `replicaSet`: (string or None) The name of the replica set to connect to. The driver will verify that all servers it connects to match this name. Implies that the hosts specified are a seed list and the driver should attempt to find all members of the set. Defaults to ``None``. - `read_preference`: The read preference for this client. If connecting directly to a secondary then a read preference mode *other* than PRIMARY is required - otherwise all queries will throw :class:`~pymongo.errors.AutoReconnect` "not master". See :class:`~pymongo.read_preferences.ReadPreference` for all available read preference options. Defaults to ``PRIMARY``. | **SSL configuration:** - `ssl`: If ``True``, create the connection to the server using SSL. Defaults to ``False``. - `ssl_keyfile`: The private keyfile used to identify the local connection against mongod. If included with the ``certfile`` then only the ``ssl_certfile`` is needed. Implies ``ssl=True``. Defaults to ``None``. - `ssl_certfile`: The certificate file used to identify the local connection against mongod. Implies ``ssl=True``. Defaults to ``None``. - `ssl_cert_reqs`: Specifies whether a certificate is required from the other side of the connection, and whether it will be validated if provided. It must be one of the three values ``ssl.CERT_NONE`` (certificates ignored), ``ssl.CERT_OPTIONAL`` (not required, but validated if provided), or ``ssl.CERT_REQUIRED`` (required and validated). If the value of this parameter is not ``ssl.CERT_NONE`` and a value is not provided for ``ssl_ca_certs`` PyMongo will attempt to load system provided CA certificates. If the python version in use does not support loading system CA certificates then the ``ssl_ca_certs`` parameter must point to a file of CA certificates. Implies ``ssl=True``. Defaults to ``ssl.CERT_REQUIRED`` if not provided and ``ssl=True``. - `ssl_ca_certs`: The ca_certs file contains a set of concatenated "certification authority" certificates, which are used to validate certificates passed from the other end of the connection. Implies ``ssl=True``. Defaults to ``None``. - `ssl_match_hostname`: If ``True`` (the default), and `ssl_cert_reqs` is not ``ssl.CERT_NONE``, enables hostname verification using the :func:`~ssl.match_hostname` function from python's :mod:`~ssl` module. Think very carefully before setting this to ``False`` as that could make your application vulnerable to man-in-the-middle attacks. .. mongodoc:: connections .. versionchanged:: 3.0 :class:`~pymongo.mongo_client.MongoClient` is now the one and only client class for a standalone server, mongos, or replica set. It includes the functionality that had been split into :class:`~pymongo.mongo_client.MongoReplicaSetClient`: it can connect to a replica set, discover all its members, and monitor the set for stepdowns, elections, and reconfigs. The :class:`~pymongo.mongo_client.MongoClient` constructor no longer blocks while connecting to the server or servers, and it no longer raises :class:`~pymongo.errors.ConnectionFailure` if they are unavailable, nor :class:`~pymongo.errors.ConfigurationError` if the user's credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads. Therefore the ``alive`` method is removed since it no longer provides meaningful information; even if the client is disconnected, it may discover a server in time to fulfill the next operation. In PyMongo 2.x, :class:`~pymongo.MongoClient` accepted a list of standalone MongoDB servers and used the first it could connect to:: MongoClient(['host1.com:27017', 'host2.com:27017']) A list of multiple standalones is no longer supported; if multiple servers are listed they must be members of the same replica set, or mongoses in the same sharded cluster. The behavior for a list of mongoses is changed from "high availability" to "load balancing". Before, the client connected to the lowest-latency mongos in the list, and used it until a network error prompted it to re-evaluate all mongoses' latencies and reconnect to one of them. In PyMongo 3, the client monitors its network latency to all the mongoses continuously, and distributes operations evenly among those with the lowest latency. See :ref:`mongos-load-balancing` for more information. The ``connect`` option is added. The ``start_request``, ``in_request``, and ``end_request`` methods are removed, as well as the ``auto_start_request`` option. The ``copy_database`` method is removed, see the :doc:`copy_database examples </examples/copydb>` for alternatives. The :meth:`MongoClient.disconnect` method is removed; it was a synonym for :meth:`~pymongo.MongoClient.close`. :class:`~pymongo.mongo_client.MongoClient` no longer returns an instance of :class:`~pymongo.database.Database` for attribute names with leading underscores. You must use dict-style lookups instead:: client['__my_database__'] Not:: client.__my_database__ """ if host is None: host = self.HOST if isinstance(host, string_type): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") seeds = set() username = None password = None dbase = None opts = {} for entity in host: if "://" in entity: if entity.startswith("mongodb://"): res = uri_parser.parse_uri(entity, port, False) seeds.update(res["nodelist"]) username = res["username"] or username password = res["password"] or password dbase = res["database"] or dbase opts = res["options"] else: idx = entity.find("://") raise InvalidURI("Invalid URI scheme: " "%s" % (entity[:idx],)) else: seeds.update(uri_parser.split_hosts(entity, port)) if not seeds: raise ConfigurationError("need to specify at least one host") # _pool_class, _monitor_class, and _condition_class are for deep # customization of PyMongo, e.g. Motor. pool_class = kwargs.pop('_pool_class', None) monitor_class = kwargs.pop('_monitor_class', None) condition_class = kwargs.pop('_condition_class', None) kwargs['document_class'] = document_class kwargs['tz_aware'] = tz_aware opts.update(kwargs) self.__options = options = ClientOptions( username, password, dbase, opts) self.__default_database_name = dbase self.__lock = threading.Lock() self.__cursor_manager = CursorManager(self) self.__kill_cursors_queue = [] # Cache of existing indexes used by ensure_index ops. self.__index_cache = {} super(MongoClient, self).__init__(options.codec_options, options.read_preference, options.write_concern) self.__all_credentials = {} creds = options.credentials if creds: self._cache_credentials(creds.source, creds) self._topology_settings = TopologySettings( seeds=seeds, replica_set_name=options.replica_set_name, pool_class=pool_class, pool_options=options.pool_options, monitor_class=monitor_class, condition_class=condition_class, local_threshold_ms=options.local_threshold_ms, server_selection_timeout=options.server_selection_timeout) self._topology = Topology(self._topology_settings) if connect: self._topology.open() def target(): client = self_ref() if client is None: return False # Stop the executor. MongoClient._process_kill_cursors_queue(client) return True executor = periodic_executor.PeriodicExecutor( condition_class=self._topology_settings.condition_class, interval=common.KILL_CURSOR_FREQUENCY, min_interval=0, target=target) # We strongly reference the executor and it weakly references us via # this closure. When the client is freed, stop the executor soon. self_ref = weakref.ref(self, executor.close) self._kill_cursors_executor = executor executor.open()
class Connection(object): # TODO support auth for pooling """Connection to MongoDB. """ HOST = "localhost" PORT = 27017 def __init__(self, host=None, port=None, pool_size=None, auto_start_request=None, timeout=None, slave_okay=False, network_timeout=None, document_class=dict, tz_aware=False, _connect=True): """Create a new connection to a single MongoDB instance at *host:port*. The resultant connection object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, :class:`~pymongo.errors.ConnectionFailure` is raised. If auto-reconnection will be performed, :class:`~pymongo.errors.AutoReconnect` will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute. Raises :class:`TypeError` if port is not an instance of ``int``. Raises :class:`~pymongo.errors.ConnectionFailure` if the connection cannot be made. The `host` parameter can be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the `port` parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. :Parameters: - `host` (optional): hostname or IPv4 address of the instance to connect to, or a mongodb URI, or a list of hostnames / mongodb URIs - `port` (optional): port number on which to connect - `pool_size` (optional): DEPRECATED - `auto_start_request` (optional): DEPRECATED - `slave_okay` (optional): is it okay to connect directly to and perform queries on a slave instance - `timeout` (optional): DEPRECATED - `network_timeout` (optional): timeout (in seconds) to use for socket operations - default is no timeout - `document_class` (optional): default class to use for documents returned from queries on this connection - `tz_aware` (optional): if ``True``, :class:`~datetime.datetime` instances returned as values in a document by this :class:`Connection` will be timezone aware (otherwise they will be naive) .. seealso:: :meth:`end_request` .. versionchanged:: 1.8 The `host` parameter can now be a full `mongodb URI <http://dochub.mongodb.org/core/connections>`_, in addition to a simple hostname. It can also be a list of hostnames or URIs. .. versionadded:: 1.8 The `tz_aware` parameter. .. versionadded:: 1.7 The `document_class` parameter. .. versionchanged:: 1.4 DEPRECATED The `pool_size`, `auto_start_request`, and `timeout` parameters. .. versionadded:: 1.1 The `network_timeout` parameter. .. mongodoc:: connections """ if host is None: host = self.HOST if isinstance(host, str): host = [host] if port is None: port = self.PORT if not isinstance(port, int): raise TypeError("port must be an instance of int") nodes = set() database = None username = None password = None for uri in host: (n, db, u, p) = _parse_uri(uri, port) nodes.update(n) database = db or database username = u or username password = p or password if not nodes: raise ConfigurationError("need to specify at least one host") self.__nodes = nodes if database and username is None: raise InvalidURI("cannot specify database without " "a username and password") if pool_size is not None: warnings.warn("The pool_size parameter to Connection is " "deprecated", DeprecationWarning) if auto_start_request is not None: warnings.warn("The auto_start_request parameter to Connection " "is deprecated", DeprecationWarning) if timeout is not None: warnings.warn("The timeout parameter to Connection is deprecated", DeprecationWarning) self.__host = None self.__port = None self.__slave_okay = slave_okay if slave_okay and len(self.__nodes) > 1: raise ConfigurationError("cannot specify slave_okay for a paired " "or replica set connection") self.__cursor_manager = CursorManager(self) self.__pool = _Pool(self.__connect) self.__last_checkout = time.time() self.__network_timeout = network_timeout self.__document_class = document_class self.__tz_aware = tz_aware # cache of existing indexes used by ensure_index ops self.__index_cache = {} if _connect: self.__find_master() if username: database = database or "admin" if not self[database].authenticate(username, password): raise ConfigurationError("authentication failed") @classmethod def from_uri(cls, uri="mongodb://localhost", **connection_args): """DEPRECATED Can pass a mongodb URI directly to Connection() instead. .. versionchanged:: 1.8 DEPRECATED .. versionadded:: 1.5 """ warnings.warn("Connection.from_uri is deprecated - can pass " "URIs to Connection() now", DeprecationWarning) return cls(uri, **connection_args) @classmethod def paired(cls, left, right=None, **connection_args): """DEPRECATED Can pass a list of hostnames to Connection() instead. .. versionchanged:: 1.8 DEPRECATED """ warnings.warn("Connection.paired is deprecated - can pass multiple " "hostnames to Connection() now", DeprecationWarning) if isinstance(left, str) or isinstance(right, str): raise TypeError("arguments to paired must be tuples") if right is None: right = (cls.HOST, cls.PORT) return cls([":".join(map(str, left)), ":".join(map(str, right))], **connection_args) def _cache_index(self, database, collection, index, ttl): """Add an index to the index cache for ensure_index operations. Return ``True`` if the index has been newly cached or if the index had expired and is being re-cached. Return ``False`` if the index exists and is valid. """ now = datetime.datetime.utcnow() expire = datetime.timedelta(seconds=ttl) + now if database not in self.__index_cache: self.__index_cache[database] = {} self.__index_cache[database][collection] = {} self.__index_cache[database][collection][index] = expire return True if collection not in self.__index_cache[database]: self.__index_cache[database][collection] = {} self.__index_cache[database][collection][index] = expire return True if index in self.__index_cache[database][collection]: if now < self.__index_cache[database][collection][index]: return False self.__index_cache[database][collection][index] = expire return True def _purge_index(self, database_name, collection_name=None, index_name=None): """Purge an index from the index cache. If `index_name` is None purge an entire collection. If `collection_name` is None purge an entire database. """ if not database_name in self.__index_cache: return if collection_name is None: del self.__index_cache[database_name] return if not collection_name in self.__index_cache[database_name]: return if index_name is None: del self.__index_cache[database_name][collection_name] return if index_name in self.__index_cache[database_name][collection_name]: del self.__index_cache[database_name][collection_name][index_name] @property def host(self): """Current connected host. .. versionchanged:: 1.3 ``host`` is now a property rather than a method. """ return self.__host @property def port(self): """Current connected port. .. versionchanged:: 1.3 ``port`` is now a property rather than a method. """ return self.__port @property def nodes(self): """List of all known nodes. Includes both nodes specified when the :class:`Connection` was created, as well as nodes discovered through the replica set discovery mechanism. .. versionadded:: 1.8 """ return self.__nodes @property def slave_okay(self): """Is it okay for this connection to connect directly to a slave? """ return self.__slave_okay def get_document_class(self): return self.__document_class def set_document_class(self, klass): self.__document_class = klass document_class = property(get_document_class, set_document_class, doc="""Default class to use for documents returned on this connection. .. versionadded:: 1.7 """) @property def tz_aware(self): """Does this connection return timezone-aware datetimes? See the `tz_aware` parameter to :meth:`Connection`. .. versionadded:: 1.8 """ return self.__tz_aware def __add_hosts_and_get_primary(self, response): if "hosts" in response: self.__nodes.update([_str_to_node(h) for h in response["hosts"]]) if "primary" in response: return _str_to_node(response["primary"]) return False def __try_node(self, node): self.disconnect() self.__host, self.__port = node try: response = self.admin.command("ismaster") self.end_request() primary = self.__add_hosts_and_get_primary(response) if response["ismaster"]: return True return primary except: self.end_request() return None def __find_master(self): """Create a new socket and use it to figure out who the master is. Sets __host and __port so that :attr:`host` and :attr:`port` will return the address of the master. Also (possibly) updates any replSet information. """ # Special case the first node to try to get the primary or any # additional hosts from a replSet: first = next(iter(self.__nodes)) primary = self.__try_node(first) if primary is True: return first # no network error if self.__slave_okay and primary is not None: return first # Wasn't the first node, but we got a primary - let's try it: tried = [first] if primary: if self.__try_node(primary) is True: return primary tried.append(primary) nodes = self.__nodes - set(tried) # Just scan # TODO parallelize these to minimize connect time? for node in nodes: if self.__try_node(node) is True: return node raise AutoReconnect("could not find master/primary") def __connect(self): """(Re-)connect to Mongo and return a new (connected) socket. Connect to the master if this is a paired connection. """ host, port = (self.__host, self.__port) if host is None or port is None: host, port = self.__find_master() try: sock = socket.socket() sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.settimeout(self.__network_timeout or _CONNECT_TIMEOUT) sock.connect((host, port)) sock.settimeout(self.__network_timeout) return sock except socket.error: self.disconnect() raise AutoReconnect("could not connect to %r" % list(self.__nodes)) def __socket(self): """Get a socket from the pool. If it's been > 1 second since the last time we checked out a socket, we also check to see if the socket has been closed - this let's us avoid seeing *some* :class:`~pymongo.errors.AutoReconnect` exceptions on server hiccups, etc. We only do this if it's been > 1 second since the last socket checkout, to keep performance reasonable - we can't avoid those completely anyway. """ sock = self.__pool.socket() t = time.time() if t - self.__last_checkout > 1: if _closed(sock): self.disconnect() sock = self.__pool.socket() self.__last_checkout = t return sock def disconnect(self): """Disconnect from MongoDB. Disconnecting will close all underlying sockets in the connection pool. If the :class:`Connection` is used again it will be automatically re-opened. Care should be taken to make sure that :meth:`disconnect` is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results. .. seealso:: :meth:`end_request` .. versionadded:: 1.3 """ self.__pool = _Pool(self.__connect) self.__host = None self.__port = None def set_cursor_manager(self, manager_class): """Set this connection's cursor manager. Raises :class:`TypeError` if `manager_class` is not a subclass of :class:`~pymongo.cursor_manager.CursorManager`. A cursor manager handles closing cursors. Different managers can implement different policies in terms of when to actually kill a cursor that has been closed. :Parameters: - `manager_class`: cursor manager to use """ manager = manager_class(self) if not isinstance(manager, CursorManager): raise TypeError("manager_class must be a subclass of " "CursorManager") self.__cursor_manager = manager def __check_response_to_last_error(self, response): """Check a response to a lastError message for errors. `response` is a byte string representing a response to the message. If it represents an error response we raise OperationFailure. Return the response as a document. """ response = helpers._unpack_response(response) assert response["number_returned"] == 1 error = response["data"][0] helpers._check_command_response(error, self.disconnect) # TODO unify logic with database.error method if error.get("err", 0) is None: return error if error["err"] == "not master": self.disconnect() raise AutoReconnect("not master") if "code" in error: if error["code"] in [11000, 11001]: raise DuplicateKeyError(error["err"]) else: raise OperationFailure(error["err"], error["code"]) else: raise OperationFailure(error["err"]) def _send_message(self, message, with_last_error=False): """Say something to Mongo. Raises ConnectionFailure if the message cannot be sent. Raises OperationFailure if `with_last_error` is ``True`` and the response to the getLastError call returns an error. Return the response from lastError, or ``None`` if `with_last_error` is ``False``. :Parameters: - `message`: message to send - `with_last_error`: check getLastError status after sending the message """ sock = self.__socket() try: (request_id, data) = message sock.sendall(data) # Safe mode. We pack the message together with a lastError # message and send both. We then get the response (to the # lastError) and raise OperationFailure if it is an error # response. if with_last_error: response = self.__receive_message_on_socket(1, request_id, sock) return self.__check_response_to_last_error(response) return None except (ConnectionFailure, socket.error) as e: self.disconnect() raise AutoReconnect(str(e)) def __receive_data_on_socket(self, length, sock): """Lowest level receive operation. Takes length to receive and repeatedly calls recv until able to return a buffer of that length, raising ConnectionFailure on error. """ message = b"" while len(message) < length: chunk = sock.recv(length - len(message)) if chunk == b"": raise ConnectionFailure("connection closed") message += chunk return message def __receive_message_on_socket(self, operation, request_id, sock): """Receive a message in response to `request_id` on `sock`. Returns the response data with the header removed. """ header = self.__receive_data_on_socket(16, sock) length = struct.unpack("<i", header[:4])[0] assert request_id == struct.unpack("<i", header[8:12])[0], \ "ids don't match %r %r" % (request_id, struct.unpack("<i", header[8:12])[0]) assert operation == struct.unpack("<i", header[12:])[0] return self.__receive_data_on_socket(length - 16, sock) def __send_and_receive(self, message, sock): """Send a message on the given socket and return the response data. """ (request_id, data) = message sock.sendall(data) return self.__receive_message_on_socket(1, request_id, sock) # we just ignore _must_use_master here: it's only relevant for # MasterSlaveConnection instances. def _send_message_with_response(self, message, _must_use_master=False, **kwargs): """Send a message to Mongo and return the response. Sends the given message and returns the response. :Parameters: - `message`: (request_id, data) pair making up the message to send """ sock = self.__socket() try: try: if "network_timeout" in kwargs: sock.settimeout(kwargs["network_timeout"]) return self.__send_and_receive(message, sock) except (ConnectionFailure, socket.error) as e: self.disconnect() raise AutoReconnect(str(e)) finally: if "network_timeout" in kwargs: sock.settimeout(self.__network_timeout) def start_request(self): """DEPRECATED all operations will start a request. .. versionchanged:: 1.4 DEPRECATED """ warnings.warn("the Connection.start_request method is deprecated", DeprecationWarning) def end_request(self): """Allow this thread's connection to return to the pool. Calling :meth:`end_request` allows the :class:`~socket.socket` that has been reserved for this thread to be returned to the pool. Other threads will then be able to re-use that :class:`~socket.socket`. If your application uses many threads, or has long-running threads that infrequently perform MongoDB operations, then judicious use of this method can lead to performance gains. Care should be taken, however, to make sure that :meth:`end_request` is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results. One important case is when a thread is dying permanently. It is best to call :meth:`end_request` when you know a thread is finished, as otherwise its :class:`~socket.socket` will not be reclaimed. """ self.__pool.return_socket() def __eq__(self, other): if isinstance(other, Connection): mytuple = (self.__host, self.__port) othertuple = (other.__host, other.__port) return mytuple == othertuple return NotImplemented def __repr__(self): if len(self.__nodes) == 1: return "Connection(%r, %r)" % (self.__host, self.__port) else: return "Connection(%r)" % ["%s:%d" % n for n in self.__nodes] def __getattr__(self, name): """Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get """ return database.Database(self, name) def __getitem__(self, name): """Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get """ return self.__getattr__(name) def close_cursor(self, cursor_id): """Close a single database cursor. Raises :class:`TypeError` if `cursor_id` is not an instance of ``(int, long)``. What closing the cursor actually means depends on this connection's cursor manager. :Parameters: - `cursor_id`: id of cursor to close .. seealso:: :meth:`set_cursor_manager` and the :mod:`~pymongo.cursor_manager` module """ if not isinstance(cursor_id, int): raise TypeError("cursor_id must be an instance of (int, long)") self.__cursor_manager.close(cursor_id) def kill_cursors(self, cursor_ids): """Send a kill cursors message with the given ids. Raises :class:`TypeError` if `cursor_ids` is not an instance of ``list``. :Parameters: - `cursor_ids`: list of cursor ids to kill """ if not isinstance(cursor_ids, list): raise TypeError("cursor_ids must be a list") return self._send_message(message.kill_cursors(cursor_ids)) def server_info(self): """Get information about the MongoDB server we're connected to. """ return self.admin.command("buildinfo") def database_names(self): """Get a list of the names of all databases on the connected server. """ return [db["name"] for db in self.admin.command("listDatabases")["databases"]] def drop_database(self, name_or_database): """Drop a database. Raises :class:`TypeError` if `name_or_database` is not an instance of ``(str, unicode, Database)`` :Parameters: - `name_or_database`: the name of a database to drop, or a :class:`~pymongo.database.Database` instance representing the database to drop """ name = name_or_database if isinstance(name, database.Database): name = name.name if not isinstance(name, str): raise TypeError("name_or_database must be an instance of " "(Database, str, unicode)") self._purge_index(name) self[name].command("dropDatabase") def copy_database(self, from_name, to_name, from_host=None, username=None, password=None): """Copy a database, potentially from another host. Raises :class:`TypeError` if `from_name` or `to_name` is not an instance of :class:`str`. Raises :class:`~pymongo.errors.InvalidName` if `to_name` is not a valid database name. If `from_host` is ``None`` the current host is used as the source. Otherwise the database is copied from `from_host`. If the source database requires authentication, `username` and `password` must be specified. :Parameters: - `from_name`: the name of the source database - `to_name`: the name of the target database - `from_host` (optional): host name to copy from - `username` (optional): username for source database - `password` (optional): password for source database .. note:: Specifying `username` and `password` requires server version **>= 1.3.3+**. .. versionadded:: 1.5 """ if not isinstance(from_name, str): raise TypeError("from_name must be an instance of str") if not isinstance(to_name, str): raise TypeError("to_name must be an instance of str") database._check_name(to_name) command = {"fromdb": from_name, "todb": to_name} if from_host is not None: command["fromhost"] = from_host if username is not None: nonce = self.admin.command("copydbgetnonce", fromhost=from_host)["nonce"] command["username"] = username command["nonce"] = nonce command["key"] = helpers._auth_key(nonce, username, password) return self.admin.command("copydb", **command) def __iter__(self): return self def __next__(self): raise TypeError("'Connection' object is not iterable")