3
O6bH                 @   s  d Z ddlmZmZ ddlmZ ddlmZ ddlm	Z	m
Z
 dZdZdZdZd	Zd1Zdd Zdd Zdd Zdd ZG dd deZG dd deZG dd deZG dd deZG dd  d eZG d!d" d"eZeeeeefZd3d#d$Zd4ZG d*d+ d+eZd,d- Z G d.d/ d/eZ!d0S )5zBUtilities for choosing which member of a replica set to read from.    )abcinteger_types)max_staleness_selectors)ConfigurationError) member_with_tags_server_selector#secondary_with_tags_server_selector            primaryprimaryPreferred	secondarysecondaryPreferrednearestc             C   sj   | dkr| S t | ts$td| f t| dkr>td| f x&| D ]}t |tjsDtd|f qDW | S )z3Validate tag sets for a MongoReplicaSetClient.
    Nz#Tag sets %r invalid, must be a listr   zETag sets %r invalid, must be None or contain at least one set of tagszqTag set %r invalid, must be an instance of dict, bson.son.SON or other type that inherits from collection.Mapping)
isinstancelist	TypeErrorlen
ValueErrorr   Mapping)tag_setstags r   W/var/www/html/sandeepIITI/myenv/lib/python3.6/site-packages/pymongo/read_preferences.py_validate_tag_sets(   s    


r   c             C   s   d|  S )Nz6maxStalenessSeconds must be a positive integer, not %sr   )max_stalenessr   r   r   _invalid_max_staleness_msg@   s    r   c             C   s:   | dkrdS t | ts"tt| | dkr6tt| | S )zValidate max_staleness.r   r   r   )r   r   r   r   r   )r   r   r   r   _validate_max_stalenessF   s    
r   c             C   s(   | dkrdS t | ts$td| f | S )zValidate hedge.Nz"hedge must be a dictionary, not %r)r   dictr   )hedger   r   r   _validate_hedgeT   s
    
r"   c               @   s   e Zd ZdZd%Zd'd	d
Zedd Zedd Zedd Z	edd Z
edd Zedd Zedd Zedd Zdd Zdd Zdd  Zd!d" Zd#d$ ZdS )(_ServerModez)Base class for all read preferences.
    __mongos_mode__mode
__tag_sets__max_staleness__hedgeNr   c             C   s2   t | | _|| _t|| _t|| _t|| _d S )N)	_MONGOS_MODES_ServerMode__mongos_mode_ServerMode__moder   _ServerMode__tag_setsr   _ServerMode__max_stalenessr"   _ServerMode__hedge)selfmoder   r   r!   r   r   r   __init__f   s
    


z_ServerMode.__init__c             C   s   | j jS )z*The name of this read preference.
        )	__class____name__)r/   r   r   r   namem   s    z_ServerMode.namec             C   s   | j S )z1The mongos mode of this read preference.
        )r*   )r/   r   r   r   mongos_modes   s    z_ServerMode.mongos_modec             C   sT   d| j i}| jdi gfkr$| j|d< | jdkr8| j|d< | jdi fkrP| j|d< |S )z'Read preference as a document.
        r0   Nr   r   ZmaxStalenessSecondsr!   r   )r*   r,   r-   r.   )r/   docr   r   r   documenty   s    




z_ServerMode.documentc             C   s   | j S )z3The mode of this read preference instance.
        )r+   )r/   r   r   r   r0      s    z_ServerMode.modec             C   s   | j rt| j S i gS )a{  Set ``tag_sets`` to a list of dictionaries like [{'dc': 'ny'}] to
        read only from members whose ``dc`` tag has the value ``"ny"``.
        To 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." MongoReplicaSetClient tries each set of tags in turn
        until it finds a set of tags with at least one matching member.

           .. seealso:: `Data-Center Awareness
               <http://www.mongodb.org/display/DOCS/Data+Center+Awareness>`_
        )r,   r   )r/   r   r   r   r      s    z_ServerMode.tag_setsc             C   s   | j S )zThe maximum estimated length of time (in seconds) a replica set
        secondary can fall behind the primary in replication before it will
        no longer be selected for operations, or -1 for no maximum.)r-   )r/   r   r   r   r      s    z_ServerMode.max_stalenessc             C   s   | j S )a  The read preference ``hedge`` parameter.

        A dictionary that configures how the server will perform hedged reads.
        It consists of the following keys:

        - ``enabled``: Enables or disables hedged reads in sharded clusters.

        Hedged reads are automatically enabled in MongoDB 4.4+ when using a
        ``nearest`` read preference. To explicitly enable hedged reads, set
        the ``enabled`` key  to ``true``::

            >>> Nearest(hedge={'enabled': True})

        To explicitly disable hedged reads, set the ``enabled`` key  to
        ``False``::

            >>> Nearest(hedge={'enabled': False})

        .. versionadded:: 3.11
        )r.   )r/   r   r   r   r!      s    z_ServerMode.hedgec             C   s   | j dkrdS dS )a  The wire protocol version the server must support.

        Some read preferences impose version requirements on all servers (e.g.
        maxStalenessSeconds requires MongoDB 3.4 / maxWireVersion 5).

        All servers' maxWireVersion must be at least this read preference's
        `min_wire_version`, or the driver raises
        :exc:`~pymongo.errors.ConfigurationError`.
        r   r      r   )r-   )r/   r   r   r   min_wire_version   s    z_ServerMode.min_wire_versionc             C   s   d| j | j| j| jf S )Nz+%s(tag_sets=%r, max_staleness=%r, hedge=%r))r4   r,   r-   r.   )r/   r   r   r   __repr__   s    z_ServerMode.__repr__c             C   s>   t |tr:| j|jko8| j|jko8| j|jko8| j|jkS tS )N)r   r#   r0   r   r   r!   NotImplemented)r/   otherr   r   r   __eq__   s    
z_ServerMode.__eq__c             C   s
   | |k S )Nr   )r/   r<   r   r   r   __ne__   s    z_ServerMode.__ne__c             C   s   | j | j| j| jdS )zeReturn value of object for pickling.

        Needed explicitly because __slots__() defined.
        )r0   r   r   r!   )r+   r,   r-   r.   )r/   r   r   r   __getstate__   s    z_ServerMode.__getstate__c             C   sD   |d | _ t| j  | _t|d | _t|d | _t|d | _dS )zRestore from pickling.r0   r   r   r!   N)	r+   r)   r*   r   r,   r   r-   r"   r.   )r/   valuer   r   r   __setstate__   s
    
z_ServerMode.__setstate__)r$   r%   r&   r'   r(   r   )Nr   N)r3   
__module____qualname____doc__	__slots__r1   propertyr4   r5   r7   r0   r   r   r!   r9   r:   r=   r>   r?   rA   r   r   r   r   r#   _   s"    

r#   c                   s<   e Zd ZdZf Z fddZdd Zdd Zdd	 Z  Z	S )
PrimaryaG  Primary read preference.

    * When directly connected to one mongod queries are allowed if the server
      is standalone or a replica set primary.
    * When connected to a mongos queries are sent to the primary of a shard.
    * When connected to a replica set queries are sent to the primary of
      the replica set.
    c                s   t t| jt d S )N)superrG   r1   _PRIMARY)r/   )r2   r   r   r1      s    zPrimary.__init__c             C   s   |j S )z*Apply this read preference to a Selection.)primary_selection)r/   	selectionr   r   r   __call__   s    zPrimary.__call__c             C   s   dS )Nz	Primary()r   )r/   r   r   r   r:      s    zPrimary.__repr__c             C   s   t |tr|jtkS tS )N)r   r#   r0   rI   r;   )r/   r<   r   r   r   r=      s    

zPrimary.__eq__)
r3   rB   rC   rD   rE   r1   rL   r:   r=   __classcell__r   r   )r2   r   rG      s   rG   c                   s.   e Zd ZdZf Zd	 fdd	Zdd Z  ZS )
PrimaryPreferreda  PrimaryPreferred read preference.

    * When directly connected to one mongod queries are allowed to standalone
      servers, to a replica set primary, or to replica set secondaries.
    * When connected to a mongos queries are sent to the primary of a shard if
      available, otherwise a shard secondary.
    * When connected to a replica set queries are sent to the primary if
      available, otherwise a secondary.

    .. note:: When a :class:`~pymongo.mongo_client.MongoClient` is first
      created reads will be routed to an available secondary until the
      primary of the replica set is discovered.

    :Parameters:
      - `tag_sets`: The :attr:`~tag_sets` to use if the primary is not
        available.
      - `max_staleness`: (integer, in seconds) 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.
        Default -1, meaning no maximum. If it is set, it must be at least
        90 seconds.
      - `hedge`: The :attr:`~hedge` to use if the primary is not available.

    .. versionchanged:: 3.11
       Added ``hedge`` parameter.
    Nr   c                s   t t| jt||| d S )N)rH   rN   r1   _PRIMARY_PREFERRED)r/   r   r   r!   )r2   r   r   r1   #  s    
zPrimaryPreferred.__init__c             C   s&   |j r|jS t| jtj| j|S dS )z(Apply this read preference to Selection.N)r   rJ   r   r   r   selectr   )r/   rK   r   r   r   rL   '  s    zPrimaryPreferred.__call__r   )Nr   N)r3   rB   rC   rD   rE   r1   rL   rM   r   r   )r2   r   rN     s   rN   c                   s.   e Zd ZdZf Zd	 fdd	Zdd Z  ZS )
	Secondarya  Secondary read preference.

    * When directly connected to one mongod queries are allowed to standalone
      servers, to a replica set primary, or to replica set secondaries.
    * When connected to a mongos queries are distributed among shard
      secondaries. An error is raised if no secondaries are available.
    * When connected to a replica set queries are distributed among
      secondaries. An error is raised if no secondaries are available.

    :Parameters:
      - `tag_sets`: The :attr:`~tag_sets` for this read preference.
      - `max_staleness`: (integer, in seconds) 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.
        Default -1, meaning no maximum. If it is set, it must be at least
        90 seconds.
      - `hedge`: The :attr:`~hedge` for this read preference.

    .. versionchanged:: 3.11
       Added ``hedge`` parameter.
    Nr   c                s   t t| jt||| d S )N)rH   rQ   r1   
_SECONDARY)r/   r   r   r!   )r2   r   r   r1   K  s    
zSecondary.__init__c             C   s   t | jtj| j|S )z(Apply this read preference to Selection.)r   r   r   rP   r   )r/   rK   r   r   r   rL   O  s    zSecondary.__call__r   )Nr   N)r3   rB   rC   rD   rE   r1   rL   rM   r   r   )r2   r   rQ   2  s   rQ   c                   s.   e Zd ZdZf Zd	 fdd	Zdd Z  ZS )
SecondaryPreferreda  SecondaryPreferred read preference.

    * When directly connected to one mongod queries are allowed to standalone
      servers, to a replica set primary, or to replica set secondaries.
    * When connected to a mongos queries are distributed among shard
      secondaries, or the shard primary if no secondary is available.
    * When connected to a replica set queries are distributed among
      secondaries, or the primary if no secondary is available.

    .. note:: When a :class:`~pymongo.mongo_client.MongoClient` is first
      created reads will be routed to the primary of the replica set until
      an available secondary is discovered.

    :Parameters:
      - `tag_sets`: The :attr:`~tag_sets` for this read preference.
      - `max_staleness`: (integer, in seconds) 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.
        Default -1, meaning no maximum. If it is set, it must be at least
        90 seconds.
      - `hedge`: The :attr:`~hedge` for this read preference.

    .. versionchanged:: 3.11
       Added ``hedge`` parameter.
    Nr   c                s   t t| jt||| d S )N)rH   rS   r1   _SECONDARY_PREFERRED)r/   r   r   r!   )r2   r   r   r1   t  s    
zSecondaryPreferred.__init__c             C   s(   t | jtj| j|}|r|S |jS dS )z(Apply this read preference to Selection.N)r   r   r   rP   r   rJ   )r/   rK   Zsecondariesr   r   r   rL   x  s    zSecondaryPreferred.__call__r   )Nr   N)r3   rB   rC   rD   rE   r1   rL   rM   r   r   )r2   r   rS   W  s   rS   c                   s.   e Zd ZdZf Zd	 fdd	Zdd Z  ZS )
Nearestav  Nearest read preference.

    * When directly connected to one mongod queries are allowed to standalone
      servers, to a replica set primary, or to replica set secondaries.
    * When connected to a mongos queries are distributed among all members of
      a shard.
    * When connected to a replica set queries are distributed among all
      members.

    :Parameters:
      - `tag_sets`: The :attr:`~tag_sets` for this read preference.
      - `max_staleness`: (integer, in seconds) 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.
        Default -1, meaning no maximum. If it is set, it must be at least
        90 seconds.
      - `hedge`: The :attr:`~hedge` for this read preference.

    .. versionchanged:: 3.11
       Added ``hedge`` parameter.
    Nr   c                s   t t| jt||| d S )N)rH   rU   r1   _NEAREST)r/   r   r   r!   )r2   r   r   r1     s    
zNearest.__init__c             C   s   t | jtj| j|S )z(Apply this read preference to Selection.)r   r   r   rP   r   )r/   rK   r   r   r   rL     s    zNearest.__call__r   )Nr   N)r3   rB   rC   rD   rE   r1   rL   rM   r   r   )r2   r   rU     s   rU   c             C   sB   | t kr4|d i gfkrtd|dkr.tdt S t|  ||S )Nz4Read preference primary cannot be combined with tagsr   zCRead preference primary cannot be combined with maxStalenessSecondsr   )rI   r   rG   _ALL_READ_PREFERENCES)r0   r   r   r   r   r   make_read_preference  s    rX   PRIMARYPRIMARY_PREFERRED	SECONDARYSECONDARY_PREFERREDNEARESTc               @   s.   e Zd ZdZe Ze Ze Z	e
 Ze ZdS )ReadPreferenceaD  An enum that defines the read preference modes supported by PyMongo.

    See :doc:`/examples/high_availability` for code examples.

    A read preference is used in three cases:

    :class:`~pymongo.mongo_client.MongoClient` connected to a single mongod:

    - ``PRIMARY``: Queries are allowed if the server is standalone or a replica
      set primary.
    - All other modes allow queries to standalone servers, to a replica set
      primary, or to replica set secondaries.

    :class:`~pymongo.mongo_client.MongoClient` initialized with the
    ``replicaSet`` option:

    - ``PRIMARY``: Read from the primary. This is the default, and provides the
      strongest consistency. If no primary is available, raise
      :class:`~pymongo.errors.AutoReconnect`.

    - ``PRIMARY_PREFERRED``: Read from the primary if available, or if there is
      none, read from a secondary.

    - ``SECONDARY``: Read from a secondary. If no secondary is available,
      raise :class:`~pymongo.errors.AutoReconnect`.

    - ``SECONDARY_PREFERRED``: Read from a secondary if available, otherwise
      from the primary.

    - ``NEAREST``: Read from any member.

    :class:`~pymongo.mongo_client.MongoClient` connected to a mongos, with a
    sharded cluster of replica sets:

    - ``PRIMARY``: Read from the primary of the shard, or raise
      :class:`~pymongo.errors.OperationFailure` if there is none.
      This is the default.

    - ``PRIMARY_PREFERRED``: Read from the primary of the shard, or if there is
      none, read from a secondary of the shard.

    - ``SECONDARY``: Read from a secondary of the shard, or raise
      :class:`~pymongo.errors.OperationFailure` if there is none.

    - ``SECONDARY_PREFERRED``: Read from a secondary of the shard if available,
      otherwise from the shard primary.

    - ``NEAREST``: Read from any shard member.
    N)r3   rB   rC   rD   rG   rY   rN   rZ   rQ   r[   rS   r\   rU   r]   r   r   r   r   r^     s   1r^   c             C   s
   t j| S )z7Get the read preference mode from mongos/uri name.
    )r)   index)r4   r   r   r   read_pref_mode_from_name  s    r`   c               @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )MovingAveragez0Tracks an exponentially-weighted moving average.c             C   s
   d | _ d S )N)average)r/   r   r   r   r1     s    zMovingAverage.__init__c             C   s6   |dk rd S | j d kr|| _ nd| j  d|  | _ d S )Nr   g?g?)rb   )r/   sampler   r   r   
add_sample  s
    
zMovingAverage.add_samplec             C   s   | j S )z6Get the calculated average, or None if no samples yet.)rb   )r/   r   r   r   get  s    zMovingAverage.getc             C   s
   d | _ d S )N)rb   )r/   r   r   r   reset  s    zMovingAverage.resetN)r3   rB   rC   rD   r1   rd   re   rf   r   r   r   r   ra     s
   ra   N)r   r   r   r   r   r   )r   )rY   rZ   r[   r\   r]   )"rD   Zbson.py3compatr   r   Zpymongor   Zpymongo.errorsr   Zpymongo.server_selectorsr   r   rI   rO   rR   rT   rV   r)   r   r   r   r"   objectr#   rG   rN   rQ   rS   rU   rW   rX   Z_MODESr^   r`   ra   r   r   r   r   <module>   sH        -%.%

    9