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