o
    y.e~                    @   s  d dl Z d dlZd dlZd dlZd dlm  mZ d dlZd dl	Zd dl
Zd dlZd dlZd dlZd dlmZ d dlmZ ejdZdZdZdZdZd Zd	Zd
ZdZdZe ddZdej_G dd de Z!G dd dej"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(dd Z)ej*G dd de$Z+d d! Z,d"d# Z-G d$d% d%e$Z.G d&d' d'e$Z/G d(d) d)e$Z0dS )*    N)custom_index)erroridlzno-classattr no-objattrscreateupdatedelete      	clusteredrelayNotice)eventrowupdatesNc                       sL   e Zd ZdZdZ fddZdd Zdd Zd	d
 Zdd Z	dd Z
  ZS )ColumnDefaultDicta  A column dictionary with on-demand generated default values

    This object acts like the Row._data column dictionary, but without the
    necessity of populating column default values. These values are generated
    on-demand and therefore only use memory once they are accessed.
    )_tablec                    s   || _ t   d S r   )r   super__init__selftable	__class__ ,/usr/lib/python3/dist-packages/ovs/db/idl.pyr   ;   s   zColumnDefaultDict.__init__c                 C   s   | j j| }tjjj|jS r   )r   columnsovsdbdataDatumdefaulttyper   columnr   r   r   __missing__?   s   zColumnDefaultDict.__missing__c                 C   s   | j j S r   )r   r   keysr   r   r   r   r&   C      zColumnDefaultDict.keysc                    s   t  fdd D S )Nc                 3   s    | ]} | V  qd S r   r   ).0kr'   r   r   	<genexpr>G   s    z+ColumnDefaultDict.values.<locals>.<genexpr>)iterr'   r   r'   r   valuesF      zColumnDefaultDict.valuesc                 C   s   t |  S r   )r,   r&   r'   r   r   r   __iter__I   r(   zColumnDefaultDict.__iter__c                 C   s   ||   v S r   )r&   )r   itemr   r   r   __contains__L   r(   zColumnDefaultDict.__contains__)__name__
__module____qualname____doc__	__slots__r   r%   r&   r-   r/   r1   __classcell__r   r   r   r   r   2   s    r   c                   @   s   e Zd ZeZeZeZdS )MonitorN)	r2   r3   r4   OVSDB_UPDATEmonitorOVSDB_UPDATE2monitor_condOVSDB_UPDATE3monitor_cond_sincer   r   r   r   r8   P   s    r8   c                   @   sx   e Zd Zdd Z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S )ConditionStatec                 C   s   dg| _ d | _d | _d S NT)	_ack_cond	_req_cond	_new_condr'   r   r   r   r   W   s   
zConditionState.__init__c                 C   s   t | j| j| jgS r   )r,   rC   rB   rA   r'   r   r   r   r/   \      zConditionState.__iter__c                 C      | j S )z/The latest freshly initialized condition changerC   r'   r   r   r   new_      zConditionState.newc                 C   rE   )z>The last condition change that has been accepted by the server)rA   r'   r   r   r   ackedd   rH   zConditionState.ackedc                 C   rE   )z>A condition that's been requested, but not acked by the server)rB   r'   r   r   r   	requestedi   rH   zConditionState.requestedc                 C   s   t dd | D S )z The most recent condition changec                 s   s    | ]	}|d ur|V  qd S r   r   )r)   condr   r   r   r+   q   s    z(ConditionState.latest.<locals>.<genexpr>)nextr'   r   r   r   latestn   s   zConditionState.latestc                 C   s
   | dgkS r@   r   )	conditionr   r   r   is_trues      
zConditionState.is_truec                 C   s
   || _ dS )z1Signal that a condition change is being initiatedNrF   )r   rK   r   r   r   initw   rP   zConditionState.initc                 C   "   | j dur| j d| _| _ dS dS )z-Signal that a condition change has been ackedN)rB   rA   r'   r   r   r   ack{      
zConditionState.ackc                 C   rR   )z1Signal that a condition change has been requestedN)rC   rB   r'   r   r   r   request   rT   zConditionState.requestc                 C   s*   | j dur| jdu r| j | _d| _ dS dS )z.Reset a requested condition change back to newNTF)rB   rC   r'   r   r   r   reset   s   

zConditionState.resetN)r2   r3   r4   r   r/   propertyrG   rI   rJ   rM   staticmethodrO   rQ   rS   rU   rV   r   r   r   r   r?   V   s"    




r?   c                   @   sN   e Zd Zdd Zdd Zedd Zedd Zejd	d Ze	d
d Z
dS )IdlTablec                 C   sT   t |tjjjs
J || _d| _t| | _	|| _
t | _dd |j D | _d S )NFc                 S   s   i | ]	\}}|t |qS r   )	IdlColumnr)   r*   vr   r   r   
<dictcomp>   s    z%IdlTable.__init__.<locals>.<dictcomp>)
isinstancer   r   schemaTableSchemar   
need_tabler   IndexedRowsrowsr   r?   _condition_stater   items)r   r   r   r   r   r   r      s   zIdlTable.__init__c                 C      t | j|S r   )getattrr   r   attrr   r   r   __getattr__   r(   zIdlTable.__getattr__c                 C   rE   r   )rd   r'   r   r   r   condition_state   rH   zIdlTable.condition_statec                 C   s   | j jS r   )rk   rM   r'   r   r   r   rN      s   zIdlTable.conditionc                 C   s"   t |tsJ | j| j| d S r   )r^   listr   cond_changename)r   rN   r   r   r   rN      s   c                    s    fdd|j  D S )Nc                    s   i | ]
\}}| |qS r   r   r[   clsr   r   r   r]      s    z*IdlTable.schema_tables.<locals>.<dictcomp>)tablesre   )rp   r   r_   r   ro   r   schema_tables      zIdlTable.schema_tablesN)r2   r3   r4   r   rj   rW   rk   rN   setterclassmethodrr   r   r   r   r   rY      s    	


rY   c                   @   s   e Zd Zdd Zdd ZdS )rZ   c                 C   s   || _ d| _d S r@   )_columnalertr#   r   r   r   r         
zIdlColumn.__init__c                 C   rf   r   )rg   rv   rh   r   r   r   rj      r(   zIdlColumn.__getattr__N)r2   r3   r4   r   rj   r   r   r   r   rZ      s    rZ   c                   @   s  e Zd ZdZdZdZdZdZdZdZ	dZ
ejeejeeje	iZ			
dkddZdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Z d-d. Z!d/d0 Z"d1d2 Z#d3d4 Z$dld5d6Z%d7d8 Z&d9d: Z'd;d< Z(d=d> Z)d?d@ Z*dAdB Z+dCdD Z,dEdF Z-dGdH Z.dIdJ Z/ejfdKdLZ0dMdN Z1dOdP Z2dldQdRZ3dSdT Z4dUdV Z5dWdX Z6dYdZ Z7d[d\ Z8d]d^ Z9d_d` Z:dadb Z;dcdd Z<dedf Z=dgdh Z>didj Z?d	S )mIdla
  Open vSwitch Database Interface Definition Language (OVSDB IDL).

    The OVSDB IDL maintains an in-memory replica of a database.  It issues RPC
    requests to an OVSDB database server and parses the responses, converting
    raw JSON into data structures that are easier for clients to digest.

    The IDL also assists with issuing database transactions.  The client
    creates a transaction, manipulates the IDL data structures, and commits or
    aborts the transaction.  The IDL then composes and issues the necessary
    JSON-RPC requests and reports to the client whether the transaction
    completed successfully.

    The client is allowed to access the following attributes directly, in a
    read-only fashion:

    - 'tables': This is the 'tables' map in the ovs.db.schema.DbSchema provided
      to the Idl constructor.  Each ovs.db.schema.TableSchema in the map is
      annotated with a new attribute 'rows', which is a dict from a uuid.UUID
      to a Row object.

      The client may directly read and write the Row objects referenced by the
      'rows' map values.  Refer to Row for more details.

    - 'change_seqno': A number that represents the IDL's state.  When the IDL
      is updated (by Idl.run()), its value changes.  The sequence number can
      occasionally change even if the database does not.  This happens if the
      connection to the database drops and reconnects, which causes the
      database contents to be reloaded even if they didn't change.  (It could
      also happen if the database server sends out a "change" that reflects
      what the IDL already thought was in the database.  The database server is
      not supposed to do that, but bugs could in theory cause it to do so.)

    - 'lock_name': The name of the lock configured with Idl.set_lock(), or None
      if no lock is configured.

    - 'has_lock': True, if the IDL is configured to obtain a lock and owns that
      lock, and False otherwise.

      Locking and unlocking happens asynchronously from the database client's
      point of view, so the information is only useful for optimization
      (e.g. if the client doesn't have the lock then there's no point in trying
      to write to the database).

    - 'is_lock_contended': True, if the IDL is configured to obtain a lock but
      the database server has indicated that some other client already owns the
      requested lock, and False otherwise.

    - 'txn': The ovs.db.idl.Transaction object for the database transaction
      currently being constructed, if there is one, or None otherwise.
r   r   r	               NTc                 C   s  t |tsJ | }t| || _|j| _|| _| |}t	j
jj||d| _d| _d| _d| _d| _t | _ttjdd| _d| _d| _d| _d| _d| _d| _d| _d| _t | _|| _ d| _!d| _"| j#| _$d| _%d| _&d| _'d| _(d| _)i | _*d| _+d| _,dS )a4  Creates and returns a connection to the database named 'db_name' on
        'remote', which should be in a form acceptable to
        ovs.jsonrpc.session.open().  The connection will maintain an in-memory
        replica of the remote database.

        'remote' can be comma separated multiple remotes and each remote
        should be in a form acceptable to ovs.jsonrpc.session.open().

        'schema_helper' should be an instance of the SchemaHelper class which
        generates schema for the remote database. The caller may have cut it
        down by removing tables or columns that are not of interest.  The IDL
        will only replicate the tables and columns that remain.  The caller may
        also add an attribute named 'alert' to selected remaining columns,
        setting its value to False; if so, then changes to those columns will
        not be considered changes to the database for the purpose of the return
        value of Idl.run() and Idl.change_seqno.  This is useful for columns
        that the IDL's client will write but not read.

        As a convenience to users, 'schema' may also be an instance of the
        SchemaHelper class.

        The IDL uses and modifies 'schema' directly.

        If 'leader_only' is set to True (default value) the IDL will only
        monitor and transact with the leader of the cluster.

        If "probe_interval" is zero it disables the connection keepalive
        feature. If non-zero the value will be forced to at least 1000
        milliseconds. If None it will just use the default value in OVS.
        )probe_intervalNr   int_ServerDatabaseF)-r^   SchemaHelperget_idl_schemarY   rr   rq   readonly_db_parse_remotesr   jsonrpcSessionopen_multiple_session_request_id_monitor_request_id_last_seqnochange_seqnouuiduuid1strUUIDlast_id_server_schema_request_id_server_monitor_request_id_db_change_aware_request_id_monitor_cancel_request_id_server_db_name_server_db_tableserver_tables
_server_dbserver_monitor_uuidleader_only
cluster_id
_min_indexIDL_S_INITIALstate	lock_namehas_lockis_lock_contended_lock_request_idtxn_outstanding_txnscond_changed
cond_seqno)r   remoteschema_helperr~   r   r_   remotesr   r   r   r      sH   !




zIdl.__init__c                 C   sJ   g }| dD ]}|r|ddkr|d  d| 7  < q|| q|S )N,:)splitfindappend)r   r   r   rr   r   r   r   G  s   zIdl._parse_remotesc                 C   s"   || _ | j| jkr|   dS dS )z8Set the id of the cluster that this idl must connect to.N)r   r   r   force_reconnect)r   r   r   r   r   set_cluster_idT  s   zIdl.set_cluster_idc                 C   s   | j | j|S )z,Create a named multi-column index on a table)rq   rc   index_create)r   r   rn   r   r   r   r   Z  s   zIdl.index_createc                 C   s   | j | jj| ||S )z9Return items in a named index between start/end inclusiverq   rc   indexesirange)r   r   rn   startendr   r   r   index_irange^  rs   zIdl.index_irangec                 C   s   | j | jj| ||S )z.Return items in a named index matching a valuer   )r   r   rn   valuer   r   r   index_equalb  rs   zIdl.index_equalc                 C   s   | j   dS )zNCloses the connection to the database.  The IDL will no longer
        update.N)r   closer'   r   r   r   r   f  s   z	Idl.closec                 C   s   | j  D ]}|j  qdS )z,Mark all requested table conditions as ackedN)rq   r-   rk   rS   r   r   r   r   ack_conditionsk  s   zIdl.ack_conditionsc                 C   sp   | j ttjddk}|rd| _| j D ] }|r$|j  |j	  q|j
 r5ttjdd| _ d| _qdS )a  Synchronize condition state when the FSM is restarted

        If a non-zero last_id is available for the DB, then upon reconnect
        the IDL should first request acked conditions to avoid missing updates
        about records that were added before the transaction with
        txn-id == last_id. If there were requested condition changes in flight
        and the IDL client didn't set new conditions, then reset the requested
        conditions to new to trigger a follow-up monitor_cond_change request.

        If there were changes in flight then there are two cases:
        a. either the server already processed the requested monitor condition
           change but the FSM was restarted before the client was notified.
           In this case the client should clear its local cache because it's
           out of sync with the monitor view on the server side.

        b. OR the server hasn't processed the requested monitor condition
           change yet.

        As there's no easy way to differentiate between the two, and given that
        this condition should be rare, reset the 'last_id', essentially
        flushing the local cached DB contents.
        r   r   FTN)r   r   r   r   r   rq   r-   rk   rU   rS   rV   )r   ack_allr   r   r   r   sync_conditionsp  s   

zIdl.sync_conditionsc                 C   s   |    |   | j| _d S r   )r    _Idl__send_server_schema_requestIDL_S_SERVER_SCHEMA_REQUESTEDr   r'   r   r   r   restart_fsm  s   zIdl.restart_fsmc           
   
   C   sl  | j rJ | j}|   | j  d}|dk r|d7 }| j}| j s&n| j }|| jkrD|| _|   | 	  | j
rB|   nm| j }|du rOnb|jtjjjtjjjfv }|rj| jrj| j|jkrjd| _|jtjjjkr|jdkrt|jdkr| |jd t |jd | _n|jtjjjkr|jdkrt|jdkr| |jd t n|jtjjjkr|jd	krt|jdkr|jd t| jkr| j|jd t| j d
 || _| ! s| "  n̐n| |jd t n| #|rn| $|rn|jtjjjkr| j%dur| j%|jkrzY|  jd7  _d| _%| j&| j'krC|j(d s3| )  | |j(d t |j(d | _n'| j&| j*krV| )  | |j(t n| j&| j+ks_J | )  | |j(t | j,| _&W n< t-j.y } zt/0d| j1 |f  | 2  W Y d}~nd}~ww |jtjjjkr| j3dur| j3|jkrz$d| _3t4d|j(}|5| j6 |7 }	|	| _8t9:| |	| _ | ;  W n t-j.y } z)t/0d| j1 |f  | j<r| 2  W Y d}~n|| _| =  W Y d}~nd}~ww |jtjjjkr~| j>dur~| j>|jkr~z(d| _>| j|j(t| j d
 || _| ! r=| =  | ?  n| "  W nmW nf t-j.y} } z)t/0d| j1 |f  | j<rk| 2  W Y d}~nF|| _| =  W Y d}~n4d}~ww |jtjjjkr| j@dur| j@|jkrd| _@n|jtjjjkr| jAdur| jA|jkr| B|j( n|jtjjjkr|jdkr| C|jd n|jtjjjkr|jdkr| C|jd n|jtjjjkr|jdkrn|jtjjjkr| j&| j'kr| j%|jkr|j-dkr| =tDjE n|jtjjjkr<| j&| j*kr<| j%|jkr<|j-dkr;| =tDjF nq|jtjjjkrf| j3durf| j3|jkrfd| _3| j<r^| "  nS|| _| =  nG|jtjjjtjjjfv r{| G|r{n2|jtjjjkr| j&| j,kr| H  |   |  jId7  _Int/Jd| j1 tjjK|jf  |dk s|| jkS )a+  Processes a batch of messages from the database server.  Returns
        True if the database as seen through the IDL changed, False if it did
        not change.  The initial fetch of the entire contents of the remote
        database is considered to be one kind of change.  If the IDL has been
        configured to acquire a database lock (with Idl.set_lock()), then
        successfully acquiring the lock is also considered to be a change.

        This function can return occasional false positives, that is, report
        that the database changed even though it didn't.  This happens if the
        connection to the database drops and reconnects, which causes the
        database contents to be reloaded even if they didn't change.  (It could
        also happen if the database server sends out a "change" that reflects
        what we already thought was in the database, but the database server is
        not supposed to do that.)

        As an alternative to checking the return value, the client may check
        for changes in self.change_seqno.r   2   r   Nupdate3rz   r	   update2r   )rq   z&%s: parse error in received schema: %sz%%s: error receiving server schema: %slockedTstolenFechozunknown methodz"%s: received unexpected %s message)Lr   r   send_cond_changer   runis_connected	get_seqnor   _Idl__txn_abort_allr   r   _Idl__send_lock_requestrecvr"   r   r   MessageT_REPLYT_ERRORr   idT_NOTIFYmethodlenparams_Idl__parse_updater=   r   r;   r   r   r9   r   _Idl__check_server_dbr   handle_monitor_canceledhandle_monitor_cancel_replyr   r   'IDL_S_DATA_MONITOR_COND_SINCE_REQUESTEDresult_Idl__clear!IDL_S_DATA_MONITOR_COND_REQUESTEDIDL_S_DATA_MONITOR_REQUESTEDIDL_S_MONITORINGr   Errorvlogerrget_name_Idl__errorr   r   register_tabler   r   r   rY   rr   !_Idl__send_server_monitor_requestr   _Idl__send_monitor_requestr   _Idl__send_db_change_awarer   r   _Idl__parse_lock_reply_Idl__parse_lock_notifyr8   r<   r:   _Idl__txn_process_replyr   r   dbgtype_to_string)
r   initial_change_seqnoiprevious_change_seqnoseqnomsgis_responseeshr_   r   r   r   r     st  










	


	

  
;zIdl.runc                 C   s   |j |jkrdS |jdkrdS |jd t| jkr t| jg}n|jd t| jkr1t| jg}ndS tjj	
d|}|j| _| | |   dS )NFmonitor_canceledr   monitor_cancelT)r"   r   r   r   r   r   r   r   r   r   create_requestr   r   send_requestr   )r   r   r   mc_msgr   r   r   r   p  s   

zIdl.handle_monitor_canceledc                 C   s*   |j |jkrdS |j| jkrdS d | _dS )NFT)r"   r   r   r   r   r   r   r   r   r     s   zIdl.handle_monitor_cancel_replyc                 C   s   | j sd S i }| j D ]}|jjd ur#d|jjig||j< |j  q|s(d S d| _ t| j}t	 | _|t| j|g}t
jjd|S )NwhereFmonitor_cond_change)r   rq   r-   rk   rG   rn   rU   r   r   r   r   r   r   r   )r   change_requestsr   old_uuidr   r   r   r   compose_cond_change  s$   




zIdl.compose_cond_changec                 C   s6   | j  r
| jd urd S |  }|r| | d S d S r   )r   r   r   r  r   r  r   r   r   r     s   zIdl.send_cond_changec                 C   s   | j |}|std| |g krdg}|jj|kr%|j| d| _|jjr>t	dd | j 
 D }| jt| d S | jtt|jj S )aG  Sets the condition for 'table_name' to 'cond', which should be a
        conditional expression suitable for use directly in the OVSDB
        protocol, with the exception that the empty condition []
        matches no rows (instead of matching every row).  That is, []
        is equivalent to [False], not to [True].
        zUnknown table "%s"FTc                 s   s    | ]}|j jV  qd S r   )rk   rU   )r)   tr   r   r   r+     s    z"Idl.cond_change.<locals>.<genexpr>r   )rq   getr   r   rk   rM   rQ   r   rG   anyr-   r   r   boolrJ   )r   
table_namerK   r   any_reqsr   r   r   rm     s   zIdl.cond_changec                 C   s.   | j r	|  dS | j| | j| dS )zArranges for poller.block() to wake up when self.run() has something
        to do or when activity occurs on a transaction on 'self'.N)r   immediate_waker   wait	recv_waitr   pollerr   r   r   r    s
   zIdl.waitc                 C   s
   | j dkS )a  Returns True, if the IDL successfully connected to the remote
        database and retrieved its contents (even if the connection
        subsequently dropped and is in the process of reconnecting).  If so,
        then the IDL contains an atomic snapshot of the database's contents
        (but it might be arbitrarily old if the connection dropped).

        Returns False if the IDL has never connected or retrieved the
        database's contents.  If so, the IDL is empty.r   )r   r'   r   r   r   has_ever_connected  s   
	zIdl.has_ever_connectedc                 C   s$   | j | jkr| j  | j  dS )zForces the IDL to drop its connection to the database and reconnect.
        In the meantime, the contents of the IDL will not change.N)r   r   r   reset_backoffr   r'   r   r   r   r     s   
zIdl.force_reconnectc                 C   s
   | j  S r   )r   r   r'   r   r   r   session_name  s   
zIdl.session_namec                 C   s`   | j rJ | jr
J | jr|r|| jkr|   d| _d| _|r,| js.|| _|   dS dS dS )aM  If 'lock_name' is not None, configures the IDL to obtain the named
        lock from the database server and to avoid modifying the database when
        the lock cannot be acquired (that is, when another client has the same
        lock).

        If 'lock_name' is None, drops the locking requirement and releases the
        lock.NF)r   r   r   _Idl__send_unlock_requestr   r   )r   r   r   r   r   set_lock  s   


zIdl.set_lockc                 C      dS )a  Hook for implementing create/update/delete notifications

        :param event:   The event that was triggered
        :type event:    ROW_CREATE, ROW_UPDATE, or ROW_DELETE
        :param row:     The row as it is after the operation has occured
        :type row:      Row
        :param updates: For updates, row with only old values of the changed
                        columns
        :type updates:  Row
        Nr   )r   r   r   r   r   r   r   notify      z
Idl.notifyc                 C   r  )aw  Hook for cooperatively yielding to eventlet/gevent/asyncio/etc.

        When a block of code is going to spend a lot of time cpu-bound without
        doing any I/O, it can cause greenthread/coroutine libraries to block.
        This call should be added to code where this can happen, but defaults
        to doing nothing to avoid overhead where it is not needed.
        Nr   r'   r   r   r   cooperative_yield  r  zIdl.cooperative_yieldc                 C   sJ   d}| j  D ]}|jrd}t||_qd| _|r#|  jd7  _d S d S )NFTr   r   )rq   r-   rc   r   rb   r   r   )r   changedr   r   r   r   __clear  s   zIdl.__clearc                 C   s6   |r| j s| jd u r|  jd7  _n	 d| _|| _ d S )Nr   F)r   r   r   r   )r   new_has_lockr   r   r   __update_has_lock&  s   


zIdl.__update_has_lockc                 C   sL   |  d d | _| j r"tjj|| jg}|j	}| j
| |S d }|S )NF)_Idl__update_has_lockr   r   r   r   r   r   r   r   r   send)r   r   r   msg_idr   r   r   __do_send_lock_request2  s   

zIdl.__do_send_lock_requestc                 C   s   |  d| _d S )Nlock)_Idl__do_send_lock_requestr   r'   r   r   r   __send_lock_request=  s   zIdl.__send_lock_requestc                 C   s   |  d d S )Nunlock)r$  r'   r   r   r   __send_unlock_request@     zIdl.__send_unlock_requestc                 C   s:   d | _ t|to|ddu }| | |sd| _d S d S )Nr   T)r   r^   dictr  r  r   )r   r   got_lockr   r   r   __parse_lock_replyC  s   

zIdl.__parse_lock_replyc                 C   sV   | j d ur!t|ttfr#|r%|d | j kr'| | |s)d| _d S d S d S d S d S d S )Nr   T)r   r^   rl   tupler  r   )r   r   r  r   r   r   __parse_lock_notifyJ  s   


zIdl.__parse_lock_notifyc                 C   s*   t jjddg}|j| _| j| d S )Nset_db_change_awareT)r   r   r   r   r   r   r   r   r  r   r   r   __send_db_change_awareS  s
   
zIdl.__send_db_change_awarec                 C   s"   |j | _| j r| j|S d S r   )r   r   r   r   r   )r   rU   r   r   r   r   Y  s   
zIdl.send_requestc           
      C   s0  | j | jkr| j| _ d}n| j | jkr!| jt| | _ t|j}n| j| _ d}i }| j	 D ]@}g }|j
 D ]}|j| jvsM|j| jv rR|| j|j vrR|| q7d|i}|dv rht|jjsh|jj|d< |g||j< q.| jjt| j|g}|dkr|t| j tjj||}	|	j| _| |	 d S )Nr<   r:   r   )r<   r>   r  r>   )r   r   r   IDL_S_SERVER_MONITOR_REQUESTEDmonitor_mapr8   rn   r   rq   r-   r   r&   r   r   r?   rO   rk   rI   r   r   r   r   r   r   r   r   r   r   r   )
r   max_versionr   monitor_requestsr   r   r$   monitor_requestargsr   r   r   r   __send_monitor_request^  s:   
zIdl.__send_monitor_requestc                 C   s:   | j | _tjjd| jt| jg}|j	| _
| | d S )N
get_schema)r   r   r   r   r   r   r   r   r   r   r   r   r  r   r   r   __send_server_schema_request~  s   z Idl.__send_server_schema_requestc                 C   s   | j | _i }| j| j }dd |j D }|j D ]
}t|ds%d|_qt	
||_d|_| |_d|i}|g||j< tjjd| jjt| j|g}|j| _| | d S )Nc                 S   s   g | ]}|qS r   r   )r)   r$   r   r   r   
<listcomp>      z5Idl.__send_server_monitor_request.<locals>.<listcomp>rw   TFr   r:   )r0  r   r   r   r   r&   r-   hasattrrw   r   rb   rc   ra   r   rn   r   r   r   r   r   r   r   r   r   r   )r   r3  r   r   r$   r4  r   r   r   r   __send_server_monitor_request  s*   
z!Idl.__send_server_monitor_requestc              
   C   sp   z|s|  ||| j W d S |  ||| W d S  tjy7 } ztd| j |f  W Y d }~d S d }~ww )Nz%s: error parsing update: %s)_Idl__do_parse_updaterq   r   r   r   r   r   r   )r   r   versionrq   r   r   r   r   __parse_update  s   zIdl.__parse_updatec                 C   s  t |tstd|g }| D ]\}}||}|s#td| t |ts0td| || D ]\}}	tj|sHtd||f |tj	|}
t |	ts\td||f | 
  |ttfv r|| ||
|	}|r{|| |  jd7  _q4tjj|	d}|dtg}|d	tg}|  |s|std
|	| ||
||}|r|| |  jd7  _q4q|D ]}| j|  qd S )Nz <table-updates> is not an objectz+<table-updates> includes unknown table "%s"z.<table-update> for table "%s" is not an objectzC<table-update> for table "%s" contains bad UUID "%s" as member namezP<table-update> for table "%s" contains <row-update> for %s that is not an objectr   z
row-updateoldrG   z,<row-update> missing "old" and "new" members)r^   r)  r   r   re   r  r   ovsuuidis_valid_stringfrom_stringr  r;   r=   _Idl__process_update2r   r   r   parserParserget_optionalfinish_Idl__process_updater  )r   table_updatesr>  rq   noticesr  table_updater   uuid_string
row_updater   changesrE  r@  rG   noticer   r   r   __do_parse_update  sj   





$zIdl.__do_parse_updatec                 C   s  |j |}d|v r!|r|j |= tt|S td||jf  d	S d|v s)d|v rg|r9td||jf  |j |= | ||}d|v rH|d }n|d }| || | 	|||}||j |< |rett
|S d	S d|v r|srtd| |||d }tt|t| |||S td|)
4Returns Notice if a column changed, False otherwise.r   z)cannot delete missing row %s from table%sinsertinitialz(cannot add existing row %s from table %smodifyzModify non-existing rowz<row-update> unknown operationF)rc   r  r   
ROW_DELETEr   warnrn   _Idl__create_row_Idl__add_default_Idl__row_update
ROW_CREATEr   r   _Idl__apply_diff
ROW_UPDATERow)r   r   r   rN  r   r  old_rowr   r   r   __process_update2  sB   





zIdl.__process_update2c              	   C   s"  |j |}d}|s!|r|j |= tt|S td||jf  dS |sWt}|s0| ||}d}nt	}td||jf  || 
|||O }|tkrN||j |< |rUtt|S dS t	}|so| ||}d}t}td||jf  || 
|||O }|tkr||j |< |rt||t| |||S dS )rR  Fz*cannot delete missing row %s from table %sTz&cannot add existing row %s to table %sz(cannot modify missing row %s in table %s)rc   r  r   rV  r   rW  rn   r[  rX  r]  rZ  r^  	from_json)r   r   r   r@  rG   r   r  opr   r   r   __process_update  sN   
 


zIdl.__process_updatec                 C   s  |   }| j| jvrtd|| j| jf  dS | j| j j}d}| D ] }| jr:| jt	dd |j
v r9|} nq%|j| jjkrE|} nq%|sUtd|| jjf  dS |jtkr|jsftd|  dS |jsrtd|  dS | jr|jstd	|  dS |jr|jd
 | jk rtd|  dS |jd
 | _dS |jtkr|jstd|  dS |jstd|  dS | jrtd|  dS dS )zAReturns True if this is a valid server database, False otherwise.z4%s: server does not have %s table in its %s databaseFNc                 S   s   t | d d S )Nr{   r   )xr   r   r   <lambda><  r:  z'Idl.__check_server_db.<locals>.<lambda>z$%s: server does not have %s databasezO%s: clustered database server has not yet joined cluster; trying another serverzQ%s: clustered database server is disconnected from cluster; trying another serverzJ%s: clustered database server is not cluster leader; trying another serverr   zC%s: clustered database server has stale data; trying another serverzZ%s: relay database server has not yet connected to the relay source; trying another serverzV%s: relay database server is disconnected from the relay source; trying another serverzC%s: relay database server cannot be a leader; trying another serverT)r  r   r   r   infor   rc   r-   r   mapcidrn   r   model	CLUSTEREDr_   	connectedr   leaderindexr   rW  RELAY)r   r  rc   databaser   r   r   r   __check_server_db,  s   


zIdl.__check_server_dbc                 C   s4   |j jj tjjjkrtj|j jj jS |j jj jS r   )	r"   keyr   r   typesUuidTyperA  to_jsonr!   r#   r   r   r   __column_namen  s   zIdl.__column_namec                 C   sn   |j  D ]/}|j|vr4|j| jvs!|j| jv r4|j| j|j vr4|jjdkr4|j s4| |||j< qd S )Nr   )r   r-   rn   r   r"   n_minis_map_Idl__column_name)r   r   rN  r$   r   r   r   __add_defaultt  s   
zIdl.__add_defaultc                 C   s   i }|  D ]]\}}|j|}|std||jf  qz
tj|j	|}W n t
jyE }	 ztd||j|	f  W Y d }	~	qd }	~	ww |j|  ||< |j| |}
|
|j| krc|
|j|< q|S )N#unknown column %s updating table %s'error parsing column %s in table %s: %s)re   r   r  r   rW  rn   r   r    ra  r"   r   r   _datacopydiff)r   r   r   row_diffr_  column_namedatum_diff_jsonr$   
datum_diffr   datumr   r   r   __apply_diff}  s.   

zIdl.__apply_diffc           
      C   s   d}|  D ]S\}}|j|}|std||jf  qz
tj|j	|}W n t
jyE }	 ztd||j|	f  W Y d }	~	qd }	~	ww ||j| krX||j|< |jrWd}q	 q|S )NFr{  r|  T)re   r   r  r   rW  rn   r   r    ra  r"   r   r   r}  rw   )
r   r   r   row_jsonr  r  
datum_jsonr$   r  r   r   r   r   __row_update  s0   

zIdl.__row_updatec                 C   s   t | ||t|S r   )r^  r   )r   r   r   r   r   r   __create_row  s   zIdl.__create_rowc                 C   s   | j   d S r   )r   r   r'   r   r   r   __error  r(  zIdl.__errorc                 C   s*   | j r| j  d }tj|_| j sd S d S )Nr   )r   popitemTransaction	TRY_AGAIN_status)r   r   r   r   r   __txn_abort_all  s   zIdl.__txn_abort_allc                 C   s&   | j |jd }|r|| dS d S r@   )r   popr   _process_reply)r   r   r   r   r   r   __txn_process_reply  s
   
zIdl.__txn_process_replyr@   r   )@r2   r3   r4   r5   r   r   r0  r   r   r   r   r8   r:   r<   r>   r1  r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   rm   r  r  r   r  r  r  r  r   r  r$  r   r  r   r   r   r   r   r   r   r   r=  rD  rI  r   ry  rY  r\  rZ  rX  r   r   r   r   r   r   r   ry      s    3
N$ U	
		 

7%-B	ry   c                 C   s   t | tr| jS | S r   )r^   r^  r   )r   r   r   r   _row_to_uuid  s   
r  c                   @   s   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zd%ddZedd Zdd Zdd  Zd!d" Zd#d$ ZdS )&r^  a  A row within an IDL.

    The client may access the following attributes directly:

    - 'uuid': a uuid.UUID object whose value is the row's database UUID.

    - An attribute for each column in the Row's table, named for the column,
      whose values are as returned by Datum.to_python() for the column's type.

      If some error occurs (e.g. the database server's idea of the column is
      different from the IDL's idea), then the attribute values is the
      "default" value return by Datum.default() for the column's type.  (It is
      important to know this because the default value may violate constraints
      for the column's type, e.g. the default integer value is 0 even if column
      contraints require the column's value to be positive.)

      When a transaction is active, column attributes may also be assigned new
      values.  Committing the transaction will then cause the new value to be
      stored into the database.

      *NOTE*: In the current implementation, the value of a column is a *copy*
      of the value in the database.  This means that modifying its value
      directly will have no useful effect.  For example, the following:
        row.mycolumn["a"] = "b"              # don't do this
      will not change anything in the database, even after commit.  To modify
      the column, instead assign the modified column value back to the column:
        d = row.mycolumn
        d["a"] = "b"
        row.mycolumn = d
c                 C   sJ   || j d< || j d< || j d< || j d< i | j d< i | j d< i | j d< d S )Nr   _idlr   r}  _changes
_mutations_prereqs)__dict__)r   r   r   r   r   r   r   r   r     s   



	

zRow.__init__c                 C   s&   t |tstS t| jd |jd k S Nr   r^   r^  NotImplementedr
  r  r   otherr   r   r   __lt__"     
z
Row.__lt__c                 C   s&   t |tstS t| jd |jd kS r  r  r  r   r   r   __eq__'  r  z
Row.__eq__c                 C   s   t | jd S r  )r   r  r'   r   r   r   __hash__,  r(  zRow.__hash__c                    s.   dj  jjd fddt jjD dS )Nz{table}({data})z, c                 3   s.    | ]}t  |rd j|t |dV  qdS )z{col}={val})colvalN)r;  formatrg   r)   cr'   r   r   r+   2  s
    zRow.__str__.<locals>.<genexpr>)r   r   )r  r   rn   joinsortedr   r'   r   r'   r   __str__/  s   
zRow.__str__c              
   C   s\   |j r,z
| jj|j j }W n ty% } zd|j j}t||d }~ww |j|S |S )NzTable {} is not registered)		ref_tabler  rq   rn   KeyErrorr  AttributeErrorrc   r  )r   atombaser   r   r   r   r   r   _uuid_to_row6  s   
zRow._uuid_to_rowc           
         s  | j d usJ | jd usJ z| jj| }W n ty'   td| jj|f w | j |}d }d| j	 v r?| jd |}d }d| j	 v rP| jd |}|d u r| j
d u rq|d u rgtd| jj|f tj|j|t}n|| j
v r| j
| }|j r| }|d ur|t| |d urtj|j|t}|   fdd|D }tj|j|t}nC|j r|| j}|d ur|| |d ur|D ]}	|	|pi vr||	d  qtj|j|t}n|d u rtd| jj|f |}|| jS )Nz!%s instance has no attribute '%s'_inserts_removesc                    s   g | ]}| vr|qS r   r   )r)   re  removes_listr   r   r9  f  s    z#Row.__getattr__.<locals>.<listcomp>)r  r  r   r   r  r  r   r2   r  r&   r}  r   r    from_pythonr"   r  is_setas_listextendrl   rx  	to_pythonr  r   r  )
r   r  r$   r  insertsremovesdlistremoves_datumdmaprr  r   r  r   rj   A  s   








zRow.__getattr__c              
   C   s2  | j d usJ | jjsJ | jj| jjv r(|| jj| jj v r(td|  d S | jj| }zt	j
|j|t}W n tjyV } ztd||f  W Y d }~d S d }~ww t| |ru| jjj D ]}|dd |jD v rt||  qc| jj| || | jjj D ]}|dd |jD v r||  qd S )Nz)attempting to write to readonly column %s/attempting to write bad value to column %s (%s)c                 s       | ]}|j V  qd S r   r$   r  r   r   r   r+         z"Row.__setattr__.<locals>.<genexpr>c                 s   r  r   r  r  r   r   r   r+     r  )r  r  r   r   rn   r   r   rW  r   r   r    r  r"   r  r   r   r   r;  rc   r   r-   remove_writeadd)r   r  r   r$   r  r   idxr   r   r   __setattr__}  s:   


zRow.__setattr__c              
   C      | | j jj| j< | jj| }ztj|j	|t
 W n tjy6 } ztd||f  W Y d }~d S d }~ww | jdi }||t }|| d S )Nr  r  r  r   	_txn_rowsr   r   r   r   r    r  r"   r  r   r   r   r   r  
setdefaultsetr  )r   r  rr  r$   r   r  column_valuer   r   r   addvalue     zRow.addvaluec              
   C   r  )Nz2attempting to delete bad value from column %s (%s)r  r  )r   r  rr  r$   r   r  r  r   r   r   delvalue  r  zRow.delvaluec           	   
   C   s   | | j jj| j< | jj| }ztj|j	||it
 W n tjy8 } ztd||f  W Y d }~d S d }~ww | jrT|| jv rT| jdi }||t }|| | jdi }||i }|||< d S )Nr  r  r  )r  r   r  r   r   r   r   r    r  r"   r  r   r   r   r   r}  r  r  r  r  )	r   r  rr  r   r$   r   r  r  r  r   r   r   setkey  s$   
z
Row.setkeyNc                 C   s   | | j jj| j< |r1ztj| j| | j}W n t	j
y"   Y d S w ||vr)d S || |kr1d S | jdi }||t }|| d S )Nr  )r  r   r  r   r   r    r  r}  r  r   r   r  r  r  r  )r   r  rr  r   	old_valuer  r  r   r   r   delkey  s"   
z
Row.delkeyc                 C   s   i }|  D ]F\}}|j|}|std||jf  qztjjj	
|j|}	W n tjyG }
 ztd||j|
f  W Y d }
~
qd }
~
ww |	||< q| ||||S )Nzunknown column %s in table %sr|  )re   r   r  r   rW  rn   r   r   r   r    ra  r"   r   r   )rp   r   r   r   r  r   r  r  r$   r  r   r   r   r   ra    s&   

zRow.from_jsonc                 C   s@   | j jsJ | jdusJ | jdu s|| jv rdS d| j|< dS )a  Causes the original contents of column 'column_name' in this row to
        be verified as a prerequisite to completing the transaction.  That is,
        if 'column_name' changed in this row (or if this row was deleted)
        between the time that the IDL originally read its contents and the time
        that the transaction commits, then the transaction aborts and
        Transaction.commit() returns Transaction.TRY_AGAIN.

        The intention is that, to ensure that no transaction commits based on
        dirty reads, an application should call Row.verify() on each data item
        read as part of a read-modify-write operation.

        In some cases Row.verify() reduces to a no-op, because the current
        value of the column is already known:

          - If this row is a row created by the current transaction (returned
            by Transaction.insert()).

          - If the column has already been modified within the current
            transaction.

        Because of the latter property, always call Row.verify() *before*
        modifying the column, for a given read-modify-write.

        A transaction must be in progress.N)r  r   r  r}  r  r   r  r   r   r   verify  s
   z
Row.verifyc                 C   s^   | j jsJ | jdusJ | jdu r| j jj| j= n| | j jj| j< | jj| j= d| jd< dS )zLDeletes this row from its table.

        A transaction must be in progress.Nr  )	r  r   r  r}  r  r   r   rc   r  r'   r   r   r   r     s   
z
Row.deletec                 C   s   | j j| | d S r   )r  r   _fetchr  r   r   r   fetch  rD   z	Row.fetchc                 C   s   | j j| | dS )a  Causes the transaction, when committed, to increment the value of
        'column_name' within this row by 1.  'column_name' must have an integer
        type.  After the transaction commits successfully, the client may
        retrieve the final (incremented) value of 'column_name' with
        Transaction.get_increment_new_value().

        The client could accomplish something similar by reading and writing
        and verify()ing columns.  However, increment() will never (by itself)
        cause a transaction to fail because of a verify error.

        The intended use is for incrementing the "next_cfg" column in
        the Open_vSwitch table.N)r  r   
_incrementr  r   r   r   	increment  s   zRow.incrementr   )r2   r3   r4   r5   r   r  r  r  r  r  rj   r  r  r  r  r  ru   ra  r  r   r  r  r   r   r   r   r^    s(    7<

 r^  c                 C   s   dt | dd S )Nzrow%s-_)r   replacer   r   r   r   _uuid_name_from_uuid/  rD   r  c                 C   s   dddt | gggS )N_uuid==r   rd  r  r   r   r   _where_uuid_equals3  rD   r  c                   @   s   e Zd Zdd ZdS )_InsertedRowc                 C   s   || _ d | _d S r   )op_indexreal)r   r  r   r   r   r   8  rx   z_InsertedRow.__init__N)r2   r3   r4   r   r   r   r   r   r  7  s    r  c                   @   s   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zed
d Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd7d+d,Zd-d. Zed/d0 Zd1d2 Z d3d4 Z!d5d6 Z"d*S )8r  a	  A transaction may modify the contents of a database by modifying the
    values of columns, deleting rows, inserting rows, or adding checks that
    columns in the database have not changed ("verify" operations), through
    Row methods.

    Reading and writing columns and inserting and deleting rows are all
    straightforward.  The reasons to verify columns are less obvious.
    Verification is the key to maintaining transactional integrity.  Because
    OVSDB handles multiple clients, it can happen that between the time that
    OVSDB client A reads a column and writes a new value, OVSDB client B has
    written that column.  Client A's write should not ordinarily overwrite
    client B's, especially if the column in question is a "map" column that
    contains several more or less independent data items.  If client A adds a
    "verify" operation before it writes the column, then the transaction fails
    in case client B modifies it first.  Client A will then see the new value
    of the column and compose a new transaction based on the new contents
    written by client B.

    When a transaction is complete, which must be before the next call to
    Idl.run(), call Transaction.commit() or Transaction.abort().

    The life-cycle of a transaction looks like this:

    1. Create the transaction and record the initial sequence number:

        seqno = idl.change_seqno(idl)
        txn = Transaction(idl)

    2. Modify the database with Row and Transaction methods.

    3. Commit the transaction by calling Transaction.commit().  The first call
       to this function probably returns Transaction.INCOMPLETE.  The client
       must keep calling again along as this remains true, calling Idl.run() in
       between to let the IDL do protocol processing.  (If the client doesn't
       have anything else to do in the meantime, it can use
       Transaction.commit_block() to avoid having to loop itself.)

    4. If the final status is Transaction.TRY_AGAIN, wait for Idl.change_seqno
       to change from the saved 'seqno' (it's possible that it's already
       changed, in which case the client should not wait at all), then start
       over from step 1.  Only a call to Idl.run() will change the return value
       of Idl.change_seqno.  (Transaction.commit_block() calls Idl.run().)uncommitted	unchanged
incompleteabortedsuccessz	try againz
not lockedr   c                 C   s   | S )zConverts one of the status values that Transaction.commit() can
        return into a human-readable string.

        (The status values are in fact such strings already, so
        there's nothing to do.)r   )statusr   r   r   status_to_string  s   zTransaction.status_to_stringc                 C   s\   |j du sJ | |_ d| _|| _d| _i | _tj| _d| _g | _	d| _
d| _g | _i | _dS )a[  Starts a new transaction on 'idl' (an instance of ovs.db.idl.Idl).
        A given Idl may only have a single active transaction at a time.

        A Transaction may modify the contents of a database by assigning new
        values to columns (attributes of Row), deleting rows (with
        Row.delete()), or inserting rows (with Transaction.insert()).  It may
        also check that columns in the database have not changed with
        Row.verify().

        When a transaction is complete (which must be before the next call to
        Idl.run()), call Transaction.commit() or Transaction.abort().NF)r   r   r   dry_runr  r  UNCOMMITTEDr  _error	_comments_inc_row_inc_column_fetch_requests_inserted_rows)r   r   r   r   r   r     s   
zTransaction.__init__c                 C   s   | j | dS )a  Appends 'comment' to the comments that will be passed to the OVSDB
        server when this transaction is committed.  (The comment will be
        committed to the OVSDB log, which "ovsdb-tool show-log" can print in a
        relatively human-readable form.)N)r  r   )r   commentr   r   r   add_comment  s   zTransaction.add_commentc                 C   s"   | j tjtjfvr|  dS dS )zTCauses poll_block() to wake up if this transaction has completed
        committing.N)r  r  r  
INCOMPLETEr  r  r   r   r   r    s
   zTransaction.waitc                    s   t |ttfrBt|dkr9|d dkr9tj|d r9tj|d } j	|d }|r7|j
d u r7dt|gS |S  fdd|D S |S )Nr	   r   r   r   z
named-uuidc                    s   g | ]}  |qS r   )_substitute_uuids)r)   elemr'   r   r   r9    s    z1Transaction._substitute_uuids.<locals>.<listcomp>)r^   rl   r,  r   r   rA  rB  rC  r  r  r}  r  )r   jsonr   r   r   r'   r   r    s   zTransaction._substitute_uuidsc                 C   s   d | j _| j D ]3}|jd u r"i |jd< i |jd< ||jj|j< n|j	d u r-|jj|j= i |jd< i |jd< i |jd< q	i | _d S )Nr  r  r  )
r   r   r  r-   r  r  r   rc   r   r}  )r   r   r   r   r   __disassemble  s   






zTransaction.__disassemblec                 C   s  | | j jkr	| jS | j jtjkrtj| _|   | jS | j j	r.| j j
s.tj| _|   | jS | j jjg}| j j	rB|d| j j	d | j D ]0}|jrwi }g }|jD ]}|| |j|  ||< qS|d|jjdt|jd||gd qGd}| j D ]}|jdu r|jjr|d	|jjt|jd
 d}n|	 nz|jrd|jji}|jdu rd|d< t|j|d< d}t|d }t|| j|j< nd|d< t|j|d< i }	|	|d< |j D ]*\}}
|jdus|
 s	| |
 |	|< |s	|jdur	|j| |
kr	d}q|jdu s|	r|| |j r2d}d|jji}d|d< |jdu r9| t|j|d< nt|j|d< g |d< d|j ! v r|j d  D ]_\}}|jj"| }|j#$ rndg}|t%| n5dg}g }|D ](}zt&j'(|j#|t)}
W n t*j+y   Y    dS w || |
  qu|| |d	|g}|d | d}qSd|j ! v r(|j d  D ]e\}}|jj"| }|j#$ rt&j'(|j#|t)}
| |
 }n5dg}g }|D ](}zt&j'(|j#|t)}
W n t*j+y   Y    dS w || |
  q|| |d|g}|d | d}q|r2|| d}q| j,ra| j,D ]$}t|d |d< |d|d jj| t|d j|d gd q:d}| j-r|rt|d | _.|d| j-jj| t| j-j| j/ddggd |d| j-jj| t| j-j| j/gd | j0r|dd 1| j0d! | j2r|dd"i |stj3| _n$t4j5j67d#|}|j8| _9| j j:;|s| | j j<| j9< tj=| _ntj| _|   | jS )$a  Attempts to commit 'txn'.  Returns the status of the commit
        operation, one of the following constants:

          Transaction.INCOMPLETE:

              The transaction is in progress, but not yet complete.  The caller
              should call again later, after calling Idl.run() to let the
              IDL do OVSDB protocol processing.

          Transaction.UNCHANGED:

              The transaction is complete.  (It didn't actually change the
              database, so the IDL didn't send any request to the database
              server.)

          Transaction.ABORTED:

              The caller previously called Transaction.abort().

          Transaction.SUCCESS:

              The transaction was successful.  The update made by the
              transaction (and possibly other changes made by other database
              clients) should already be visible in the IDL.

          Transaction.TRY_AGAIN:

              The transaction failed for some transient reason, e.g. because a
              "verify" operation reported an inconsistency or due to a network
              problem.  The caller should wait for a change to the database,
              then compose a new transaction, and commit the new transaction.

              Use Idl.change_seqno to wait for a change in the database.  It is
              important to use its value *before* the initial call to
              Transaction.commit() as the baseline for this purpose, because
              the change that one should wait for can happen after the initial
              call but before the call that returns Transaction.TRY_AGAIN, and
              using some other baseline value in that situation could cause an
              indefinite wait if the database rarely changes.

          Transaction.NOT_LOCKED:

              The transaction failed because the IDL has been configured to
              require a database lock (with Idl.set_lock()) but didn't
              get it yet or has already lost it.

        Committing a transaction rolls back all of the changes that it made to
        the IDL's copy of the database.  If the transaction commits
        successfully, then the database server will send an update and, thus,
        the IDL will be updated with the committed changes.assert)rb  r#  r  r   r  )rb  r   timeoutr  untilr   rc   FNr   )rb  r   r  Tr   rS  rb  z	uuid-namer   r   r  r   mutate	mutationsr  r  r  rn  selectr  )rb  r   r  r   z+=)rb  r   r  r  r  
)rb  r  aborttransact)>r   r   r  r   ry   r   r  r  _Transaction__disassembler   r   
NOT_LOCKEDr   rn   r   r  r-   r  r}  ru  r   r  r   r  is_rootr  r   r  r  re   
is_defaultr  r  r&   r   r"   rx  rl   r   r    r  r  r   r   r  r  
_inc_indexr  r  r  r  	UNCHANGEDr   r   r   r   r   r   r   r   r   r  )r   
operationsr   rc   r   r  any_updatesrb  r  r  r  addopr  datr$   opdatinner_opdatelemutationr  r  r   r   r   r   commit  sP  5

	

















zTransaction.commitc                 C   sL   	 |   }|tjkr|S | j  tj }| j| | | |	  q)aI  Attempts to commit this transaction, blocking until the commit
        either succeeds or fails.  Returns the final commit status, which may
        be any Transaction.* value other than Transaction.INCOMPLETE.

        This function calls Idl.run() on this transaction'ss IDL, so it may
        cause Idl.change_seqno to change.)
r  r  r  r   r   r   r  Pollerr  block)r   r  r  r   r   r   commit_block  s   



zTransaction.commit_blockc                 C   s   | j tjksJ | jS )zReturns the final (incremented) value of the column in this
        transaction that was set to be incremented by Row.increment.  This
        transaction must have committed successfully.)r  r  SUCCESS_inc_new_valuer'   r   r   r   get_increment_new_value  s   z#Transaction.get_increment_new_valuec                 C   s*   |    | jtjtjfv rtj| _dS dS )zAborts this transaction.  If Transaction.commit() has already been
        called then the transaction might get committed anyhow.N)r  r  r  r  r  ABORTEDr'   r   r   r   r    s   zTransaction.abortc                 C   s(   | j tjkrt| j S | jr| jS dS )zjReturns a string representing this transaction's current status,
        suitable for use in log messages.zno error details available)r  r  ERRORr  r  r'   r   r   r   	get_error  s
   zTransaction.get_errorc                 C   s    | j d u rtj|| _ d S d S r   )r  r   r  	to_string)r   r  r   r   r   __set_error_json  s   
zTransaction.__set_error_jsonc                 C   s0   | j tjtjfv sJ | j|}|r|jS dS )aX  Finds and returns the permanent UUID that the database assigned to a
        newly inserted row, given the UUID that Transaction.insert() assigned
        locally to that row.

        Returns None if 'uuid' is not a UUID assigned by Transaction.insert()
        or if it was assigned by that function and then deleted by Row.delete()
        within the same transaction.  (Rows that are inserted and then deleted
        within a single transaction are never sent to the database server, so
        it never assigns them a permanent UUID.)

        This transaction must have completed successfully.N)r  r  r  r  r  r  r  )r   r   inserted_rowr   r   r   get_insert_uuid  s   
zTransaction.get_insert_uuidc                 C   s   | j rJ || _ || _d S r   )r  r  )r   r   r$   r   r   r   r    s   

zTransaction._incrementc                 C   s   | j ||d d S )N)r   r  )r  r   )r   r   r  r   r   r   r  
  r.   zTransaction._fetchc                 C   s   |j d usJ |jd usJ |jj}|js4|jd ur4|j|j|kr4|j |j}|d u s2||kr4d S ||j|j	< d|jv rI|jd 
|jd  d|jv rX|jd 
|jd  | |j |j< d S )Nr  r  )r  r  r  r   rw   r}  r  rn   r  r   r  r~  )r   r   r$   r  r   	new_valuer   r   r   r    s   

zTransaction._writeNc                 C   sL   | j tjksJ |du rt }t| j||d}||j|j< || j|j< |S )a3  Inserts and returns a new row in 'table', which must be one of the
        ovs.db.schema.TableSchema objects in the Idl's 'tables' dict.

        The new row is assigned a provisional UUID.  If 'uuid' is None then one
        is randomly generated; otherwise 'uuid' should specify a randomly
        generated uuid.UUID not otherwise in use.  ovsdb-server will assign a
        different UUID when 'txn' is committed, but the IDL will replace any
        uses of the provisional UUID in the data to be to be committed by the
        UUID assigned by ovsdb-server.N)	r  r  r  r   uuid4r^  r   rc   r  )r   r   new_uuidr   r   r   r   rS  ,  s   
zTransaction.insertc           	      C   sp  |j tjjjkrtj| _d S t|j	t
tfstd d S d}d}d}|j	}|D ]>}|d u r1d}q(t|trZ|d}|d urY|dkrFd}q(|dkrMd}q(|dkrRq(d}| | q(d}| | td q(|s|s|s| jrw| |swd}| jr| |r| j jd	7  _nd}| j D ]
}| ||sd}q|rtj| _d S |rtj| _d S |rtj| _d S tj| _d S )
Nz%reply to "transact" is not JSON arrayFTr   z	timed outz	not ownerr  z*operation reply is not JSON null or objectr   )r"   r   r   r   r   r  r  r  r^   r   rl   r,  r   rW  r)  r  _Transaction__set_error_jsonr  _Transaction__process_inc_replyr  !_Transaction__process_fetch_replyr   r   r  r-   "_Transaction__process_insert_replyr  r  r  )	r   r   hard_errorssoft_errorslock_errorsopsrb  r   rS  r   r   r   r  >  sX   




zTransaction._process_replyc                 C   sB   | st d|  dS t| t|st d|t| f  dS dS )Nz%s is missingFz%s has unexpected type %sT)r   rW  r^   r,  r"   )r  rs  rn   r   r   r   __check_json_typex  s   zTransaction.__check_json_typec                 C   s   d}| j D ]]}|d }|d }|d }|j}|| }|d}	t|	ttfds+ dS t|	dkr;t	dt|	  q|	d	 }
t|
t
fd
sHq|j|}|
|}tj|j|}||j|< d}q|S )NFr   r  rn  rc   "select" reply "rows"r   2"select" reply "rows" has %d elements instead of 1r   "select" reply rowT)r  r   r  r  _Transaction__check_json_typerl   r,  r   r   rW  r)  r   r   r    ra  r"   r}  )r   r)  r   fetch_requestr   r  rn  r   r  fetched_rowsfetched_rowr$   r  r  r   r   r   __process_fetch_reply  s8   




z!Transaction.__process_fetch_replyc                 C   s  | j d t|krtdt|| j d f  || j  }|d}t|tfds+dS |dkr8td|  dS || j d  }|d}t|tt	fd	sOdS t|dkr`td
t|  dS |d }t|t
fdsndS || j}t|tfds~dS || _dS )Nr	   zIreply does not contain enough operations for increment (has %d, needs %d)countz"mutate" reply "count"Fr   z)"mutate" reply "count" is %d instead of 1rc   r+  r,  r   r-  z"select" reply inc columnT)r  r   r   rW  r  r  r.  r   rl   r,  r)  r  r  )r   r)  r  r3  r  rc   r   r$   r   r   r   __process_inc_reply  sH   





zTransaction.__process_inc_replyc                 C   s   |j t|krtdt||j f  dS ||j  }|d}t|ttfds*dS zt	j
|}W n tjyB   td Y dS w ||_dS )NzFreply does not contain enough operations for insert (has %d, needs %d)Fr   z"insert" reply "uuid"z("insert" reply "uuid" is not a JSON UUIDT)r  r   r   rW  r  r  r.  r,  rl   r   rA  ra  r   r   r  )r   rS  r)  reply	json_uuiduuid_r   r   r   __process_insert_reply  s&   


z"Transaction.__process_insert_replyr   )#r2   r3   r4   r5   r  r  r  r  r  r  r  r  rX   r  r   r  r  r  r  r  r  r  r  r  r"  r  r  r  r  rS  r  r.  r$  r#  r%  r   r   r   r   r  =  sF    .
 q

:
 (r  c                   @   sF   e Zd ZdZdddZg fddZdd Zd	d
 Zdd Zdd Z	dS )r   a  IDL Schema helper.

    This class encapsulates the logic required to generate schemas suitable
    for creating 'ovs.db.idl.Idl' objects.  Clients should register columns
    they are interested in using register_columns().  When finished, the
    get_idl_schema() function may be called.

    The location on disk of the schema used may be found in the
    'schema_location' variable.Nc                 C   sT   |r|rt d|du r|du rdtjj }tj|}|| _i | _i | _d| _	dS )zCreates a new Schema object.

        'location' file path to ovs schema. None means default location
        'schema_json' schema in json preresentation in memory
        zAboth location and schema_json can't be specified. it's ambiguous.Nz%s/vswitch.ovsschemaF)

ValueErrorr   dirs
PKGDATADIRr  	from_fileschema_json_tables	_readonly_all)r   locationr=  r   r   r   r     s   
zSchemaHelper.__init__c                 C   sL   t |tsJ t |tsJ t|| j|t B }|| j|< || j|< dS )a,  Registers interest in the given 'columns' of 'table'.  Future calls
        to get_idl_schema() will include 'table':column for each column in
        'columns'. This function automatically avoids adding duplicate entries
        to the schema.
        A subset of 'columns' can be specified as 'readonly'. The readonly
        columns are not replicated but can be fetched on-demand by the user
        with Row.fetch().

        'table' must be a string.
        'columns' must be a list of strings.
        'readonly' must be a list of strings.
        N)r^   r   rl   r  r>  r  r?  )r   r   r   r   r   r   r   register_columns	  s
   
zSchemaHelper.register_columnsc                 C   s   t |tsJ t | j|< dS )zRegisters interest in the given all columns of 'table'. Future calls
        to get_idl_schema() will include all columns of 'table'.

        'table' must be a string
        N)r^   r   r  r>  r   r   r   r   r   	  s   zSchemaHelper.register_tablec                 C   s
   d| _ dS )z2Registers interest in every column of every table.TN)r@  r'   r   r   r   register_all%	  rP   zSchemaHelper.register_allc                 C   sZ   t jjj| j}d| _| js'i }| j D ]\}}| 	|||||< q||_
| j|_|S )zGets a schema appropriate for the creation of an 'ovs.db.id.IDL'
        object based on columns registered using the register_columns()
        function.N)r   r   r_   DbSchemara  r=  r@  r>  re   _keep_table_columnsrq   r?  r   )r   r_   rr   r   r   r   r   r   r   )	  s   zSchemaHelper.get_idl_schemac                 C   sb   ||j v sJ |j | }|s|S i }|D ]}t|tsJ ||jv s$J |j| ||< q||_|S r   )rq   r^   r   r   )r   r_   r  r   r   new_columnsr  r   r   r   rE  ;	  s   
z SchemaHelper._keep_table_columns)NN)
r2   r3   r4   r5   r   rB  r   rC  r   rE  r   r   r   r   r     s    

	r   )1collectionsenum	functoolsr   ovs.db.datar   r   ovs.db.parserr   ovs.db.schemaovs.jsonrpcovs.ovsuuid
ovs.pollerovs.vlogovs.dbr   r   r   Vlog__pychecker__r[  r]  rV  r9   r;   r=   rk  ro  
namedtupler   __new____defaults__r)  r   IntEnumr8   objectr?   rY   rZ   ry   r  total_orderingr^  r  r  r  r  r   r   r   r   r   <module>   sl   9 	          e     0