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