forked from sysrepo/sysrepo-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.py
1706 lines (1501 loc) · 61 KB
/
session.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2020 6WIND S.A.
# SPDX-License-Identifier: BSD-3-Clause
from contextlib import contextmanager
import inspect
import logging
from typing import Any, Callable, Dict, Iterator, List, Optional
import libyang
from _sysrepo import ffi, lib
from .change import Change
from .errors import (
SysrepoError,
SysrepoInternalError,
SysrepoNotFoundError,
SysrepoUnsupportedError,
check_call,
)
from .subscription import Subscription
from .util import c2str, is_async_func, str2c
from .value import Value
LOG = logging.getLogger(__name__)
# ------------------------------------------------------------------------------
class SysrepoSession:
"""
Python representation of `sr_session_ctx_t *`.
.. attention::
Do not instantiate this class manually, use `SysrepoConnection.start_session`.
"""
__slots__ = (
"cdata",
"is_implicit",
"subscriptions",
)
# begin: general
def __init__(self, cdata, implicit: bool = False):
"""
:arg "sr_session_ctx_t *" cdata:
The session pointer allocated by :func:`SysrepoConnection.start_session`.
:arg implicit:
Used to identify sessions provided in subscription callbacks.
"""
self.cdata = cdata
self.is_implicit = implicit
self.subscriptions = []
def __enter__(self) -> "SysrepoSession":
return self
def __exit__(self, *args, **kwargs) -> None:
self.stop()
def stop(self) -> None:
"""
Stop current session and releases resources tied to the session.
Also releases any locks held and frees subscriptions created (only) by this
session.
"""
if self.cdata is None:
return # already stopped
if self.is_implicit:
raise SysrepoUnsupportedError("implicit sessions cannot be stopped")
# clear subscriptions
while self.subscriptions:
sub = self.subscriptions.pop()
try:
sub.unsubscribe()
except Exception:
LOG.exception("Subscription.unsubscribe failed")
# stop session
try:
check_call(lib.sr_session_stop, self.cdata)
finally:
self.cdata = None
def release_context(self):
conn = lib.sr_session_get_connection(self.cdata)
lib.sr_release_context(conn)
def acquire_context(self) -> libyang.Context:
"""
:returns:
The libyang context object associated with this session.
"""
conn = lib.sr_session_get_connection(self.cdata)
if not conn:
raise SysrepoInternalError("sr_session_get_connection failed")
ctx = lib.sr_acquire_context(conn)
if not ctx:
raise SysrepoInternalError("sr_get_context failed")
return libyang.Context(cdata=ctx)
def get_datastore(self) -> str:
"""
Get the datastore a session operates on.
:returns str:
The datastore name.
"""
return datastore_name(lib.sr_session_get_ds(self.cdata))
def lock(self, module_name: str = "", timeout_ms: int = 0) -> None:
"""
Locks the data of the specified module or the whole datastore.
:arg module_name:
Optional name of the module to be locked.
:arg timeout_ms:
Optional timeout in ms for waiting. If 0, no waiting is performed.
"""
module = str2c(module_name) if len(module_name) > 0 else ffi.NULL
check_call(lib.sr_lock, self.cdata, module, timeout_ms)
def unlock(self, module_name: str = "") -> None:
"""
Unlocks the data of the specified module or the whole datastore.
:arg module_name:
Optional name of the module to be locked.
"""
module = str2c(module_name) if len(module_name) > 0 else ffi.NULL
check_call(lib.sr_unlock, self.cdata, module)
@contextmanager
def locked(self, module_name: str = "", timeout_ms: int = 0):
"""
Convenience method which manages un-/locking the data of the specified module
or the whole datastore.
:arg module_name:
Optional name of the module to be locked.
:arg timeout_ms:
Optional timeout in ms for waiting. If 0, no waiting is performed.
"""
try:
self.lock(module_name, timeout_ms)
yield
finally:
self.unlock(module_name)
def switch_datastore(self, datastore: str) -> None:
"""
Change datastore which the session operates on. All subsequent calls will be
issued on the chosen datastore. Previous calls are not affected (previous
subscriptions, for instance).
:arg str datastore:
New datastore that will be operated on. Can be one of `running`,
`startup`, `operational` or `candidate`.
"""
if self.is_implicit:
raise SysrepoUnsupportedError(
"cannot change datastore of implicit sessions"
)
ds = datastore_value(datastore)
check_call(lib.sr_session_switch_ds, self.cdata, ds)
def set_error(self, err: BaseException):
"""
Set detailed error information into provided session. Used to notify the client
library about errors that occurred in the application code. Does not print the
message.
Intended for change, RPC/action, or operational callbacks to be used on the
provided session.
:arg BaseException err:
The python exception object that carries the error information.
"""
if not self.is_implicit:
raise SysrepoUnsupportedError("can only report errors on implicit sessions")
if isinstance(err, SysrepoError):
code = err.rc
message = err.msg
else:
code = lib.SR_ERR_CALLBACK_FAILED
message = str(err)
check_call(
lib.sr_session_set_error,
self.cdata,
ffi.NULL,
code,
str2c("%s"),
str2c(message),
)
def get_originator_name(self) -> str:
"""
It can only be called on an implicit sysrepo.Session (i.e., it can only be
called from an event callback).
:returns: the originator name for the event originator sysrepo session
"""
if not self.is_implicit:
raise SysrepoUnsupportedError(
"can only report originator name on implicit sessions"
)
return c2str(lib.sr_session_get_orig_name(self.cdata))
def set_extra_info(self, originator_name: str, netconf_id: int, user: str) -> None:
"""
Set the Session extra infos.
This function is mainly used for testing purpose.
:arg str originator_name:
The originator name, should be netopeer2.
:arg int netconf_id:
The netconf_id.
:arg str originator_name:
The user name.
"""
# orig name
check_call(lib.sr_session_set_orig_name, self.cdata, str2c(originator_name))
# netconf_id
c_netconf_id = ffi.new("uint32_t *")
c_netconf_id[0] = netconf_id
p_netconf_id = ffi.cast("const void **", c_netconf_id)
check_call(
lib.sr_session_push_orig_data,
self.cdata,
ffi.sizeof(c_netconf_id),
p_netconf_id,
)
# user
c_user = ffi.new("char[]", user.encode())
p_user = ffi.cast("const void **", c_user)
check_call(
lib.sr_session_push_orig_data, self.cdata, ffi.sizeof(c_user), p_user
)
def get_netconf_id(self) -> int:
"""
It can only be called on an implicit sysrepo.Session (i.e., it can only be
called from an event callback).
:returns: the NETCONF session ID set for the event originator sysrepo session
"""
if not self.is_implicit:
raise SysrepoUnsupportedError(
"can only report netconf id on implicit sessions"
)
if self.get_originator_name() != "netopeer2":
raise SysrepoUnsupportedError("can only report netconf id for netopeer2")
size = ffi.new("uint32_t *")
p_nc_id = ffi.new("const void **")
check_call(lib.sr_session_get_orig_data, self.cdata, 0, size, p_nc_id)
nc_id = ffi.cast("uint32_t *", p_nc_id[0])
return nc_id[0]
def get_user(self) -> str:
"""
It can only be called on an implicit sysrepo.Session (i.e., it can only be
called from an event callback)
:returns: the effective username of the event originator sysrepo session
"""
if not self.is_implicit:
raise SysrepoUnsupportedError("can only report user on implicit sessions")
size = ffi.new("uint32_t *")
p_user = ffi.new("const void **")
check_call(lib.sr_session_get_orig_data, self.cdata, 1, size, p_user)
user = ffi.cast("const char *", p_user[0])
return c2str(user)
@contextmanager
def get_ly_ctx(self) -> libyang.Context:
"""
:returns:
The libyang context object associated with this session.
"""
try:
yield self.acquire_context()
finally:
self.release_context()
# end: general
# begin: subscription
ModuleChangeCallbackType = Callable[[str, int, List[Change], Any], None]
"""
Callback to be called when the change in the datastore occurs.
:arg event:
Type of the callback event that has occurred. Can be one of: "update", "change",
"done", "abort", "enabled".
:arg req_id:
Request ID unique for the specific module name. Connected events for one request
("change" and "done" for example) have the same request ID.
:arg changes:
List of `sysrepo.Change` objects representing what parts of the configuration
have changed.
:arg private_data:
Private context opaque to sysrepo used when subscribing.
:arg kwargs (optional):
If the callback was registered with the argument extra_info=True (see
Session.subscribe_module_change), then extra keyword arguments are passed when
calling the callback:
* netconf_id: the NETCONF session ID set for the event originator
sysrepo session
* user: the effective username of the event originator sysrepo session
When event is one of ("update", "change"), if the callback raises an exception, the
changes will be rejected and the error will be forwarded to the client that made the
change. If the exception is a subclass of `SysrepoError`, the traceback will not be
sent to the logging system. For consistency and to avoid confusion with unexpected
errors, the callback should raise explicit `SysrepoValidationFailedError` exceptions
to reject changes.
"""
# pylint: disable=too-many-arguments
def subscribe_module_change(
self,
module: str,
xpath: Optional[str],
callback: ModuleChangeCallbackType,
*,
priority: int = 0,
no_thread: bool = False,
passive: bool = False,
done_only: bool = False,
enabled: bool = False,
update: bool = False,
filter_origin: bool = False,
private_data: Any = None,
asyncio_register: bool = False,
include_implicit_defaults: bool = True,
include_deleted_values: bool = False,
extra_info: bool = False,
) -> None:
"""
Subscribe for changes made in the specified module.
:arg module:
Name of the module of interest for change notifications.
:arg xpath:
Optional xpath further filtering the changes that will be handled
by this subscription.
:arg callback:
Callback to be called when the change in the datastore occurs.
:arg priority:
Specifies the order in which the callbacks (**within module**) will
be called.
:arg no_thread:
There will be no thread created for handling this subscription
meaning no event will be processed! Default to `True` if
asyncio_register is `True`.
:arg passive:
The subscriber is not the "owner" of the subscribed data tree, just
a passive watcher for changes.
:arg done_only:
The subscriber does not support verification of the changes and
wants to be notified only after the changes has been applied in the
datastore, without the possibility to deny them.
:arg enabled:
The subscriber wants to be notified about the current configuration
at the moment of subscribing.
:arg update:
The subscriber wants to be called before the configuration is applied.
:arg filter_origin:
Filter events on the originator side to unburden the subscriber, but
results in 0 value for filtered-out changes in the subscriber infos.
:arg private_data:
Private context passed to the callback function, opaque to sysrepo.
:arg asyncio_register:
Add the created subscription event pipe into asyncio event loop
monitored read file descriptors. Implies `no_thread=True`.
:arg include_implicit_defaults:
Include implicit default nodes in changes.
:arg include_deleted_values:
Include deleted nodes values in changes.
:arg extra_info:
When True, the given callback is called with extra keyword arguments
containing extra information of the sysrepo session that gave origin to the
event (see ModuleChangeCallbackType for more details)
"""
if self.is_implicit:
raise SysrepoUnsupportedError("cannot subscribe with implicit sessions")
_check_subscription_callback(callback, self.ModuleChangeCallbackType)
sub = Subscription(
callback,
private_data,
asyncio_register=asyncio_register,
include_implicit_defaults=include_implicit_defaults,
include_deleted_values=include_deleted_values,
extra_info=extra_info,
)
sub_p = ffi.new("sr_subscription_ctx_t **")
if asyncio_register:
no_thread = True # we manage our own event loop
flags = _subscribe_flags(
no_thread=no_thread,
passive=passive,
done_only=done_only,
enabled=enabled,
update=update,
filter_origin=filter_origin,
)
check_call(
lib.sr_module_change_subscribe,
self.cdata,
str2c(module),
str2c(xpath),
lib.srpy_module_change_cb,
sub.handle,
priority,
flags,
sub_p,
)
sub.init(sub_p[0])
self.subscriptions.append(sub)
UnsafeModuleChangeCallbackType = Callable[["SysrepoSession", str, int, Any], None]
"""
Callback to be called when the change in the datastore occurs. Provides implicit
session object instead of list of changes. THE CALLBACK SHOULD NEVER KEEP A
REFERENCE ON THE IMPLICIT SESSION OBJECT TO AVOID USER-AFTER-FREE BUGS.
:arg session:
Implicit session (do not stop) with information about the changed data.
:arg event:
Type of the callback event that has occurred. Can be one of: "update", "change",
"done", "abort", "enabled".
:arg req_id:
Request ID unique for the specific module name. Connected events for one request
("change" and "done" for example) have the same request ID.
:arg private_data:
Private context opaque to sysrepo used when subscribing.
When event is one of ("update", "change"), if the callback raises an exception, the
changes will be rejected and the error will be forwarded to the client that made the
change. If the exception is a subclass of `SysrepoError`, the traceback will not be
sent to the logging system. For consistency and to avoid confusion with unexpected
errors, the callback should raise explicit `SysrepoValidationFailedError` exceptions
to reject changes.
"""
def subscribe_module_change_unsafe(
self,
module: str,
xpath: Optional[str],
callback: UnsafeModuleChangeCallbackType,
*,
priority: int = 0,
no_thread: bool = False,
passive: bool = False,
done_only: bool = False,
enabled: bool = False,
update: bool = False,
filter_origin: bool = False,
private_data: Any = None,
asyncio_register: bool = False,
) -> None:
"""
Subscribe for changes made in the specified module. Implicit session object
is returned to callback instead of list of changes. When callback returns to
Sysrepo, the session is freed, so we cannot keep a reference on it and
schedule async code to run later. For this reason, async callbacks are NOT
allowed here.
:arg module:
Name of the module of interest for change notifications.
:arg xpath:
Optional xpath further filtering the changes that will be handled
by this subscription.
:arg callback:
Callback to be called when the change in the datastore occurs.
:arg priority:
Specifies the order in which the callbacks (**within module**) will
be called.
:arg no_thread:
There will be no thread created for handling this subscription
meaning no event will be processed! Default to `True` if
asyncio_register is `True`.
:arg passive:
The subscriber is not the "owner" of the subscribed data tree, just
a passive watcher for changes.
:arg done_only:
The subscriber does not support verification of the changes and
wants to be notified only after the changes has been applied in the
datastore, without the possibility to deny them.
:arg enabled:
The subscriber wants to be notified about the current configuration
at the moment of subscribing.
:arg update:
The subscriber wants to be called before the configuration is applied.
:arg filter_origin:
Filter events on the originator side to unburden the subscriber, but
results in 0 value for filtered-out changes in the subscriber infos.
:arg private_data:
Private context passed to the callback function, opaque to sysrepo.
:arg asyncio_register:
Add the created subscription event pipe into asyncio event loop
monitored read file descriptors. Implies `no_thread=True`.
"""
if self.is_implicit:
raise SysrepoUnsupportedError("cannot subscribe with implicit sessions")
if is_async_func(callback):
raise SysrepoUnsupportedError(
"cannot use unsafe subscription with async callback"
)
_check_subscription_callback(callback, self.UnsafeModuleChangeCallbackType)
sub = Subscription(
callback,
private_data,
asyncio_register=asyncio_register,
unsafe=True,
)
sub_p = ffi.new("sr_subscription_ctx_t **")
if asyncio_register:
no_thread = True # we manage our own event loop
flags = _subscribe_flags(
no_thread=no_thread,
passive=passive,
done_only=done_only,
enabled=enabled,
update=update,
filter_origin=filter_origin,
)
check_call(
lib.sr_module_change_subscribe,
self.cdata,
str2c(module),
str2c(xpath),
lib.srpy_module_change_cb,
sub.handle,
priority,
flags,
sub_p,
)
sub.init(sub_p[0])
self.subscriptions.append(sub)
OperDataCallbackType = Callable[[str, Any], Optional[Dict]]
"""
Callback to be called when the operational data are requested.
:arg xpath:
The XPath requested by a client. Can be None if the client requested for all the
module operational data.
:arg private_data:
Private context opaque to sysrepo used when subscribing.
:arg kwargs (optional):
If the callback was registered with the argument extra_info=True (see
Session.subscribe_module_change), then extra keyword arguments are passed when
calling the callback:
* netconf_id: the NETCONF session ID set for the event originator
sysrepo session
* user: the effective username of the event originator sysrepo session
The callback is expected to return a python dictionary containing the operational
data. The dictionary should be in the libyang "dict" format. It will be parsed to a
libyang lyd_node before returning to sysrepo using `libyang.Module.parse_data_dict`.
If the callback returns `None`, nothing is returned to sysrepo. If the callback
raises an exception, the error message is forwarded to the client that requested for
data. If the exception is a subclass of `SysrepoError`, no traceback is sent to the
logging system.
"""
def subscribe_oper_data_request(
self,
module: str,
xpath: str,
callback: OperDataCallbackType,
*,
no_thread: bool = False,
oper_merge: bool = False,
private_data: Any = None,
asyncio_register: bool = False,
strict: bool = False,
extra_info: bool = False,
) -> None:
"""
Register for providing operational data at the given xpath.
:arg module:
Name of the affected module.
:arg xpath:
Xpath identifying the subtree which the provider is able to provide.
Predicates can be used to provide only specific instances of nodes.
:arg callback:
Callback to be called when the operational data for the given xpath are
requested.
:arg no_thread:
There will be no thread created for handling this subscription meaning no
event will be processed! Default to `True` if asyncio_register is `True`.
:arg oper_merge:
Instead of removing any previous existing matching data before
getting them from an operational subscription callback, keep
them. Then the returned data are merged into the existing
data. Valid only for operational subscriptions.
:arg private_data:
Private context passed to the callback function, opaque to sysrepo.
:arg asyncio_register:
Add the created subscription event pipe into asyncio event loop monitored
read file descriptors. Implies `no_thread=True`.
:arg strict:
Reject the whole data returned by callback if it contains elements without
schema definition.
:arg extra_info:
When True, the given callback is called with extra keyword arguments
containing extra information of the sysrepo session that gave origin to the
event (see OperDataCallbackType for more details)
"""
if self.is_implicit:
raise SysrepoUnsupportedError("cannot subscribe with implicit sessions")
_check_subscription_callback(callback, self.OperDataCallbackType)
sub = Subscription(
callback,
private_data,
asyncio_register=asyncio_register,
strict=strict,
extra_info=extra_info,
)
sub_p = ffi.new("sr_subscription_ctx_t **")
if asyncio_register:
no_thread = True # we manage our own event loop
flags = _subscribe_flags(no_thread=no_thread, oper_merge=oper_merge)
check_call(
lib.sr_oper_get_subscribe,
self.cdata,
str2c(module),
str2c(xpath),
lib.srpy_oper_data_cb,
sub.handle,
flags,
sub_p,
)
sub.init(sub_p[0])
self.subscriptions.append(sub)
RpcCallbackType = Callable[[str, Dict, str, Any], Optional[Dict]]
"""
Callback to be called when the RPC/action is invoked.
:arg xpath:
The full data path to the invoked RPC/action. When it is an RPC, the form is
`/prefix:rpc-name`. When it is an action, it is the full data path with all
parent nodes: `/prefix:container/list[key="val"]/action-name`.
:arg input_params:
The input arguments in a python dictionary. The contents are limited to the
children of the "input" node. For example, with a YANG rpc defined like this::
rpc rpc-name {
input {
leaf param1 {
type uint32;
}
leaf param2 {
type string;
}
}
output {
leaf foo {
type int8;
}
leaf bar {
type string;
}
}
}
The input_params dict may look like this::
{'param1': 42, 'param2': 'foobar'}
If there are no input parameters provided by the client, the dict will be empty.
For actions, the xpath argument allows to determine the parent node of the
action input parameters.
:arg event:
In most cases, it is always 'rpc'. When multiple callbacks are registered for
the same RPC and one of the callbacks failed. The remainder of the callbacks
will be called with 'abort'.
:arg private_data:
Private context opaque to sysrepo used when subscribing.
:arg kwargs (optional):
If the callback was registered with the argument extra_info=True (see
Session.subscribe_module_change), then extra keyword arguments are passed when
calling the callback:
* netconf_id: the NETCONF session ID set for the event originator
sysrepo session
* user: the effective username of the event originator sysrepo session
The callback is expected to return a python dictionary containing the RPC output
data. The dictionary should be in the libyang "dict" format and must only contain
the actual output parameters without any parents. Using the previous example::
{'foo': 47, 'bar': 'baz'}
It will be passed to libyang.DRpc.merge_data_dict() to return output data to
sysrepo. If the callback returns None, nothing is returned to sysrepo. If the
callback raises an exception, the error message is forwarded to the client that
called the RPC. If the exception is a subclass of SysrepoError, no traceback is sent
to the logging system.
"""
def subscribe_rpc_call(
self,
xpath: str,
callback: RpcCallbackType,
*,
priority: int = 0,
no_thread: bool = False,
private_data: Any = None,
asyncio_register: bool = False,
strict: bool = False,
include_implicit_defaults: bool = True,
extra_info: bool = False,
) -> None:
"""
Subscribe for the delivery of an RPC/action.
:arg xpath:
XPath identifying the RPC/action. Any predicates are allowed.
:arg callback:
Callback to be called when the RPC/action is invoked.
:arg priority:
Specifies the order in which the callbacks (**within RPC/action**) will be
called.
:arg no_thread:
There will be no thread created for handling this subscription meaning no
event will be processed! Default to True if asyncio_register is True.
:arg private_data:
Private context passed to the callback function, opaque to sysrepo.
:arg asyncio_register:
Add the created subscription event pipe into asyncio event loop monitored
read file descriptors. Implies no_thread=True.
:arg strict:
Reject the whole data returned by callback if it contains elements without
schema definition.
:arg include_implicit_defaults:
Include implicit defaults into input parameters passed to callbacks.
:arg extra_info:
When True, the given callback is called with extra keyword arguments
containing extra information of the sysrepo session that gave origin to the
event (see RpcCallbackType for more details)
"""
if self.is_implicit:
raise SysrepoUnsupportedError("cannot subscribe with implicit sessions")
_check_subscription_callback(callback, self.RpcCallbackType)
sub = Subscription(
callback,
private_data,
asyncio_register=asyncio_register,
strict=strict,
include_implicit_defaults=include_implicit_defaults,
extra_info=extra_info,
)
sub_p = ffi.new("sr_subscription_ctx_t **")
if asyncio_register:
no_thread = True # we manage our own event loop
flags = _subscribe_flags(no_thread=no_thread)
check_call(
lib.sr_rpc_subscribe_tree,
self.cdata,
str2c(xpath),
lib.srpy_rpc_tree_cb,
sub.handle,
priority,
flags,
sub_p,
)
sub.init(sub_p[0])
self.subscriptions.append(sub)
NotificationCallbackType = Callable[[str, str, Dict, int, Any], None]
"""
Callback to be called when a notification is received.
:arg xpath:
The full xpath to the received notification.
:arg notification_type:
Type of the notification event. Can be one of: "realtime", "replay",
"replay_complete", "stop", "suspended", "resumed".
:arg notification:
The notification as a python dictionary. For example, with a YANG notification
defined like this::
notification some-notification {
leaf param1 {
type uint32;
}
leaf param2 {
type string;
}
}
The notification dict may look like this::
{'param1': 42, 'param2': 'foobar'}
:arg timestamp:
Timestamp of the notification as an unsigned 32-bits integer.
:arg private_data:
Private context opaque to sysrepo used when subscribing.
:arg kwargs (optional):
If the callback was registered with the argument extra_info=True (see
Session.subscribe_module_change), then extra keyword arguments are passed when
calling the callback:
* netconf_id: the NETCONF session ID set for the event originator
sysrepo session
* user: the effective username of the event originator sysrepo session
"""
def subscribe_notification(
self,
module: str,
xpath: str,
callback: NotificationCallbackType,
*,
start_time: int = 0,
stop_time: int = 0,
no_thread: bool = False,
asyncio_register: bool = False,
private_data: Any = None,
extra_info: bool = False,
) -> None:
"""
Subscribe for the delivery of a notification.
:arg module:
Name of the module whose notifications to subscribe to.
:arg xpath:
XPath identifying the notification.
:arg callback:
Callback to be called when the notification is received.
:arg start_time:
Optional start time of the subscription. Used for replaying stored
notifications.
:arg stop_time:
Optional stop time ending the notification subscription.
:arg no_thread:
There will be no thread created for handling this subscription meaning no
event will be processed! Default to True if asyncio_register is True.
:arg asyncio_register:
Add the created subscription event pipe into asyncio event loop monitored
read file descriptors. Implies no_thread=True.
:arg private_data:
Private context passed to the callback function, opaque to sysrepo.
:arg extra_info:
When True, the given callback is called with extra keyword arguments
containing extra information of the sysrepo session that gave origin to the
event (see RpcCallbackType for more details)
"""
if self.is_implicit:
raise SysrepoUnsupportedError("cannot subscribe with implicit sessions")
_check_subscription_callback(callback, self.NotificationCallbackType)
sub = Subscription(
callback,
private_data,
asyncio_register=asyncio_register,
extra_info=extra_info,
)
sub_p = ffi.new("sr_subscription_ctx_t **")
if asyncio_register:
no_thread = True # we manage our own event loop
flags = _subscribe_flags(no_thread=no_thread)
c_start_time = ffi.new("struct timespec *")
c_start_time.tv_sec = start_time
c_stop_time = ffi.new("struct timespec *")
c_stop_time.tv_sec = stop_time
check_call(
lib.sr_notif_subscribe_tree,
self.cdata,
str2c(module),
str2c(xpath),
c_start_time,
c_stop_time,
lib.srpy_event_notif_tree_cb,
sub.handle,
flags,
sub_p,
)
sub.init(sub_p[0])
self.subscriptions.append(sub)
# end: subscription
# begin: changes
def get_changes(
self,
xpath: str,
include_implicit_defaults: bool = True,
include_deleted_values: bool = False,
) -> Iterator[Change]:
"""
Return an iterator that will yield all pending changes in the current session.
:arg xpath:
Xpath selecting the requested changes. Be careful, you must select all the
changes, not just subtrees! To get a full change subtree `//.` can be
appended to the XPath.
:arg include_implicit_defaults:
Include implicit default nodes.
:arg include_deleted_values:
Include deleted node values into the returned Change objects.
:returns:
An iterator that will yield `sysrepo.Change` objects.
"""
iter_p = ffi.new("sr_change_iter_t **")
check_call(lib.sr_get_changes_iter, self.cdata, str2c(xpath), iter_p)
op_p = ffi.new("sr_change_oper_t *")
node_p = ffi.new("struct lyd_node **")
prev_val_p = ffi.new("char **")
prev_list_p = ffi.new("char **")
prev_dflt_p = ffi.new("int *")
try:
ret = check_call(
lib.sr_get_change_tree_next,
self.cdata,
iter_p[0],
op_p,
node_p,
prev_val_p,
prev_list_p,
prev_dflt_p,
valid_codes=(lib.SR_ERR_OK, lib.SR_ERR_NOT_FOUND),
)
while ret == lib.SR_ERR_OK:
try:
with self.get_ly_ctx() as ctx:
yield Change.parse(
operation=op_p[0],
node=libyang.DNode.new(ctx, node_p[0]),
prev_val=c2str(prev_val_p[0]),
prev_list=c2str(prev_list_p[0]),
prev_dflt=bool(prev_dflt_p[0]),
include_implicit_defaults=include_implicit_defaults,
include_deleted_values=include_deleted_values,
)
except Change.Skip:
pass
ret = check_call(
lib.sr_get_change_tree_next,
self.cdata,
iter_p[0],
op_p,
node_p,
prev_val_p,
prev_list_p,
prev_dflt_p,
valid_codes=(lib.SR_ERR_OK, lib.SR_ERR_NOT_FOUND),
)
finally:
lib.sr_free_change_iter(iter_p[0])
# end: changes
# begin: get
def get_item(self, xpath: str, timeout_ms: int = 0) -> Value:
"""
Retrieve a single data element selected by the provided path.
:arg xpath: