HEX
Server: LiteSpeed
System: Linux us-phx-web1284.main-hosting.eu 4.18.0-553.109.1.lve.el8.x86_64 #1 SMP Thu Mar 5 20:23:46 UTC 2026 x86_64
User: u300739242 (300739242)
PHP: 8.2.30
Disabled: system, shell_exec, passthru, mysql_list_dbs, ini_alter, dl, symlink, link, chgrp, leak, popen, apache_child_terminate, virtual, mb_send_mail
Upload Files
File: //opt/alt/python311/lib/python3.11/site-packages/pyroute2/ndb/__pycache__/main.cpython-311.pyc
�

�;f�S���dZddlZddlZddlZddlZddlZddlZddlZddlm	Z	ddl
mZddlm
Z
ddlmZddlmZdd	lmZdd
lmZddlmZddlmZmZ	dd
lmZn#e$r	dd
lmZYnwxYw	ddlZn#e$rddlZYnwxYwej e!��Z"dZ#Gd�d��Z$Gd�d��Z%Gd�d��Z&Gd�d��Z'Gd�d��Z(dS)a.
.. testsetup::

    from pyroute2 import NDB
    ndb = NDB(sources=[{'target': 'localhost', 'kind': 'IPMock'}])

.. testsetup:: netns

    from types import MethodType

    from pyroute2 import NDB

    ndb = NDB(sources=[{'target': 'localhost', 'kind': 'IPMock'}])

    def add_mock_netns(self, netns):
        return self.add_orig(target=netns, kind='IPMock', preset='netns')

    ndb.sources.add_orig = ndb.sources.add
    ndb.sources.add = MethodType(add_mock_netns, ndb.sources)

.. testcleanup:: *

    for key, value in tuple(globals().items()):
        if key.startswith('ndb') and hasattr(value, 'close'):
            value.close()

NDB is a high level network management module. IT allows to manage interfaces,
routes, addresses etc. of connected systems, containers and network
namespaces.

In a nutshell, NDB collects and aggregates netlink events in an SQL database,
provides Python objects to reflect the system state, and applies changes back
to the system. The database expects updates only from the sources, no manual
SQL updates are expected normally.

.. aafig::
    :scale: 80
    :textual:

        +----------------------------------------------------------------+
      +----------------------------------------------------------------+ |
    +----------------------------------------------------------------+ | |
    |                                                                | | |
    |                              kernel                            | |-+
    |                                                                |-+
    +----------------------------------------------------------------+
            |                      | ^                     | ^
            | `netlink events`     | |                     | |
            | `inotify events`     | |                     | |
            | `...`                | |                     | |
            v                      v |                     v |
     +--------------+        +--------------+        +--------------+
     |     source   |        |     source   |        |     source   |<--\
     +--------------+        +--------------+        +--------------+   |
            |                       |                       |           |
            |                       |                       |           |
            \-----------------------+-----------------------/           |
                                    |                                   |
              parsed netlink events | `NDB._event_queue`                |
                                    |                                   |
                                    v                                   |
                        +------------------------+                      |
                        | `NDB.__dbm__()` thread |                      |
                        +------------------------+                      |
                                    |                                   |
                                    v                                   |
                     +-----------------------------+                    |
                     | `NDB.schema.load_netlink()` |                    |
                     | `NDB.objects.*.load*()`     |                    |
                     +-----------------------------+                    |
                                    |                                   |
                                    v                                   |
                         +----------------------+                       |
                         |  SQL database        |                       |
                         |     `SQLite`         |                       |
                         |     `PostgreSQL`     |                       |
                         +----------------------+                       |
                                    |                                   |
                                    |                                   |
                                    V                                   |
                              +---------------+                         |
                            +---------------+ |                         |
                          +---------------+ | |  `RTNL_Object.apply()`  |
                          | NDB object:   | | |-------------------------/
                          |  `interface`  | | |
                          |  `address`    | | |
                          |  `route`      | |-+
                          |  `...`        |-+
                          +---------------+

.. container:: aafig-caption

    object names on the diagram are clickable

The goal of NDB is to provide an easy access to RTNL info and entities via
Python objects, like `pyroute2.ndb.objects.interface` (see also:
:ref:`ndbinterfaces`), `pyroute2.ndb.objects.route` (see also:
:ref:`ndbroutes`) etc. These objects do not
only reflect the system state for the time of their instantiation, but
continuously monitor the system for relevant updates. The monitoring is
done via netlink notifications, thus no polling. Also the objects allow
to apply changes back to the system and rollback the changes.

On the other hand it's too expensive to create Python objects for all the
available RTNL entities, e.g. when there are hundreds of interfaces and
thousands of routes. Thus NDB creates objects only upon request, when
the user calls `.create()` to create new objects or runs
`ndb.<view>[selector]` (e.g. `ndb.interfaces['eth0']`) to access an
existing object.

To list existing RTNL entities NDB uses objects of the class `RecordSet`
that `yield` individual `Record` objects for every entity (see also:
:ref:`ndbreports`). An object of the `Record` class is immutable, doesn't
monitor any updates, doesn't contain any links to other objects and essentially
behaves like a simple named tuple.

.. aafig::
    :scale: 80
    :textual:


      +---------------------+
      |                     |
      |                     |
      | `NDB() instance`    |
      |                     |
      |                     |
      +---------------------+
                 |
                 |
        +-------------------+
      +-------------------+ |
    +-------------------+ | |-----------+--------------------------+
    |                   | | |           |                          |
    |                   | | |           |                          |
    | `View()`          | | |           |                          |
    |                   | |-+           |                          |
    |                   |-+             |                          |
    +-------------------+               |                          |
                               +------------------+       +------------------+
                               |                  |       |                  |
                               |                  |       |                  |
                               | `.dump()`        |       | `.create()`      |
                               | `.summary()`     |       | `.__getitem__()` |
                               |                  |       |                  |
                               |                  |       |                  |
                               +------------------+       +------------------+
                                        |                           |
                                        |                           |
                                        v                           v
                              +-------------------+        +------------------+
                              |                   |      +------------------+ |
                              |                   |    +------------------+ | |
                              | `RecordSet()`     |    | `Interface()`    | | |
                              |                   |    | `Address()`      | | |
                              |                   |    | `Route()`        | | |
                              +-------------------+    | `Neighbour()`    | | |
                                        |              | `Rule()`         | |-+
                                        |              |  ...             |-+
                                        v              +------------------+
                                +-------------------+
                              +-------------------+ |
                            +-------------------+ | |
                            | `filter()`        | | |
                            | `select()`        | | |
                            | `transform()`     | | |
                            | `join()`          | |-+
                            |  ...              |-+
                            +-------------------+
                                        |
                                        v
                                +-------------------+
                              +-------------------+ |
                            +-------------------+ | |
                            |                   | | |
                            |                   | | |
                            | `Record()`        | | |
                            |                   | |-+
                            |                   |-+
                            +-------------------+

.. container:: aafig-caption

    object names on the diagram are clickable

Here are some simple NDB usage examples. More info see in the reference
documentation below.

Print all the interface names on the system, assume we have an NDB
instance `ndb`:

.. testcode::

    for interface in ndb.interfaces.dump():
        print(interface.ifname)

.. testoutput::

    lo
    eth0

Print the routing information in the CSV format:

.. testcode::

    for record in ndb.routes.summary().format('csv'):
        print(record)

.. testoutput::

    'target','tflags','table','ifname','dst','dst_len','gateway'
    'localhost',0,254,'eth0','',0,'192.168.122.1'
    'localhost',0,254,'eth0','192.168.122.0',24,
    'localhost',0,255,'lo','127.0.0.0',8,
    'localhost',0,255,'lo','127.0.0.1',32,
    'localhost',0,255,'lo','127.255.255.255',32,
    'localhost',0,255,'eth0','192.168.122.28',32,
    'localhost',0,255,'eth0','192.168.122.255',32,

.. note:: More on report filtering and formatting: :ref:`ndbreports`

Print IP addresses of interfaces in several network namespaces as:

.. testcode:: netns

    nslist = ['netns01',
              'netns02',
              'netns03']

    for nsname in nslist:
        ndb.sources.add(netns=nsname)

    report = ndb.addresses.summary()
    report.select_records(target=lambda x: x.startswith('netns'))
    report.select_fields('address', 'ifname', 'target')
    for line in report.format('json'):
        print(line)

.. testoutput:: netns

    [
        {
            "address": "127.0.0.1",
            "ifname": "lo",
            "target": "netns01"
        },
        {
            "address": "127.0.0.1",
            "ifname": "lo",
            "target": "netns02"
        },
        {
            "address": "127.0.0.1",
            "ifname": "lo",
            "target": "netns03"
        }
    ]

Add an IP address on an interface:

.. testcode::

    with ndb.interfaces['eth0'] as eth0:
        eth0.add_ip('10.0.0.1/24')
    # ---> <---  NDB waits until the address setup

Change an interface property:

.. testcode::

    with ndb.interfaces['eth0'] as eth0:
        eth0.set(
            state='up',
            address='00:11:22:33:44:55',
        )
    # ---> <---  NDB waits here for the changes to be applied
    #            the commit() is called automatically by the
    #            context manager's __exit__()

�N)�config)�
basestring�)�AuthManager��ShutdownException)�cmsg)�
DBProvider)�TaskManager)�Transaction)�SourcesView�View)�urlparse))�
interfacesr)�	addressesr)�routesr)�
neighboursr)�
af_bridge_fdb�fdb)�rulesr)�netnsr)�af_bridge_vlans�vlansc��eZdZd
d�Zdejfd�Zed���Zed���Z	d�Z
d�Zd�Zd	�Z
d
�Zd�Zd�ZdS)�LogNc���d|_d|_|pt|��|_t	jd|jz��|_|�d��|_dS)NFzpyroute2.ndb.%s�main)�logger�state�id�log_id�logging�	getLogger�channelr)�selfr!s  �D/opt/alt/python311/lib/python3.11/site-packages/pyroute2/ndb/main.py�__init__zLog.__init__IsS�������
��(��4������'�(9�D�K�(G�H�H����L�L��(�(��	�	�	�c��|�	|jduS|j�6t|jj��D]}|j�|���|dvrN|jrE|j�d��|j�tj����dS|dvrtj	��}n�|dkr tj	��}tj
}n�t|t��r�t|��}|js!|jrtj|j��}nU|jdkr9tj�|j�d�����}nt)d���|}||ur+d	}tj|��}|�|��|j�|��|j�|��dS)
N)�offFr)�on�stderr�debug�syslog�:)�addresszlogging scheme not supportedz0%(asctime)s %(levelname)8s %(name)s: %(message)s)r�tuple�handlers�
removeHandlerr�setLevel�
addHandlerr"�NullHandler�
StreamHandler�DEBUG�
isinstancerr�scheme�path�FileHandler�
SysLogHandler�netloc�split�
ValueError�	Formatter�setFormatter)r%�target�level�handler�url�fmt�	formatters       r&�__call__zLog.__call__Ps����>��;�d�*�*��;�"� ���!5�6�6�
3�
3����)�)�'�2�2�2�2��^�#�#��z�
>���$�$�Q�'�'�'���&�&�w�':�'<�'<�=�=�=��F��%�%�%��+�-�-�G�G�
�w�
�
��+�-�-�G��M�E�E�
��
�
+�
+�	��6�"�"�C��:�
A�#�(�
A�!�-�c�h�7�7�����x�'�'�!�*�8�8��J�,�,�S�1�1�9�����!�!?�@�@�@��G��&� � �D�C��)�#�.�.�I�� � ��+�+�+�����w�'�'�'�����U�#�#�#�#�#r(c�2�|�d���dS)Nr+�rC�rI�r%s r&r+zLog.onys���
�
�T�
�"�"�"�"�"r(c�2�|�d���dS)Nr*rKrLrMs r&r*zLog.off}s���
�
�U�
�#�#�#�#�#r(c���|jj}|jj}g}|j���D],}|�|��r|�|���-|D]
}|j|=�~~~dS�N)r�manager�name�
loggerDict�keys�
startswith�append)r%rQrR�
purge_listrs     r&�closez	Log.close�s����+�%���{����
��(�-�-�/�/�	*�	*�F�� � ��&�&�
*��!�!�&�)�)�)�� �	+�	+�F��"�6�*�*����J�Jr(c�@�tjd|j�d|����S)Nz
pyroute2.ndb.�.)r"r#r!)r%rRs  r&r$zLog.channel�s#��� � �����d�d�!K�L�L�Lr(c�&�|jj|i|��SrP)rr-�r%�argv�kwargs   r&r-z	Log.debug�����t�y���.��.�.�.r(c�&�|jj|i|��SrP)r�infor\s   r&razLog.info�s���t�y�~�t�-�u�-�-�-r(c�&�|jj|i|��SrP)r�warningr\s   r&rczLog.warning�s�� �t�y� �$�0�%�0�0�0r(c�&�|jj|i|��SrP)r�errorr\s   r&rez	Log.error�r_r(c�&�|jj|i|��SrP)r�criticalr\s   r&rgzLog.critical�s��!�t�y�!�4�1�5�1�1�1r(rP)�__name__�
__module__�__qualname__r'r"�INFOrI�propertyr+r*rXr$r-rarcrerg�r(r&rrHs�������)�)�)�)�#�'�,�'$�'$�'$�'$�R�#�#��X�#��$�$��X�$����$M�M�M�/�/�/�.�.�.�1�1�1�/�/�/�2�2�2�2�2r(rc��eZdZd�ZdS)�DeadEndc� �td���)Nzshutdown in progressrr\s   r&�putzDeadEnd.put�s��� 6�7�7�7r(N)rhrirjrqrmr(r&roro�s#������8�8�8�8�8r(roc�6�eZdZd�Zdd�Zd�Zdd�Zd�Zd�ZdS)	�
EventQueuec�@�tj|i|��x|_|_dSrP)�queue�Queue�_bypass�_queuer\s   r&r'zEventQueue.__init__�s#��%*�[�$�%@�%�%@�%@�@���t�{�{�{r(Nc�:�|j�||f��SrP)rxrq�r%�msg�sources   r&rqzEventQueue.put�s���{�����}�-�-�-r(c�,�t��|_dSrP)rorxrMs r&�shutdownzEventQueue.shutdown�s���i�i����r(c�:�|j�||f��SrP)rwrqrzs   r&�bypasszEventQueue.bypass�s���|�����
�.�.�.r(c�&�|jj|i|��SrP)rw�getr\s   r&r�zEventQueue.get�s���t�|���/��/�/�/r(c�4�|j���SrP)rw�qsizerMs r&r�zEventQueue.qsize�s���|�!�!�#�#�#r(rP)	rhrirjr'rqr~r�r�r�rmr(r&rsrs�s{������A�A�A�.�.�.�.� � � �/�/�/�/�0�0�0�$�$�$�$�$r(rsc��eZdZd�ZdS)�	AuthProxyc��||_||_tD]2\}}t|j||j���}t	|||���3dS)N��
auth_managers)�_ndb�_auth_managers�NDB_VIEWS_SPECSr�setattr)r%�ndbr��vtable�vname�views      r&r'zAuthProxy.__init__�s\����	�+���,�	'�	'�M�F�E���	�6��9L�M�M�M�D��D�%��&�&�&�&�	'�	'r(N)rhrirjr'rmr(r&r�r��s#������'�'�'�'�'r(r�c�x�eZdZed���Z									dd�Zdd	�Zd
�Zd�Zd�Z	d
�Z
d�Zd�Zd�Z
dd�ZdS)�NDBc��d|jzS)Nz%s/nsmanager)�	localhostrMs r&�	nsmanagerz
NDB.nsmanager�s�����.�.r(Nr��sqlite3�:memory:TFc
���|dkrd}||_d|_|	p2tjtj�d��d���|_tt|�����|_	d|_
d|_tj
��|_tj
��|_tj��|_t%d���|_d|_|r�t+|t,��r|�	|��nYt+|t.t0f��r|j	|�n2t+|t2��r|j	di|��nt5d	���|�\t6jrd
dd�g}nt|jd
dd�g}t:j�d��r|� |j!dd���n+t+|t0t.f��stEd���|D]}
d|
vr|j|
d<n�tGdddd�|j	�$d����}tK||g���|_&i|_'||_(tSj*|j+��|j�,��d|_-t]t_|����||||dd�|_ta|��|_1tj2|j1j3d���|_d|j_4|j�5��|j�6��|j-�|j-�tnD])\}}
tq|||g���}ts||
|���*dS)N�postgres�psycopg2�cT)�	use_errno)r!�d)�maxsizezwrong log spec formatr��IPMock)rC�kind�localr)rCr��
nlm_generator�linuxr�zsources format not supportedrC�zobj:listzobj:readz
obj:modify�authr��false)�provider�spec�
rtnl_debug�
db_cleanup�
auto_netns�recordset_pipez
NDB main loop)rCrRrm):r��schema�ctypes�CDLL�util�find_library�libcrr �log�_db�_dbm_thread�	threading�Event�
_dbm_ready�
_dbm_shutdown�Lock�_global_lockrs�_event_queue�	messengerr9rr1�list�dict�	TypeErrorr�mock_iproute�sys�platformrUrVr�r@rr$r
�sources�_call_registry�_nl�atexit�registerrX�clear�
_dbm_error�strr
r�task_manager�Thread�run�daemon�start�waitr�rr�)r%r�r��db_provider�db_specr�r�r�r�r�r��amr�r�r�s               r&r'zNDB.__init__�s����*�$�$�$�K�"�������
�F�K��K�$�$�S�)�)�T�
�
�
��	��b��h�h�'�'�'���������#�/�+�+���&�_�.�.���%�N�,�,���&�s�3�3�3�������	9��#�z�*�*�
9�����
�
�
�
��C�%���/�/�
9����#�����C��&�&�
9������3������ 7�8�8�8��?��"�

�&1�8�D�D�E���#'�.� '�)*������<�*�*�7�3�3���N�N�#'�>�;�G�G������G�d�E�]�3�3�	=��;�<�<�<��	�	�D��t�#�#�!%���X����$���4�t�D�D��H���V�$�$�
�
��#�4��t�<�<�<��� ���������
�#�#�#������������J�{�3�3�4�4��$�$�$�%�

�
���(��-�-���$�+��$�(��
�
�
���#'�������� � � ���������?�&��/�!�,�	'�	'�M�F�E���f�R�D�9�9�9�D��D�%��&�&�&�&�	'�	'r(c�&�t||||��SrP)r)r%�table�chainr�s    r&�	_get_viewz
NDB._get_view-s���D�%��
�6�6�6r(c��|SrPrmrMs r&�	__enter__z
NDB.__enter__0s���r(c�.�|���dSrP)rX)r%�exc_type�	exc_value�	tracebacks    r&�__exit__zNDB.__exit__3s���
�
�����r(c�P�t|j�d����S)N�transaction)rr�r$rMs r&�beginz	NDB.begin6s ���4�8�+�+�M�:�:�;�;�;r(c��|�tdddd�|j�d������S)NTFr�r�)�
auth_proxyrr�r$rMs r&�readonlyzNDB.readonly9sE������!�t�5�I�I��� � ��(�(�
�
�
�
�	
r(c�$�t||g��SrP)r�)r%�auth_managers  r&r�zNDB.auth_proxyAs�����~�.�.�.r(c��|j5|j���r	ddd��dS|j���t	t
d��rtj|j��n9	t
j�	|jdif��n#t$rYnwxYw|j���|j�
tdt����f��|j���|j���ddd��dS#1swxYwYdS)N�
unregisterrm)r�r��is_set�set�hasattrr�r�rX�
_exithandlers�remover@r�r~r�r	rr��joinr�rMs r&rXz	NDB.closeDs���
�
�	�	��!�(�(�*�*�
)��	�	�	�	�	�	�	�	��"�&�&�(�(�(��v�|�,�,�
��!�$�*�-�-�-�-���(�/�/���R��0D�E�E�E�E��!�����D�����
��&�&�(�(�(���$�$�d�4�1B�1D�1D�&E�&E�%G�H�H�H���!�!�#�#�#��H�N�N����#	�	�	�	�	�	�	�	�	�	�	�	����	�	�	�	�	�	s<�D>�AD>�9'B!� D>�!
B.�+D>�-B.�.BD>�>E�Ec�:�|j�|��dSrP)r��	db_backup)r%r�s  r&�backupz
NDB.backupXs����#�#�D�)�)�)�)�)r(c�|�|j���D]!}|�|j|vr|����"dSrP)r��valuesr��restart)r%�kindsr|s   r&�reloadz
NDB.reload[sL���l�)�)�+�+�	!�	!�F�� �V�[�E�%9�%9���� � � ��	!�	!r()	Nr�r�r�TFFFN)NNrP)rhrirjrlr�r'r�r�r�r�r�r�rXr�r�rmr(r&r�r��s�������
�/�/��X�/�
��������
�\'�\'�\'�\'�~7�7�7�7�������<�<�<�
�
�
�/�/�/����(*�*�*�!�!�!�!�!�!r(r�))�__doc__r�r��ctypes.utilr"�logging.handlersr�r��pyroute2r�pyroute2.commonrr�r�eventsr�messagesr	r�r
r�rr�rr�r
rr�ImportError�urllib.parserurvr#rhr�r�rrorsr�r�rmr(r&�<module>rs���W�W�r�
�
�
�
�
�
�
�������������
�
�
�
�����������&�&�&�&�&�&�&�%�%�%�%�%�%�%�%�%�%�%�������������%�%�%�%�%�%�$�$�$�$�$�$�#�#�#�#�#�#�#�#�&�!�!�!�!�!�!�!���&�&�&�%�%�%�%�%�%�%�%�&������L�L�L�L�����������������g���!�!��	��[2�[2�[2�[2�[2�[2�[2�[2�|8�8�8�8�8�8�8�8�
$�$�$�$�$�$�$�$�('�'�'�'�'�'�'�'�U!�U!�U!�U!�U!�U!�U!�U!�U!�U!s$�A�A-�,A-�1A6�6	B�B