7357eb7e413ca4774b3e40395ea2d8198fadf5cd
[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 from bt2 import error as bt2_error
16 from bt2 import integer_range_set as bt2_integer_range_set
17 import sys
18
19
20 class _IncompleteUserClass(Exception):
21 pass
22
23
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.
28 #
29 # Subclasses must implement some methods that this base class uses:
30 #
31 # - _bt_as_component_class_ptr: static method, convert the passed component class
32 # pointer to a 'bt_component_class *'.
33
34
35 class _ComponentClassConst(bt2_object._SharedObject):
36 @property
37 def name(self):
38 ptr = self._bt_as_component_class_ptr(self._ptr)
39 name = native_bt.component_class_get_name(ptr)
40 assert name is not None
41 return name
42
43 @property
44 def description(self):
45 ptr = self._bt_as_component_class_ptr(self._ptr)
46 return native_bt.component_class_get_description(ptr)
47
48 @property
49 def help(self):
50 ptr = self._bt_as_component_class_ptr(self._ptr)
51 return native_bt.component_class_get_help(ptr)
52
53 def _bt_component_class_ptr(self):
54 return self._bt_as_component_class_ptr(self._ptr)
55
56 def __eq__(self, other):
57 if not isinstance(other, _ComponentClassConst):
58 try:
59 if not issubclass(other, _UserComponent):
60 return False
61 except TypeError:
62 return False
63
64 return self.addr == other.addr
65
66
67 class _SourceComponentClassConst(_ComponentClassConst):
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
76 _bt_as_component_class_ptr = staticmethod(
77 native_bt.component_class_source_as_component_class
78 )
79
80
81 class _FilterComponentClassConst(_ComponentClassConst):
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
90 _bt_as_component_class_ptr = staticmethod(
91 native_bt.component_class_filter_as_component_class
92 )
93
94
95 class _SinkComponentClassConst(_ComponentClassConst):
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
104 _bt_as_component_class_ptr = staticmethod(
105 native_bt.component_class_sink_as_component_class
106 )
107
108
109 class _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
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
126
127 self._at += 1
128 return name
129
130
131 class _ComponentPorts(collections.abc.Mapping):
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
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 ):
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
149
150 def __getitem__(self, key):
151 bt2_utils._check_str(key)
152 port_ptr = self._borrow_port_ptr_by_name(self._component_ptr, key)
153
154 if port_ptr is None:
155 raise KeyError(key)
156
157 return self._port_pycls._create_from_ptr_and_get_ref(port_ptr)
158
159 def __len__(self):
160 count = self._get_port_count(self._component_ptr)
161 assert count >= 0
162 return count
163
164 def __iter__(self):
165 return _PortIterator(self)
166
167
168 # This class holds the methods which are common to both generic
169 # component objects and Python user component objects.
170 #
171 # Subclasses must provide these methods or property:
172 #
173 # - _bt_borrow_component_class_ptr: static method, must return a pointer to the
174 # specialized component class (e.g. 'bt_component_class_sink *') of the
175 # passed specialized component pointer (e.g. 'bt_component_sink *').
176 # - _bt_comp_cls_type: property, one of the native_bt.COMPONENT_CLASS_TYPE_*
177 # constants.
178 # - _bt_as_component_ptr: static method, must return the passed specialized
179 # component pointer (e.g. 'bt_component_sink *') as a 'bt_component *'.
180
181
182 class _ComponentConst:
183 @property
184 def name(self):
185 ptr = self._bt_as_component_ptr(self._ptr)
186 name = native_bt.component_get_name(ptr)
187 assert name is not None
188 return name
189
190 @property
191 def logging_level(self):
192 ptr = self._bt_as_component_ptr(self._ptr)
193 return native_bt.component_get_logging_level(ptr)
194
195 @property
196 def cls(self):
197 cc_ptr = self._bt_borrow_component_class_ptr(self._ptr)
198 assert cc_ptr is not None
199 return _create_component_class_from_const_ptr_and_get_ref(
200 cc_ptr, self._bt_comp_cls_type
201 )
202
203 def __eq__(self, other):
204 if not hasattr(other, "addr"):
205 return False
206
207 return self.addr == other.addr
208
209
210 class _SourceComponentConst(_ComponentConst):
211 _bt_borrow_component_class_ptr = staticmethod(
212 native_bt.component_source_borrow_class_const
213 )
214 _bt_comp_cls_type = native_bt.COMPONENT_CLASS_TYPE_SOURCE
215 _bt_as_component_class_ptr = staticmethod(
216 native_bt.component_class_source_as_component_class
217 )
218 _bt_as_component_ptr = staticmethod(native_bt.component_source_as_component_const)
219
220
221 class _FilterComponentConst(_ComponentConst):
222 _bt_borrow_component_class_ptr = staticmethod(
223 native_bt.component_filter_borrow_class_const
224 )
225 _bt_comp_cls_type = native_bt.COMPONENT_CLASS_TYPE_FILTER
226 _bt_as_component_class_ptr = staticmethod(
227 native_bt.component_class_filter_as_component_class
228 )
229 _bt_as_component_ptr = staticmethod(native_bt.component_filter_as_component_const)
230
231
232 class _SinkComponentConst(_ComponentConst):
233 _bt_borrow_component_class_ptr = staticmethod(
234 native_bt.component_sink_borrow_class_const
235 )
236 _bt_comp_cls_type = native_bt.COMPONENT_CLASS_TYPE_SINK
237 _bt_as_component_class_ptr = staticmethod(
238 native_bt.component_class_sink_as_component_class
239 )
240 _bt_as_component_ptr = staticmethod(native_bt.component_sink_as_component_const)
241
242
243 # This is analogous to _SourceComponentClassConst, but for source
244 # component objects.
245 class _GenericSourceComponentConst(bt2_object._SharedObject, _SourceComponentConst):
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)
253
254 @property
255 def output_ports(self):
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,
261 bt2_port._OutputPortConst,
262 )
263
264
265 # This is analogous to _FilterComponentClassConst, but for filter
266 # component objects.
267 class _GenericFilterComponentConst(bt2_object._SharedObject, _FilterComponentConst):
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)
275
276 @property
277 def output_ports(self):
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,
283 bt2_port._OutputPortConst,
284 )
285
286 @property
287 def input_ports(self):
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,
293 bt2_port._InputPortConst,
294 )
295
296
297 # This is analogous to _SinkComponentClassConst, but for sink
298 # component objects.
299 class _GenericSinkComponentConst(bt2_object._SharedObject, _SinkComponentConst):
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)
307
308 @property
309 def input_ports(self):
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,
315 bt2_port._InputPortConst,
316 )
317
318
319 _COMP_CLS_TYPE_TO_GENERIC_COMP_PYCLS = {
320 native_bt.COMPONENT_CLASS_TYPE_SOURCE: _GenericSourceComponentConst,
321 native_bt.COMPONENT_CLASS_TYPE_FILTER: _GenericFilterComponentConst,
322 native_bt.COMPONENT_CLASS_TYPE_SINK: _GenericSinkComponentConst,
323 }
324
325
326 _COMP_CLS_TYPE_TO_GENERIC_COMP_CLS_PYCLS = {
327 native_bt.COMPONENT_CLASS_TYPE_SOURCE: _SourceComponentClassConst,
328 native_bt.COMPONENT_CLASS_TYPE_FILTER: _FilterComponentClassConst,
329 native_bt.COMPONENT_CLASS_TYPE_SINK: _SinkComponentClassConst,
330 }
331
332
333 # Create a component Python object of type _GenericSourceComponentConst,
334 # _GenericFilterComponentConst or _GenericSinkComponentConst, depending on
335 # comp_cls_type.
336 #
337 # Steals the reference to ptr from the caller.
338
339
340 def _create_component_from_const_ptr(ptr, comp_cls_type):
341 return _COMP_CLS_TYPE_TO_GENERIC_COMP_PYCLS[comp_cls_type]._create_from_ptr(ptr)
342
343
344 # Same as the above, but acquire a new reference instead of stealing the
345 # reference from the caller.
346
347
348 def _create_component_from_const_ptr_and_get_ref(ptr, comp_cls_type):
349 return _COMP_CLS_TYPE_TO_GENERIC_COMP_PYCLS[
350 comp_cls_type
351 ]._create_from_ptr_and_get_ref(ptr)
352
353
354 # Create a component class Python object of type
355 # _SourceComponentClassConst, _FilterComponentClassConst or
356 # _SinkComponentClassConst, depending on comp_cls_type.
357 #
358 # Acquires a new reference to ptr.
359
360
361 def _create_component_class_from_const_ptr_and_get_ref(ptr, comp_cls_type):
362 return _COMP_CLS_TYPE_TO_GENERIC_COMP_CLS_PYCLS[
363 comp_cls_type
364 ]._create_from_ptr_and_get_ref(ptr)
365
366
367 def _trim_docstring(docstring):
368 lines = docstring.expandtabs().splitlines()
369
370 if len(lines) == 0:
371 return ""
372
373 indent = sys.maxsize
374
375 if len(lines) > 1:
376 for line in lines[1:]:
377 stripped = line.lstrip()
378
379 if stripped:
380 indent = min(indent, len(line) - len(stripped))
381
382 trimmed = [lines[0].strip()]
383
384 if indent < sys.maxsize and len(lines) > 1:
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
394 return "\n".join(trimmed)
395
396
397 # Metaclass for component classes defined by Python code.
398 #
399 # The Python user can create a standard Python class which inherits one
400 # of the three base classes (_UserSourceComponent, _UserFilterComponent,
401 # or _UserSinkComponent). Those base classes set this class
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
409 # the _ComponentClassConst interface.
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
429 # which must accept the following parameters:
430 #
431 # def __init__(self, config, params, obj):
432 # ...
433 #
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.
442 #
443 # User-defined source and filter component classes must use the
444 # `message_iterator_class` class parameter to specify the
445 # message iterator class to use for this component class:
446 #
447 # class MyMessageIterator(bt2._UserMessageIterator):
448 # ...
449 #
450 # class MySource(bt2._UserSourceComponent,
451 # message_iterator_class=MyMessageIterator):
452 # ...
453 #
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`.
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).
469 class _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
478 own_bases = (
479 "_UserComponent",
480 "_UserFilterSinkComponent",
481 "_UserSourceComponent",
482 "_UserFilterComponent",
483 "_UserSinkComponent",
484 )
485
486 if class_name in own_bases:
487 return
488
489 comp_cls_name = kwargs.get("name", class_name)
490 bt2_utils._check_str(comp_cls_name)
491 comp_cls_descr = None
492 comp_cls_help = None
493
494 if hasattr(cls, "__doc__") and cls.__doc__ is not None:
495 bt2_utils._check_str(cls.__doc__)
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:
503 comp_cls_help = "\n".join(lines[2:])
504
505 iter_cls = kwargs.get("message_iterator_class")
506
507 if _UserSourceComponent in bases:
508 _UserComponentType._bt_set_iterator_class(cls, iter_cls)
509 cc_ptr = native_bt.bt2_component_class_source_create(
510 cls, comp_cls_name, comp_cls_descr, comp_cls_help
511 )
512 elif _UserFilterComponent in bases:
513 _UserComponentType._bt_set_iterator_class(cls, iter_cls)
514 cc_ptr = native_bt.bt2_component_class_filter_create(
515 cls, comp_cls_name, comp_cls_descr, comp_cls_help
516 )
517 elif _UserSinkComponent in bases:
518 if not hasattr(cls, "_user_consume"):
519 raise _IncompleteUserClass(
520 "cannot create component class '{}': missing a _user_consume() method".format(
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 )
528 else:
529 raise _IncompleteUserClass(
530 "cannot find a known component class base in the bases of '{}'".format(
531 class_name
532 )
533 )
534
535 if cc_ptr is None:
536 raise bt2_error._MemoryError(
537 "cannot create component class '{}'".format(class_name)
538 )
539
540 cls._bt_cc_ptr = cc_ptr
541
542 def _bt_init_from_native(cls, comp_ptr, params_ptr, obj):
543 # create instance, not user-initialized yet
544 self = cls.__new__(cls)
545
546 # config object
547 config = cls._config_pycls()
548
549 # pointer to native self component object (weak/borrowed)
550 self._bt_ptr = comp_ptr
551
552 # call user's __init__() method
553 if params_ptr is not None:
554 params = bt2_value._create_from_const_ptr_and_get_ref(params_ptr)
555 else:
556 params = None
557
558 self.__init__(config, params, obj)
559 return self
560
561 def __call__(cls, *args, **kwargs):
562 raise RuntimeError(
563 "cannot directly instantiate a user component from a Python module"
564 )
565
566 @staticmethod
567 def _bt_set_iterator_class(cls, iter_cls):
568 if iter_cls is None:
569 raise _IncompleteUserClass(
570 "cannot create component class '{}': missing message iterator class".format(
571 cls.__name__
572 )
573 )
574
575 if not issubclass(iter_cls, bt2_message_iterator._UserMessageIterator):
576 raise _IncompleteUserClass(
577 "cannot create component class '{}': message iterator class does not inherit bt2._UserMessageIterator".format(
578 cls.__name__
579 )
580 )
581
582 if not hasattr(iter_cls, "__next__"):
583 raise _IncompleteUserClass(
584 "cannot create component class '{}': message iterator class is missing a __next__() method".format(
585 cls.__name__
586 )
587 )
588
589 if hasattr(iter_cls, "_user_can_seek_ns_from_origin") and not hasattr(
590 iter_cls, "_user_seek_ns_from_origin"
591 ):
592 raise _IncompleteUserClass(
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
598 if hasattr(iter_cls, "_user_can_seek_beginning") and not hasattr(
599 iter_cls, "_user_seek_beginning"
600 ):
601 raise _IncompleteUserClass(
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
607 cls._iter_cls = iter_cls
608
609 @property
610 def name(cls):
611 ptr = cls._bt_as_component_class_ptr(cls._bt_cc_ptr)
612 return native_bt.component_class_get_name(ptr)
613
614 @property
615 def description(cls):
616 ptr = cls._bt_as_component_class_ptr(cls._bt_cc_ptr)
617 return native_bt.component_class_get_description(ptr)
618
619 @property
620 def help(cls):
621 ptr = cls._bt_as_component_class_ptr(cls._bt_cc_ptr)
622 return native_bt.component_class_get_help(ptr)
623
624 @property
625 def addr(cls):
626 return int(cls._bt_cc_ptr)
627
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:
631 params = bt2_value._create_from_const_ptr_and_get_ref(params_ptr)
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
638 if type(range_set) is not bt2_integer_range_set.UnsignedIntegerRangeSet:
639 # this can raise, but the native side checks the exception
640 range_set = bt2_integer_range_set.UnsignedIntegerRangeSet(range_set)
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
649 def _bt_query_from_native(
650 cls, priv_query_exec_ptr, object_name, params_ptr, method_obj
651 ):
652 # this can raise, but the native side checks the exception
653 if params_ptr is not None:
654 params = bt2_value._create_from_const_ptr_and_get_ref(params_ptr)
655 else:
656 params = None
657
658 priv_query_exec = bt2_query_executor._PrivateQueryExecutor(priv_query_exec_ptr)
659
660 try:
661 # this can raise, but the native side checks the exception
662 results = cls._user_query(priv_query_exec, object_name, params, method_obj)
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()
671
672 # this can raise, but the native side checks the exception
673 results = bt2_value.create_value(results)
674
675 if results is None:
676 results_ptr = native_bt.value_null
677 else:
678 results_ptr = results._ptr
679
680 # return new reference
681 bt2_value._Value._get_ref(results_ptr)
682 return int(results_ptr)
683
684 def _user_query(cls, priv_query_executor, object_name, params, method_obj):
685 raise bt2_utils.UnknownObject
686
687 def _bt_component_class_ptr(self):
688 return self._bt_as_component_class_ptr(self._bt_cc_ptr)
689
690 def __del__(cls):
691 if hasattr(cls, "_bt_cc_ptr"):
692 cc_ptr = cls._bt_as_component_class_ptr(cls._bt_cc_ptr)
693 native_bt.component_class_put_ref(cc_ptr)
694 native_bt.bt2_unregister_cc_ptr_to_py_cls(cc_ptr)
695
696
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
704 class _UserComponentConfiguration:
705 pass
706
707
708 class _UserSourceComponentConfiguration(_UserComponentConfiguration):
709 pass
710
711
712 class _UserFilterComponentConfiguration(_UserComponentConfiguration):
713 pass
714
715
716 class _UserSinkComponentConfiguration(_UserComponentConfiguration):
717 pass
718
719
720 # Subclasses must provide these methods or property:
721 #
722 # - _bt_as_not_self_specific_component_ptr: static method, must return the passed
723 # specialized self component pointer (e.g. 'bt_self_component_sink *') as a
724 # specialized non-self pointer (e.g. 'bt_component_sink *').
725 # - _bt_borrow_component_class_ptr: static method, must return a pointer to the
726 # specialized component class (e.g. 'bt_component_class_sink *') of the
727 # passed specialized component pointer (e.g. 'bt_component_sink *').
728 # - _bt_comp_cls_type: property, one of the native_bt.COMPONENT_CLASS_TYPE_*
729 # constants.
730
731
732 class _UserComponent(metaclass=_UserComponentType):
733 @property
734 def name(self):
735 ptr = self._bt_as_not_self_specific_component_ptr(self._bt_ptr)
736 ptr = self._bt_as_component_ptr(ptr)
737 name = native_bt.component_get_name(ptr)
738 assert name is not None
739 return name
740
741 @property
742 def logging_level(self):
743 ptr = self._bt_as_not_self_specific_component_ptr(self._bt_ptr)
744 ptr = self._bt_as_component_ptr(ptr)
745 return native_bt.component_get_logging_level(ptr)
746
747 @property
748 def cls(self):
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)
751 return _create_component_class_from_const_ptr_and_get_ref(
752 cc_ptr, self._bt_comp_cls_type
753 )
754
755 @property
756 def addr(self):
757 return int(self._bt_ptr)
758
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
764 def __init__(self, config, params, obj):
765 pass
766
767 def _user_finalize(self):
768 pass
769
770 def _user_port_connected(self, port, other_port):
771 pass
772
773 def _bt_port_connected_from_native(
774 self, self_port_ptr, self_port_type, other_port_ptr
775 ):
776 port = bt2_port._create_self_from_ptr_and_get_ref(self_port_ptr, self_port_type)
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
783 other_port = bt2_port._create_from_const_ptr_and_get_ref(
784 other_port_ptr, other_port_type
785 )
786 self._user_port_connected(port, other_port)
787
788 def _create_trace_class(
789 self, user_attributes=None, assigns_automatic_stream_class_id=True
790 ):
791 ptr = self._bt_as_self_component_ptr(self._bt_ptr)
792 tc_ptr = native_bt.trace_class_create(ptr)
793
794 if tc_ptr is None:
795 raise bt2_error._MemoryError("could not create trace class")
796
797 tc = bt2_trace_class._TraceClass._create_from_ptr(tc_ptr)
798 tc._assigns_automatic_stream_class_id = assigns_automatic_stream_class_id
799
800 if user_attributes is not None:
801 tc._user_attributes = user_attributes
802
803 return tc
804
805 def _create_clock_class(
806 self,
807 frequency=None,
808 name=None,
809 user_attributes=None,
810 description=None,
811 precision=None,
812 offset=None,
813 origin_is_unix_epoch=True,
814 uuid=None,
815 ):
816 ptr = self._bt_as_self_component_ptr(self._bt_ptr)
817 cc_ptr = native_bt.clock_class_create(ptr)
818
819 if cc_ptr is None:
820 raise bt2_error._MemoryError("could not create clock class")
821
822 cc = bt2_clock_class._ClockClass._create_from_ptr(cc_ptr)
823
824 if frequency is not None:
825 cc._frequency = frequency
826
827 if name is not None:
828 cc._name = name
829
830 if user_attributes is not None:
831 cc._user_attributes = user_attributes
832
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
847 return cc
848
849
850 class _UserSourceComponent(_UserComponent, _SourceComponentConst):
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 )
857 _config_pycls = _UserSourceComponentConfiguration
858
859 @property
860 def _output_ports(self):
861 def get_output_port_count(self_ptr):
862 ptr = self._bt_as_not_self_specific_component_ptr(self_ptr)
863 return native_bt.component_source_get_output_port_count(ptr)
864
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,
870 bt2_port._UserComponentOutputPort,
871 )
872
873 def _add_output_port(self, name, user_data=None):
874 bt2_utils._check_str(name)
875
876 if name in self._output_ports:
877 raise ValueError(
878 "source component `{}` already contains an output port named `{}`".format(
879 self.name, name
880 )
881 )
882
883 fn = native_bt.self_component_source_add_output_port
884 comp_status, self_port_ptr = fn(self._bt_ptr, name, user_data)
885 bt2_utils._handle_func_status(
886 comp_status, "cannot add output port to source component object"
887 )
888 assert self_port_ptr is not None
889 return bt2_port._UserComponentOutputPort._create_from_ptr_and_get_ref(
890 self_port_ptr
891 )
892
893
894 class _UserFilterComponent(_UserComponent, _FilterComponentConst):
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 )
901 _config_pycls = _UserFilterComponentConfiguration
902
903 @property
904 def _output_ports(self):
905 def get_output_port_count(self_ptr):
906 ptr = self._bt_as_not_self_specific_component_ptr(self_ptr)
907 return native_bt.component_filter_get_output_port_count(ptr)
908
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,
914 bt2_port._UserComponentOutputPort,
915 )
916
917 @property
918 def _input_ports(self):
919 def get_input_port_count(self_ptr):
920 ptr = self._bt_as_not_self_specific_component_ptr(self_ptr)
921 return native_bt.component_filter_get_input_port_count(ptr)
922
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,
928 bt2_port._UserComponentInputPort,
929 )
930
931 def _add_output_port(self, name, user_data=None):
932 bt2_utils._check_str(name)
933
934 if name in self._output_ports:
935 raise ValueError(
936 "filter component `{}` already contains an output port named `{}`".format(
937 self.name, name
938 )
939 )
940
941 fn = native_bt.self_component_filter_add_output_port
942 comp_status, self_port_ptr = fn(self._bt_ptr, name, user_data)
943 bt2_utils._handle_func_status(
944 comp_status, "cannot add output port to filter component object"
945 )
946 assert self_port_ptr
947 return bt2_port._UserComponentOutputPort._create_from_ptr_and_get_ref(
948 self_port_ptr
949 )
950
951 def _add_input_port(self, name, user_data=None):
952 bt2_utils._check_str(name)
953
954 if name in self._input_ports:
955 raise ValueError(
956 "filter component `{}` already contains an input port named `{}`".format(
957 self.name, name
958 )
959 )
960
961 fn = native_bt.self_component_filter_add_input_port
962 comp_status, self_port_ptr = fn(self._bt_ptr, name, user_data)
963 bt2_utils._handle_func_status(
964 comp_status, "cannot add input port to filter component object"
965 )
966 assert self_port_ptr
967 return bt2_port._UserComponentInputPort._create_from_ptr_and_get_ref(
968 self_port_ptr
969 )
970
971
972 class _UserSinkComponent(_UserComponent, _SinkComponentConst):
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 )
979 _config_pycls = _UserSinkComponentConfiguration
980
981 def _bt_graph_is_configured_from_native(self):
982 self._user_graph_is_configured()
983
984 def _user_graph_is_configured(self):
985 pass
986
987 @property
988 def _input_ports(self):
989 def get_input_port_count(self_ptr):
990 ptr = self._bt_as_not_self_specific_component_ptr(self_ptr)
991 return native_bt.component_sink_get_input_port_count(ptr)
992
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,
998 bt2_port._UserComponentInputPort,
999 )
1000
1001 def _add_input_port(self, name, user_data=None):
1002 bt2_utils._check_str(name)
1003
1004 if name in self._input_ports:
1005 raise ValueError(
1006 "sink component `{}` already contains an input port named `{}`".format(
1007 self.name, name
1008 )
1009 )
1010
1011 fn = native_bt.self_component_sink_add_input_port
1012 comp_status, self_port_ptr = fn(self._bt_ptr, name, user_data)
1013 bt2_utils._handle_func_status(
1014 comp_status, "cannot add input port to sink component object"
1015 )
1016 assert self_port_ptr
1017 return bt2_port._UserComponentInputPort._create_from_ptr_and_get_ref(
1018 self_port_ptr
1019 )
1020
1021 def _create_message_iterator(self, input_port):
1022 bt2_utils._check_type(input_port, bt2_port._UserComponentInputPort)
1023
1024 if not input_port.is_connected:
1025 raise ValueError("input port is not connected")
1026
1027 (
1028 status,
1029 msg_iter_ptr,
1030 ) = native_bt.bt2_message_iterator_create_from_sink_component(
1031 self._bt_ptr, input_port._ptr
1032 )
1033 bt2_utils._handle_func_status(status, "cannot create message iterator object")
1034 assert msg_iter_ptr is not None
1035
1036 return bt2_message_iterator._UserComponentInputPortMessageIterator(msg_iter_ptr)
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.05466 seconds and 3 git commands to generate.