test_error.py: remove dangling print()
[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
23from bt2 import utils
24import bt2
3d60267b 25import itertools
5602ef81 26import bt2.message_iterator
85dcce24 27import datetime
85dcce24
PP
28from collections import namedtuple
29import numbers
30
31
3d60267b
PP
32# a pair of component and ComponentSpec
33_ComponentAndSpec = namedtuple('_ComponentAndSpec', ['comp', 'spec'])
85dcce24
PP
34
35
3d60267b 36class ComponentSpec:
cfbd7cf3
FD
37 def __init__(
38 self,
39 plugin_name,
40 class_name,
41 params=None,
42 logging_level=bt2.logging.LoggingLevel.NONE,
43 ):
85dcce24 44 utils._check_str(plugin_name)
e8ac1aae 45 utils._check_str(class_name)
e874da19 46 utils._check_log_level(logging_level)
85dcce24 47 self._plugin_name = plugin_name
e8ac1aae 48 self._class_name = class_name
e874da19 49 self._logging_level = logging_level
85dcce24
PP
50
51 if type(params) is str:
73760435 52 self._params = bt2.create_value({'inputs': [params]})
85dcce24
PP
53 else:
54 self._params = bt2.create_value(params)
55
56 @property
57 def plugin_name(self):
58 return self._plugin_name
59
60 @property
e8ac1aae
PP
61 def class_name(self):
62 return self._class_name
85dcce24 63
e874da19
PP
64 @property
65 def logging_level(self):
66 return self._logging_level
67
85dcce24
PP
68 @property
69 def params(self):
70 return self._params
71
72
73# datetime.datetime or integral to nanoseconds
74def _get_ns(obj):
75 if obj is None:
76 return
77
78 if isinstance(obj, numbers.Real):
79 # consider that it's already in seconds
80 s = obj
81 elif isinstance(obj, datetime.datetime):
82 # s -> ns
83 s = obj.timestamp()
84 else:
cfbd7cf3
FD
85 raise TypeError(
86 '"{}" is not an integral number or a datetime.datetime object'.format(obj)
87 )
85dcce24
PP
88
89 return int(s * 1e9)
90
91
3d60267b
PP
92class _CompClsType:
93 SOURCE = 0
94 FILTER = 1
95
96
5602ef81 97class TraceCollectionMessageIterator(bt2.message_iterator._MessageIterator):
cfbd7cf3
FD
98 def __init__(
99 self,
100 source_component_specs,
101 filter_component_specs=None,
102 stream_intersection_mode=False,
103 begin=None,
104 end=None,
105 ):
85dcce24
PP
106 utils._check_bool(stream_intersection_mode)
107 self._stream_intersection_mode = stream_intersection_mode
108 self._begin_ns = _get_ns(begin)
109 self._end_ns = _get_ns(end)
3d60267b
PP
110
111 if type(source_component_specs) is ComponentSpec:
112 source_component_specs = [source_component_specs]
113
114 if type(filter_component_specs) is ComponentSpec:
115 filter_component_specs = [filter_component_specs]
116 elif filter_component_specs is None:
117 filter_component_specs = []
118
85dcce24 119 self._src_comp_specs = source_component_specs
3d60267b 120 self._flt_comp_specs = filter_component_specs
85dcce24
PP
121 self._next_suffix = 1
122 self._connect_ports = False
123
3d60267b 124 # lists of _ComponentAndSpec
85dcce24 125 self._src_comps_and_specs = []
3d60267b 126 self._flt_comps_and_specs = []
85dcce24 127
3d60267b
PP
128 self._validate_component_specs(source_component_specs)
129 self._validate_component_specs(filter_component_specs)
85dcce24
PP
130 self._build_graph()
131
3d60267b
PP
132 def _validate_component_specs(self, comp_specs):
133 for comp_spec in comp_specs:
134 if type(comp_spec) is not ComponentSpec:
cfbd7cf3
FD
135 raise TypeError(
136 '"{}" object is not a ComponentSpec'.format(type(comp_spec))
137 )
85dcce24
PP
138
139 def __next__(self):
5602ef81 140 return next(self._msg_iter)
85dcce24 141
907f2b70 142 def _create_stream_intersection_trimmer(self, component, port):
85dcce24 143 # find the original parameters specified by the user to create
73760435 144 # this port's component to get the `inputs` parameter
85dcce24 145 for src_comp_and_spec in self._src_comps_and_specs:
907f2b70 146 if component == src_comp_and_spec.comp:
85dcce24
PP
147 break
148
149 try:
73760435 150 inputs = src_comp_and_spec.spec.params['inputs']
907f2b70 151 except Exception as e:
ce4923b0 152 raise ValueError(
73760435 153 'all source components must be created with an "inputs" parameter in stream intersection mode'
cfbd7cf3 154 ) from e
85dcce24 155
73760435 156 params = {'inputs': inputs}
85dcce24
PP
157
158 # query the port's component for the `trace-info` object which
159 # contains the stream intersection range for each exposed
160 # trace
161 query_exec = bt2.QueryExecutor()
cfbd7cf3
FD
162 trace_info_res = query_exec.query(
163 src_comp_and_spec.comp.cls, 'trace-info', params
164 )
85dcce24
PP
165 begin = None
166 end = None
167
a38d7650 168 # find the trace info for this port's trace
87b768aa
PP
169 try:
170 for trace_info in trace_info_res:
a38d7650
SM
171 for stream in trace_info['streams']:
172 if stream['port-name'] == port.name:
173 range_ns = trace_info['intersection-range-ns']
174 begin = range_ns['begin']
175 end = range_ns['end']
176 break
907f2b70 177 except Exception:
87b768aa 178 pass
85dcce24
PP
179
180 if begin is None or end is None:
ce4923b0 181 raise RuntimeError(
cfbd7cf3
FD
182 'cannot find stream intersection range for port "{}"'.format(port.name)
183 )
85dcce24 184
907f2b70 185 name = 'trimmer-{}-{}'.format(src_comp_and_spec.comp.name, port.name)
85dcce24
PP
186 return self._create_trimmer(begin, end, name)
187
188 def _create_muxer(self):
189 plugin = bt2.find_plugin('utils')
190
191 if plugin is None:
ce4923b0 192 raise RuntimeError('cannot find "utils" plugin (needed for the muxer)')
85dcce24
PP
193
194 if 'muxer' not in plugin.filter_component_classes:
ce4923b0 195 raise RuntimeError(
cfbd7cf3
FD
196 'cannot find "muxer" filter component class in "utils" plugin'
197 )
85dcce24
PP
198
199 comp_cls = plugin.filter_component_classes['muxer']
200 return self._graph.add_component(comp_cls, 'muxer')
201
907f2b70 202 def _create_trimmer(self, begin_ns, end_ns, name):
85dcce24
PP
203 plugin = bt2.find_plugin('utils')
204
205 if plugin is None:
ce4923b0 206 raise RuntimeError('cannot find "utils" plugin (needed for the trimmer)')
85dcce24
PP
207
208 if 'trimmer' not in plugin.filter_component_classes:
ce4923b0 209 raise RuntimeError(
cfbd7cf3
FD
210 'cannot find "trimmer" filter component class in "utils" plugin'
211 )
85dcce24
PP
212
213 params = {}
214
907f2b70
SM
215 def ns_to_string(ns):
216 s_part = ns // 1000000000
217 ns_part = ns % 1000000000
218 return '{}.{:09d}'.format(s_part, ns_part)
85dcce24 219
907f2b70
SM
220 if begin_ns is not None:
221 params['begin'] = ns_to_string(begin_ns)
222
223 if end_ns is not None:
224 params['end'] = ns_to_string(end_ns)
85dcce24
PP
225
226 comp_cls = plugin.filter_component_classes['trimmer']
227 return self._graph.add_component(comp_cls, name, params)
228
3d60267b 229 def _get_unique_comp_name(self, comp_spec):
cfbd7cf3
FD
230 name = '{}-{}'.format(comp_spec.plugin_name, comp_spec.class_name)
231 comps_and_specs = itertools.chain(
232 self._src_comps_and_specs, self._flt_comps_and_specs
233 )
85dcce24 234
3d60267b 235 if name in [comp_and_spec.comp.name for comp_and_spec in comps_and_specs]:
85dcce24
PP
236 name += '-{}'.format(self._next_suffix)
237 self._next_suffix += 1
238
239 return name
240
3d60267b 241 def _create_comp(self, comp_spec, comp_cls_type):
85dcce24
PP
242 plugin = bt2.find_plugin(comp_spec.plugin_name)
243
244 if plugin is None:
ce4923b0 245 raise ValueError('no such plugin: {}'.format(comp_spec.plugin_name))
85dcce24 246
3d60267b
PP
247 if comp_cls_type == _CompClsType.SOURCE:
248 comp_classes = plugin.source_component_classes
249 else:
250 comp_classes = plugin.filter_component_classes
251
e8ac1aae 252 if comp_spec.class_name not in comp_classes:
3d60267b 253 cc_type = 'source' if comp_cls_type == _CompClsType.SOURCE else 'filter'
ce4923b0 254 raise ValueError(
cfbd7cf3
FD
255 'no such {} component class in "{}" plugin: {}'.format(
256 cc_type, comp_spec.plugin_name, comp_spec.class_name
257 )
258 )
85dcce24 259
e8ac1aae 260 comp_cls = comp_classes[comp_spec.class_name]
3d60267b 261 name = self._get_unique_comp_name(comp_spec)
cfbd7cf3
FD
262 comp = self._graph.add_component(
263 comp_cls, name, comp_spec.params, comp_spec.logging_level
264 )
85dcce24
PP
265 return comp
266
267 def _get_free_muxer_input_port(self):
268 for port in self._muxer_comp.input_ports.values():
269 if not port.is_connected:
270 return port
271
907f2b70 272 def _connect_src_comp_port(self, component, port):
85dcce24
PP
273 # if this trace collection iterator is in stream intersection
274 # mode, we need this connection:
275 #
276 # port -> trimmer -> muxer
277 #
278 # otherwise, simply:
279 #
280 # port -> muxer
281 if self._stream_intersection_mode:
907f2b70 282 trimmer_comp = self._create_stream_intersection_trimmer(component, port)
85dcce24
PP
283 self._graph.connect_ports(port, trimmer_comp.input_ports['in'])
284 port_to_muxer = trimmer_comp.output_ports['out']
285 else:
286 port_to_muxer = port
287
288 self._graph.connect_ports(port_to_muxer, self._get_free_muxer_input_port())
289
907f2b70 290 def _graph_port_added(self, component, port):
85dcce24
PP
291 if not self._connect_ports:
292 return
293
907f2b70 294 if type(port) is bt2.port._InputPort:
85dcce24
PP
295 return
296
907f2b70 297 if component not in [comp.comp for comp in self._src_comps_and_specs]:
85dcce24
PP
298 # do not care about non-source components (muxer, trimmer, etc.)
299 return
300
907f2b70 301 self._connect_src_comp_port(component, port)
85dcce24
PP
302
303 def _build_graph(self):
304 self._graph = bt2.Graph()
907f2b70 305 self._graph.add_port_added_listener(self._graph_port_added)
85dcce24
PP
306 self._muxer_comp = self._create_muxer()
307
308 if self._begin_ns is not None or self._end_ns is not None:
cfbd7cf3
FD
309 trimmer_comp = self._create_trimmer(self._begin_ns, self._end_ns, 'trimmer')
310 self._graph.connect_ports(
311 self._muxer_comp.output_ports['out'], trimmer_comp.input_ports['in']
312 )
5602ef81 313 msg_iter_port = trimmer_comp.output_ports['out']
85dcce24 314 else:
5602ef81 315 msg_iter_port = self._muxer_comp.output_ports['out']
85dcce24 316
3d60267b
PP
317 # create extra filter components (chained)
318 for comp_spec in self._flt_comp_specs:
319 comp = self._create_comp(comp_spec, _CompClsType.FILTER)
320 self._flt_comps_and_specs.append(_ComponentAndSpec(comp, comp_spec))
321
322 # connect the extra filter chain
323 for comp_and_spec in self._flt_comps_and_specs:
324 in_port = list(comp_and_spec.comp.input_ports.values())[0]
325 out_port = list(comp_and_spec.comp.output_ports.values())[0]
5602ef81
SM
326 self._graph.connect_ports(msg_iter_port, in_port)
327 msg_iter_port = out_port
3d60267b 328
85dcce24
PP
329 # Here we create the components, self._graph_port_added() is
330 # called when they add ports, but the callback returns early
331 # because self._connect_ports is False. This is because the
332 # self._graph_port_added() could not find the associated source
333 # component specification in self._src_comps_and_specs because
334 # it does not exist yet (it needs the created component to
335 # exist).
336 for comp_spec in self._src_comp_specs:
3d60267b
PP
337 comp = self._create_comp(comp_spec, _CompClsType.SOURCE)
338 self._src_comps_and_specs.append(_ComponentAndSpec(comp, comp_spec))
85dcce24
PP
339
340 # Now we connect the ports which exist at this point. We allow
341 # self._graph_port_added() to automatically connect _new_ ports.
342 self._connect_ports = True
343
344 for comp_and_spec in self._src_comps_and_specs:
345 # Keep a separate list because comp_and_spec.output_ports
346 # could change during the connection of one of its ports.
347 # Any new port is handled by self._graph_port_added().
348 out_ports = [port for port in comp_and_spec.comp.output_ports.values()]
349
350 for out_port in out_ports:
907f2b70 351 if out_port.is_connected:
85dcce24
PP
352 continue
353
907f2b70 354 self._connect_src_comp_port(comp_and_spec.comp, out_port)
85dcce24 355
5602ef81 356 # create this trace collection iterator's message iterator
907f2b70 357 self._msg_iter = self._graph.create_output_port_message_iterator(msg_iter_port)
This page took 0.051858 seconds and 4 git commands to generate.