Ë %'J‡ý”ôãó¼—dZddlZddlZddlZddlZddlZej e«ZGd„de «Z Gd„d«Z Gd„de «Z Gd „d «Z Gd „d «Zy) aÏ One object ---------- All the changes done using one object are applied in the order defined by the corresponding object class. .. code-block:: python eth0 = ndb.interfaces["eth0"] eth0.add_ip(address="10.0.0.1", prefixlen=24) eth0.set(state="up") eth0.set(mtu=1400) eth0.commit() In the example above first the interface attributes like state, mtu, ifname etc. will be applied, and only then IP addresses, bridge ports and like that, regardless the order they are referenced before the `commit()` call. The order is ok for most of cases. But if not, one can control it by calling `commit()` in the required places, breaking one transaction into several sequential transactions. And since RTNL object methods return the object itself, it is possible to write chains with multiple `commit()`: .. code-block:: python ( ndb.interfaces .create(ifname="test", kind="dummy") .add_ip(address="10.0.0.1", prefixlen=24) .commit() .set(state="up") .commit() ) Here the order is forced by explicit commits. Multiple objects ---------------- An important functionality of NDB are rollbacks. And there is a way to batch changes on multiple objects so one failure will trigger rollback of all the changes on all the objects. .. code-block:: python ctx = ndb.begin() ctx.push( # first set up a bridge ( ndb.interfaces .create(ifname="br0", kind="bridge") .add_port("eth0") .add_port("eth1") .set(state="up") .add_ip("10.0.0.2/24") ), # and only then create a route ( ndb.routes .create( dst="192.168.0.0", dst_len=24, gateway="10.0.0.1" ) ) ) ctx.commit() # if something goes wrong, the whole batch will be reverted Ping a remote host ------------------ The simplest usecase for external checks is to test if a remote IP is still reachable after the changes are applied: .. code-block:: python from pyroute2.ndb.transaction import PingAddress ctx = ndb.begin() ctx.push( ndb.routes.create(dst="10.0.0.0", dst_len=24, gateway="172.16.0.1"), PingAddress("10.0.0.1") ) ctx.commit() # the route will be removed if ping fails Or on the contrary, don't run transaction if a remote IP is reachable: .. code-block:: python from pyroute2.ndb.transaction import Not, PingAddress ctx = ndb.begin() ctx.push( Not(PingAddress("10.0.0.1")), ndb.routes.create(dst="10.0.0.0", dst_len=24, gateway="172.16.0.1") ) try: ctx.commit() except CheckProcessException: pass In this example, the route will be added only if `10.0.0.1` is not reachable. The default ping timeout is set to 1, but it is possible to customize it: .. code-block:: python PingAddress("10.0.0.1", timeout=10) Check an external processes --------------------------- A more generic type of check is CheckProcess: .. code-block:: python from pyroute2.ndb.transaction import CheckProcess with ndb.begin() as ctx: ctx.push(ndb.routes.create( dst="10.0.0.0", dst_len=24, gateway="172.16.0.1" )) ctx.push(CheckProcess('/path/to/script.sh')) # # --> <-- the route will be removed if the script fails `CheckProcess` is `subprocess.Popen` based, is not a shell call, thus no pipes or other shell syntax are allowed. `CheckProcess` also accepts `timeout` argument: .. code-block:: python CheckProcess('/path/to/script.sh', timeout=10).commit() If the subprocess doens't finish within the timeout, it will be terminated with SIGTERM. SIGKILL is not used. Logging and debug ----------------- `CheckProcess` and `PingAddress` accept log as an argument: .. code-block:: python PingAddress("10.0.0.1", log=ndb.log.channel("util")).commit() CheckProcess("/path/to/script.sh", log=ndb.log.channel("util")).commit() The check objects are thread safe and reusable, it is possible to run `commit()` on them multiple times. The subprocess' stdout and stderr will be both logged and saved: .. code-block:: python check = CheckProcess("/path/to/script.sh") while True: check.commit() # periodic check, the loop breaks on failure print(f'stdout: {check.out}') print(f'stderr: {check.err}') print(f'return code: {check.return_code}') time.sleep(10) Check negation -------------- It is possible to negate the check for `CheckProcess` and child classes .. code-block:: python from pyroute2.ndb.transaction import Not, CheckProcess check = Not(CheckProcess('/path/to/script.sh')) check.commit() API --- éNcó —eZdZy)ÚCheckProcessExceptionN)Ú__name__Ú __module__Ú __qualname__©óú=/usr/lib/python3.12/site-packages/pyroute2/ndb/transaction.pyrrÃs„Ør rcó*—eZdZdZdd„Zd„Zd„Zd„Zy)Ú CheckProcessz« Run an external process on `commit()` and raise `CheckProcessException` if the return code is not 0. Objects of this class are thread safe and reusable. Ncó6—t|t«s td«‚t|«dkDs td«‚|xst|_||_tj|«|_ ||_ d|_ d|_ d|_ tj«|_y)Nz"command must be a non empty stringr)Ú isinstanceÚstrÚ TypeErrorÚlenÚ global_logÚlogÚcommandÚshlexÚsplitÚargsÚtimeoutÚ return_codeÚoutÚerrÚ threadingÚLockÚlock)Úselfrrrs r Ú__init__zCheckProcess.__init__Ïs~€Ü˜'¤3Ô'ÜÐ@ÓAÐ AÜ�7‹|˜aÒÜÐ@ÓAÐ AØÒ$œ*ˆŒØˆŒ Ü—K‘K Ó(ˆŒ ؈Œ ØˆÔØˆŒØˆŒÜ—N‘NÓ$ˆ� r có—|j5tj|jd«|jd<|jd€ t «‚t j |jt jt j¬«} |jjd|j›�«|j|j¬«\|_ |_ |jjd|j›�«|jjd|j›�«|j'«|_|j(dk7r t+d«‚ ddd«y#t j$rb|jjd«|j«|j j#«|j$j#«YŒ­wxYw#|j'«|_wxYw#1swYyxYw) Nr)ÚstdoutÚstderrzprocess check )rzprocess output: zprocess stderr: zprocess timeout expiredzCheckProcess failed)rÚshutilÚwhichrÚFileNotFoundErrorÚ subprocessÚPopenÚPIPErÚdebugÚ communicaterrrÚTimeoutExpiredÚ terminater"Úcloser#Úwaitrr)rÚprocesss r ÚcommitzCheckProcess.commitÝs|€Ø �Y‹YÜ!Ÿ<™<¨¯ © °!© Ó5ˆD�I‰I�a‰LØ�y‰y˜‰|Ð#Ü'Ó)Ð)Ü ×&Ñ&Ø— ‘ ¤*§/¡/¼*¿/¹/ôˆGð 2Ø—‘—‘ °· ± ¨{Ð;Ô<Ø%,×%8Ñ%8ÀÇÁÐ%8Ó%NÑ"�”˜$œ(Ø—‘—‘Ð!1°$·(±(°Ð<Ô=Ø—‘—‘Ð!1°$·(±(°Ð<Ô=ð$+§<¡<£>�Ô Ø×Ñ 1Ò$Ü+Ð,AÓBÐBð%÷'ˆYøô×,Ñ,ò 'Ø—‘—‘Ð8Ô9Ø×!Ñ!Ô#Ø—‘×$Ñ$Ô&Ø—‘×$Ñ$Ö&ð  'ûð $+§<¡<£>�Õ ú÷%ˆYús>�BHÂB!E/Ä6/HÅ/A2G$Ç!G'Ç#G$Ç$G'Ç'G>Ç>HÈH có—y©Nr©rs r ÚrollbackzCheckProcess.rollbackôó€Ø r có"—d|j›d�S)NÚ[Ú])rr4s r Ú__repr__zCheckProcess.__repr__÷s€Ø�4—<‘<�. Ð"Ð"r )NN)rrrÚ__doc__r r1r5r:rr r r r Çs„ñó %òCò. ó#r r có ‡—eZdZdˆfd„ ZˆxZS)Ú PingAddresscó<•—tt|� d|›d|›�|¬«y)Nz ping -c 1 -W Ú )r)Úsuperr=r )rÚaddressrrÚ __class__s €r r zPingAddress.__init__üs)ø€Ü Œk˜4Ñ)ؘG˜9 A g YÐ /°Sð *õ r )Né)rrrr Ú __classcell__)rBs@r r=r=ûs ø„÷ ñ r r=có"—eZdZdZd„Zd„Zd„Zy)ÚNotz¸ Negate the `CheckProcess` results. If `CheckProcess.commit()` succeeds, raise CheckProcessException, and vice versa, if `CheckProcess.commit()` fails, return success. có—||_yr3)Útx)rÚ transactions r r z Not.__init__ s €Øˆ�r có”—d} |jj«|rt|j›d�«‚y#t$rd}YŒ(wxYw)NTFz succeeded)rHr1Ú Exceptionr)rÚsuccesss r r1z Not.commit sP€Øˆð Ø �G‰G�N‰NÔ ñ Ü'¨4¯7©7¨)°:Ð(>Ó?Ð ?ð øôò ØŠGð ús„9¹ AÁAcó—yr3rr4s r r5z Not.rollbackr6r N)rrrr;r r1r5rr r rFrFs„ñò ò@ó r rFcóX—eZdZdZdd„Zd„Zd„Zd„Zd„Zdd„Z d „Z d „Z dd „Z d „Z d „Zy)Ú Transactiona’ `Transaction` class is an independent utility class. Being designed to be used with NDB object transactions, it may be used with any object implementing commit/rollback protocol, see `commit()` method. The class supports the context manager protocol and `Transaction` objects may be used in `with` statements: .. code-block:: python with Transaction() as tx: tx.push(obj0) # enqueue objects tx.push(obj1) # --> <-- run commit() for every object in self.queue # # if any commit() fails, run rollback() for every # executed commit() in the reverse order NDB provides a utility method to create `Transaction` objects: .. code-block:: python with ndb.begin() as tx: tx.push(ndb.interfaces["eth0"].set(state="up")) tx.push(ndb.interfaces["eth1"].set(state="up")) NcóÌ—g|_tj«|_|jj «t xs||_|j jd«y)Nzbegin transaction)ÚqueuerÚEventÚeventÚclearrrr*)rrs r r zTransaction.__init__5sD€ØˆŒ Ü—_‘_Ó&ˆŒ Ø � ‰ ×ÑÔÜÒ$ ˆŒØ �‰�‰Ð*Õ+r có—|Sr3rr4s r Ú __enter__zTransaction.__enter__<s€Øˆ r có*—|€|j«yyr3)r1)rÚexc_typeÚ exc_valueÚ tracebacks r Ú__exit__zTransaction.__exit__?s€Ø Ð Ø �K‰K�Mð r có˜—|D]D}|jjdt|«z«|jj |«ŒF|S)zú Push objects to the transaction queue. One may use any number of positional arguments: .. code-block:: python tx.push(obj0) tx.push(obj0, obj1, obj2) tx.push(*[obj0, obj1, obj2]) úqueue %s)rr*ÚtyperQÚappend)rÚargvÚobjs r ÚpushzTransaction.pushCs@€óˆCØ �H‰H�N‰N˜:¬¨S« Ñ1Ô 2Ø �J‰J× Ñ ˜cÕ "ððˆ r cóv—|jjdt|«z«|j|«|S)z1 Append one object to the queue. r])rr*r^rb)rras r r_zTransaction.appendSs-€ð �‰�‰�z¤D¨£IÑ-Ô.Ø � ‰ �#ŒØˆ r cóx—|jjd|z«|jj|«|S)zz Pop an object from the queue. If an index is not specified, pop the last (the rightmost) object. zpop %s)rr*rQÚpop)rÚindexs r rezTransaction.pop[s.€ð �‰�‰�x %Ñ'Ô(Ø � ‰ �‰�uÔØˆ r có�—|jjd|t|«fz«|jj ||«|S)zR Insert an object into the queue. The position index is required. z insert %i %s)rr*r^rQÚinsert)rrfras r rhzTransaction.insertds;€ð �‰�‰�~¨´°S³ Ð(:Ñ:Ô;Ø � ‰ ×ј% Ô%؈ r cóJ—|jjd«g|_|S)z= Cancel the transaction and empty the queue. zcancel transaction)rr*rQr4s r ÚcancelzTransaction.cancells!€ð �‰�‰Ð+Ô,؈Œ ؈ r có8—|jj|«S)zJ Wait until the transaction to be successfully committed. )rSr/)rrs r r/zTransaction.waitts€ð�z‰z�‰˜wÓ'Ð'r có6—|jj«S)z1 Check if the done event is set. )rSÚis_setr4s r ÚdonezTransaction.donezs€ð�z‰z× Ñ Ó"Ð"r có —|jjd«g}|jD]$}|j|« |j «Œ&|jj«|S#t $rWt |«D]G} |j«Œ#t $r(}|jjd|z«Yd}~ŒAd}~wwxYw‚wxYw)a[ Execute `commit()` for every queued object. If an execution fails, execute `rollback()` for every executed commit. All objects in the queue that follows the failed one will remain intact. Raises the original exception of the failed `commit()`. All the `rollback()` exceptions are ignored. r1zignore rollback exception: %sN) rr*rQr_r1rKÚreversedr5ÚwarningrSÚset)rÚ rollbacksraÚrbÚes r r1zTransaction.commit€s¹€ð �‰�‰�xÔ Øˆ Ø—:”:ˆCØ × Ñ ˜SÔ !ð Ø— ‘ • ðð � ‰ �‰Ô؈ øôò Ü" 9Ö-�BðNØŸ ™ � øÜ$òNØŸ™×(Ñ(Ð)HÈ1Ñ)L×MÑMûðNúð.ð ð  ús5¿A-Á-C ÂBÂC  C ÂC Â=C ÃC ÃC r3)éÿÿÿÿ)rrrr;r rVr[rbr_rerhrjr/rnr1rr r rOrOs>„ñó6,òòòò óòòó(ò #ó r rO)r;Úloggingrr$r'rÚ getLoggerrrrKrr r=rFrOrr r ÚryshðñxórÛ Û ÛÛà ˆW× Ñ ˜xÓ (€ ô ˜Iô ÷1#ñ1#ôh �,ô ÷ ñ ÷.òr