Current File : /opt/alt/python311/lib/python3.11/site-packages/pyroute2/ndb/__pycache__//main.cpython-311.pyc
�
�;f�S � � � d Z ddlZddlZddlZddlZddlZddlZddlZddlm Z ddl
mZ ddlm
Z
ddlmZ ddlmZ dd lmZ dd
lmZ ddlmZ ddlmZmZ dd
lmZ n# e$ r dd
lmZ Y nw xY w ddlZn# e$ r ddlZY nw xY w ej e!� � Z"dZ# G d� d� � Z$ G d� d� � Z% G d� d� � Z& G d� d� � Z' G d� 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 � � e Zd Zd
d�Zdej fd�Zed� � � Zed� � � Z d� Z
d� Zd� Zd � Z
d
� Zd� Zd� ZdS )�LogNc �� � d | _ d| _ |pt | � � | _ t j d| j z � � | _ | � d� � | _ d S )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__zLog.__init__I sS � ������
��(��4������'�(9�D�K�(G�H�H����L�L��(�(�� � � � c � � |� | j d uS | j �6t | j j � � D ]}| j � |� � �|dv rN| j rE| j � d� � | j � t j � � � � d S |dv rt j � � }n�|dk r t j � � }t j
}n�t |t � � r�t |� � }|j s!|j rt j |j � � }nU|j dk r9t j � |j � d� � �� � }nt) d� � �|}||ur+d }t j |� � }|� |� � | j � |� � | j � |� � d S )
N)�offFr )�on�stderr�debug�syslog�:)�addresszlogging scheme not supportedz0%(asctime)s %(levelname)8s %(name)s: %(message)s)r �tuple�handlers�
removeHandlerr �setLevel�
addHandlerr"