b56b17a26c325a8d41a2a6e30f8d73ebff17fcdb
[babeltrace.git] / src / bindings / python / bt2 / bt2 / message_iterator.py
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
23 from bt2 import native_bt, object, utils
24 import bt2.message
25 import collections.abc
26 import bt2.component
27 import bt2
28
29
30 class _MessageIterator(collections.abc.Iterator):
31 def __next__(self):
32 raise NotImplementedError
33
34
35 class _GenericMessageIterator(object._SharedObject, _MessageIterator):
36 def __init__(self, ptr):
37 self._current_msgs = []
38 self._at = 0
39 super().__init__(ptr)
40
41 def _handle_status(self, status, gen_error_msg):
42 if status == native_bt.MESSAGE_ITERATOR_STATUS_AGAIN:
43 raise bt2.TryAgain
44 elif status == native_bt.MESSAGE_ITERATOR_STATUS_END:
45 raise bt2.Stop
46 elif status < 0:
47 raise bt2.Error(gen_error_msg)
48
49 def __next__(self):
50 if len(self._current_msgs) == self._at:
51 status, msgs = self._get_msg_range(self._ptr)
52 self._handle_status(status,
53 'unexpected error: cannot advance the message iterator')
54 self._current_msgs = msgs
55 self._at = 0
56
57 msg_ptr = self._current_msgs[self._at]
58 self._at += 1
59
60 return bt2.message._create_from_ptr(msg_ptr)
61
62 @property
63 def can_seek_beginning(self):
64 res = self._can_seek_beginning(self._ptr)
65 return res != 0
66
67 def seek_beginning(self):
68 # Forget about buffered messages, they won't be valid after seeking..
69 self._current_msgs.clear()
70 self._at = 0
71
72 status = self._seek_beginning(self._ptr)
73 self._handle_status(status, 'cannot seek message iterator beginning')
74
75
76 # This is created when a component wants to iterate on one of its input ports.
77 class _UserComponentInputPortMessageIterator(_GenericMessageIterator):
78 _get_msg_range = staticmethod(native_bt.py3_self_component_port_input_get_msg_range)
79 _get_ref = staticmethod(native_bt.self_component_port_input_message_iterator_get_ref)
80 _put_ref = staticmethod(native_bt.self_component_port_input_message_iterator_put_ref)
81 _can_seek_beginning = staticmethod(native_bt.self_component_port_input_message_iterator_can_seek_beginning)
82 _seek_beginning = staticmethod(native_bt.self_component_port_input_message_iterator_seek_beginning)
83
84
85 # This is created when the user wants to iterate on a component's output port,
86 # from outside the graph.
87 class _OutputPortMessageIterator(_GenericMessageIterator):
88 _get_msg_range = staticmethod(native_bt.py3_port_output_get_msg_range)
89 _get_ref = staticmethod(native_bt.port_output_message_iterator_get_ref)
90 _put_ref = staticmethod(native_bt.port_output_message_iterator_put_ref)
91 _can_seek_beginning = staticmethod(native_bt.port_output_message_iterator_can_seek_beginning)
92 _seek_beginning = staticmethod(native_bt.port_output_message_iterator_seek_beginning)
93
94
95 # This is extended by the user to implement component classes in Python. It
96 # is created for a given output port when an input port message iterator is
97 # created on the input port on the other side of the connection. It is also
98 # created when an output port message iterator is created on this output port.
99 #
100 # Its purpose is to feed the messages that should go out through this output
101 # port.
102 class _UserMessageIterator(_MessageIterator):
103 def __new__(cls, ptr):
104 # User iterator objects are always created by the native side,
105 # that is, never instantiated directly by Python code.
106 #
107 # The native code calls this, then manually calls
108 # self.__init__() without the `ptr` argument. The user has
109 # access to self.component during this call, thanks to this
110 # self._ptr argument being set.
111 #
112 # self._ptr is NOT owned by this object here, so there's nothing
113 # to do in __del__().
114 self = super().__new__(cls)
115 self._ptr = ptr
116 return self
117
118 def _init_from_native(self, self_output_port_ptr):
119 self_output_port = bt2.port._create_self_from_ptr_and_get_ref(
120 self_output_port_ptr, native_bt.PORT_TYPE_OUTPUT)
121 self.__init__(self_output_port)
122
123 def __init__(self, output_port):
124 pass
125
126 @property
127 def _component(self):
128 return native_bt.py3_get_user_component_from_user_msg_iter(self._ptr)
129
130 @property
131 def addr(self):
132 return int(self._ptr)
133
134 def _finalize(self):
135 pass
136
137 def __next__(self):
138 raise bt2.Stop
139
140 def _next_from_native(self):
141 # this can raise anything: it's catched by the native part
142 try:
143 msg = next(self)
144 except StopIteration:
145 raise bt2.Stop
146 except:
147 raise
148
149 utils._check_type(msg, bt2.message._Message)
150
151 # The reference we return will be given to the message array.
152 # However, the `msg` Python object may stay alive, if the user has kept
153 # a reference to it. Acquire a new reference to account for that.
154 msg._get_ref(msg._ptr)
155 return int(msg._ptr)
156
157 @property
158 def _can_seek_beginning_from_native(self):
159 # Here, we mimic the behavior of the C API:
160 #
161 # - If the iterator has a _can_seek_beginning attribute, read it and use
162 # that result.
163 # - Otherwise, the presence or absence of a `_seek_beginning`
164 # method indicates whether the iterator can seek beginning.
165 if hasattr(self, '_can_seek_beginning'):
166 can_seek_beginning = self._can_seek_beginning
167 utils._check_bool(can_seek_beginning)
168 return can_seek_beginning
169 else:
170 return hasattr(self, '_seek_beginning')
171
172 def _seek_beginning_from_native(self):
173 self._seek_beginning()
174
175 def _create_event_message(self, event_class, packet, default_clock_snapshot=None):
176 utils._check_type(event_class, bt2.event_class._EventClass)
177 utils._check_type(packet, bt2.packet._Packet)
178
179 if default_clock_snapshot is not None:
180 if event_class.stream_class.default_clock_class is None:
181 raise ValueError('event messages in this stream must not have a default clock snapshot')
182
183 utils._check_uint64(default_clock_snapshot)
184 ptr = native_bt.message_event_create_with_default_clock_snapshot(
185 self._ptr, event_class._ptr, packet._ptr, default_clock_snapshot)
186 else:
187 if event_class.stream_class.default_clock_class is not None:
188 raise ValueError('event messages in this stream must have a default clock snapshot')
189
190 ptr = native_bt.message_event_create(
191 self._ptr, event_class._ptr, packet._ptr)
192
193 if ptr is None:
194 raise bt2.CreationError('cannot create event message object')
195
196 return bt2.message._EventMessage(ptr)
197
198 def _create_message_iterator_inactivity_message(self, clock_class, clock_snapshot):
199 utils._check_type(clock_class, bt2.clock_class._ClockClass)
200 ptr = native_bt.message_message_iterator_inactivity_create(
201 self._ptr, clock_class._ptr, clock_snapshot)
202
203 if ptr is None:
204 raise bt2.CreationError('cannot create inactivity message object')
205
206 return bt2.message._MessageIteratorInactivityMessage(ptr)
207
208 _unknown_clock_snapshot = bt2.message._StreamActivityMessageUnknownClockSnapshot()
209 _infinite_clock_snapshot = bt2.message._StreamActivityMessageInfiniteClockSnapshot()
210
211 @staticmethod
212 def _validate_stream_activity_message_default_clock_snapshot(stream, default_cs):
213 isinst_infinite = isinstance(default_cs, bt2.message._StreamActivityMessageInfiniteClockSnapshot)
214 isinst_unknown = isinstance(default_cs, bt2.message._StreamActivityMessageUnknownClockSnapshot)
215
216 if utils._is_uint64(default_cs):
217 pass
218 elif isinst_infinite or isinst_unknown:
219 if default_cs is not _UserMessageIterator._unknown_clock_snapshot and default_cs is not _UserMessageIterator._infinite_clock_snapshot:
220 raise ValueError('unexpected value for default clock snapshot')
221 else:
222 raise TypeError("unexpected type '{}' for default clock snapshot".format(default_cs.__class__.__name__))
223
224 if stream.cls.default_clock_class is None:
225 if utils._is_uint64(default_cs):
226 raise ValueError('stream activity messages in this stream cannot have a known default clock snapshot')
227
228 def _create_stream_beginning_message(self, stream):
229 utils._check_type(stream, bt2.stream._Stream)
230
231 ptr = native_bt.message_stream_beginning_create(self._ptr, stream._ptr)
232 if ptr is None:
233 raise bt2.CreationError('cannot create stream beginning message object')
234
235 return bt2.message._StreamBeginningMessage(ptr)
236
237 def _create_stream_activity_beginning_message(self, stream,
238 default_clock_snapshot=_unknown_clock_snapshot):
239 utils._check_type(stream, bt2.stream._Stream)
240 self._validate_stream_activity_message_default_clock_snapshot(stream, default_clock_snapshot)
241 ptr = native_bt.message_stream_activity_beginning_create(self._ptr, stream._ptr)
242
243 if ptr is None:
244 raise bt2.CreationError(
245 'cannot create stream activity beginning message object')
246
247 msg = bt2.message._StreamActivityBeginningMessage(ptr)
248 msg._default_clock_snapshot = default_clock_snapshot
249 return msg
250
251 def _create_stream_activity_end_message(self, stream,
252 default_clock_snapshot=_unknown_clock_snapshot):
253 utils._check_type(stream, bt2.stream._Stream)
254 self._validate_stream_activity_message_default_clock_snapshot(stream, default_clock_snapshot)
255 ptr = native_bt.message_stream_activity_end_create(self._ptr, stream._ptr)
256
257 if ptr is None:
258 raise bt2.CreationError(
259 'cannot create stream activity end message object')
260
261 msg = bt2.message._StreamActivityEndMessage(ptr)
262 msg._default_clock_snapshot = default_clock_snapshot
263 return msg
264
265 def _create_stream_end_message(self, stream):
266 utils._check_type(stream, bt2.stream._Stream)
267
268 ptr = native_bt.message_stream_end_create(self._ptr, stream._ptr)
269 if ptr is None:
270 raise bt2.CreationError('cannot create stream end message object')
271
272 return bt2.message._StreamEndMessage(ptr)
273
274 def _create_packet_beginning_message(self, packet, default_clock_snapshot=None):
275 utils._check_type(packet, bt2.packet._Packet)
276
277 if packet.stream.cls.packets_have_beginning_default_clock_snapshot:
278 if default_clock_snapshot is None:
279 raise ValueError("packet beginning messages in this stream must have a default clock snapshot")
280
281 utils._check_uint64(default_clock_snapshot)
282 ptr = native_bt.message_packet_beginning_create_with_default_clock_snapshot(
283 self._ptr, packet._ptr, default_clock_snapshot)
284 else:
285 if default_clock_snapshot is not None:
286 raise ValueError("packet beginning messages in this stream must not have a default clock snapshot")
287
288 ptr = native_bt.message_packet_beginning_create(self._ptr, packet._ptr)
289
290 if ptr is None:
291 raise bt2.CreationError('cannot create packet beginning message object')
292
293 return bt2.message._PacketBeginningMessage(ptr)
294
295 def _create_packet_end_message(self, packet, default_clock_snapshot=None):
296 utils._check_type(packet, bt2.packet._Packet)
297
298 if packet.stream.cls.packets_have_end_default_clock_snapshot:
299 if default_clock_snapshot is None:
300 raise ValueError("packet end messages in this stream must have a default clock snapshot")
301
302 utils._check_uint64(default_clock_snapshot)
303 ptr = native_bt.message_packet_end_create_with_default_clock_snapshot(
304 self._ptr, packet._ptr, default_clock_snapshot)
305 else:
306 if default_clock_snapshot is not None:
307 raise ValueError("packet end messages in this stream must not have a default clock snapshot")
308
309 ptr = native_bt.message_packet_end_create(self._ptr, packet._ptr)
310
311 if ptr is None:
312 raise bt2.CreationError('cannot create packet end message object')
313
314 return bt2.message._PacketEndMessage(ptr)
315
316 def _create_discarded_events_message(self, stream, count=None,
317 beg_clock_snapshot=None,
318 end_clock_snapshot=None):
319 utils._check_type(stream, bt2.stream._Stream)
320
321 if not stream.cls.supports_discarded_events:
322 raise ValueError('stream class does not support discarded events')
323
324 if stream.cls.discarded_events_have_default_clock_snapshots:
325 if beg_clock_snapshot is None or end_clock_snapshot is None:
326 raise ValueError('discarded events have default clock snapshots for this stream class')
327
328 utils._check_uint64(beg_clock_snapshot)
329 utils._check_uint64(end_clock_snapshot)
330 ptr = native_bt.message_discarded_events_create_with_default_clock_snapshots(
331 self._ptr, stream._ptr, beg_clock_snapshot, end_clock_snapshot)
332 else:
333 if beg_clock_snapshot is not None or end_clock_snapshot is not None:
334 raise ValueError('discarded events have no default clock snapshots for this stream class')
335
336 ptr = native_bt.message_discarded_events_create(
337 self._ptr, stream._ptr)
338
339 if ptr is None:
340 raise bt2.CreationError('cannot discarded events message object')
341
342 msg = bt2.message._DiscardedEventsMessage(ptr)
343
344 if count is not None:
345 msg._count = count
346
347 return msg
348
349 def _create_discarded_packets_message(self, stream, count=None, beg_clock_snapshot=None, end_clock_snapshot=None):
350 utils._check_type(stream, bt2.stream._Stream)
351
352 if not stream.cls.supports_discarded_packets:
353 raise ValueError('stream class does not support discarded packets')
354
355 if stream.cls.discarded_packets_have_default_clock_snapshots:
356 if beg_clock_snapshot is None or end_clock_snapshot is None:
357 raise ValueError('discarded packets have default clock snapshots for this stream class')
358
359 utils._check_uint64(beg_clock_snapshot)
360 utils._check_uint64(end_clock_snapshot)
361 ptr = native_bt.message_discarded_packets_create_with_default_clock_snapshots(
362 self._ptr, stream._ptr, beg_clock_snapshot, end_clock_snapshot)
363 else:
364 if beg_clock_snapshot is not None or end_clock_snapshot is not None:
365 raise ValueError('discarded packets have no default clock snapshots for this stream class')
366
367 ptr = native_bt.message_discarded_packets_create(
368 self._ptr, stream._ptr)
369
370 if ptr is None:
371 raise bt2.CreationError('cannot discarded packets message object')
372
373 msg = bt2.message._DiscardedPacketsMessage(ptr)
374
375 if count is not None:
376 msg._count = count
377
378 return msg
379
This page took 0.037044 seconds and 3 git commands to generate.