Fix: src.ctf.fs: initialize the other_entry variable
[babeltrace.git] / src / bindings / python / bt2 / bt2 / trace_collection_message_iterator.py
CommitLineData
85dcce24
PP
1# The MIT License (MIT)
2#
3# Copyright (c) 2017 Philippe Proulx <pproulx@efficios.com>
4#
5# Permission is hereby granted, free of charge, to any person obtaining a copy
6# of this software and associated documentation files (the "Software"), to deal
7# in the Software without restriction, including without limitation the rights
8# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9# copies of the Software, and to permit persons to whom the Software is
10# furnished to do so, subject to the following conditions:
11#
12# The above copyright notice and this permission notice shall be included in
13# all copies or substantial portions of the Software.
14#
15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21# THE SOFTWARE.
22
f3c9a159 23from bt2 import utils, native_bt
85dcce24 24import bt2
3d60267b 25import itertools
3fb99a22 26from bt2 import message_iterator as bt2_message_iterator
3fb99a22 27from bt2 import port as bt2_port
c1859f69 28from bt2 import component as bt2_component
f3c9a159
SM
29from bt2 import value as bt2_value
30from bt2 import plugin as bt2_plugin
85dcce24 31import datetime
85dcce24
PP
32from collections import namedtuple
33import numbers
34
35
3d60267b
PP
36# a pair of component and ComponentSpec
37_ComponentAndSpec = namedtuple('_ComponentAndSpec', ['comp', 'spec'])
85dcce24
PP
38
39
f3c9a159 40class _BaseComponentSpec:
c87f23fa
SM
41 # Base for any component spec that can be passed to
42 # TraceCollectionMessageIterator.
f3c9a159
SM
43 def __init__(self, params, obj, logging_level):
44 if logging_level is not None:
45 utils._check_log_level(logging_level)
46
47 self._params = bt2.create_value(params)
48 self._obj = obj
49 self._logging_level = logging_level
50
51 @property
52 def params(self):
53 return self._params
54
55 @property
56 def obj(self):
57 return self._obj
58
59 @property
60 def logging_level(self):
61 return self._logging_level
62
63
64class ComponentSpec(_BaseComponentSpec):
c87f23fa 65 # A component spec with a specific component class.
cfbd7cf3
FD
66 def __init__(
67 self,
c87f23fa 68 component_class,
cfbd7cf3 69 params=None,
66964f3f 70 obj=None,
c87f23fa 71 logging_level=bt2.LoggingLevel.NONE,
cfbd7cf3 72 ):
f3c9a159
SM
73 if type(params) is str:
74 params = {'inputs': [params]}
75
76 super().__init__(params, obj, logging_level)
77
c87f23fa 78 is_cc_object = isinstance(
615238be
FD
79 component_class,
80 (bt2._SourceComponentClassConst, bt2._FilterComponentClassConst),
c87f23fa
SM
81 )
82 is_user_cc_type = isinstance(
83 component_class, bt2_component._UserComponentType
84 ) and issubclass(
85 component_class, (bt2._UserSourceComponent, bt2._UserFilterComponent)
86 )
f3c9a159 87
c87f23fa
SM
88 if not is_cc_object and not is_user_cc_type:
89 raise TypeError(
90 "'{}' is not a source or filter component class".format(
91 component_class.__class__.__name__
92 )
93 )
85dcce24 94
c87f23fa 95 self._component_class = component_class
85dcce24
PP
96
97 @property
c87f23fa
SM
98 def component_class(self):
99 return self._component_class
100
101 @classmethod
102 def from_named_plugin_and_component_class(
103 cls,
104 plugin_name,
105 component_class_name,
106 params=None,
107 obj=None,
108 logging_level=bt2.LoggingLevel.NONE,
109 ):
110 plugin = bt2.find_plugin(plugin_name)
111
112 if plugin is None:
113 raise ValueError('no such plugin: {}'.format(plugin_name))
114
115 if component_class_name in plugin.source_component_classes:
116 comp_class = plugin.source_component_classes[component_class_name]
117 elif component_class_name in plugin.filter_component_classes:
118 comp_class = plugin.filter_component_classes[component_class_name]
119 else:
120 raise KeyError(
121 'source or filter component class `{}` not found in plugin `{}`'.format(
122 component_class_name, plugin_name
123 )
124 )
125
126 return cls(comp_class, params, obj, logging_level)
85dcce24 127
e874da19 128
f3c9a159 129class AutoSourceComponentSpec(_BaseComponentSpec):
c87f23fa 130 # A component spec that does automatic source discovery.
f3c9a159
SM
131 _no_obj = object()
132
133 def __init__(self, input, params=None, obj=_no_obj, logging_level=None):
134 super().__init__(params, obj, logging_level)
135 self._input = input
85dcce24 136
66964f3f 137 @property
f3c9a159
SM
138 def input(self):
139 return self._input
140
141
142def _auto_discover_source_component_specs(auto_source_comp_specs, plugin_set):
143 # Transform a list of `AutoSourceComponentSpec` in a list of `ComponentSpec`
144 # using the automatic source discovery mechanism.
145 inputs = bt2.ArrayValue([spec.input for spec in auto_source_comp_specs])
146
147 if plugin_set is None:
148 plugin_set = bt2.find_plugins()
149 else:
150 utils._check_type(plugin_set, bt2_plugin._PluginSet)
151
152 res_ptr = native_bt.bt2_auto_discover_source_components(
153 inputs._ptr, plugin_set._ptr
154 )
155
156 if res_ptr is None:
157 raise bt2._MemoryError('cannot auto discover source components')
158
159 res = bt2_value._create_from_ptr(res_ptr)
160
161 assert type(res) == bt2.MapValue
162 assert 'status' in res
163
164 status = res['status']
165 utils._handle_func_status(status, 'cannot auto-discover source components')
166
167 comp_specs = []
168 comp_specs_raw = res['results']
169 assert type(comp_specs_raw) == bt2.ArrayValue
170
39b351f9
SM
171 used_input_indices = set()
172
f3c9a159
SM
173 for comp_spec_raw in comp_specs_raw:
174 assert type(comp_spec_raw) == bt2.ArrayValue
175 assert len(comp_spec_raw) == 4
176
177 plugin_name = comp_spec_raw[0]
178 assert type(plugin_name) == bt2.StringValue
179 plugin_name = str(plugin_name)
180
181 class_name = comp_spec_raw[1]
182 assert type(class_name) == bt2.StringValue
183 class_name = str(class_name)
184
185 comp_inputs = comp_spec_raw[2]
186 assert type(comp_inputs) == bt2.ArrayValue
187
188 comp_orig_indices = comp_spec_raw[3]
189 assert type(comp_orig_indices)
190
191 params = bt2.MapValue()
192 logging_level = bt2.LoggingLevel.NONE
193 obj = None
194
195 # Compute `params` for this component by piling up params given to all
196 # AutoSourceComponentSpec objects that contributed in the instantiation
197 # of this component.
198 #
199 # The effective log level for a component is the last one specified
200 # across the AutoSourceComponentSpec that contributed in its
201 # instantiation.
202 for idx in comp_orig_indices:
203 orig_spec = auto_source_comp_specs[idx]
204
205 if orig_spec.params is not None:
206 params.update(orig_spec.params)
207
208 if orig_spec.logging_level is not None:
209 logging_level = orig_spec.logging_level
210
211 if orig_spec.obj is not AutoSourceComponentSpec._no_obj:
212 obj = orig_spec.obj
213
39b351f9
SM
214 used_input_indices.add(int(idx))
215
f3c9a159
SM
216 params['inputs'] = comp_inputs
217
218 comp_specs.append(
c87f23fa 219 ComponentSpec.from_named_plugin_and_component_class(
f3c9a159
SM
220 plugin_name,
221 class_name,
222 params=params,
223 obj=obj,
224 logging_level=logging_level,
225 )
226 )
227
39b351f9
SM
228 if len(used_input_indices) != len(inputs):
229 unused_input_indices = set(range(len(inputs))) - used_input_indices
230 unused_input_indices = sorted(unused_input_indices)
231 unused_inputs = [str(inputs[x]) for x in unused_input_indices]
232
233 msg = (
234 'Some auto source component specs did not produce any component: '
235 + ', '.join(unused_inputs)
236 )
237 raise RuntimeError(msg)
238
f3c9a159 239 return comp_specs
66964f3f 240
85dcce24
PP
241
242# datetime.datetime or integral to nanoseconds
243def _get_ns(obj):
244 if obj is None:
245 return
246
247 if isinstance(obj, numbers.Real):
248 # consider that it's already in seconds
249 s = obj
250 elif isinstance(obj, datetime.datetime):
251 # s -> ns
252 s = obj.timestamp()
253 else:
cfbd7cf3
FD
254 raise TypeError(
255 '"{}" is not an integral number or a datetime.datetime object'.format(obj)
256 )
85dcce24
PP
257
258 return int(s * 1e9)
259
260
c1859f69 261class _TraceCollectionMessageIteratorProxySink(bt2_component._UserSinkComponent):
59225a3e 262 def __init__(self, config, params, msg_list):
c1859f69
PP
263 assert type(msg_list) is list
264 self._msg_list = msg_list
265 self._add_input_port('in')
266
267 def _user_graph_is_configured(self):
9a2c8b8e 268 self._msg_iter = self._create_message_iterator(self._input_ports['in'])
c1859f69
PP
269
270 def _user_consume(self):
271 assert self._msg_list[0] is None
272 self._msg_list[0] = next(self._msg_iter)
273
274
3fb99a22 275class TraceCollectionMessageIterator(bt2_message_iterator._MessageIterator):
cfbd7cf3
FD
276 def __init__(
277 self,
278 source_component_specs,
279 filter_component_specs=None,
280 stream_intersection_mode=False,
281 begin=None,
282 end=None,
f3c9a159 283 plugin_set=None,
cfbd7cf3 284 ):
85dcce24
PP
285 utils._check_bool(stream_intersection_mode)
286 self._stream_intersection_mode = stream_intersection_mode
287 self._begin_ns = _get_ns(begin)
288 self._end_ns = _get_ns(end)
c1859f69 289 self._msg_list = [None]
3d60267b 290
f3c9a159
SM
291 # If a single item is provided, convert to a list.
292 if type(source_component_specs) in (
293 ComponentSpec,
294 AutoSourceComponentSpec,
295 str,
296 ):
3d60267b
PP
297 source_component_specs = [source_component_specs]
298
f3c9a159
SM
299 # Convert any string to an AutoSourceComponentSpec.
300 def str_to_auto(item):
301 if type(item) is str:
302 item = AutoSourceComponentSpec(item)
303
304 return item
305
306 source_component_specs = [str_to_auto(s) for s in source_component_specs]
307
3d60267b
PP
308 if type(filter_component_specs) is ComponentSpec:
309 filter_component_specs = [filter_component_specs]
310 elif filter_component_specs is None:
311 filter_component_specs = []
312
f3c9a159
SM
313 self._validate_source_component_specs(source_component_specs)
314 self._validate_filter_component_specs(filter_component_specs)
315
316 # Pass any `ComponentSpec` instance as-is.
317 self._src_comp_specs = [
318 spec for spec in source_component_specs if type(spec) is ComponentSpec
319 ]
320
321 # Convert any `AutoSourceComponentSpec` in concrete `ComponentSpec` instances.
322 auto_src_comp_specs = [
323 spec
324 for spec in source_component_specs
325 if type(spec) is AutoSourceComponentSpec
326 ]
327 self._src_comp_specs += _auto_discover_source_component_specs(
328 auto_src_comp_specs, plugin_set
329 )
330
3d60267b 331 self._flt_comp_specs = filter_component_specs
85dcce24
PP
332 self._next_suffix = 1
333 self._connect_ports = False
334
3d60267b 335 # lists of _ComponentAndSpec
85dcce24 336 self._src_comps_and_specs = []
3d60267b 337 self._flt_comps_and_specs = []
85dcce24 338
85dcce24
PP
339 self._build_graph()
340
30947af0
SM
341 def _compute_stream_intersections(self):
342 # Pre-compute the trimmer range to use for each port in the graph, when
343 # stream intersection mode is enabled.
344 self._stream_inter_port_to_range = {}
345
346 for src_comp_and_spec in self._src_comps_and_specs:
5f2a1585 347 # Query the port's component for the `babeltrace.trace-infos`
30947af0
SM
348 # object which contains the range for each stream, from which we can
349 # compute the intersection of the streams in each trace.
350 query_exec = bt2.QueryExecutor(
3f3d89b4 351 src_comp_and_spec.spec.component_class,
5f2a1585 352 'babeltrace.trace-infos',
3f3d89b4 353 src_comp_and_spec.spec.params,
30947af0
SM
354 )
355 trace_infos = query_exec.query()
356
357 for trace_info in trace_infos:
358 begin = max(
5f2a1585
SM
359 [
360 stream['range-ns']['begin']
361 for stream in trace_info['stream-infos']
362 ]
30947af0
SM
363 )
364 end = min(
5f2a1585 365 [stream['range-ns']['end'] for stream in trace_info['stream-infos']]
30947af0
SM
366 )
367
368 # Each port associated to this trace will have this computed
369 # range.
5f2a1585 370 for stream in trace_info['stream-infos']:
30947af0
SM
371 # A port name is unique within a component, but not
372 # necessarily across all components. Use a component
373 # and port name pair to make it unique across the graph.
374 port_name = str(stream['port-name'])
375 key = (src_comp_and_spec.comp.addr, port_name)
376 self._stream_inter_port_to_range[key] = (begin, end)
377
f3c9a159
SM
378 def _validate_source_component_specs(self, comp_specs):
379 for comp_spec in comp_specs:
380 if (
381 type(comp_spec) is not ComponentSpec
382 and type(comp_spec) is not AutoSourceComponentSpec
383 ):
384 raise TypeError(
385 '"{}" object is not a ComponentSpec or AutoSourceComponentSpec'.format(
386 type(comp_spec)
387 )
388 )
389
390 def _validate_filter_component_specs(self, comp_specs):
3d60267b
PP
391 for comp_spec in comp_specs:
392 if type(comp_spec) is not ComponentSpec:
cfbd7cf3
FD
393 raise TypeError(
394 '"{}" object is not a ComponentSpec'.format(type(comp_spec))
395 )
85dcce24
PP
396
397 def __next__(self):
c1859f69
PP
398 assert self._msg_list[0] is None
399 self._graph.run_once()
400 msg = self._msg_list[0]
401 assert msg is not None
402 self._msg_list[0] = None
403 return msg
85dcce24 404
907f2b70 405 def _create_stream_intersection_trimmer(self, component, port):
30947af0
SM
406 key = (component.addr, port.name)
407 begin, end = self._stream_inter_port_to_range[key]
408 name = 'trimmer-{}-{}'.format(component.name, port.name)
85dcce24
PP
409 return self._create_trimmer(begin, end, name)
410
411 def _create_muxer(self):
412 plugin = bt2.find_plugin('utils')
413
414 if plugin is None:
ce4923b0 415 raise RuntimeError('cannot find "utils" plugin (needed for the muxer)')
85dcce24
PP
416
417 if 'muxer' not in plugin.filter_component_classes:
ce4923b0 418 raise RuntimeError(
cfbd7cf3
FD
419 'cannot find "muxer" filter component class in "utils" plugin'
420 )
85dcce24
PP
421
422 comp_cls = plugin.filter_component_classes['muxer']
423 return self._graph.add_component(comp_cls, 'muxer')
424
907f2b70 425 def _create_trimmer(self, begin_ns, end_ns, name):
85dcce24
PP
426 plugin = bt2.find_plugin('utils')
427
428 if plugin is None:
ce4923b0 429 raise RuntimeError('cannot find "utils" plugin (needed for the trimmer)')
85dcce24
PP
430
431 if 'trimmer' not in plugin.filter_component_classes:
ce4923b0 432 raise RuntimeError(
cfbd7cf3
FD
433 'cannot find "trimmer" filter component class in "utils" plugin'
434 )
85dcce24
PP
435
436 params = {}
437
907f2b70
SM
438 def ns_to_string(ns):
439 s_part = ns // 1000000000
440 ns_part = ns % 1000000000
441 return '{}.{:09d}'.format(s_part, ns_part)
85dcce24 442
907f2b70
SM
443 if begin_ns is not None:
444 params['begin'] = ns_to_string(begin_ns)
445
446 if end_ns is not None:
447 params['end'] = ns_to_string(end_ns)
85dcce24
PP
448
449 comp_cls = plugin.filter_component_classes['trimmer']
450 return self._graph.add_component(comp_cls, name, params)
451
c87f23fa
SM
452 def _get_unique_comp_name(self, comp_cls):
453 name = comp_cls.name
cfbd7cf3
FD
454 comps_and_specs = itertools.chain(
455 self._src_comps_and_specs, self._flt_comps_and_specs
456 )
85dcce24 457
3d60267b 458 if name in [comp_and_spec.comp.name for comp_and_spec in comps_and_specs]:
85dcce24
PP
459 name += '-{}'.format(self._next_suffix)
460 self._next_suffix += 1
461
462 return name
463
c87f23fa
SM
464 def _create_comp(self, comp_spec):
465 comp_cls = comp_spec.component_class
466 name = self._get_unique_comp_name(comp_cls)
cfbd7cf3 467 comp = self._graph.add_component(
66964f3f 468 comp_cls, name, comp_spec.params, comp_spec.obj, comp_spec.logging_level
cfbd7cf3 469 )
85dcce24
PP
470 return comp
471
472 def _get_free_muxer_input_port(self):
473 for port in self._muxer_comp.input_ports.values():
474 if not port.is_connected:
475 return port
476
907f2b70 477 def _connect_src_comp_port(self, component, port):
85dcce24
PP
478 # if this trace collection iterator is in stream intersection
479 # mode, we need this connection:
480 #
481 # port -> trimmer -> muxer
482 #
483 # otherwise, simply:
484 #
485 # port -> muxer
486 if self._stream_intersection_mode:
907f2b70 487 trimmer_comp = self._create_stream_intersection_trimmer(component, port)
85dcce24
PP
488 self._graph.connect_ports(port, trimmer_comp.input_ports['in'])
489 port_to_muxer = trimmer_comp.output_ports['out']
490 else:
491 port_to_muxer = port
492
493 self._graph.connect_ports(port_to_muxer, self._get_free_muxer_input_port())
494
907f2b70 495 def _graph_port_added(self, component, port):
85dcce24
PP
496 if not self._connect_ports:
497 return
498
5813b3a3 499 if type(port) is bt2_port._InputPortConst:
85dcce24
PP
500 return
501
907f2b70 502 if component not in [comp.comp for comp in self._src_comps_and_specs]:
85dcce24
PP
503 # do not care about non-source components (muxer, trimmer, etc.)
504 return
505
907f2b70 506 self._connect_src_comp_port(component, port)
85dcce24 507
2080bf80 508 def _get_greatest_operative_mip_version(self):
c87f23fa 509 def append_comp_specs_descriptors(descriptors, comp_specs):
2080bf80 510 for comp_spec in comp_specs:
2080bf80 511 descriptors.append(
c87f23fa
SM
512 bt2.ComponentDescriptor(
513 comp_spec.component_class, comp_spec.params, comp_spec.obj
514 )
2080bf80
PP
515 )
516
517 descriptors = []
c87f23fa
SM
518 append_comp_specs_descriptors(descriptors, self._src_comp_specs)
519 append_comp_specs_descriptors(descriptors, self._flt_comp_specs)
2080bf80
PP
520
521 if self._stream_intersection_mode:
522 # we also need at least one `flt.utils.trimmer` component
c87f23fa
SM
523 comp_spec = ComponentSpec.from_named_plugin_and_component_class(
524 'utils', 'trimmer'
525 )
526 append_comp_specs_descriptors(descriptors, [comp_spec])
2080bf80
PP
527
528 mip_version = bt2.get_greatest_operative_mip_version(descriptors)
529
530 if mip_version is None:
531 msg = 'failed to find an operative message interchange protocol version (components are not interoperable)'
532 raise RuntimeError(msg)
533
534 return mip_version
535
85dcce24 536 def _build_graph(self):
2080bf80 537 self._graph = bt2.Graph(self._get_greatest_operative_mip_version())
907f2b70 538 self._graph.add_port_added_listener(self._graph_port_added)
85dcce24
PP
539 self._muxer_comp = self._create_muxer()
540
541 if self._begin_ns is not None or self._end_ns is not None:
cfbd7cf3
FD
542 trimmer_comp = self._create_trimmer(self._begin_ns, self._end_ns, 'trimmer')
543 self._graph.connect_ports(
544 self._muxer_comp.output_ports['out'], trimmer_comp.input_ports['in']
545 )
c1859f69 546 last_flt_out_port = trimmer_comp.output_ports['out']
85dcce24 547 else:
c1859f69 548 last_flt_out_port = self._muxer_comp.output_ports['out']
85dcce24 549
3d60267b
PP
550 # create extra filter components (chained)
551 for comp_spec in self._flt_comp_specs:
c87f23fa 552 comp = self._create_comp(comp_spec)
3d60267b
PP
553 self._flt_comps_and_specs.append(_ComponentAndSpec(comp, comp_spec))
554
555 # connect the extra filter chain
556 for comp_and_spec in self._flt_comps_and_specs:
557 in_port = list(comp_and_spec.comp.input_ports.values())[0]
558 out_port = list(comp_and_spec.comp.output_ports.values())[0]
c1859f69
PP
559 self._graph.connect_ports(last_flt_out_port, in_port)
560 last_flt_out_port = out_port
3d60267b 561
85dcce24
PP
562 # Here we create the components, self._graph_port_added() is
563 # called when they add ports, but the callback returns early
564 # because self._connect_ports is False. This is because the
565 # self._graph_port_added() could not find the associated source
566 # component specification in self._src_comps_and_specs because
567 # it does not exist yet (it needs the created component to
568 # exist).
569 for comp_spec in self._src_comp_specs:
c87f23fa 570 comp = self._create_comp(comp_spec)
3d60267b 571 self._src_comps_and_specs.append(_ComponentAndSpec(comp, comp_spec))
85dcce24 572
30947af0
SM
573 if self._stream_intersection_mode:
574 self._compute_stream_intersections()
575
85dcce24
PP
576 # Now we connect the ports which exist at this point. We allow
577 # self._graph_port_added() to automatically connect _new_ ports.
578 self._connect_ports = True
579
580 for comp_and_spec in self._src_comps_and_specs:
581 # Keep a separate list because comp_and_spec.output_ports
582 # could change during the connection of one of its ports.
583 # Any new port is handled by self._graph_port_added().
584 out_ports = [port for port in comp_and_spec.comp.output_ports.values()]
585
586 for out_port in out_ports:
907f2b70 587 if out_port.is_connected:
85dcce24
PP
588 continue
589
907f2b70 590 self._connect_src_comp_port(comp_and_spec.comp, out_port)
85dcce24 591
c1859f69
PP
592 # Add the proxy sink, passing our message list to share consumed
593 # messages with this trace collection message iterator.
594 sink = self._graph.add_component(
595 _TraceCollectionMessageIteratorProxySink, 'proxy-sink', obj=self._msg_list
596 )
597 sink_in_port = sink.input_ports['in']
598
599 # connect last filter to proxy sink
600 self._graph.connect_ports(last_flt_out_port, sink_in_port)
This page took 0.083997 seconds and 4 git commands to generate.