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