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