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