python: make all _get_ref/_put_ref proper static methods
[babeltrace.git] / src / bindings / python / bt2 / bt2 / component.py
CommitLineData
0235b0db 1# SPDX-License-Identifier: MIT
81447b5b
PP
2#
3# Copyright (c) 2017 Philippe Proulx <pproulx@efficios.com>
81447b5b
PP
4
5from bt2 import native_bt, object, utils
3fb99a22 6from bt2 import message_iterator as bt2_message_iterator
81447b5b 7import collections.abc
3fb99a22
PP
8from bt2 import value as bt2_value
9from bt2 import trace_class as bt2_trace_class
10from bt2 import clock_class as bt2_clock_class
11from bt2 import query_executor as bt2_query_executor
3fb99a22 12from bt2 import port as bt2_port
40910fbb 13import sys
81447b5b 14import bt2
811644b8
PP
15
16
81447b5b
PP
17# This class wraps a component class pointer. This component class could
18# have been created by Python code, but since we only have the pointer,
19# we can only wrap it in a generic way and lose the original Python
20# class.
601c0026
SM
21#
22# Subclasses must implement some methods that this base class uses:
23#
85906b6b 24# - _bt_as_component_class_ptr: static method, convert the passed component class
601c0026
SM
25# pointer to a 'bt_component_class *'.
26
cfbd7cf3 27
615238be 28class _ComponentClassConst(object._SharedObject):
81447b5b
PP
29 @property
30 def name(self):
85906b6b 31 ptr = self._bt_as_component_class_ptr(self._ptr)
601c0026
SM
32 name = native_bt.component_class_get_name(ptr)
33 assert name is not None
811644b8 34 return name
81447b5b
PP
35
36 @property
37 def description(self):
85906b6b 38 ptr = self._bt_as_component_class_ptr(self._ptr)
601c0026 39 return native_bt.component_class_get_description(ptr)
81447b5b 40
40910fbb
PP
41 @property
42 def help(self):
85906b6b 43 ptr = self._bt_as_component_class_ptr(self._ptr)
601c0026
SM
44 return native_bt.component_class_get_help(ptr)
45
85906b6b
FD
46 def _bt_component_class_ptr(self):
47 return self._bt_as_component_class_ptr(self._ptr)
40910fbb 48
811644b8 49 def __eq__(self, other):
615238be 50 if not isinstance(other, _ComponentClassConst):
811644b8
PP
51 try:
52 if not issubclass(other, _UserComponent):
53 return False
54 except TypeError:
55 return False
81447b5b 56
811644b8 57 return self.addr == other.addr
81447b5b
PP
58
59
615238be 60class _SourceComponentClassConst(_ComponentClassConst):
9dee90bd
SM
61 @staticmethod
62 def _get_ref(ptr):
63 native_bt.component_class_source_get_ref(ptr)
64
65 @staticmethod
66 def _put_ref(ptr):
67 native_bt.component_class_source_put_ref(ptr)
68
cfbd7cf3
FD
69 _bt_as_component_class_ptr = staticmethod(
70 native_bt.component_class_source_as_component_class
71 )
81447b5b
PP
72
73
615238be 74class _FilterComponentClassConst(_ComponentClassConst):
9dee90bd
SM
75 @staticmethod
76 def _get_ref(ptr):
77 native_bt.component_class_filter_get_ref(ptr)
78
79 @staticmethod
80 def _put_ref(ptr):
81 native_bt.component_class_filter_put_ref(ptr)
82
cfbd7cf3
FD
83 _bt_as_component_class_ptr = staticmethod(
84 native_bt.component_class_filter_as_component_class
85 )
81447b5b
PP
86
87
615238be 88class _SinkComponentClassConst(_ComponentClassConst):
9dee90bd
SM
89 @staticmethod
90 def _get_ref(ptr):
91 native_bt.component_class_sink_get_ref(ptr)
92
93 @staticmethod
94 def _put_ref(ptr):
95 native_bt.component_class_sink_put_ref(ptr)
96
cfbd7cf3
FD
97 _bt_as_component_class_ptr = staticmethod(
98 native_bt.component_class_sink_as_component_class
99 )
81447b5b
PP
100
101
811644b8
PP
102class _PortIterator(collections.abc.Iterator):
103 def __init__(self, comp_ports):
104 self._comp_ports = comp_ports
105 self._at = 0
106
107 def __next__(self):
108 if self._at == len(self._comp_ports):
109 raise StopIteration
110
111 comp_ports = self._comp_ports
894a8df5
SM
112 comp_ptr = comp_ports._component_ptr
113
114 port_ptr = comp_ports._borrow_port_ptr_at_index(comp_ptr, self._at)
115 assert port_ptr is not None
116
117 name = native_bt.port_get_name(comp_ports._port_pycls._as_port_ptr(port_ptr))
118 assert name is not None
811644b8 119
811644b8
PP
120 self._at += 1
121 return name
122
123
124class _ComponentPorts(collections.abc.Mapping):
894a8df5
SM
125
126 # component_ptr is a bt_component_source *, bt_component_filter * or
127 # bt_component_sink *. Its type must match the type expected by the
128 # functions passed as arguments.
129
cfbd7cf3
FD
130 def __init__(
131 self,
132 component_ptr,
133 borrow_port_ptr_by_name,
134 borrow_port_ptr_at_index,
135 get_port_count,
136 port_pycls,
137 ):
894a8df5
SM
138 self._component_ptr = component_ptr
139 self._borrow_port_ptr_by_name = borrow_port_ptr_by_name
140 self._borrow_port_ptr_at_index = borrow_port_ptr_at_index
141 self._get_port_count = get_port_count
142 self._port_pycls = port_pycls
811644b8
PP
143
144 def __getitem__(self, key):
145 utils._check_str(key)
894a8df5 146 port_ptr = self._borrow_port_ptr_by_name(self._component_ptr, key)
811644b8
PP
147
148 if port_ptr is None:
149 raise KeyError(key)
150
894a8df5 151 return self._port_pycls._create_from_ptr_and_get_ref(port_ptr)
811644b8
PP
152
153 def __len__(self):
894a8df5
SM
154 count = self._get_port_count(self._component_ptr)
155 assert count >= 0
811644b8
PP
156 return count
157
158 def __iter__(self):
159 return _PortIterator(self)
160
161
81447b5b 162# This class holds the methods which are common to both generic
601c0026
SM
163# component objects and Python user component objects.
164#
165# Subclasses must provide these methods or property:
166#
85906b6b 167# - _bt_borrow_component_class_ptr: static method, must return a pointer to the
601c0026
SM
168# specialized component class (e.g. 'bt_component_class_sink *') of the
169# passed specialized component pointer (e.g. 'bt_component_sink *').
85906b6b 170# - _bt_comp_cls_type: property, one of the native_bt.COMPONENT_CLASS_TYPE_*
601c0026 171# constants.
85906b6b 172# - _bt_as_component_ptr: static method, must return the passed specialized
1c9ed2ff 173# component pointer (e.g. 'bt_component_sink *') as a 'bt_component *'.
601c0026 174
cfbd7cf3 175
615238be 176class _ComponentConst:
81447b5b
PP
177 @property
178 def name(self):
85906b6b 179 ptr = self._bt_as_component_ptr(self._ptr)
1c9ed2ff
SM
180 name = native_bt.component_get_name(ptr)
181 assert name is not None
811644b8
PP
182 return name
183
e874da19
PP
184 @property
185 def logging_level(self):
85906b6b 186 ptr = self._bt_as_component_ptr(self._ptr)
e874da19
PP
187 return native_bt.component_get_logging_level(ptr)
188
81447b5b 189 @property
e8ac1aae 190 def cls(self):
85906b6b 191 cc_ptr = self._bt_borrow_component_class_ptr(self._ptr)
601c0026 192 assert cc_ptr is not None
615238be 193 return _create_component_class_from_const_ptr_and_get_ref(
cfbd7cf3
FD
194 cc_ptr, self._bt_comp_cls_type
195 )
81447b5b 196
811644b8 197 def __eq__(self, other):
f5567ea8 198 if not hasattr(other, "addr"):
811644b8 199 return False
81447b5b 200
811644b8 201 return self.addr == other.addr
81447b5b 202
81447b5b 203
615238be 204class _SourceComponentConst(_ComponentConst):
cfbd7cf3
FD
205 _bt_borrow_component_class_ptr = staticmethod(
206 native_bt.component_source_borrow_class_const
207 )
85906b6b 208 _bt_comp_cls_type = native_bt.COMPONENT_CLASS_TYPE_SOURCE
cfbd7cf3
FD
209 _bt_as_component_class_ptr = staticmethod(
210 native_bt.component_class_source_as_component_class
211 )
85906b6b 212 _bt_as_component_ptr = staticmethod(native_bt.component_source_as_component_const)
81447b5b 213
81447b5b 214
615238be 215class _FilterComponentConst(_ComponentConst):
cfbd7cf3
FD
216 _bt_borrow_component_class_ptr = staticmethod(
217 native_bt.component_filter_borrow_class_const
218 )
85906b6b 219 _bt_comp_cls_type = native_bt.COMPONENT_CLASS_TYPE_FILTER
cfbd7cf3
FD
220 _bt_as_component_class_ptr = staticmethod(
221 native_bt.component_class_filter_as_component_class
222 )
85906b6b 223 _bt_as_component_ptr = staticmethod(native_bt.component_filter_as_component_const)
81447b5b 224
81447b5b 225
615238be 226class _SinkComponentConst(_ComponentConst):
cfbd7cf3
FD
227 _bt_borrow_component_class_ptr = staticmethod(
228 native_bt.component_sink_borrow_class_const
229 )
85906b6b 230 _bt_comp_cls_type = native_bt.COMPONENT_CLASS_TYPE_SINK
cfbd7cf3
FD
231 _bt_as_component_class_ptr = staticmethod(
232 native_bt.component_class_sink_as_component_class
233 )
85906b6b 234 _bt_as_component_ptr = staticmethod(native_bt.component_sink_as_component_const)
81447b5b
PP
235
236
615238be 237# This is analogous to _SourceComponentClassConst, but for source
81447b5b 238# component objects.
615238be 239class _GenericSourceComponentConst(object._SharedObject, _SourceComponentConst):
9dee90bd
SM
240 @staticmethod
241 def _get_ref(ptr):
242 native_bt.component_source_get_ref(ptr)
243
244 @staticmethod
245 def _put_ref(ptr):
246 native_bt.component_source_put_ref(ptr)
894a8df5 247
811644b8
PP
248 @property
249 def output_ports(self):
cfbd7cf3
FD
250 return _ComponentPorts(
251 self._ptr,
252 native_bt.component_source_borrow_output_port_by_name_const,
253 native_bt.component_source_borrow_output_port_by_index_const,
254 native_bt.component_source_get_output_port_count,
5813b3a3 255 bt2_port._OutputPortConst,
cfbd7cf3 256 )
81447b5b
PP
257
258
615238be 259# This is analogous to _FilterComponentClassConst, but for filter
81447b5b 260# component objects.
615238be 261class _GenericFilterComponentConst(object._SharedObject, _FilterComponentConst):
9dee90bd
SM
262 @staticmethod
263 def _get_ref(ptr):
264 native_bt.component_filter_get_ref(ptr)
265
266 @staticmethod
267 def _put_ref(ptr):
268 native_bt.component_filter_put_ref(ptr)
894a8df5 269
811644b8
PP
270 @property
271 def output_ports(self):
cfbd7cf3
FD
272 return _ComponentPorts(
273 self._ptr,
274 native_bt.component_filter_borrow_output_port_by_name_const,
275 native_bt.component_filter_borrow_output_port_by_index_const,
276 native_bt.component_filter_get_output_port_count,
5813b3a3 277 bt2_port._OutputPortConst,
cfbd7cf3 278 )
811644b8
PP
279
280 @property
281 def input_ports(self):
cfbd7cf3
FD
282 return _ComponentPorts(
283 self._ptr,
284 native_bt.component_filter_borrow_input_port_by_name_const,
285 native_bt.component_filter_borrow_input_port_by_index_const,
286 native_bt.component_filter_get_input_port_count,
5813b3a3 287 bt2_port._InputPortConst,
cfbd7cf3 288 )
81447b5b
PP
289
290
615238be 291# This is analogous to _SinkComponentClassConst, but for sink
81447b5b 292# component objects.
615238be 293class _GenericSinkComponentConst(object._SharedObject, _SinkComponentConst):
9dee90bd
SM
294 @staticmethod
295 def _get_ref(ptr):
296 native_bt.component_sink_get_ref(ptr)
297
298 @staticmethod
299 def _put_ref(ptr):
300 native_bt.component_sink_put_ref(ptr)
601c0026 301
811644b8
PP
302 @property
303 def input_ports(self):
cfbd7cf3
FD
304 return _ComponentPorts(
305 self._ptr,
306 native_bt.component_sink_borrow_input_port_by_name_const,
307 native_bt.component_sink_borrow_input_port_by_index_const,
308 native_bt.component_sink_get_input_port_count,
5813b3a3 309 bt2_port._InputPortConst,
cfbd7cf3 310 )
81447b5b
PP
311
312
811644b8 313_COMP_CLS_TYPE_TO_GENERIC_COMP_PYCLS = {
615238be
FD
314 native_bt.COMPONENT_CLASS_TYPE_SOURCE: _GenericSourceComponentConst,
315 native_bt.COMPONENT_CLASS_TYPE_FILTER: _GenericFilterComponentConst,
316 native_bt.COMPONENT_CLASS_TYPE_SINK: _GenericSinkComponentConst,
81447b5b
PP
317}
318
319
811644b8 320_COMP_CLS_TYPE_TO_GENERIC_COMP_CLS_PYCLS = {
615238be
FD
321 native_bt.COMPONENT_CLASS_TYPE_SOURCE: _SourceComponentClassConst,
322 native_bt.COMPONENT_CLASS_TYPE_FILTER: _FilterComponentClassConst,
323 native_bt.COMPONENT_CLASS_TYPE_SINK: _SinkComponentClassConst,
81447b5b
PP
324}
325
326
615238be
FD
327# Create a component Python object of type _GenericSourceComponentConst,
328# _GenericFilterComponentConst or _GenericSinkComponentConst, depending on
601c0026
SM
329# comp_cls_type.
330#
331# Steals the reference to ptr from the caller.
332
cfbd7cf3 333
615238be 334def _create_component_from_const_ptr(ptr, comp_cls_type):
811644b8 335 return _COMP_CLS_TYPE_TO_GENERIC_COMP_PYCLS[comp_cls_type]._create_from_ptr(ptr)
81447b5b 336
5f25509b
SM
337
338# Same as the above, but acquire a new reference instead of stealing the
339# reference from the caller.
340
cfbd7cf3 341
615238be 342def _create_component_from_const_ptr_and_get_ref(ptr, comp_cls_type):
cfbd7cf3
FD
343 return _COMP_CLS_TYPE_TO_GENERIC_COMP_PYCLS[
344 comp_cls_type
345 ]._create_from_ptr_and_get_ref(ptr)
5f25509b
SM
346
347
601c0026 348# Create a component class Python object of type
615238be
FD
349# _SourceComponentClassConst, _FilterComponentClassConst or
350# _SinkComponentClassConst, depending on comp_cls_type.
601c0026
SM
351#
352# Acquires a new reference to ptr.
81447b5b 353
cfbd7cf3 354
615238be 355def _create_component_class_from_const_ptr_and_get_ref(ptr, comp_cls_type):
cfbd7cf3
FD
356 return _COMP_CLS_TYPE_TO_GENERIC_COMP_CLS_PYCLS[
357 comp_cls_type
358 ]._create_from_ptr_and_get_ref(ptr)
81447b5b
PP
359
360
40910fbb
PP
361def _trim_docstring(docstring):
362 lines = docstring.expandtabs().splitlines()
ade5c95e
PP
363
364 if len(lines) == 0:
f5567ea8 365 return ""
ade5c95e 366
40910fbb
PP
367 indent = sys.maxsize
368
ade5c95e
PP
369 if len(lines) > 1:
370 for line in lines[1:]:
371 stripped = line.lstrip()
40910fbb 372
ade5c95e
PP
373 if stripped:
374 indent = min(indent, len(line) - len(stripped))
40910fbb
PP
375
376 trimmed = [lines[0].strip()]
377
ade5c95e 378 if indent < sys.maxsize and len(lines) > 1:
40910fbb
PP
379 for line in lines[1:]:
380 trimmed.append(line[indent:].rstrip())
381
382 while trimmed and not trimmed[-1]:
383 trimmed.pop()
384
385 while trimmed and not trimmed[0]:
386 trimmed.pop(0)
387
f5567ea8 388 return "\n".join(trimmed)
40910fbb
PP
389
390
81447b5b
PP
391# Metaclass for component classes defined by Python code.
392#
393# The Python user can create a standard Python class which inherits one
811644b8
PP
394# of the three base classes (_UserSourceComponent, _UserFilterComponent,
395# or _UserSinkComponent). Those base classes set this class
81447b5b
PP
396# (_UserComponentType) as their metaclass.
397#
398# Once the body of a user-defined component class is executed, this
399# metaclass is used to create and initialize the class. The metaclass
400# creates a native BT component class of the corresponding type and
401# associates it with this user-defined class. The metaclass also defines
402# class methods like the `name` and `description` properties to match
615238be 403# the _ComponentClassConst interface.
81447b5b
PP
404#
405# The component class name which is used is either:
406#
407# * The `name` parameter of the class:
408#
409# class MySink(bt2.SinkComponent, name='my-custom-sink'):
410# ...
411#
412# * If the `name` class parameter is not used: the name of the class
413# itself (`MySink` in the example above).
414#
415# The component class description which is used is the user-defined
416# class's docstring:
417#
418# class MySink(bt2.SinkComponent):
419# 'Description goes here'
420# ...
421#
422# A user-defined Python component class can have an __init__() method
101fde11 423# which must accept the following parameters:
81447b5b 424#
101fde11 425# def __init__(self, config, params, obj):
81447b5b
PP
426# ...
427#
101fde11
SM
428# The value of the `obj` parameter is what was passed as the `obj`
429# parameter if the component was instantiated from Python with
430# Graph.add_component(). If the component was not instantiated from
431# Python, is is always `None`.
432#
433# The user-defined component class can also have a _user_finalize()
434# method (do NOT use __del__()) to be notified when the component object
435# is finalized.
81447b5b
PP
436#
437# User-defined source and filter component classes must use the
5602ef81
SM
438# `message_iterator_class` class parameter to specify the
439# message iterator class to use for this component class:
81447b5b 440#
5602ef81 441# class MyMessageIterator(bt2._UserMessageIterator):
81447b5b
PP
442# ...
443#
811644b8 444# class MySource(bt2._UserSourceComponent,
5602ef81 445# message_iterator_class=MyMessageIterator):
81447b5b
PP
446# ...
447#
101fde11
SM
448# This message iterator class must inherit bt2._UserMessageIterator.
449# It can implement the __init__() method, which must accept the
450# following parameters:
451#
452# def __init__(self, config, port):
453# ...
454#
455# It can also implement the __next__() and _user_finalize() methods
456# (again, do NOT use __del__()), which don't accept any parameters
457# other than `self`.
81447b5b
PP
458#
459# When the user-defined class is destroyed, this metaclass's __del__()
460# method is called: the native BT component class pointer is put (not
461# needed anymore, at least not by any Python code since all references
462# are dropped for __del__() to be called).
463class _UserComponentType(type):
464 # __new__() is used to catch custom class parameters
465 def __new__(meta_cls, class_name, bases, attrs, **kwargs):
466 return super().__new__(meta_cls, class_name, bases, attrs)
467
468 def __init__(cls, class_name, bases, namespace, **kwargs):
469 super().__init__(class_name, bases, namespace)
470
471 # skip our own bases; they are never directly instantiated by the user
811644b8 472 own_bases = (
f5567ea8
FD
473 "_UserComponent",
474 "_UserFilterSinkComponent",
475 "_UserSourceComponent",
476 "_UserFilterComponent",
477 "_UserSinkComponent",
811644b8
PP
478 )
479
480 if class_name in own_bases:
81447b5b
PP
481 return
482
f5567ea8 483 comp_cls_name = kwargs.get("name", class_name)
811644b8 484 utils._check_str(comp_cls_name)
40910fbb
PP
485 comp_cls_descr = None
486 comp_cls_help = None
487
f5567ea8 488 if hasattr(cls, "__doc__") and cls.__doc__ is not None:
811644b8 489 utils._check_str(cls.__doc__)
40910fbb
PP
490 docstring = _trim_docstring(cls.__doc__)
491 lines = docstring.splitlines()
492
493 if len(lines) >= 1:
494 comp_cls_descr = lines[0]
495
496 if len(lines) >= 3:
f5567ea8 497 comp_cls_help = "\n".join(lines[2:])
40910fbb 498
f5567ea8 499 iter_cls = kwargs.get("message_iterator_class")
81447b5b 500
811644b8 501 if _UserSourceComponent in bases:
85906b6b 502 _UserComponentType._bt_set_iterator_class(cls, iter_cls)
cfbd7cf3
FD
503 cc_ptr = native_bt.bt2_component_class_source_create(
504 cls, comp_cls_name, comp_cls_descr, comp_cls_help
505 )
811644b8 506 elif _UserFilterComponent in bases:
85906b6b 507 _UserComponentType._bt_set_iterator_class(cls, iter_cls)
cfbd7cf3
FD
508 cc_ptr = native_bt.bt2_component_class_filter_create(
509 cls, comp_cls_name, comp_cls_descr, comp_cls_help
510 )
811644b8 511 elif _UserSinkComponent in bases:
f5567ea8 512 if not hasattr(cls, "_user_consume"):
cb06aa27 513 raise bt2._IncompleteUserClass(
6a91742b 514 "cannot create component class '{}': missing a _user_consume() method".format(
cfbd7cf3
FD
515 class_name
516 )
517 )
518
519 cc_ptr = native_bt.bt2_component_class_sink_create(
520 cls, comp_cls_name, comp_cls_descr, comp_cls_help
521 )
81447b5b 522 else:
cb06aa27 523 raise bt2._IncompleteUserClass(
cfbd7cf3
FD
524 "cannot find a known component class base in the bases of '{}'".format(
525 class_name
526 )
527 )
81447b5b
PP
528
529 if cc_ptr is None:
694c792b 530 raise bt2._MemoryError(
cfbd7cf3
FD
531 "cannot create component class '{}'".format(class_name)
532 )
81447b5b 533
85906b6b 534 cls._bt_cc_ptr = cc_ptr
81447b5b 535
66964f3f 536 def _bt_init_from_native(cls, comp_ptr, params_ptr, obj):
811644b8 537 # create instance, not user-initialized yet
81447b5b
PP
538 self = cls.__new__(cls)
539
59225a3e
SM
540 # config object
541 config = cls._config_pycls()
542
601c0026 543 # pointer to native self component object (weak/borrowed)
85906b6b 544 self._bt_ptr = comp_ptr
81447b5b 545
811644b8
PP
546 # call user's __init__() method
547 if params_ptr is not None:
e42e1587 548 params = bt2_value._create_from_const_ptr_and_get_ref(params_ptr)
811644b8
PP
549 else:
550 params = None
81447b5b 551
59225a3e 552 self.__init__(config, params, obj)
81447b5b
PP
553 return self
554
811644b8 555 def __call__(cls, *args, **kwargs):
ce4923b0 556 raise RuntimeError(
f5567ea8 557 "cannot directly instantiate a user component from a Python module"
cfbd7cf3 558 )
81447b5b
PP
559
560 @staticmethod
85906b6b 561 def _bt_set_iterator_class(cls, iter_cls):
81447b5b 562 if iter_cls is None:
cb06aa27 563 raise bt2._IncompleteUserClass(
cfbd7cf3
FD
564 "cannot create component class '{}': missing message iterator class".format(
565 cls.__name__
566 )
567 )
81447b5b 568
3fb99a22 569 if not issubclass(iter_cls, bt2_message_iterator._UserMessageIterator):
cb06aa27 570 raise bt2._IncompleteUserClass(
cfbd7cf3
FD
571 "cannot create component class '{}': message iterator class does not inherit bt2._UserMessageIterator".format(
572 cls.__name__
573 )
574 )
81447b5b 575
f5567ea8 576 if not hasattr(iter_cls, "__next__"):
cb06aa27 577 raise bt2._IncompleteUserClass(
cfbd7cf3
FD
578 "cannot create component class '{}': message iterator class is missing a __next__() method".format(
579 cls.__name__
580 )
581 )
81447b5b 582
f5567ea8
FD
583 if hasattr(iter_cls, "_user_can_seek_ns_from_origin") and not hasattr(
584 iter_cls, "_user_seek_ns_from_origin"
2e1b5615
SM
585 ):
586 raise bt2._IncompleteUserClass(
587 "cannot create component class '{}': message iterator class implements _user_can_seek_ns_from_origin but not _user_seek_ns_from_origin".format(
588 cls.__name__
589 )
590 )
591
f5567ea8
FD
592 if hasattr(iter_cls, "_user_can_seek_beginning") and not hasattr(
593 iter_cls, "_user_seek_beginning"
2e1b5615
SM
594 ):
595 raise bt2._IncompleteUserClass(
596 "cannot create component class '{}': message iterator class implements _user_can_seek_beginning but not _user_seek_beginning".format(
597 cls.__name__
598 )
599 )
600
81447b5b
PP
601 cls._iter_cls = iter_cls
602
603 @property
604 def name(cls):
85906b6b 605 ptr = cls._bt_as_component_class_ptr(cls._bt_cc_ptr)
601c0026 606 return native_bt.component_class_get_name(ptr)
81447b5b
PP
607
608 @property
609 def description(cls):
85906b6b 610 ptr = cls._bt_as_component_class_ptr(cls._bt_cc_ptr)
601c0026 611 return native_bt.component_class_get_description(ptr)
81447b5b 612
40910fbb
PP
613 @property
614 def help(cls):
85906b6b 615 ptr = cls._bt_as_component_class_ptr(cls._bt_cc_ptr)
601c0026 616 return native_bt.component_class_get_help(ptr)
40910fbb 617
81447b5b
PP
618 @property
619 def addr(cls):
85906b6b 620 return int(cls._bt_cc_ptr)
81447b5b 621
fd57054b
PP
622 def _bt_get_supported_mip_versions_from_native(cls, params_ptr, obj, log_level):
623 # this can raise, but the native side checks the exception
624 if params_ptr is not None:
e42e1587 625 params = bt2_value._create_from_const_ptr_and_get_ref(params_ptr)
fd57054b
PP
626 else:
627 params = None
628
629 # this can raise, but the native side checks the exception
630 range_set = cls._user_get_supported_mip_versions(params, obj, log_level)
631
632 if type(range_set) is not bt2.UnsignedIntegerRangeSet:
633 # this can raise, but the native side checks the exception
634 range_set = bt2.UnsignedIntegerRangeSet(range_set)
635
636 # return new reference
637 range_set._get_ref(range_set._ptr)
638 return int(range_set._ptr)
639
640 def _user_get_supported_mip_versions(cls, params, obj, log_level):
641 return [0]
642
0b9ddc00
PP
643 def _bt_query_from_native(
644 cls, priv_query_exec_ptr, object_name, params_ptr, method_obj
645 ):
fd57054b 646 # this can raise, but the native side checks the exception
811644b8 647 if params_ptr is not None:
e42e1587 648 params = bt2_value._create_from_const_ptr_and_get_ref(params_ptr)
811644b8
PP
649 else:
650 params = None
651
3c729b9a 652 priv_query_exec = bt2_query_executor._PrivateQueryExecutor(priv_query_exec_ptr)
811644b8 653
3c729b9a
PP
654 try:
655 # this can raise, but the native side checks the exception
0b9ddc00 656 results = cls._user_query(priv_query_exec, object_name, params, method_obj)
3c729b9a
PP
657 finally:
658 # the private query executor is a private view on the query
659 # executor; it's not a shared object (the library does not
660 # offer an API to get/put a reference, just like "self"
661 # objects) from this query's point of view, so invalidate
662 # the object in case the user kept a reference and uses it
663 # later
664 priv_query_exec._invalidate()
811644b8 665
c7eee084
PP
666 # this can raise, but the native side checks the exception
667 results = bt2.create_value(results)
911dec08
PP
668
669 if results is None:
b5947615 670 results_ptr = native_bt.value_null
911dec08 671 else:
b5947615 672 results_ptr = results._ptr
911dec08 673
3c729b9a 674 # return new reference
3fb99a22 675 bt2_value._Value._get_ref(results_ptr)
b5947615 676 return int(results_ptr)
911dec08 677
0b9ddc00 678 def _user_query(cls, priv_query_executor, object_name, params, method_obj):
76b6c2f7 679 raise bt2.UnknownObject
811644b8 680
85906b6b
FD
681 def _bt_component_class_ptr(self):
682 return self._bt_as_component_class_ptr(self._bt_cc_ptr)
911dec08 683
81447b5b 684 def __del__(cls):
f5567ea8 685 if hasattr(cls, "_bt_cc_ptr"):
85906b6b 686 cc_ptr = cls._bt_as_component_class_ptr(cls._bt_cc_ptr)
601c0026 687 native_bt.component_class_put_ref(cc_ptr)
ab1cea3f 688 native_bt.bt2_unregister_cc_ptr_to_py_cls(cc_ptr)
81447b5b 689
cfbd7cf3 690
59225a3e
SM
691# Configuration objects for components.
692#
693# These are passed in __init__ to allow components to change some configuration
694# parameters during initialization and not after. As you can see, they are not
695# used at the moment, but are there in case we want to add such parameters.
696
697
698class _UserComponentConfiguration:
699 pass
700
701
702class _UserSourceComponentConfiguration(_UserComponentConfiguration):
703 pass
704
705
706class _UserFilterComponentConfiguration(_UserComponentConfiguration):
707 pass
708
709
710class _UserSinkComponentConfiguration(_UserComponentConfiguration):
711 pass
712
713
1c9ed2ff
SM
714# Subclasses must provide these methods or property:
715#
85906b6b 716# - _bt_as_not_self_specific_component_ptr: static method, must return the passed
1c9ed2ff
SM
717# specialized self component pointer (e.g. 'bt_self_component_sink *') as a
718# specialized non-self pointer (e.g. 'bt_component_sink *').
85906b6b 719# - _bt_borrow_component_class_ptr: static method, must return a pointer to the
1c9ed2ff
SM
720# specialized component class (e.g. 'bt_component_class_sink *') of the
721# passed specialized component pointer (e.g. 'bt_component_sink *').
85906b6b 722# - _bt_comp_cls_type: property, one of the native_bt.COMPONENT_CLASS_TYPE_*
1c9ed2ff 723# constants.
81447b5b 724
cfbd7cf3 725
811644b8
PP
726class _UserComponent(metaclass=_UserComponentType):
727 @property
728 def name(self):
85906b6b
FD
729 ptr = self._bt_as_not_self_specific_component_ptr(self._bt_ptr)
730 ptr = self._bt_as_component_ptr(ptr)
1c9ed2ff
SM
731 name = native_bt.component_get_name(ptr)
732 assert name is not None
811644b8 733 return name
81447b5b 734
e874da19
PP
735 @property
736 def logging_level(self):
85906b6b
FD
737 ptr = self._bt_as_not_self_specific_component_ptr(self._bt_ptr)
738 ptr = self._bt_as_component_ptr(ptr)
e874da19
PP
739 return native_bt.component_get_logging_level(ptr)
740
811644b8 741 @property
e8ac1aae 742 def cls(self):
85906b6b
FD
743 comp_ptr = self._bt_as_not_self_specific_component_ptr(self._bt_ptr)
744 cc_ptr = self._bt_borrow_component_class_ptr(comp_ptr)
615238be 745 return _create_component_class_from_const_ptr_and_get_ref(
cfbd7cf3
FD
746 cc_ptr, self._bt_comp_cls_type
747 )
81447b5b 748
81447b5b
PP
749 @property
750 def addr(self):
85906b6b 751 return int(self._bt_ptr)
81447b5b 752
056deb59
PP
753 @property
754 def _graph_mip_version(self):
755 ptr = self._bt_as_self_component_ptr(self._bt_ptr)
756 return native_bt.self_component_get_graph_mip_version(ptr)
757
59225a3e 758 def __init__(self, config, params, obj):
81447b5b
PP
759 pass
760
6a91742b 761 def _user_finalize(self):
81447b5b
PP
762 pass
763
6a91742b 764 def _user_port_connected(self, port, other_port):
811644b8 765 pass
81447b5b 766
cfbd7cf3
FD
767 def _bt_port_connected_from_native(
768 self, self_port_ptr, self_port_type, other_port_ptr
769 ):
3fb99a22 770 port = bt2_port._create_self_from_ptr_and_get_ref(self_port_ptr, self_port_type)
2c67587a
SM
771
772 if self_port_type == native_bt.PORT_TYPE_OUTPUT:
773 other_port_type = native_bt.PORT_TYPE_INPUT
774 else:
775 other_port_type = native_bt.PORT_TYPE_OUTPUT
776
5813b3a3 777 other_port = bt2_port._create_from_const_ptr_and_get_ref(
cfbd7cf3
FD
778 other_port_ptr, other_port_type
779 )
6a91742b 780 self._user_port_connected(port, other_port)
81447b5b 781
5783664e
PP
782 def _create_trace_class(
783 self, user_attributes=None, assigns_automatic_stream_class_id=True
784 ):
85906b6b 785 ptr = self._bt_as_self_component_ptr(self._bt_ptr)
fbbe9302
SM
786 tc_ptr = native_bt.trace_class_create(ptr)
787
788 if tc_ptr is None:
f5567ea8 789 raise bt2._MemoryError("could not create trace class")
fbbe9302 790
3fb99a22 791 tc = bt2_trace_class._TraceClass._create_from_ptr(tc_ptr)
fbbe9302
SM
792 tc._assigns_automatic_stream_class_id = assigns_automatic_stream_class_id
793
5783664e
PP
794 if user_attributes is not None:
795 tc._user_attributes = user_attributes
796
fbbe9302
SM
797 return tc
798
cfbd7cf3
FD
799 def _create_clock_class(
800 self,
801 frequency=None,
802 name=None,
5783664e 803 user_attributes=None,
cfbd7cf3
FD
804 description=None,
805 precision=None,
806 offset=None,
807 origin_is_unix_epoch=True,
808 uuid=None,
809 ):
85906b6b 810 ptr = self._bt_as_self_component_ptr(self._bt_ptr)
3cdfbaea
SM
811 cc_ptr = native_bt.clock_class_create(ptr)
812
813 if cc_ptr is None:
f5567ea8 814 raise bt2._MemoryError("could not create clock class")
3cdfbaea 815
3fb99a22 816 cc = bt2_clock_class._ClockClass._create_from_ptr(cc_ptr)
2ae9f48c
SM
817
818 if frequency is not None:
819 cc._frequency = frequency
820
be7bbff9
SM
821 if name is not None:
822 cc._name = name
823
5783664e
PP
824 if user_attributes is not None:
825 cc._user_attributes = user_attributes
826
be7bbff9
SM
827 if description is not None:
828 cc._description = description
829
830 if precision is not None:
831 cc._precision = precision
832
833 if offset is not None:
834 cc._offset = offset
835
836 cc._origin_is_unix_epoch = origin_is_unix_epoch
837
838 if uuid is not None:
839 cc._uuid = uuid
840
2ae9f48c 841 return cc
3cdfbaea 842
81447b5b 843
615238be 844class _UserSourceComponent(_UserComponent, _SourceComponentConst):
cfbd7cf3
FD
845 _bt_as_not_self_specific_component_ptr = staticmethod(
846 native_bt.self_component_source_as_component_source
847 )
848 _bt_as_self_component_ptr = staticmethod(
849 native_bt.self_component_source_as_self_component
850 )
59225a3e 851 _config_pycls = _UserSourceComponentConfiguration
1c9ed2ff 852
81447b5b 853 @property
811644b8 854 def _output_ports(self):
894a8df5 855 def get_output_port_count(self_ptr):
85906b6b 856 ptr = self._bt_as_not_self_specific_component_ptr(self_ptr)
894a8df5
SM
857 return native_bt.component_source_get_output_port_count(ptr)
858
cfbd7cf3
FD
859 return _ComponentPorts(
860 self._bt_ptr,
861 native_bt.self_component_source_borrow_output_port_by_name,
862 native_bt.self_component_source_borrow_output_port_by_index,
863 get_output_port_count,
3fb99a22 864 bt2_port._UserComponentOutputPort,
cfbd7cf3 865 )
811644b8 866
2e00bc76 867 def _add_output_port(self, name, user_data=None):
811644b8 868 utils._check_str(name)
157a98ed
SM
869
870 if name in self._output_ports:
871 raise ValueError(
f5567ea8 872 "source component `{}` already contains an output port named `{}`".format(
157a98ed
SM
873 self.name, name
874 )
875 )
876
894a8df5 877 fn = native_bt.self_component_source_add_output_port
85906b6b 878 comp_status, self_port_ptr = fn(self._bt_ptr, name, user_data)
cfbd7cf3 879 utils._handle_func_status(
f5567ea8 880 comp_status, "cannot add output port to source component object"
cfbd7cf3 881 )
894a8df5 882 assert self_port_ptr is not None
a91462c9
PP
883 return bt2_port._UserComponentOutputPort._create_from_ptr_and_get_ref(
884 self_port_ptr
885 )
811644b8
PP
886
887
615238be 888class _UserFilterComponent(_UserComponent, _FilterComponentConst):
cfbd7cf3
FD
889 _bt_as_not_self_specific_component_ptr = staticmethod(
890 native_bt.self_component_filter_as_component_filter
891 )
892 _bt_as_self_component_ptr = staticmethod(
893 native_bt.self_component_filter_as_self_component
894 )
59225a3e 895 _config_pycls = _UserFilterComponentConfiguration
1c9ed2ff 896
811644b8
PP
897 @property
898 def _output_ports(self):
894a8df5 899 def get_output_port_count(self_ptr):
85906b6b 900 ptr = self._bt_as_not_self_specific_component_ptr(self_ptr)
894a8df5
SM
901 return native_bt.component_filter_get_output_port_count(ptr)
902
cfbd7cf3
FD
903 return _ComponentPorts(
904 self._bt_ptr,
905 native_bt.self_component_filter_borrow_output_port_by_name,
906 native_bt.self_component_filter_borrow_output_port_by_index,
907 get_output_port_count,
3fb99a22 908 bt2_port._UserComponentOutputPort,
cfbd7cf3 909 )
81447b5b 910
811644b8
PP
911 @property
912 def _input_ports(self):
894a8df5 913 def get_input_port_count(self_ptr):
85906b6b 914 ptr = self._bt_as_not_self_specific_component_ptr(self_ptr)
894a8df5
SM
915 return native_bt.component_filter_get_input_port_count(ptr)
916
cfbd7cf3
FD
917 return _ComponentPorts(
918 self._bt_ptr,
919 native_bt.self_component_filter_borrow_input_port_by_name,
920 native_bt.self_component_filter_borrow_input_port_by_index,
921 get_input_port_count,
3fb99a22 922 bt2_port._UserComponentInputPort,
cfbd7cf3 923 )
811644b8 924
2e00bc76 925 def _add_output_port(self, name, user_data=None):
811644b8 926 utils._check_str(name)
157a98ed
SM
927
928 if name in self._output_ports:
929 raise ValueError(
f5567ea8 930 "filter component `{}` already contains an output port named `{}`".format(
157a98ed
SM
931 self.name, name
932 )
933 )
934
894a8df5 935 fn = native_bt.self_component_filter_add_output_port
85906b6b 936 comp_status, self_port_ptr = fn(self._bt_ptr, name, user_data)
cfbd7cf3 937 utils._handle_func_status(
f5567ea8 938 comp_status, "cannot add output port to filter component object"
cfbd7cf3 939 )
894a8df5 940 assert self_port_ptr
a91462c9
PP
941 return bt2_port._UserComponentOutputPort._create_from_ptr_and_get_ref(
942 self_port_ptr
943 )
811644b8 944
2e00bc76 945 def _add_input_port(self, name, user_data=None):
811644b8 946 utils._check_str(name)
157a98ed
SM
947
948 if name in self._input_ports:
949 raise ValueError(
f5567ea8 950 "filter component `{}` already contains an input port named `{}`".format(
157a98ed
SM
951 self.name, name
952 )
953 )
954
894a8df5 955 fn = native_bt.self_component_filter_add_input_port
85906b6b 956 comp_status, self_port_ptr = fn(self._bt_ptr, name, user_data)
cfbd7cf3 957 utils._handle_func_status(
f5567ea8 958 comp_status, "cannot add input port to filter component object"
cfbd7cf3 959 )
894a8df5 960 assert self_port_ptr
a91462c9
PP
961 return bt2_port._UserComponentInputPort._create_from_ptr_and_get_ref(
962 self_port_ptr
963 )
811644b8
PP
964
965
615238be 966class _UserSinkComponent(_UserComponent, _SinkComponentConst):
cfbd7cf3
FD
967 _bt_as_not_self_specific_component_ptr = staticmethod(
968 native_bt.self_component_sink_as_component_sink
969 )
970 _bt_as_self_component_ptr = staticmethod(
971 native_bt.self_component_sink_as_self_component
972 )
59225a3e 973 _config_pycls = _UserSinkComponentConfiguration
1c9ed2ff 974
d14a864a 975 def _bt_graph_is_configured_from_native(self):
6a91742b 976 self._user_graph_is_configured()
d14a864a 977
6a91742b 978 def _user_graph_is_configured(self):
cd1ef6f2
PP
979 pass
980
811644b8
PP
981 @property
982 def _input_ports(self):
894a8df5 983 def get_input_port_count(self_ptr):
85906b6b 984 ptr = self._bt_as_not_self_specific_component_ptr(self_ptr)
894a8df5
SM
985 return native_bt.component_sink_get_input_port_count(ptr)
986
cfbd7cf3
FD
987 return _ComponentPorts(
988 self._bt_ptr,
989 native_bt.self_component_sink_borrow_input_port_by_name,
990 native_bt.self_component_sink_borrow_input_port_by_index,
991 get_input_port_count,
3fb99a22 992 bt2_port._UserComponentInputPort,
cfbd7cf3 993 )
811644b8 994
2e00bc76 995 def _add_input_port(self, name, user_data=None):
811644b8 996 utils._check_str(name)
157a98ed
SM
997
998 if name in self._input_ports:
999 raise ValueError(
f5567ea8 1000 "sink component `{}` already contains an input port named `{}`".format(
157a98ed
SM
1001 self.name, name
1002 )
1003 )
1004
894a8df5 1005 fn = native_bt.self_component_sink_add_input_port
85906b6b 1006 comp_status, self_port_ptr = fn(self._bt_ptr, name, user_data)
cfbd7cf3 1007 utils._handle_func_status(
f5567ea8 1008 comp_status, "cannot add input port to sink component object"
cfbd7cf3 1009 )
5f25509b 1010 assert self_port_ptr
a91462c9
PP
1011 return bt2_port._UserComponentInputPort._create_from_ptr_and_get_ref(
1012 self_port_ptr
1013 )
ca02df0a 1014
9a2c8b8e 1015 def _create_message_iterator(self, input_port):
3fb99a22 1016 utils._check_type(input_port, bt2_port._UserComponentInputPort)
ca02df0a 1017
415d43a1 1018 if not input_port.is_connected:
f5567ea8 1019 raise ValueError("input port is not connected")
415d43a1 1020
75882e97
FD
1021 (
1022 status,
1023 msg_iter_ptr,
9a2c8b8e 1024 ) = native_bt.bt2_message_iterator_create_from_sink_component(
ca02df0a
PP
1025 self._bt_ptr, input_port._ptr
1026 )
f5567ea8 1027 utils._handle_func_status(status, "cannot create message iterator object")
e803df70 1028 assert msg_iter_ptr is not None
ca02df0a 1029
3fb99a22 1030 return bt2_message_iterator._UserComponentInputPortMessageIterator(msg_iter_ptr)
9b4f9b42
PP
1031
1032 @property
1033 def _is_interrupted(self):
1034 return bool(native_bt.self_component_sink_is_interrupted(self._bt_ptr))
This page took 0.131917 seconds and 4 git commands to generate.