-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
mongo_client.py
1883 lines (1594 loc) · 79.8 KB
/
mongo_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2009-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License. You
# may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
"""Tools for connecting to MongoDB.
.. seealso:: :doc:`/examples/high_availability` for examples of connecting
to replica sets or sets of mongos servers.
To get a :class:`~pymongo.database.Database` instance from a
:class:`MongoClient` use either dictionary-style or attribute-style
access:
.. doctest::
>>> from pymongo import MongoClient
>>> c = MongoClient()
>>> c.test_database
Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), u'test_database')
>>> c['test-database']
Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), u'test-database')
"""
import contextlib
import datetime
import threading
import warnings
import weakref
from collections import defaultdict
from bson.codec_options import DEFAULT_CODEC_OPTIONS
from bson.py3compat import (integer_types,
string_type)
from bson.son import SON
from pymongo import (common,
database,
helpers,
message,
periodic_executor,
uri_parser,
client_session)
from pymongo.change_stream import ClusterChangeStream
from pymongo.client_options import ClientOptions
from pymongo.command_cursor import CommandCursor
from pymongo.cursor_manager import CursorManager
from pymongo.errors import (AutoReconnect,
BulkWriteError,
ConfigurationError,
ConnectionFailure,
InvalidOperation,
NetworkTimeout,
NotMasterError,
OperationFailure,
PyMongoError,
ServerSelectionTimeoutError)
from pymongo.read_preferences import ReadPreference
from pymongo.server_selectors import (writable_preferred_server_selector,
writable_server_selector)
from pymongo.server_type import SERVER_TYPE
from pymongo.topology import Topology
from pymongo.topology_description import TOPOLOGY_TYPE
from pymongo.settings import TopologySettings
from pymongo.write_concern import DEFAULT_WRITE_CONCERN
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=None,
connect=None,
**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
percent encoded following RFC 2396::
try:
# Python 3.x
from urllib.parse import quote_plus
except ImportError:
# Python 2.x
from urllib import quote_plus
uri = "mongodb://%s:%s@%s" % (
quote_plus(user), quote_plus(password), host)
client = MongoClient(uri)
Unix domain sockets are also supported. The socket path must be percent
encoded in the URI::
uri = "mongodb://%s:%s@%s" % (
quote_plus(user), quote_plus(password), quote_plus(socket_path))
client = MongoClient(uri)
But not when passed as a simple hostname::
client = MongoClient('/tmp/mongodb-27017.sock')
Starting with version 3.6, PyMongo supports mongodb+srv:// URIs. The
URI must include one, and only one, hostname. The hostname will be
resolved to one or more DNS `SRV records
<https://en.wikipedia.org/wiki/SRV_record>`_ which will be used
as the seed list for connecting to the MongoDB deployment. When using
SRV URIs, the `authSource` and `replicaSet` configuration options can
be specified using `TXT records
<https://en.wikipedia.org/wiki/TXT_record>`_. See the
`Initial DNS Seedlist Discovery spec
<https://github.com/mongodb/specifications/blob/master/source/
initial-dns-seedlist-discovery/initial-dns-seedlist-discovery.rst>`_
for more details. Note that the use of SRV URIs implicitly enables
TLS support. Pass ssl=false in the URI to override.
.. note:: MongoClient creation will block waiting for answers from
DNS when mongodb+srv:// URIs are used.
.. note:: Starting with version 3.0 the :class:`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. You can check if the server is available
like this::
from pymongo.errors import ConnectionFailure
client = MongoClient()
try:
# The ismaster command is cheap and does not require auth.
client.admin.command('ismaster')
except ConnectionFailure:
print("Server not available")
.. warning:: When using PyMongo in a multiprocessing context, please
read :ref:`multiprocessing` first.
:Parameters:
- `host` (optional): hostname or IP address or Unix domain socket
path of a single mongod or mongos 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).
Multihomed and round robin DNS addresses are **not** supported.
- `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 allowable number of
concurrent connections to each connected server. Requests to a
server will block if there are `maxPoolSize` outstanding
connections to the requested server. Defaults to 100. Cannot be 0.
- `minPoolSize` (optional): The minimum required number of concurrent
connections that the pool will maintain to each connected server.
Default is 0.
- `maxIdleTimeMS` (optional): The maximum number of milliseconds that
a connection can remain idle in the pool before being removed and
replaced. Defaults to `None` (no limit).
- `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).
- `heartbeatFrequencyMS`: (optional) The number of milliseconds
between periodic server checks, or None to accept the default
frequency of 10 seconds.
- `appname`: (string or None) The name of the application that
created this MongoClient instance. MongoDB 3.4 and newer will
print this value in the server log upon establishing each
connection. It is also recorded in the slow query log and
profile collections.
- `driver`: (pair or None) A driver implemented on top of PyMongo can
pass a :class:`~pymongo.driver_info.DriverInfo` to add its name,
version, and platform to the message printed in the server log when
establishing a connection.
- `event_listeners`: a list or tuple of event listeners. See
:mod:`~pymongo.monitoring` for details.
- `retryWrites`: (boolean) Whether supported write operations
executed within this MongoClient will be retried once after a
network error on MongoDB 3.6+. Defaults to ``False``.
The supported write operations are:
- :meth:`~pymongo.collection.Collection.bulk_write`, as long as
:class:`~pymongo.operations.UpdateMany` or
:class:`~pymongo.operations.DeleteMany` are not included.
- :meth:`~pymongo.collection.Collection.delete_one`
- :meth:`~pymongo.collection.Collection.insert_one`
- :meth:`~pymongo.collection.Collection.insert_many`
- :meth:`~pymongo.collection.Collection.replace_one`
- :meth:`~pymongo.collection.Collection.update_one`
- :meth:`~pymongo.collection.Collection.find_one_and_delete`
- :meth:`~pymongo.collection.Collection.find_one_and_replace`
- :meth:`~pymongo.collection.Collection.find_one_and_update`
Unsupported write operations include, but are not limited to,
:meth:`~pymongo.collection.Collection.aggregate` using the ``$out``
pipeline operator and any operation with an unacknowledged write
concern (e.g. {w: 0})). See
https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst
- `socketKeepAlive`: (boolean) **DEPRECATED** Whether to send
periodic keep-alive packets on connected sockets. Defaults to
``True``. Disabling it is not recommended, see
https://docs.mongodb.com/manual/faq/diagnostics/#does-tcp-keepalive-time-affect-mongodb-deployments",
- `compressors`: Comma separated list of compressors for wire
protocol compression. The list is used to negotiate a compressor
with the server. Currently supported options are "snappy" and
"zlib". Support for snappy requires the
`python-snappy <https://pypi.org/project/python-snappy/>`_ package.
zlib support requires the Python standard library zlib module.
By default no compression is used. Compression support must also be
enabled on the server. MongoDB 3.4+ supports snappy compression.
MongoDB 3.6+ supports snappy and zlib.
- `zlibCompressionLevel`: (int) The zlib compression level to use
when zlib is used as the wire protocol compressor. Supported values
are -1 through 9. -1 tells the zlib library to use its default
compression level (usually 6). 0 means no compression. 1 is best
speed. 9 is best compression. Defaults to -1.
| **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:**
- `readPreference`: The replica set read preference for this client.
One of ``primary``, ``primaryPreferred``, ``secondary``,
``secondaryPreferred``, or ``nearest``. Defaults to ``primary``.
- `readPreferenceTags`: Specifies a tag set as a comma-separated list
of colon-separated key-value pairs. For example ``dc:ny,rack:1``.
Defaults to ``None``.
- `maxStalenessSeconds`: (integer) The maximum estimated
length of time a replica set secondary can fall behind the primary
in replication before it will no longer be selected for operations.
Defaults to ``-1``, meaning no maximum. If maxStalenessSeconds
is set, it must be a positive integer greater than or equal to
90 seconds.
| **Authentication:**
- `username`: A string.
- `password`: A string.
Although username and password must be percent-escaped in a MongoDB
URI, they must not be percent-escaped when passed as parameters. In
this example, both the space and slash special characters are passed
as-is::
MongoClient(username="user name", password="pass/word")
- `authSource`: The database to authenticate on. Defaults to the
database specified in the URI, if provided, or to "admin".
- `authMechanism`: See :data:`~pymongo.auth.MECHANISMS` for options.
If no mechanism is specified, PyMongo automatically uses MONGODB-CR
when connected to a pre-3.0 version of MongoDB, SCRAM-SHA-1 when
connected to MongoDB 3.0 through 3.6, and negotiates the mechanism
to use (SCRAM-SHA-1 or SCRAM-SHA-256) when connected to MongoDB
4.0+.
- `authMechanismProperties`: Used to specify authentication mechanism
specific options. To specify the service name for GSSAPI
authentication pass authMechanismProperties='SERVICE_NAME:<service
name>'
.. seealso:: :doc:`/examples/authentication`
| **SSL configuration:**
- `ssl`: If ``True``, create the connection to the server using SSL.
Defaults to ``False``.
- `ssl_certfile`: The certificate file used to identify the local
connection against mongod. Implies ``ssl=True``. Defaults to
``None``.
- `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_pem_passphrase`: The password or passphrase for decrypting
the private key in ``ssl_certfile`` or ``ssl_keyfile``. Only
necessary if the private key is encrypted. Only supported by python
2.7.9+ (pypy 2.5.1+) and 3.3+. 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_REQUIRED`` (certificates
required and validated), or ``ssl.CERT_OPTIONAL`` (the same as
CERT_REQUIRED, unless the server was configured to use anonymous
ciphers). 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_crlfile`: The path to a PEM or DER formatted certificate
revocation list. Only supported by python 2.7.9+ (pypy 2.5.1+)
and 3.4+. 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.
| **Read Concern options:**
| (If not set explicitly, this will use the server default)
- `readConcernLevel`: (string) The read concern level specifies the
level of isolation for read operations. For example, a read
operation using a read concern level of ``majority`` will only
return data that has been written to a majority of nodes. If the
level is left unspecified, the server default will be used.
.. mongodoc:: connections
.. versionchanged:: 3.6
Added support for mongodb+srv:// URIs.
Added the ``retryWrites`` keyword argument and URI option.
.. versionchanged:: 3.7
Added the ``driver`` keyword argument.
.. versionchanged:: 3.5
Add ``username`` and ``password`` options. Document the
``authSource``, ``authMechanism``, and ``authMechanismProperties ``
options.
Deprecated the `socketKeepAlive` keyword argument and URI option.
`socketKeepAlive` now defaults to ``True``.
.. 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:
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:
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
if tz_aware is None:
tz_aware = opts.get('tz_aware', False)
if connect is None:
connect = opts.get('connect', True)
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)
# Username and password passed as kwargs override user info in URI.
username = opts.get("username", username)
password = opts.get("password", password)
if 'socketkeepalive' in opts:
warnings.warn(
"The socketKeepAlive option is deprecated. It now"
"defaults to true and disabling it is not recommended, see "
"https://docs.mongodb.com/manual/faq/diagnostics/"
"#does-tcp-keepalive-time-affect-mongodb-deployments",
DeprecationWarning, stacklevel=2)
self.__options = options = ClientOptions(
username, password, dbase, opts)
self.__default_database_name = dbase
self.__lock = threading.Lock()
self.__cursor_manager = None
self.__kill_cursors_queue = []
self._event_listeners = options.pool_options.event_listeners
# Cache of existing indexes used by ensure_index ops.
self.__index_cache = {}
self.__index_cache_lock = threading.Lock()
super(MongoClient, self).__init__(options.codec_options,
options.read_preference,
options.write_concern,
options.read_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,
heartbeat_frequency=options.heartbeat_frequency)
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_periodic_tasks(client)
return True
executor = periodic_executor.PeriodicExecutor(
interval=common.KILL_CURSOR_FREQUENCY,
min_interval=0.5,
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()
with self.__index_cache_lock:
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
with self.__index_cache_lock:
if dbname 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.
"""
with self.__index_cache_lock:
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):
"""An attribute of the current server's description.
If the client is not connected, this will block until a connection is
established or raise ServerSelectionTimeoutError if no server is
available.
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.
"""
server = self._topology.select_server(
writable_server_selector)
return getattr(server.description, attr_name)
def watch(self, pipeline=None, full_document='default', resume_after=None,
max_await_time_ms=None, batch_size=None, collation=None,
start_at_operation_time=None, session=None):
"""Watch changes on this cluster.
Performs an aggregation with an implicit initial ``$changeStream``
stage and returns a
:class:`~pymongo.change_stream.ClusterChangeStream` cursor which
iterates over changes on all databases on this cluster.
Introduced in MongoDB 4.0.
.. code-block:: python
with client.watch() as stream:
for change in stream:
print(change)
The :class:`~pymongo.change_stream.ClusterChangeStream` iterable
blocks until the next change document is returned or an error is
raised. If the
:meth:`~pymongo.change_stream.ClusterChangeStream.next` method
encounters a network error when retrieving a batch from the server,
it will automatically attempt to recreate the cursor such that no
change events are missed. Any error encountered during the resume
attempt indicates there may be an outage and will be raised.
.. code-block:: python
try:
with client.watch(
[{'$match': {'operationType': 'insert'}}]) as stream:
for insert_change in stream:
print(insert_change)
except pymongo.errors.PyMongoError:
# The ChangeStream encountered an unrecoverable error or the
# resume attempt failed to recreate the cursor.
logging.error('...')
For a precise description of the resume process see the
`change streams specification`_.
:Parameters:
- `pipeline` (optional): A list of aggregation pipeline stages to
append to an initial ``$changeStream`` stage. Not all
pipeline stages are valid after a ``$changeStream`` stage, see the
MongoDB documentation on change streams for the supported stages.
- `full_document` (optional): The fullDocument to pass as an option
to the ``$changeStream`` stage. Allowed values: 'default',
'updateLookup'. Defaults to 'default'.
When set to 'updateLookup', the change notification for partial
updates will include both a delta describing the changes to the
document, as well as a copy of the entire document that was
changed from some time after the change occurred.
- `resume_after` (optional): The logical starting point for this
change stream.
- `max_await_time_ms` (optional): The maximum time in milliseconds
for the server to wait for changes before responding to a getMore
operation.
- `batch_size` (optional): The maximum number of documents to return
per batch.
- `collation` (optional): The :class:`~pymongo.collation.Collation`
to use for the aggregation.
- `start_at_operation_time` (optional): If provided, the resulting
change stream will only return changes that occurred at or after
the specified :class:`~bson.timestamp.Timestamp`. Requires
MongoDB >= 4.0.
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
:Returns:
A :class:`~pymongo.change_stream.ClusterChangeStream` cursor.
.. versionadded:: 3.7
.. mongodoc:: changeStreams
.. _change streams specification:
https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.rst
"""
return ClusterChangeStream(
self.admin, pipeline, full_document, resume_after, max_await_time_ms,
batch_size, collation, start_at_operation_time, session
)
@property
def event_listeners(self):
"""The event listeners registered for this client.
See :mod:`~pymongo.monitoring` for details.
"""
return self._event_listeners.event_listeners
@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.
If the client is not connected, this will block until a connection is
established or raise ServerSelectionTimeoutError if no server is
available.
.. versionadded:: 3.0
"""
topology_type = self._topology._description.topology_type
if topology_type == TOPOLOGY_TYPE.Sharded:
raise InvalidOperation(
'Cannot use "address" property when load balancing among'
' mongoses, use "nodes" instead.')
if topology_type not in (TOPOLOGY_TYPE.ReplicaSetWithPrimary,
TOPOLOGY_TYPE.Single):
return None
return self._server_property('address')
@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 is connected to a server that can accept writes.
True if the current server is a standalone, mongos, or the primary of
a replica set. If the client is not connected, this will block until a
connection is established or raise ServerSelectionTimeoutError if no
server is available.
"""
return self._server_property('is_writable')
@property
def is_mongos(self):
"""If this client is connected to mongos. If the client is not
connected, this will block until a connection is established or raise
ServerSelectionTimeoutError if no server is available..
"""
return self._server_property('server_type') == SERVER_TYPE.Mongos
@property
def max_pool_size(self):
"""The maximum allowable number of concurrent connections to each
connected server. Requests to a server will block if there are
`maxPoolSize` outstanding connections to the requested server.
Defaults to 100. Cannot be 0.
When a server's pool has reached `max_pool_size`, operations for that
server 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 min_pool_size(self):
"""The minimum required number of concurrent connections that the pool
will maintain to each connected server. Default is 0.
"""
return self.__options.pool_options.min_pool_size
@property
def max_idle_time_ms(self):
"""The maximum number of milliseconds that a connection can remain
idle in the pool before being removed and replaced. Defaults to
`None` (no limit).
"""
seconds = self.__options.pool_options.max_idle_time_seconds
if seconds is None:
return None
return 1000 * seconds
@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.
If the client is not connected, this will block until a connection is
established or raise ServerSelectionTimeoutError if no server is
available.
"""
return self._server_property('max_bson_size')
@property
def max_message_size(self):
"""The largest message the connected server accepts in bytes.
If the client is not connected, this will block until a connection is
established or raise ServerSelectionTimeoutError if no server is
available.
"""
return self._server_property('max_message_size')
@property
def max_write_batch_size(self):
"""The maxWriteBatchSize reported by the server.
If the client is not connected, this will block until a connection is
established or raise ServerSelectionTimeoutError if no server is
available.
Returns a default value when connected to server versions prior to
MongoDB 2.6.
"""
return self._server_property('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
@property
def retry_writes(self):
"""If this instance should retry supported write operations."""
return self.__options.retry_writes
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 _end_sessions(self, session_ids):
"""Send endSessions command(s) with the given session ids."""
try:
# Use SocketInfo.command directly to avoid implicitly creating
# another session.
with self._socket_for_reads(
ReadPreference.PRIMARY_PREFERRED) as (sock_info, slave_ok):
if not sock_info.supports_sessions:
return
for i in range(0, len(session_ids), common._MAX_END_SESSIONS):
spec = SON([('endSessions',
session_ids[i:i + common._MAX_END_SESSIONS])])
sock_info.command(
'admin', spec, slave_ok=slave_ok, client=self)
except PyMongoError:
# Drivers MUST ignore any errors returned by the endSessions
# command.
pass
def close(self):
"""Cleanup client resources and disconnect from MongoDB.
On MongoDB >= 3.6, end all server sessions created by this client by
sending one or more endSessions commands.