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