Ë жê7ØÊ?¯ãó”—dZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZddlmZdd lmZdd lmZdd lmZdd lmZmZ dd lmZ ddlZej@e!«Z"dZ#Gd„d«Z$Gd„d«Z%Gd„d«Z&Gd„d«Z'Gd„d«Z(y#e$r dd lmZYŒYwxYw#e$rddlZYŒcwxYw)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.[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„Zdej fd„Zed„«Zed„«Z d„Z d„Z d„Z d „Z d „Zd „Zd „Zy)ÚLogNcó—d|_d|_|xs t|«|_t j d|jz«|_|j d«|_y)NFzpyroute2.ndb.%sÚmain)ÚloggerÚstateÚidÚlog_idÚloggingÚ getLoggerÚchannelr)Úselfr!s ú6/usr/lib/python3.12/site-packages/pyroute2/ndb/main.pyÚ__init__z Log.__init__HsL€ØˆŒ ؈Œ ØÒ(¤ 4£ˆŒ Ü×'Ñ'Ð(9¸D¿K¹KÑ(GÓHˆŒ Ø—L‘L Ó(ˆ� ócó—|€|jduS|j�?t|jj«D]}|jj|«Œ|dvrU|jrH|jj d«|jj tj««y|dvrtj«}nÓ|dk(r%tj«}tj}n©t|t«r—t|«}|js,|jr tj |j«}nV|jdk(r:tjj#|j$j'd«¬«}n t)d«‚|}||ur(d }tj*|«}|j-|«|jj |«|jj |«y) 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__Os”€Ø ˆ>Ø—;‘; dÐ*Ð *à �;‰;Ð "Ü  §¡×!5Ñ!5Ö6�Ø— ‘ ×)Ñ)¨'Õ2ð7ð �^Ñ #Ø�zŠzØ— ‘ ×$Ñ$ QÔ'Ø— ‘ ×&Ñ&¤w×':Ñ':Ó'<Ô=Ø à Ð%Ñ %Ü×+Ñ+Ó-‰GØ �wÒ Ü×+Ñ+Ó-ˆGÜ—M‘M‰EÜ ˜¤ Ô +ܘ6Ó"ˆCØ—:’: #§(¢(Ü!×-Ñ-¨c¯h©hÓ7‘Ø—‘˜xÒ'Ü!×*Ñ*×8Ñ8ØŸJ™J×,Ñ,¨SÓ1ð9ó‘ô!Ð!?Ó@Ð@àˆGð ˜&Ñ ØDˆCÜ×)Ñ)¨#Ó.ˆIØ × Ñ  Ô +à � ‰ ×јwÔ'Ø � ‰ ×јUÕ#r(có(—|jd¬«y)Nr+©rC©rI©r%s r&r+zLog.onxs€à � ‰ ˜Tˆ Õ"r(có(—|jd¬«y)Nr*rKrLrMs r&r*zLog.off|s€à � ‰ ˜Uˆ Õ#r(có—|jj}|jj}g}|jj «D]%}|j |«sŒ|j |«Œ'|D]}|j|=Œ~~~y©N)rÚmanagerÚnameÚ loggerDictÚkeysÚ startswithÚappend)r%rQrRÚ purge_listrs r&Úclosez Log.close€s�€Ø—+‘+×%Ñ%ˆØ�{‰{×Ñˆðˆ Ø×(Ñ(×-Ñ-Ö/ˆFØ× Ñ  Õ&Ø×!Ñ! &Õ)ð0ó!ˆFØ×"Ñ" 6Ñ*ð!ð Ø Ù r(cóL—tjd|j›d|›�«S)Nz pyroute2.ndb.Ú.)r"r#r!)r%rRs r&r$z Log.channel’s€Ü× Ò ¸¿»ÁdÐ!KÓLÐLr(có:—|jj|i|¤ŽSrP)rr-©r%ÚargvÚkwargs r&r-z Log.debug•ó€Øˆt�y‰y�‰ Ð.¨Ñ.Ð.r(có:—|jj|i|¤ŽSrP)rÚinfor\s r&razLog.info˜s€Øˆt�y‰y�~‰~˜tÐ- uÑ-Ð-r(có:—|jj|i|¤ŽSrP)rÚwarningr\s r&rcz Log.warning›s€Ø ˆt�y‰y× Ñ  $Ð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‰y×!Ñ! 4Ð1¨5Ñ1Ð1r(rP)Ú__name__Ú __module__Ú __qualname__r'r"ÚINFOrIÚpropertyr+r*rXr$r-rarcrerg©r(r&rrGsd„ó)ð#¨'¯,©,ó'$ðRñ#óð#ðñ$óð$òò$Mò/ò.ò1ò/ó2r(rcó—eZdZd„Zy)ÚDeadEndcó—td«‚)Nzshutdown in progressrr\s r&Úputz DeadEnd.put¦s€ÜÐ 6Ó7Ð7r(N)rhrirjrqrmr(r&roro¥s„ó8r(rocó4—eZdZd„Zdd„Zd„Zdd„Zd„Zd„Zy) Ú EventQueuecóF—tj|i|¤Žx|_|_yrP)ÚqueueÚQueueÚ_bypassÚ_queuer\s r&r'zEventQueue.__init__«s€Ü%*§[¡[°$Ð%@¸%Ñ%@Ð@ˆŒ �t•{r(Ncó<—|jj||f«SrP)rxrq©r%ÚmsgÚsources r&rqzEventQueue.put®s€Ø�{‰{�‰ ¨˜}Ó-Ð-r(có"—t«|_yrP)rorxrMs r&ÚshutdownzEventQueue.shutdown±s €Ü“iˆ� r(có<—|jj||f«SrP)rwrqrzs r&ÚbypasszEventQueue.bypass´s€Ø�|‰|×Ñ ¨  Ó.Ð.r(có:—|jj|i|¤ŽSrP)rwÚgetr\s r&r‚zEventQueue.get·s€Øˆt�|‰|×Ñ Ð/¨Ñ/Ð/r(có6—|jj«SrP)rwÚqsizerMs r&r„zEventQueue.qsizeºs€Ø�|‰|×!Ñ!Ó#Ð#r(rP) rhrirjr'rqr~r€r‚r„rmr(r&rsrsªs!„òAó.ò ó/ò0ó$r(rscó—eZdZd„Zy)Ú AuthProxycóš—||_||_tD]4\}}t|j||j¬«}t |||«Œ6y)N©Ú auth_managers)Ú_ndbÚ_auth_managersÚNDB_VIEWS_SPECSrÚsetattr)r%Úndbr‰ÚvtableÚvnameÚviews r&r'zAuthProxy.__init__¿sC€ØˆŒ Ø+ˆÔç,‰MˆF�EܘŸ ™  6¸×9LÑ9LÔMˆDÜ �D˜% Õ &ñ-r(N)rhrirjr'rmr(r&r†r†¾s„ó'r(r†cóp—eZdZed„«Z d d„Zdd„Zd„Zd„Zd„Z d„Z d „Z d „Z d „Z dd „Zy)ÚNDBcó —d|jzS)Nz %s/nsmanager)Ú localhostrMs r&Ú nsmanagerz NDB.nsmanagerÉs€à §¡Ñ.Ð.r(Nc óÚ—|dk(rd}||_d|_| xs4tjtjj d«d¬«|_tt|«¬«|_ d|_ d|_ tj«|_tj«|_tj «|_t%d¬«|_d|_|rvt+|t,«r|j|«nTt+|t.t0f«r|j|Žn.t+|t2«r|jdi|¤Žn t5d «‚|€ft6j8rd d d œg}np|jd ddœg}t:j<j?d«r@|jA|jBdd œ«n!t+|t0t.f«s tEd«‚|D]} d| vsŒ|j| d<ntGddddœ|jjId««} tK|| g¬«|_&i|_'||_(tSjT|jV«|jjY«d|_-t]t_|««||||ddœ|_ta|«|_1tjd|jbjfd¬«|_ d|j_4|jjk«|jjm«|jZ� |jZ‚tnD]!\} } tq|| | g¬«}ts|| |«Œ#y)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Ü �K‰K× $Ñ $ SÓ )°Tô ˆŒ ôœb ›hÔ'ˆŒØˆŒØˆÔÜ#Ÿ/™/Ó+ˆŒÜ&Ÿ_™_Ó.ˆÔÜ%ŸN™NÓ,ˆÔÜ&¨sÔ3ˆÔ؈Œá ܘ#œzÔ*Ø—‘˜• ܘC¤%¬ Ô/Ø�—‘˜#’ܘC¤Ô&Ø�—‘‘˜3“äÐ 7Ó8Ð8ð ˆ?Ü×"Ò"Ø&1¸8ÑDÐE‘ð#'§.¡.Ø 'Ø)*ñð�ô—<‘<×*Ñ*¨7Ô3Ø—N‘NØ#'§>¡>¸;ÑGõô˜G¤d¬E ]Ô3ÜÐ;Ó<Ð <ãˆDؘtÒ#Ø!%§¡��X‘Ùðô ب4¸tÑ DØ �H‰H× Ñ ˜VÓ $ó ˆô# 4¸°tÔ<ˆŒ Ø ˆÔ؈ŒÜ�‰˜Ÿ ™ Ô#Ø �‰×ÑÔØˆŒäœJ {Ó3Ó4ØØ$Ø$Ø$Ø%ñ  ˆŒ ô(¨Ó-ˆÔÜ$×+Ñ+Ø×$Ñ$×(Ñ(¨ô ˆÔð#'ˆ×ÑÔØ ×Ñ×ÑÔ Ø �‰×ÑÔØ �?‰?Ð &Ø—/‘/Ð !ß,‰MˆF�Eܘ˜f°R°DÔ9ˆDÜ �D˜% Õ &ñ-r(có—t||||«SrP)r)r%ÚtableÚchainr‰s r&Ú _get_viewz NDB._get_view,s€Ü�D˜% ¨ Ó6Ð6r(có—|SrPrmrMs r&Ú __enter__z NDB.__enter__/s€Øˆ r(có$—|j«yrP)rX)r%Úexc_typeÚ exc_valueÚ tracebacks r&Ú__exit__z NDB.__exit__2s €Ø � ‰ � r(cóJ—t|jjd««S)NÚ transaction)r r²r$rMs r&Úbeginz NDB.begin5s€Ü˜4Ÿ8™8×+Ñ+¨MÓ:Ó;Ð;r(cór—|jtddddœ|jjd«««S)NTFr£r¤)Ú auth_proxyrr²r$rMs r&Úreadonlyz NDB.readonly8s7€Ø�‰Ü Ø!¨tÀ5ÑIØ—‘× Ñ  Ó(ó ó ð r(có—t||g«SrP)r†)r%Ú auth_managers r&rãzNDB.auth_proxy@s€Ü˜  ˜~Ó.Ð.r(có’—|j5|jj«r ddd«y|jj«t t d«r t j |j«n- t jj|jdif«|jj«|jjtdt««f«|j j#«|j$j«ddd«y#t$rYŒ�wxYw#1swYyxYw)NÚ unregisterrm)rºr¸Úis_setÚsetÚhasattrrÆrèrXÚ _exithandlersÚremover@r»r~r€r rr´Újoinr²rMs r&rXz NDB.closeCs÷€Ø × Ó Ø×!Ñ!×(Ñ(Ô*Ø÷Ð ð×"Ñ"×&Ñ&Ô(Ü”v˜|Ô,Ü×!Ñ! $§*¡*Õ-ðÜ×(Ñ(×/Ñ/°·±¸RÀÐ0DÔEð × Ñ × &Ñ &Ô (Ø × Ñ × $Ñ $¤d¨4Ô1BÓ1DÓ&EÐ%GÔ HØ × Ñ × !Ñ !Ô #à �H‰H�N‰NÔ ÷#Ð øô"òÙðú÷Ð ús6�D=²A D=Á=,D.Â)ArsÊðñWópÛ ÛÛÛÛ ÛåÝ&õ&Ý%ÝÝÝ%Ý$ß#ð&Ý!ðÛð€g×јÓ!€ð €÷[2ñ[2÷|8ñ8÷ $ñ$÷('ñ'÷U!òU!øðqò&ß%ð&ûð òÝðús$ÁB*ÁB;Â* B8Â7B8Â; CÃC