30aff6941ddc501ec46e4056b2c3be6e9842bf15
[babeltrace.git] / src / plugins / ctf / lttng-live / lttng-live.cpp
1 /*
2 * SPDX-License-Identifier: MIT
3 *
4 * Copyright 2019 Francis Deslauriers <francis.deslauriers@efficios.com>
5 * Copyright 2016 Jérémie Galarneau <jeremie.galarneau@efficios.com>
6 * Copyright 2016 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 *
8 * Babeltrace CTF LTTng-live Client Component
9 */
10
11 #include <glib.h>
12 #include <unistd.h>
13
14 #include "common/assert.h"
15 #include "cpp-common/bt2/wrap.hpp"
16 #include "cpp-common/bt2c/fmt.hpp" /* IWYU pragma: keep */
17 #include "cpp-common/bt2c/glib-up.hpp"
18 #include "cpp-common/bt2c/vector.hpp"
19 #include "cpp-common/bt2s/make-unique.hpp"
20 #include "cpp-common/vendor/fmt/format.h"
21
22 #include "plugins/common/muxing/muxing.h"
23 #include "plugins/common/param-validation/param-validation.h"
24
25 #include "data-stream.hpp"
26 #include "lttng-live.hpp"
27 #include "metadata.hpp"
28
29 #define MAX_QUERY_SIZE (256 * 1024)
30 #define URL_PARAM "url"
31 #define INPUTS_PARAM "inputs"
32 #define SESS_NOT_FOUND_ACTION_PARAM "session-not-found-action"
33 #define SESS_NOT_FOUND_ACTION_CONTINUE_STR "continue"
34 #define SESS_NOT_FOUND_ACTION_FAIL_STR "fail"
35 #define SESS_NOT_FOUND_ACTION_END_STR "end"
36
37 void lttng_live_stream_iterator_set_state(struct lttng_live_stream_iterator *stream_iter,
38 enum lttng_live_stream_state new_state)
39 {
40 BT_CPPLOGD_SPEC(stream_iter->logger,
41 "Setting live stream iterator state: viewer-stream-id={}, "
42 "old-state={}, new-state={}",
43 stream_iter->viewer_stream_id, stream_iter->state, new_state);
44
45 stream_iter->state = new_state;
46 }
47
48 #define LTTNG_LIVE_LOGD_STREAM_ITER(live_stream_iter) \
49 do { \
50 BT_CPPLOGD_SPEC((live_stream_iter)->logger, \
51 "Live stream iterator state={}, " \
52 "last-inact-ts-is-set={}, last-inact-ts-value={}, " \
53 "curr-inact-ts={}", \
54 (live_stream_iter)->state, (live_stream_iter)->last_inactivity_ts.is_set, \
55 (live_stream_iter)->last_inactivity_ts.value, \
56 (live_stream_iter)->current_inactivity_ts); \
57 } while (0);
58
59 bool lttng_live_graph_is_canceled(struct lttng_live_msg_iter *msg_iter)
60 {
61 if (!msg_iter) {
62 return false;
63 }
64
65 return bt_self_message_iterator_is_interrupted(msg_iter->selfMsgIter.libObjPtr());
66 }
67
68 static struct lttng_live_trace *
69 lttng_live_session_borrow_trace_by_id(struct lttng_live_session *session, uint64_t trace_id)
70 {
71 for (lttng_live_trace::UP& trace : session->traces) {
72 if (trace->id == trace_id) {
73 return trace.get();
74 }
75 }
76
77 return nullptr;
78 }
79
80 static struct lttng_live_trace *lttng_live_create_trace(struct lttng_live_session *session,
81 uint64_t trace_id)
82 {
83 BT_CPPLOGD_SPEC(session->logger, "Creating live trace: session-id={}, trace-id={}", session->id,
84 trace_id);
85
86 auto trace = bt2s::make_unique<lttng_live_trace>(session->logger);
87
88 trace->session = session;
89 trace->id = trace_id;
90 trace->metadata_stream_state = LTTNG_LIVE_METADATA_STREAM_STATE_NEEDED;
91
92 const auto ret = trace.get();
93 session->traces.emplace_back(std::move(trace));
94 return ret;
95 }
96
97 struct lttng_live_trace *
98 lttng_live_session_borrow_or_create_trace_by_id(struct lttng_live_session *session,
99 uint64_t trace_id)
100 {
101 if (lttng_live_trace *trace = lttng_live_session_borrow_trace_by_id(session, trace_id)) {
102 return trace;
103 }
104
105 /* The session is the owner of the newly created trace. */
106 return lttng_live_create_trace(session, trace_id);
107 }
108
109 int lttng_live_add_session(struct lttng_live_msg_iter *lttng_live_msg_iter, uint64_t session_id,
110 const char *hostname, const char *session_name)
111 {
112 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
113 "Adding live session: "
114 "session-id={}, hostname=\"{}\", session-name=\"{}\"",
115 session_id, hostname, session_name);
116
117 auto session = bt2s::make_unique<lttng_live_session>(lttng_live_msg_iter->logger,
118 lttng_live_msg_iter->selfComp);
119
120 session->id = session_id;
121 session->lttng_live_msg_iter = lttng_live_msg_iter;
122 session->new_streams_needed = true;
123 session->hostname = hostname;
124 session->session_name = session_name;
125
126 lttng_live_msg_iter->sessions.emplace_back(std::move(session));
127
128 return 0;
129 }
130
131 lttng_live_session::~lttng_live_session()
132 {
133 BT_CPPLOGD_SPEC(this->logger, "Destroying live session: session-id={}, session-name=\"{}\"",
134 this->id, this->session_name);
135
136 if (this->id != -1ULL) {
137 if (lttng_live_session_detach(this)) {
138 if (!lttng_live_graph_is_canceled(this->lttng_live_msg_iter)) {
139 /* Old relayd cannot detach sessions. */
140 BT_CPPLOGD_SPEC(this->logger, "Unable to detach lttng live session {}", this->id);
141 }
142 }
143
144 this->id = -1ULL;
145 }
146 }
147
148 lttng_live_msg_iter::~lttng_live_msg_iter()
149 {
150 this->sessions.clear();
151
152 BT_ASSERT(this->lttng_live_comp);
153 BT_ASSERT(this->lttng_live_comp->has_msg_iter);
154
155 /* All stream iterators must be destroyed at this point. */
156 BT_ASSERT(this->active_stream_iter == 0);
157 this->lttng_live_comp->has_msg_iter = false;
158 }
159
160 void lttng_live_msg_iter_finalize(bt_self_message_iterator *self_msg_iter)
161 {
162 lttng_live_msg_iter::UP {
163 static_cast<lttng_live_msg_iter *>(bt_self_message_iterator_get_data(self_msg_iter))};
164 }
165
166 static enum lttng_live_iterator_status
167 lttng_live_iterator_next_check_stream_state(struct lttng_live_stream_iterator *lttng_live_stream)
168 {
169 switch (lttng_live_stream->state) {
170 case LTTNG_LIVE_STREAM_QUIESCENT:
171 case LTTNG_LIVE_STREAM_ACTIVE_DATA:
172 break;
173 case LTTNG_LIVE_STREAM_ACTIVE_NO_DATA:
174 /* Invalid state. */
175 BT_CPPLOGF_SPEC(lttng_live_stream->logger, "Unexpected stream state \"ACTIVE_NO_DATA\"");
176 bt_common_abort();
177 case LTTNG_LIVE_STREAM_QUIESCENT_NO_DATA:
178 /* Invalid state. */
179 BT_CPPLOGF_SPEC(lttng_live_stream->logger, "Unexpected stream state \"QUIESCENT_NO_DATA\"");
180 bt_common_abort();
181 case LTTNG_LIVE_STREAM_EOF:
182 break;
183 }
184 return LTTNG_LIVE_ITERATOR_STATUS_OK;
185 }
186
187 /*
188 * For active no data stream, fetch next index. As a result of that it can
189 * become either:
190 * - quiescent: won't have events for a bit,
191 * - have data: need to get that data and produce the event,
192 * - have no data on this stream at this point: need to retry (AGAIN) or return
193 * EOF.
194 */
195 static enum lttng_live_iterator_status lttng_live_iterator_next_handle_one_no_data_stream(
196 struct lttng_live_msg_iter *lttng_live_msg_iter,
197 struct lttng_live_stream_iterator *lttng_live_stream)
198 {
199 enum lttng_live_iterator_status ret = LTTNG_LIVE_ITERATOR_STATUS_OK;
200 enum lttng_live_stream_state orig_state = lttng_live_stream->state;
201 struct packet_index index;
202
203 if (lttng_live_stream->trace->metadata_stream_state ==
204 LTTNG_LIVE_METADATA_STREAM_STATE_NEEDED) {
205 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
206 "Need to get an update for the metadata stream before proceeding "
207 "further with this stream: stream-name=\"{}\"",
208 lttng_live_stream->name);
209 ret = LTTNG_LIVE_ITERATOR_STATUS_CONTINUE;
210 goto end;
211 }
212
213 if (lttng_live_stream->trace->session->new_streams_needed) {
214 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
215 "Need to get an update of all streams before proceeding further "
216 "with this stream: stream-name=\"{}\"",
217 lttng_live_stream->name);
218 ret = LTTNG_LIVE_ITERATOR_STATUS_CONTINUE;
219 goto end;
220 }
221
222 if (lttng_live_stream->state != LTTNG_LIVE_STREAM_ACTIVE_NO_DATA &&
223 lttng_live_stream->state != LTTNG_LIVE_STREAM_QUIESCENT_NO_DATA) {
224 goto end;
225 }
226 ret = lttng_live_get_next_index(lttng_live_msg_iter, lttng_live_stream, &index);
227 if (ret != LTTNG_LIVE_ITERATOR_STATUS_OK) {
228 goto end;
229 }
230
231 BT_ASSERT_DBG(lttng_live_stream->state != LTTNG_LIVE_STREAM_EOF);
232
233 if (lttng_live_stream->state == LTTNG_LIVE_STREAM_QUIESCENT) {
234 uint64_t last_inact_ts = lttng_live_stream->last_inactivity_ts.value,
235 curr_inact_ts = lttng_live_stream->current_inactivity_ts;
236
237 if (orig_state == LTTNG_LIVE_STREAM_QUIESCENT_NO_DATA && last_inact_ts == curr_inact_ts) {
238 /*
239 * Because the stream is in the QUIESCENT_NO_DATA
240 * state, we can assert that the last_inactivity_ts was
241 * set and can be safely used in the `if` above.
242 */
243 BT_ASSERT(lttng_live_stream->last_inactivity_ts.is_set);
244
245 ret = LTTNG_LIVE_ITERATOR_STATUS_AGAIN;
246 LTTNG_LIVE_LOGD_STREAM_ITER(lttng_live_stream);
247 } else {
248 ret = LTTNG_LIVE_ITERATOR_STATUS_CONTINUE;
249 }
250 goto end;
251 }
252
253 lttng_live_stream->curPktInfo.emplace(lttng_live_stream_iterator::CurPktInfo {
254 bt2c::DataLen::fromBytes(index.offset),
255 bt2c::DataLen::fromBits(index.packet_size),
256 });
257
258 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
259 "Setting live stream reading info: stream-name=\"{}\", "
260 "viewer-stream-id={}, stream-offset-in-relay={}, stream-len-bytes={}",
261 lttng_live_stream->name, lttng_live_stream->viewer_stream_id,
262 lttng_live_stream->curPktInfo->offsetInRelay.bytes(),
263 lttng_live_stream->curPktInfo->len.bytes());
264
265 end:
266 if (ret == LTTNG_LIVE_ITERATOR_STATUS_OK) {
267 ret = lttng_live_iterator_next_check_stream_state(lttng_live_stream);
268 }
269 return ret;
270 }
271
272 /*
273 * Creation of the message requires the ctf trace class to be created
274 * beforehand, but the live protocol gives us all streams (including metadata)
275 * at once. So we split it in three steps: getting streams, getting metadata
276 * (which creates the ctf trace class), and then creating the per-stream
277 * messages.
278 */
279 static enum lttng_live_iterator_status
280 lttng_live_get_session(struct lttng_live_msg_iter *lttng_live_msg_iter,
281 struct lttng_live_session *session)
282 {
283 enum lttng_live_iterator_status status;
284
285 if (!session->attached) {
286 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger, "Attach to session: session-id={}",
287 session->id);
288 lttng_live_viewer_status attach_status = lttng_live_session_attach(session);
289 if (attach_status != LTTNG_LIVE_VIEWER_STATUS_OK) {
290 if (lttng_live_graph_is_canceled(lttng_live_msg_iter)) {
291 /*
292 * Clear any causes appended in
293 * `lttng_live_attach_session()` as we want to
294 * return gracefully since the graph was
295 * cancelled.
296 */
297 bt_current_thread_clear_error();
298 return LTTNG_LIVE_ITERATOR_STATUS_AGAIN;
299 } else {
300 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
301 "Error attaching to LTTng live session");
302 return LTTNG_LIVE_ITERATOR_STATUS_ERROR;
303 }
304 }
305 }
306
307 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
308 "Updating all data streams: session-id={}, session-name=\"{}\"", session->id,
309 session->session_name);
310
311 status = lttng_live_session_get_new_streams(session);
312 switch (status) {
313 case LTTNG_LIVE_ITERATOR_STATUS_OK:
314 break;
315 case LTTNG_LIVE_ITERATOR_STATUS_END:
316 /*
317 * We received a `_END` from the `_get_new_streams()` function,
318 * which means no more data will ever be received from the data
319 * streams of this session. But it's possible that the metadata
320 * is incomplete.
321 * The live protocol guarantees that we receive all the
322 * metadata needed before we receive data streams needing it.
323 * But it's possible to receive metadata NOT needed by
324 * data streams after the session was closed. For example, this
325 * could happen if a new event is registered and the session is
326 * stopped before any tracepoint for that event is actually
327 * fired.
328 */
329 BT_CPPLOGD_SPEC(
330 lttng_live_msg_iter->logger,
331 "Updating streams returned _END status. Override status to _OK in order fetch any remaining metadata:"
332 "session-id={}, session-name=\"{}\"",
333 session->id, session->session_name);
334 return LTTNG_LIVE_ITERATOR_STATUS_OK;
335 default:
336 return status;
337 }
338
339 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
340 "Updating metadata stream for session: session-id={}, session-name=\"{}\"",
341 session->id, session->session_name);
342
343 for (lttng_live_trace::UP& trace : session->traces) {
344 status = lttng_live_metadata_update(trace.get());
345 switch (status) {
346 case LTTNG_LIVE_ITERATOR_STATUS_END:
347 break;
348 case LTTNG_LIVE_ITERATOR_STATUS_OK:
349 break;
350 case LTTNG_LIVE_ITERATOR_STATUS_CONTINUE:
351 case LTTNG_LIVE_ITERATOR_STATUS_AGAIN:
352 return status;
353 default:
354 BT_CPPLOGE_APPEND_CAUSE_SPEC(
355 lttng_live_msg_iter->logger,
356 "Error updating trace metadata: stream-iter-status={}, trace-id={}", status,
357 trace->id);
358 return status;
359 }
360 }
361
362 /*
363 * Now that we have the metadata we can initialize the downstream
364 * iterator.
365 */
366 return lttng_live_lazy_msg_init(session, lttng_live_msg_iter->selfMsgIter);
367 }
368
369 static void
370 lttng_live_force_new_streams_and_metadata(struct lttng_live_msg_iter *lttng_live_msg_iter)
371 {
372 for (const auto& session : lttng_live_msg_iter->sessions) {
373 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
374 "Force marking session as needing new streams: "
375 "session-id={}",
376 session->id);
377 session->new_streams_needed = true;
378 for (lttng_live_trace::UP& trace : session->traces) {
379 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
380 "Force marking trace metadata state as needing an update: "
381 "session-id={}, trace-id={}",
382 session->id, trace->id);
383
384 BT_ASSERT(trace->metadata_stream_state != LTTNG_LIVE_METADATA_STREAM_STATE_CLOSED);
385
386 trace->metadata_stream_state = LTTNG_LIVE_METADATA_STREAM_STATE_NEEDED;
387 }
388 }
389 }
390
391 static enum lttng_live_iterator_status
392 lttng_live_iterator_handle_new_streams_and_metadata(struct lttng_live_msg_iter *lttng_live_msg_iter)
393 {
394 enum lttng_live_viewer_status viewer_status;
395 uint64_t nr_sessions_opened = 0;
396 enum session_not_found_action sess_not_found_act =
397 lttng_live_msg_iter->lttng_live_comp->params.sess_not_found_act;
398
399 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
400 "Update data and metadata of all sessions: "
401 "live-msg-iter-addr={}",
402 fmt::ptr(lttng_live_msg_iter));
403 /*
404 * In a remotely distant future, we could add a "new
405 * session" flag to the protocol, which would tell us that we
406 * need to query for new sessions even though we have sessions
407 * currently ongoing.
408 */
409 if (lttng_live_msg_iter->sessions.empty()) {
410 if (sess_not_found_act != SESSION_NOT_FOUND_ACTION_CONTINUE) {
411 BT_CPPLOGD_SPEC(
412 lttng_live_msg_iter->logger,
413 "No session found. Exiting in accordance with the `session-not-found-action` parameter");
414 return LTTNG_LIVE_ITERATOR_STATUS_END;
415 } else {
416 BT_CPPLOGD_SPEC(
417 lttng_live_msg_iter->logger,
418 "No session found. Try creating a new one in accordance with the `session-not-found-action` parameter");
419 /*
420 * Retry to create a viewer session for the requested
421 * session name.
422 */
423 viewer_status = lttng_live_create_viewer_session(lttng_live_msg_iter);
424 if (viewer_status != LTTNG_LIVE_VIEWER_STATUS_OK) {
425 if (viewer_status == LTTNG_LIVE_VIEWER_STATUS_ERROR) {
426 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
427 "Error creating LTTng live viewer session");
428 return LTTNG_LIVE_ITERATOR_STATUS_ERROR;
429 } else if (viewer_status == LTTNG_LIVE_VIEWER_STATUS_INTERRUPTED) {
430 return LTTNG_LIVE_ITERATOR_STATUS_AGAIN;
431 } else {
432 bt_common_abort();
433 }
434 }
435 }
436 }
437
438 for (const auto& session : lttng_live_msg_iter->sessions) {
439 const auto status = lttng_live_get_session(lttng_live_msg_iter, session.get());
440 switch (status) {
441 case LTTNG_LIVE_ITERATOR_STATUS_OK:
442 case LTTNG_LIVE_ITERATOR_STATUS_END:
443 /*
444 * A session returned `_END`. Other sessions may still
445 * be active so we override the status and continue
446 * looping if needed.
447 */
448 break;
449 default:
450 return status;
451 }
452 if (!session->closed) {
453 nr_sessions_opened++;
454 }
455 }
456
457 if (sess_not_found_act != SESSION_NOT_FOUND_ACTION_CONTINUE && nr_sessions_opened == 0) {
458 return LTTNG_LIVE_ITERATOR_STATUS_END;
459 } else {
460 return LTTNG_LIVE_ITERATOR_STATUS_OK;
461 }
462 }
463
464 static enum lttng_live_iterator_status
465 emit_inactivity_message(struct lttng_live_msg_iter *lttng_live_msg_iter,
466 struct lttng_live_stream_iterator *stream_iter,
467 bt2::ConstMessage::Shared& message, uint64_t timestamp)
468 {
469 BT_ASSERT(stream_iter->trace->clock_class);
470 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
471 "Emitting inactivity message for stream: ctf-stream-id={}, "
472 "viewer-stream-id={}, timestamp={}",
473 stream_iter->ctf_stream_class_id.value, stream_iter->viewer_stream_id,
474 timestamp);
475
476 const auto msg = bt_message_message_iterator_inactivity_create(
477 lttng_live_msg_iter->selfMsgIter.libObjPtr(), stream_iter->trace->clock_class->libObjPtr(),
478 timestamp);
479
480 if (!msg) {
481 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
482 "Error emitting message iterator inactivity message");
483 return LTTNG_LIVE_ITERATOR_STATUS_ERROR;
484 }
485
486 message = bt2::ConstMessage::Shared::createWithoutRef(msg);
487 return LTTNG_LIVE_ITERATOR_STATUS_OK;
488 }
489
490 static enum lttng_live_iterator_status lttng_live_iterator_next_handle_one_quiescent_stream(
491 struct lttng_live_msg_iter *lttng_live_msg_iter,
492 struct lttng_live_stream_iterator *lttng_live_stream, bt2::ConstMessage::Shared& message)
493 {
494 if (lttng_live_stream->state != LTTNG_LIVE_STREAM_QUIESCENT) {
495 return LTTNG_LIVE_ITERATOR_STATUS_OK;
496 }
497
498 /*
499 * Check if we already sent an inactivty message downstream for this
500 * `current_inactivity_ts` value.
501 */
502 if (lttng_live_stream->last_inactivity_ts.is_set &&
503 lttng_live_stream->current_inactivity_ts == lttng_live_stream->last_inactivity_ts.value) {
504 lttng_live_stream_iterator_set_state(lttng_live_stream,
505 LTTNG_LIVE_STREAM_QUIESCENT_NO_DATA);
506
507 return LTTNG_LIVE_ITERATOR_STATUS_CONTINUE;
508 }
509
510 const auto status = emit_inactivity_message(lttng_live_msg_iter, lttng_live_stream, message,
511 lttng_live_stream->current_inactivity_ts);
512
513 if (status != LTTNG_LIVE_ITERATOR_STATUS_OK) {
514 return status;
515 }
516
517 lttng_live_stream->last_inactivity_ts.value = lttng_live_stream->current_inactivity_ts;
518 lttng_live_stream->last_inactivity_ts.is_set = true;
519
520 return LTTNG_LIVE_ITERATOR_STATUS_OK;
521 }
522
523 static int live_get_msg_ts_ns(struct lttng_live_msg_iter *lttng_live_msg_iter,
524 bt2::ConstMessage msg, int64_t last_msg_ts_ns, int64_t *ts_ns)
525 {
526 bt2::OptionalBorrowedObject<bt2::ConstClockSnapshot> clockSnapshot;
527
528 BT_ASSERT_DBG(ts_ns);
529
530 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
531 "Getting message's timestamp: iter-data-addr={}, msg-addr={}, last-msg-ts={}",
532 fmt::ptr(lttng_live_msg_iter), fmt::ptr(msg.libObjPtr()), last_msg_ts_ns);
533
534 switch (msg.type()) {
535 case bt2::MessageType::Event:
536 clockSnapshot = msg.asEvent().defaultClockSnapshot();
537 break;
538 case bt2::MessageType::PacketBeginning:
539
540 clockSnapshot = msg.asPacketBeginning().defaultClockSnapshot();
541 break;
542 case bt2::MessageType::PacketEnd:
543 clockSnapshot = msg.asPacketEnd().defaultClockSnapshot();
544 break;
545 case bt2::MessageType::DiscardedEvents:
546 clockSnapshot = msg.asDiscardedEvents().beginningDefaultClockSnapshot();
547 break;
548 case bt2::MessageType::DiscardedPackets:
549 clockSnapshot = msg.asDiscardedPackets().beginningDefaultClockSnapshot();
550 break;
551 case bt2::MessageType::MessageIteratorInactivity:
552 clockSnapshot = msg.asMessageIteratorInactivity().clockSnapshot();
553 break;
554 default:
555 /* All the other messages have a higher priority */
556 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
557 "Message has no timestamp, using the last message timestamp: "
558 "iter-data-addr={}, msg-addr={}, last-msg-ts={}, ts={}",
559 fmt::ptr(lttng_live_msg_iter), fmt::ptr(msg.libObjPtr()), last_msg_ts_ns,
560 *ts_ns);
561 *ts_ns = last_msg_ts_ns;
562 return 0;
563 }
564
565 *ts_ns = clockSnapshot->nsFromOrigin();
566
567 BT_CPPLOGD_SPEC(
568 lttng_live_msg_iter->logger,
569 "Found message's timestamp: iter-data-addr={}, msg-addr={}, last-msg-ts={}, ts={}",
570 fmt::ptr(lttng_live_msg_iter), fmt::ptr(msg.libObjPtr()), last_msg_ts_ns, *ts_ns);
571
572 return 0;
573 }
574
575 static enum lttng_live_iterator_status lttng_live_iterator_next_handle_one_active_data_stream(
576 struct lttng_live_msg_iter *lttng_live_msg_iter,
577 struct lttng_live_stream_iterator *lttng_live_stream, bt2::ConstMessage::Shared& message)
578 {
579 for (const auto& session : lttng_live_msg_iter->sessions) {
580 if (session->new_streams_needed) {
581 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
582 "Need an update for streams: session-id={}", session->id);
583 return LTTNG_LIVE_ITERATOR_STATUS_CONTINUE;
584 }
585
586 for (const auto& trace : session->traces) {
587 if (trace->metadata_stream_state == LTTNG_LIVE_METADATA_STREAM_STATE_NEEDED) {
588 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
589 "Need an update for metadata stream: session-id={}, trace-id={}",
590 session->id, trace->id);
591 return LTTNG_LIVE_ITERATOR_STATUS_CONTINUE;
592 }
593 }
594 }
595
596 if (lttng_live_stream->state != LTTNG_LIVE_STREAM_ACTIVE_DATA) {
597 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
598 "Invalid state of live stream iterator: stream-iter-status={}",
599 lttng_live_stream->state);
600 return LTTNG_LIVE_ITERATOR_STATUS_ERROR;
601 }
602
603 if (!lttng_live_stream->msg_iter) {
604 /* The first time we're called for this stream, the MsgIter is not instantiated. */
605 enum lttng_live_iterator_status ret =
606 lttng_live_stream_iterator_create_msg_iter(lttng_live_stream);
607 if (ret != LTTNG_LIVE_ITERATOR_STATUS_OK) {
608 return ret;
609 }
610 }
611
612 try {
613 message = lttng_live_stream->msg_iter->next();
614 if (message) {
615 return LTTNG_LIVE_ITERATOR_STATUS_OK;
616 } else {
617 return LTTNG_LIVE_ITERATOR_STATUS_END;
618 }
619 } catch (const bt2c::TryAgain&) {
620 return LTTNG_LIVE_ITERATOR_STATUS_AGAIN;
621 } catch (const bt2::Error&) {
622 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
623 "CTF message iterator failed to get next message: msg-iter={}",
624 fmt::ptr(&*lttng_live_stream->msg_iter));
625 return LTTNG_LIVE_ITERATOR_STATUS_ERROR;
626 }
627 }
628
629 static enum lttng_live_iterator_status
630 lttng_live_iterator_close_stream(struct lttng_live_msg_iter *lttng_live_msg_iter,
631 struct lttng_live_stream_iterator *stream_iter,
632 bt2::ConstMessage::Shared& curr_msg)
633 {
634 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
635 "Closing live stream iterator: stream-name=\"{}\", "
636 "viewer-stream-id={}",
637 stream_iter->name, stream_iter->viewer_stream_id);
638
639 /*
640 * The viewer has hung up on us so we are closing the stream. The
641 * `ctf_msg_iter` should simply realize that it needs to close the
642 * stream properly by emitting the necessary stream end message.
643 */
644 try {
645 if (!stream_iter->msg_iter) {
646 BT_CPPLOGI_SPEC(lttng_live_msg_iter->logger,
647 "Reached the end of the live stream iterator.");
648 return LTTNG_LIVE_ITERATOR_STATUS_END;
649 }
650
651 curr_msg = stream_iter->msg_iter->next();
652 if (!curr_msg) {
653 BT_CPPLOGI_SPEC(lttng_live_msg_iter->logger,
654 "Reached the end of the live stream iterator.");
655 return LTTNG_LIVE_ITERATOR_STATUS_END;
656 }
657
658 return LTTNG_LIVE_ITERATOR_STATUS_OK;
659 } catch (const bt2::Error&) {
660 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
661 "Error getting the next message from CTF message iterator");
662 return LTTNG_LIVE_ITERATOR_STATUS_ERROR;
663 }
664 }
665
666 /*
667 * helper function:
668 * handle_no_data_streams()
669 * retry:
670 * - for each ACTIVE_NO_DATA stream:
671 * - query relayd for stream data, or quiescence info.
672 * - if need metadata, get metadata, goto retry.
673 * - if new stream, get new stream as ACTIVE_NO_DATA, goto retry
674 * - if quiescent, move to QUIESCENT streams
675 * - if fetched data, move to ACTIVE_DATA streams
676 * (at this point each stream either has data, or is quiescent)
677 *
678 *
679 * iterator_next:
680 * handle_new_streams_and_metadata()
681 * - query relayd for known streams, add them as ACTIVE_NO_DATA
682 * - query relayd for metadata
683 *
684 * call handle_active_no_data_streams()
685 *
686 * handle_quiescent_streams()
687 * - if at least one stream is ACTIVE_DATA:
688 * - peek stream event with lowest timestamp -> next_ts
689 * - for each quiescent stream
690 * - if next_ts >= quiescent end
691 * - set state to ACTIVE_NO_DATA
692 * - else
693 * - for each quiescent stream
694 * - set state to ACTIVE_NO_DATA
695 *
696 * call handle_active_no_data_streams()
697 *
698 * handle_active_data_streams()
699 * - if at least one stream is ACTIVE_DATA:
700 * - get stream event with lowest timestamp from heap
701 * - make that stream event the current message.
702 * - move this stream heap position to its next event
703 * - if we need to fetch data from relayd, move
704 * stream to ACTIVE_NO_DATA.
705 * - return OK
706 * - return AGAIN
707 *
708 * end criterion: ctrl-c on client. If relayd exits or the session
709 * closes on the relay daemon side, we keep on waiting for streams.
710 * Eventually handle --end timestamp (also an end criterion).
711 *
712 * When disconnected from relayd: try to re-connect endlessly.
713 */
714 static enum lttng_live_iterator_status
715 lttng_live_iterator_next_msg_on_stream(struct lttng_live_msg_iter *lttng_live_msg_iter,
716 struct lttng_live_stream_iterator *stream_iter,
717 bt2::ConstMessage::Shared& curr_msg)
718 {
719 enum lttng_live_iterator_status live_status;
720
721 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
722 "Advancing live stream iterator until next message if possible: "
723 "stream-name=\"{}\", viewer-stream-id={}",
724 stream_iter->name, stream_iter->viewer_stream_id);
725
726 if (stream_iter->has_stream_hung_up) {
727 /*
728 * The stream has hung up and the stream was properly closed
729 * during the last call to the current function. Return _END
730 * status now so that this stream iterator is removed for the
731 * stream iterator list.
732 */
733 live_status = LTTNG_LIVE_ITERATOR_STATUS_END;
734 goto end;
735 }
736
737 retry:
738 LTTNG_LIVE_LOGD_STREAM_ITER(stream_iter);
739
740 /*
741 * Make sure we have the most recent metadata and possibly some new
742 * streams.
743 */
744 live_status = lttng_live_iterator_handle_new_streams_and_metadata(lttng_live_msg_iter);
745 if (live_status != LTTNG_LIVE_ITERATOR_STATUS_OK) {
746 goto end;
747 }
748
749 live_status =
750 lttng_live_iterator_next_handle_one_no_data_stream(lttng_live_msg_iter, stream_iter);
751 if (live_status != LTTNG_LIVE_ITERATOR_STATUS_OK) {
752 if (live_status == LTTNG_LIVE_ITERATOR_STATUS_END) {
753 /*
754 * We overwrite `live_status` since `curr_msg` is
755 * likely set to a valid message in this function.
756 */
757 live_status =
758 lttng_live_iterator_close_stream(lttng_live_msg_iter, stream_iter, curr_msg);
759 }
760 goto end;
761 }
762
763 live_status = lttng_live_iterator_next_handle_one_quiescent_stream(lttng_live_msg_iter,
764 stream_iter, curr_msg);
765 if (live_status != LTTNG_LIVE_ITERATOR_STATUS_OK) {
766 BT_ASSERT(!curr_msg);
767 goto end;
768 }
769 if (curr_msg) {
770 goto end;
771 }
772 live_status = lttng_live_iterator_next_handle_one_active_data_stream(lttng_live_msg_iter,
773 stream_iter, curr_msg);
774 if (live_status != LTTNG_LIVE_ITERATOR_STATUS_OK) {
775 BT_ASSERT(!curr_msg);
776 }
777
778 end:
779 if (live_status == LTTNG_LIVE_ITERATOR_STATUS_CONTINUE) {
780 BT_CPPLOGD_SPEC(
781 lttng_live_msg_iter->logger,
782 "Ask the relay daemon for an updated view of the data and metadata streams");
783 goto retry;
784 }
785
786 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
787 "Returning from advancing live stream iterator: status={}, "
788 "stream-name=\"{}\", viewer-stream-id={}",
789 live_status, stream_iter->name, stream_iter->viewer_stream_id);
790
791 return live_status;
792 }
793
794 static bool is_discarded_packet_or_event_message(const bt2::ConstMessage msg)
795 {
796 return msg.type() == bt2::MessageType::DiscardedEvents ||
797 msg.type() == bt2::MessageType::DiscardedPackets;
798 }
799
800 static enum lttng_live_iterator_status
801 adjust_discarded_packets_message(bt_self_message_iterator *iter, bt2::Stream stream,
802 bt2::ConstDiscardedPacketsMessage msgIn,
803 bt2::ConstMessage::Shared& msgOut, uint64_t new_begin_ts)
804 {
805 BT_ASSERT_DBG(msgIn.count());
806
807 const auto msg = bt_message_discarded_packets_create_with_default_clock_snapshots(
808 iter, stream.libObjPtr(), new_begin_ts, msgIn.endDefaultClockSnapshot().value());
809
810 if (!msg) {
811 return LTTNG_LIVE_ITERATOR_STATUS_NOMEM;
812 }
813
814 bt_message_discarded_packets_set_count(msg, *msgIn.count());
815 msgOut = bt2::Message::Shared::createWithoutRef(msg);
816
817 return LTTNG_LIVE_ITERATOR_STATUS_OK;
818 }
819
820 static enum lttng_live_iterator_status
821 adjust_discarded_events_message(bt_self_message_iterator *iter, const bt2::Stream stream,
822 bt2::ConstDiscardedEventsMessage msgIn,
823 bt2::ConstMessage::Shared& msgOut, uint64_t new_begin_ts)
824 {
825 BT_ASSERT_DBG(msgIn.count());
826
827 const auto msg = bt_message_discarded_events_create_with_default_clock_snapshots(
828 iter, stream.libObjPtr(), new_begin_ts, msgIn.endDefaultClockSnapshot().value());
829
830 if (!msg) {
831 return LTTNG_LIVE_ITERATOR_STATUS_NOMEM;
832 }
833
834 bt_message_discarded_events_set_count(msg, *msgIn.count());
835 msgOut = bt2::Message::Shared::createWithoutRef(msg);
836
837 return LTTNG_LIVE_ITERATOR_STATUS_OK;
838 }
839
840 static enum lttng_live_iterator_status
841 handle_late_message(struct lttng_live_msg_iter *lttng_live_msg_iter,
842 struct lttng_live_stream_iterator *stream_iter, int64_t late_msg_ts_ns,
843 const bt2::ConstMessage& late_msg)
844 {
845 /*
846 * The timestamp of the current message is before the last message sent
847 * by this component. We CANNOT send it as is.
848 *
849 * The only expected scenario in which that could happen is the
850 * following, everything else is a bug in this component, relay daemon,
851 * or CTF parser.
852 *
853 * Expected scenario: The CTF message iterator emitted discarded
854 * packets and discarded events with synthesized beginning and end
855 * timestamps from the bounds of the last known packet and the newly
856 * decoded packet header. The CTF message iterator is not aware of
857 * stream inactivity beacons. Hence, we have to adjust the beginning
858 * timestamp of those types of messages if a stream signalled its
859 * inactivity up until _after_ the last known packet's beginning
860 * timestamp.
861 *
862 * Otherwise, the monotonicity guarantee of message timestamps would
863 * not be preserved.
864 *
865 * In short, the only scenario in which it's okay and fixable to
866 * received a late message is when:
867 * 1. the late message is a discarded packets or discarded events
868 * message,
869 * 2. this stream produced an inactivity message downstream, and
870 * 3. the timestamp of the late message is within the inactivity
871 * timespan we sent downstream through the inactivity message.
872 */
873
874 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
875 "Handling late message on live stream iterator: "
876 "stream-name=\"{}\", viewer-stream-id={}",
877 stream_iter->name, stream_iter->viewer_stream_id);
878
879 if (!stream_iter->last_inactivity_ts.is_set) {
880 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
881 "Invalid live stream state: "
882 "have a late message when no inactivity message "
883 "was ever sent for that stream.");
884 return LTTNG_LIVE_ITERATOR_STATUS_ERROR;
885 }
886
887 if (!is_discarded_packet_or_event_message(late_msg)) {
888 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
889 "Invalid live stream state: "
890 "have a late message that is not a packet discarded or "
891 "event discarded message: late-msg-type={}",
892 late_msg.type());
893 return LTTNG_LIVE_ITERATOR_STATUS_ERROR;
894 }
895
896 const auto streamClass = stream_iter->stream->cls();
897 const auto clockClass = streamClass.defaultClockClass();
898
899 int64_t last_inactivity_ts_ns =
900 clockClass->cyclesToNsFromOrigin(stream_iter->last_inactivity_ts.value);
901 if (last_inactivity_ts_ns <= late_msg_ts_ns) {
902 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
903 "Invalid live stream state: "
904 "have a late message that is none included in a stream "
905 "inactivity timespan: last-inactivity-ts-ns={}, "
906 "late-msg-ts-ns={}",
907 last_inactivity_ts_ns, late_msg_ts_ns);
908 return LTTNG_LIVE_ITERATOR_STATUS_ERROR;
909 }
910
911 /*
912 * We now know that it's okay for this message to be late, we can now
913 * adjust its timestamp to ensure monotonicity.
914 */
915 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
916 "Adjusting the timestamp of late message: late-msg-type={}, msg-new-ts-ns={}",
917 late_msg.type(), stream_iter->last_inactivity_ts.value);
918
919 bt2::ConstMessage::Shared adjustedMessage;
920
921 const auto adjust_status = bt2c::call([&] {
922 switch (late_msg.type()) {
923 case bt2::MessageType::DiscardedEvents:
924 return adjust_discarded_events_message(lttng_live_msg_iter->selfMsgIter.libObjPtr(),
925 *stream_iter->stream,
926 late_msg.asDiscardedEvents(), adjustedMessage,
927 stream_iter->last_inactivity_ts.value);
928
929 case bt2::MessageType::DiscardedPackets:
930 return adjust_discarded_packets_message(lttng_live_msg_iter->selfMsgIter.libObjPtr(),
931 *stream_iter->stream,
932 late_msg.asDiscardedPackets(), adjustedMessage,
933 stream_iter->last_inactivity_ts.value);
934
935 default:
936 bt_common_abort();
937 }
938 });
939
940 if (adjust_status != LTTNG_LIVE_ITERATOR_STATUS_OK) {
941 return adjust_status;
942 }
943
944 BT_ASSERT_DBG(adjustedMessage);
945 stream_iter->current_msg = std::move(adjustedMessage);
946 stream_iter->current_msg_ts_ns = last_inactivity_ts_ns;
947
948 return LTTNG_LIVE_ITERATOR_STATUS_OK;
949 }
950
951 static enum lttng_live_iterator_status
952 next_stream_iterator_for_trace(struct lttng_live_msg_iter *lttng_live_msg_iter,
953 struct lttng_live_trace *live_trace,
954 struct lttng_live_stream_iterator **youngest_trace_stream_iter)
955 {
956 struct lttng_live_stream_iterator *youngest_candidate_stream_iter = NULL;
957 int64_t youngest_candidate_msg_ts = INT64_MAX;
958 uint64_t stream_iter_idx;
959
960 BT_ASSERT_DBG(live_trace);
961
962 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
963 "Finding the next stream iterator for trace: "
964 "trace-id={}",
965 live_trace->id);
966 /*
967 * Update the current message of every stream iterators of this trace.
968 * The current msg of every stream must have a timestamp equal or
969 * larger than the last message returned by this iterator. We must
970 * ensure monotonicity.
971 */
972 stream_iter_idx = 0;
973 while (stream_iter_idx < live_trace->stream_iterators.size()) {
974 bool stream_iter_is_ended = false;
975 lttng_live_stream_iterator *stream_iter =
976 live_trace->stream_iterators[stream_iter_idx].get();
977
978 /*
979 * If there is no current message for this stream, go fetch
980 * one.
981 */
982 while (!stream_iter->current_msg) {
983 bt2::ConstMessage::Shared msg;
984 int64_t curr_msg_ts_ns = INT64_MAX;
985
986 const auto stream_iter_status =
987 lttng_live_iterator_next_msg_on_stream(lttng_live_msg_iter, stream_iter, msg);
988
989 if (stream_iter_status == LTTNG_LIVE_ITERATOR_STATUS_END) {
990 stream_iter_is_ended = true;
991 break;
992 }
993
994 if (stream_iter_status != LTTNG_LIVE_ITERATOR_STATUS_OK) {
995 return stream_iter_status;
996 }
997
998 BT_ASSERT_DBG(msg);
999
1000 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
1001 "Live stream iterator returned message: msg-type={}, "
1002 "stream-name=\"{}\", viewer-stream-id={}",
1003 msg->type(), stream_iter->name, stream_iter->viewer_stream_id);
1004
1005 /*
1006 * Get the timestamp in nanoseconds from origin of this
1007 * message.
1008 */
1009 live_get_msg_ts_ns(lttng_live_msg_iter, *msg, lttng_live_msg_iter->last_msg_ts_ns,
1010 &curr_msg_ts_ns);
1011
1012 /*
1013 * Check if the message of the current live stream
1014 * iterator occurred at the exact same time or after the
1015 * last message returned by this component's message
1016 * iterator. If not, we need to handle it with care.
1017 */
1018 if (curr_msg_ts_ns >= lttng_live_msg_iter->last_msg_ts_ns) {
1019 stream_iter->current_msg = std::move(msg);
1020 stream_iter->current_msg_ts_ns = curr_msg_ts_ns;
1021 } else {
1022 /*
1023 * We received a message from the past. This
1024 * may be fixable but it can also be an error.
1025 */
1026 if (handle_late_message(lttng_live_msg_iter, stream_iter, curr_msg_ts_ns, *msg) !=
1027 LTTNG_LIVE_ITERATOR_STATUS_OK) {
1028 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
1029 "Late message could not be handled correctly: "
1030 "lttng-live-msg-iter-addr={}, "
1031 "stream-name=\"{}\", "
1032 "curr-msg-ts={}, last-msg-ts={}",
1033 fmt::ptr(lttng_live_msg_iter), stream_iter->name,
1034 curr_msg_ts_ns,
1035 lttng_live_msg_iter->last_msg_ts_ns);
1036 return LTTNG_LIVE_ITERATOR_STATUS_ERROR;
1037 }
1038 }
1039 }
1040
1041 BT_ASSERT_DBG(stream_iter != youngest_candidate_stream_iter);
1042
1043 if (!stream_iter_is_ended) {
1044 if (G_UNLIKELY(youngest_candidate_stream_iter == NULL) ||
1045 stream_iter->current_msg_ts_ns < youngest_candidate_msg_ts) {
1046 /*
1047 * Update the current best candidate message
1048 * for the stream iterator of this live trace
1049 * to be forwarded downstream.
1050 */
1051 youngest_candidate_msg_ts = stream_iter->current_msg_ts_ns;
1052 youngest_candidate_stream_iter = stream_iter;
1053 } else if (stream_iter->current_msg_ts_ns == youngest_candidate_msg_ts) {
1054 /*
1055 * Order the messages in an arbitrary but
1056 * deterministic way.
1057 */
1058 BT_ASSERT_DBG(stream_iter != youngest_candidate_stream_iter);
1059 int ret = common_muxing_compare_messages(
1060 stream_iter->current_msg->libObjPtr(),
1061 youngest_candidate_stream_iter->current_msg->libObjPtr());
1062 if (ret < 0) {
1063 /*
1064 * The `youngest_candidate_stream_iter->current_msg`
1065 * should go first. Update the next
1066 * iterator and the current timestamp.
1067 */
1068 youngest_candidate_msg_ts = stream_iter->current_msg_ts_ns;
1069 youngest_candidate_stream_iter = stream_iter;
1070 } else if (ret == 0) {
1071 /*
1072 * Unable to pick which one should go
1073 * first.
1074 */
1075 BT_CPPLOGW_SPEC(
1076 lttng_live_msg_iter->logger,
1077 "Cannot deterministically pick next live stream message iterator because they have identical next messages: "
1078 "stream-iter-addr={}"
1079 "stream-iter-addr={}",
1080 fmt::ptr(stream_iter), fmt::ptr(youngest_candidate_stream_iter));
1081 }
1082 }
1083
1084 stream_iter_idx++;
1085 } else {
1086 /*
1087 * The live stream iterator has ended. That
1088 * iterator is removed from the array, but
1089 * there is no need to increment
1090 * stream_iter_idx as
1091 * g_ptr_array_remove_index_fast replaces the
1092 * removed element with the array's last
1093 * element.
1094 */
1095 bt2c::vectorFastRemove(live_trace->stream_iterators, stream_iter_idx);
1096 }
1097 }
1098
1099 if (youngest_candidate_stream_iter) {
1100 *youngest_trace_stream_iter = youngest_candidate_stream_iter;
1101 return LTTNG_LIVE_ITERATOR_STATUS_OK;
1102 } else {
1103 /*
1104 * The only case where we don't have a candidate for this trace
1105 * is if we reached the end of all the iterators.
1106 */
1107 BT_ASSERT(live_trace->stream_iterators.empty());
1108 return LTTNG_LIVE_ITERATOR_STATUS_END;
1109 }
1110 }
1111
1112 static enum lttng_live_iterator_status
1113 next_stream_iterator_for_session(struct lttng_live_msg_iter *lttng_live_msg_iter,
1114 struct lttng_live_session *session,
1115 struct lttng_live_stream_iterator **youngest_session_stream_iter)
1116 {
1117 enum lttng_live_iterator_status stream_iter_status;
1118 uint64_t trace_idx = 0;
1119 int64_t youngest_candidate_msg_ts = INT64_MAX;
1120 struct lttng_live_stream_iterator *youngest_candidate_stream_iter = NULL;
1121
1122 BT_CPPLOGD_SPEC(lttng_live_msg_iter->logger,
1123 "Finding the next stream iterator for session: "
1124 "session-id={}",
1125 session->id);
1126 /*
1127 * Make sure we are attached to the session and look for new streams
1128 * and metadata.
1129 */
1130 stream_iter_status = lttng_live_get_session(lttng_live_msg_iter, session);
1131 if (stream_iter_status != LTTNG_LIVE_ITERATOR_STATUS_OK &&
1132 stream_iter_status != LTTNG_LIVE_ITERATOR_STATUS_CONTINUE &&
1133 stream_iter_status != LTTNG_LIVE_ITERATOR_STATUS_END) {
1134 return stream_iter_status;
1135 }
1136
1137 while (trace_idx < session->traces.size()) {
1138 bool trace_is_ended = false;
1139 struct lttng_live_stream_iterator *stream_iter;
1140 lttng_live_trace *trace = session->traces[trace_idx].get();
1141
1142 stream_iter_status =
1143 next_stream_iterator_for_trace(lttng_live_msg_iter, trace, &stream_iter);
1144 if (stream_iter_status == LTTNG_LIVE_ITERATOR_STATUS_END) {
1145 /*
1146 * All the live stream iterators for this trace are
1147 * ENDed. Remove the trace from this session.
1148 */
1149 trace_is_ended = true;
1150 } else if (stream_iter_status != LTTNG_LIVE_ITERATOR_STATUS_OK) {
1151 return stream_iter_status;
1152 }
1153
1154 if (!trace_is_ended) {
1155 BT_ASSERT_DBG(stream_iter);
1156
1157 if (G_UNLIKELY(youngest_candidate_stream_iter == NULL) ||
1158 stream_iter->current_msg_ts_ns < youngest_candidate_msg_ts) {
1159 youngest_candidate_msg_ts = stream_iter->current_msg_ts_ns;
1160 youngest_candidate_stream_iter = stream_iter;
1161 } else if (stream_iter->current_msg_ts_ns == youngest_candidate_msg_ts) {
1162 /*
1163 * Order the messages in an arbitrary but
1164 * deterministic way.
1165 */
1166 int ret = common_muxing_compare_messages(
1167 stream_iter->current_msg->libObjPtr(),
1168 youngest_candidate_stream_iter->current_msg->libObjPtr());
1169 if (ret < 0) {
1170 /*
1171 * The `youngest_candidate_stream_iter->current_msg`
1172 * should go first. Update the next iterator
1173 * and the current timestamp.
1174 */
1175 youngest_candidate_msg_ts = stream_iter->current_msg_ts_ns;
1176 youngest_candidate_stream_iter = stream_iter;
1177 } else if (ret == 0) {
1178 /* Unable to pick which one should go first. */
1179 BT_CPPLOGW_SPEC(
1180 lttng_live_msg_iter->logger,
1181 "Cannot deterministically pick next live stream message iterator because they have identical next messages: "
1182 "stream-iter-addr={}"
1183 "youngest-candidate-stream-iter-addr={}",
1184 fmt::ptr(stream_iter), fmt::ptr(youngest_candidate_stream_iter));
1185 }
1186 }
1187 trace_idx++;
1188 } else {
1189 /*
1190 * trace_idx is not incremented since
1191 * vectorFastRemove replaces the
1192 * element at trace_idx with the array's last element.
1193 */
1194 bt2c::vectorFastRemove(session->traces, trace_idx);
1195 }
1196 }
1197 if (youngest_candidate_stream_iter) {
1198 *youngest_session_stream_iter = youngest_candidate_stream_iter;
1199 return LTTNG_LIVE_ITERATOR_STATUS_OK;
1200 } else {
1201 /*
1202 * The only cases where we don't have a candidate for this
1203 * trace is:
1204 * 1. if we reached the end of all the iterators of all the
1205 * traces of this session,
1206 * 2. if we never had live stream iterator in the first place.
1207 *
1208 * In either cases, we return END.
1209 */
1210 BT_ASSERT(session->traces.empty());
1211 return LTTNG_LIVE_ITERATOR_STATUS_END;
1212 }
1213 }
1214
1215 static inline void put_messages(bt_message_array_const msgs, uint64_t count)
1216 {
1217 uint64_t i;
1218
1219 for (i = 0; i < count; i++) {
1220 BT_MESSAGE_PUT_REF_AND_RESET(msgs[i]);
1221 }
1222 }
1223
1224 bt_message_iterator_class_next_method_status
1225 lttng_live_msg_iter_next(bt_self_message_iterator *self_msg_it, bt_message_array_const msgs,
1226 uint64_t capacity, uint64_t *count)
1227 {
1228 try {
1229 bt_message_iterator_class_next_method_status status;
1230 enum lttng_live_viewer_status viewer_status;
1231 struct lttng_live_msg_iter *lttng_live_msg_iter =
1232 (struct lttng_live_msg_iter *) bt_self_message_iterator_get_data(self_msg_it);
1233 struct lttng_live_component *lttng_live = lttng_live_msg_iter->lttng_live_comp;
1234 enum lttng_live_iterator_status stream_iter_status;
1235
1236 *count = 0;
1237
1238 BT_ASSERT_DBG(lttng_live_msg_iter);
1239
1240 if (G_UNLIKELY(lttng_live_msg_iter->was_interrupted)) {
1241 /*
1242 * The iterator was interrupted in a previous call to the
1243 * `_next()` method. We currently do not support generating
1244 * messages after such event. The babeltrace2 CLI should never
1245 * be running the graph after being interrupted. So this check
1246 * is to prevent other graph users from using this live
1247 * iterator in an messed up internal state.
1248 */
1249 BT_CPPLOGE_APPEND_CAUSE_SPEC(
1250 lttng_live_msg_iter->logger,
1251 "Message iterator was interrupted during a previous call to the `next()` and currently does not support continuing after such event.");
1252 return BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_ERROR;
1253 }
1254
1255 /*
1256 * Clear all the invalid message reference that might be left over in
1257 * the output array.
1258 */
1259 memset(msgs, 0, capacity * sizeof(*msgs));
1260
1261 /*
1262 * If no session are exposed on the relay found at the url provided by
1263 * the user, session count will be 0. In this case, we return status
1264 * end to return gracefully.
1265 */
1266 if (lttng_live_msg_iter->sessions.empty()) {
1267 if (lttng_live->params.sess_not_found_act != SESSION_NOT_FOUND_ACTION_CONTINUE) {
1268 return BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_END;
1269 } else {
1270 /*
1271 * The are no more active session for this session
1272 * name. Retry to create a viewer session for the
1273 * requested session name.
1274 */
1275 viewer_status = lttng_live_create_viewer_session(lttng_live_msg_iter);
1276 if (viewer_status != LTTNG_LIVE_VIEWER_STATUS_OK) {
1277 if (viewer_status == LTTNG_LIVE_VIEWER_STATUS_ERROR) {
1278 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
1279 "Error creating LTTng live viewer session");
1280 return BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_ERROR;
1281 } else if (viewer_status == LTTNG_LIVE_VIEWER_STATUS_INTERRUPTED) {
1282 return BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_AGAIN;
1283 } else {
1284 bt_common_abort();
1285 }
1286 }
1287 }
1288 }
1289
1290 if (lttng_live_msg_iter->active_stream_iter == 0) {
1291 lttng_live_force_new_streams_and_metadata(lttng_live_msg_iter);
1292 }
1293
1294 /*
1295 * Here the muxing of message is done.
1296 *
1297 * We need to iterate over all the streams of all the traces of all the
1298 * viewer sessions in order to get the message with the smallest
1299 * timestamp. In this case, a session is a viewer session and there is
1300 * one viewer session per consumer daemon. (UST 32bit, UST 64bit and/or
1301 * kernel). Each viewer session can have multiple traces, for example,
1302 * 64bit UST viewer sessions could have multiple per-pid traces.
1303 *
1304 * We iterate over the streams of each traces to update and see what is
1305 * their next message's timestamp. From those timestamps, we select the
1306 * message with the smallest timestamp as the best candidate message
1307 * for that trace and do the same thing across all the sessions.
1308 *
1309 * We then compare the timestamp of best candidate message of all the
1310 * sessions to pick the message with the smallest timestamp and we
1311 * return it.
1312 */
1313 while (*count < capacity) {
1314 struct lttng_live_stream_iterator *youngest_stream_iter = NULL,
1315 *candidate_stream_iter = NULL;
1316 int64_t youngest_msg_ts_ns = INT64_MAX;
1317
1318 uint64_t session_idx = 0;
1319 while (session_idx < lttng_live_msg_iter->sessions.size()) {
1320 lttng_live_session *session = lttng_live_msg_iter->sessions[session_idx].get();
1321
1322 /* Find the best candidate message to send downstream. */
1323 stream_iter_status = next_stream_iterator_for_session(lttng_live_msg_iter, session,
1324 &candidate_stream_iter);
1325
1326 /* If we receive an END status, it means that either:
1327 * - Those traces never had active streams (UST with no
1328 * data produced yet),
1329 * - All live stream iterators have ENDed.
1330 */
1331 if (stream_iter_status == LTTNG_LIVE_ITERATOR_STATUS_END) {
1332 if (session->closed && session->traces.empty()) {
1333 /*
1334 * Remove the session from the list.
1335 * session_idx is not modified since
1336 * g_ptr_array_remove_index_fast
1337 * replaces the the removed element with
1338 * the array's last element.
1339 */
1340 bt2c::vectorFastRemove(lttng_live_msg_iter->sessions, session_idx);
1341 } else {
1342 session_idx++;
1343 }
1344 continue;
1345 }
1346
1347 if (stream_iter_status != LTTNG_LIVE_ITERATOR_STATUS_OK) {
1348 goto return_status;
1349 }
1350
1351 if (G_UNLIKELY(youngest_stream_iter == NULL) ||
1352 candidate_stream_iter->current_msg_ts_ns < youngest_msg_ts_ns) {
1353 youngest_msg_ts_ns = candidate_stream_iter->current_msg_ts_ns;
1354 youngest_stream_iter = candidate_stream_iter;
1355 } else if (candidate_stream_iter->current_msg_ts_ns == youngest_msg_ts_ns) {
1356 /*
1357 * The currently selected message to be sent
1358 * downstream next has the exact same timestamp
1359 * that of the current candidate message. We
1360 * must break the tie in a predictable manner.
1361 */
1362 BT_CPPLOGD_SPEC(
1363 lttng_live_msg_iter->logger,
1364 "Two of the next message candidates have the same timestamps, pick one deterministically.");
1365 /*
1366 * Order the messages in an arbitrary but
1367 * deterministic way.
1368 */
1369 int ret = common_muxing_compare_messages(
1370 candidate_stream_iter->current_msg->libObjPtr(),
1371 youngest_stream_iter->current_msg->libObjPtr());
1372 if (ret < 0) {
1373 /*
1374 * The `candidate_stream_iter->current_msg`
1375 * should go first. Update the next
1376 * iterator and the current timestamp.
1377 */
1378 youngest_msg_ts_ns = candidate_stream_iter->current_msg_ts_ns;
1379 youngest_stream_iter = candidate_stream_iter;
1380 } else if (ret == 0) {
1381 /* Unable to pick which one should go first. */
1382 BT_CPPLOGW_SPEC(
1383 lttng_live_msg_iter->logger,
1384 "Cannot deterministically pick next live stream message iterator because they have identical next messages: "
1385 "next-stream-iter-addr={}"
1386 "candidate-stream-iter-addr={}",
1387 fmt::ptr(youngest_stream_iter), fmt::ptr(candidate_stream_iter));
1388 }
1389 }
1390
1391 session_idx++;
1392 }
1393
1394 if (!youngest_stream_iter) {
1395 stream_iter_status = LTTNG_LIVE_ITERATOR_STATUS_AGAIN;
1396 goto return_status;
1397 }
1398
1399 BT_ASSERT_DBG(youngest_stream_iter->current_msg);
1400 /* Ensure monotonicity. */
1401 BT_ASSERT_DBG(lttng_live_msg_iter->last_msg_ts_ns <=
1402 youngest_stream_iter->current_msg_ts_ns);
1403
1404 /*
1405 * Insert the next message to the message batch. This will set
1406 * stream iterator current message to NULL so that next time
1407 * we fetch the next message of that stream iterator
1408 */
1409 msgs[*count] = youngest_stream_iter->current_msg.release().libObjPtr();
1410 (*count)++;
1411
1412 /* Update the last timestamp in nanoseconds sent downstream. */
1413 lttng_live_msg_iter->last_msg_ts_ns = youngest_msg_ts_ns;
1414 youngest_stream_iter->current_msg_ts_ns = INT64_MAX;
1415
1416 stream_iter_status = LTTNG_LIVE_ITERATOR_STATUS_OK;
1417 }
1418
1419 return_status:
1420 switch (stream_iter_status) {
1421 case LTTNG_LIVE_ITERATOR_STATUS_OK:
1422 case LTTNG_LIVE_ITERATOR_STATUS_AGAIN:
1423 /*
1424 * If we gathered messages, return _OK even if the graph was
1425 * interrupted. This allows for the components downstream to at
1426 * least get the those messages. If the graph was indeed
1427 * interrupted there should not be another _next() call as the
1428 * application will tear down the graph. This component class
1429 * doesn't support restarting after an interruption.
1430 */
1431 if (*count > 0) {
1432 status = BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_OK;
1433 } else {
1434 status = BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_AGAIN;
1435 }
1436 break;
1437 case LTTNG_LIVE_ITERATOR_STATUS_END:
1438 status = BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_END;
1439 break;
1440 case LTTNG_LIVE_ITERATOR_STATUS_NOMEM:
1441 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
1442 "Memory error preparing the next batch of messages: "
1443 "live-iter-status={}",
1444 stream_iter_status);
1445 status = BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_MEMORY_ERROR;
1446 break;
1447 case LTTNG_LIVE_ITERATOR_STATUS_ERROR:
1448 case LTTNG_LIVE_ITERATOR_STATUS_INVAL:
1449 case LTTNG_LIVE_ITERATOR_STATUS_UNSUPPORTED:
1450 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
1451 "Error preparing the next batch of messages: "
1452 "live-iter-status={}",
1453 stream_iter_status);
1454
1455 status = BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_ERROR;
1456 /* Put all existing messages on error. */
1457 put_messages(msgs, *count);
1458 break;
1459 default:
1460 bt_common_abort();
1461 }
1462
1463 return status;
1464 } catch (const std::bad_alloc&) {
1465 return BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_MEMORY_ERROR;
1466 } catch (const bt2::Error&) {
1467 return BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_ERROR;
1468 }
1469 }
1470
1471 static lttng_live_msg_iter::UP
1472 lttng_live_msg_iter_create(struct lttng_live_component *lttng_live_comp,
1473 const bt2::SelfMessageIterator selfMsgIter)
1474 {
1475 auto msg_iter = bt2s::make_unique<struct lttng_live_msg_iter>(
1476 lttng_live_comp->logger, lttng_live_comp->selfComp, selfMsgIter);
1477
1478 msg_iter->lttng_live_comp = lttng_live_comp;
1479 msg_iter->active_stream_iter = 0;
1480 msg_iter->last_msg_ts_ns = INT64_MIN;
1481 msg_iter->was_interrupted = false;
1482
1483 return msg_iter;
1484 }
1485
1486 bt_message_iterator_class_initialize_method_status
1487 lttng_live_msg_iter_init(bt_self_message_iterator *self_msg_it,
1488 bt_self_message_iterator_configuration *, bt_self_component_port_output *)
1489 {
1490 try {
1491 struct lttng_live_component *lttng_live;
1492 enum lttng_live_viewer_status viewer_status;
1493 bt_self_component *self_comp = bt_self_message_iterator_borrow_component(self_msg_it);
1494
1495 lttng_live = (lttng_live_component *) bt_self_component_get_data(self_comp);
1496
1497 /* There can be only one downstream iterator at the same time. */
1498 BT_ASSERT(!lttng_live->has_msg_iter);
1499 lttng_live->has_msg_iter = true;
1500
1501 auto lttng_live_msg_iter = lttng_live_msg_iter_create(lttng_live, bt2::wrap(self_msg_it));
1502 if (!lttng_live_msg_iter) {
1503 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live->logger,
1504 "Failed to create lttng_live_msg_iter");
1505 return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_MEMORY_ERROR;
1506 }
1507
1508 viewer_status = live_viewer_connection_create(
1509 lttng_live->params.url.c_str(), false, lttng_live_msg_iter.get(),
1510 lttng_live_msg_iter->logger, lttng_live_msg_iter->viewer_connection);
1511 if (viewer_status != LTTNG_LIVE_VIEWER_STATUS_OK) {
1512 if (viewer_status == LTTNG_LIVE_VIEWER_STATUS_ERROR) {
1513 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
1514 "Failed to create viewer connection");
1515 } else if (viewer_status == LTTNG_LIVE_VIEWER_STATUS_INTERRUPTED) {
1516 /*
1517 * Interruption in the _iter_init() method is not
1518 * supported. Return an error.
1519 */
1520 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
1521 "Interrupted while creating viewer connection");
1522 }
1523
1524 return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
1525 }
1526
1527 viewer_status = lttng_live_create_viewer_session(lttng_live_msg_iter.get());
1528 if (viewer_status != LTTNG_LIVE_VIEWER_STATUS_OK) {
1529 if (viewer_status == LTTNG_LIVE_VIEWER_STATUS_ERROR) {
1530 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
1531 "Failed to create viewer session");
1532 } else if (viewer_status == LTTNG_LIVE_VIEWER_STATUS_INTERRUPTED) {
1533 /*
1534 * Interruption in the _iter_init() method is not
1535 * supported. Return an error.
1536 */
1537 BT_CPPLOGE_APPEND_CAUSE_SPEC(lttng_live_msg_iter->logger,
1538 "Interrupted when creating viewer session");
1539 }
1540
1541 return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
1542 }
1543
1544 if (lttng_live_msg_iter->sessions.empty()) {
1545 switch (lttng_live->params.sess_not_found_act) {
1546 case SESSION_NOT_FOUND_ACTION_CONTINUE:
1547 BT_CPPLOGI_SPEC(
1548 lttng_live_msg_iter->logger,
1549 "Unable to connect to the requested live viewer session. "
1550 "Keep trying to connect because of {}=\"{}\" component parameter: url=\"{}\"",
1551 SESS_NOT_FOUND_ACTION_PARAM, SESS_NOT_FOUND_ACTION_CONTINUE_STR,
1552 lttng_live->params.url);
1553 break;
1554 case SESSION_NOT_FOUND_ACTION_FAIL:
1555 BT_CPPLOGE_APPEND_CAUSE_SPEC(
1556 lttng_live_msg_iter->logger,
1557 "Unable to connect to the requested live viewer session. "
1558 "Fail the message iterator initialization because of {}=\"{}\" "
1559 "component parameter: url =\"{}\"",
1560 SESS_NOT_FOUND_ACTION_PARAM, SESS_NOT_FOUND_ACTION_FAIL_STR,
1561 lttng_live->params.url);
1562 return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
1563 case SESSION_NOT_FOUND_ACTION_END:
1564 BT_CPPLOGI_SPEC(lttng_live_msg_iter->logger,
1565 "Unable to connect to the requested live viewer session. "
1566 "End gracefully at the first _next() call because of {}=\"{}\""
1567 " component parameter: url=\"{}\"",
1568 SESS_NOT_FOUND_ACTION_PARAM, SESS_NOT_FOUND_ACTION_END_STR,
1569 lttng_live->params.url);
1570 break;
1571 default:
1572 bt_common_abort();
1573 }
1574 }
1575
1576 bt_self_message_iterator_set_data(self_msg_it, lttng_live_msg_iter.release());
1577 return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_OK;
1578 } catch (const std::bad_alloc&) {
1579 return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_MEMORY_ERROR;
1580 } catch (const bt2::Error&) {
1581 return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
1582 }
1583 }
1584
1585 static struct bt_param_validation_map_value_entry_descr list_sessions_params[] = {
1586 {URL_PARAM, BT_PARAM_VALIDATION_MAP_VALUE_ENTRY_MANDATORY,
1587 bt_param_validation_value_descr::makeString()},
1588 BT_PARAM_VALIDATION_MAP_VALUE_ENTRY_END};
1589
1590 static bt2::Value::Shared lttng_live_query_list_sessions(const bt2::ConstMapValue params,
1591 const bt2c::Logger& logger)
1592 {
1593 const char *url;
1594 live_viewer_connection::UP viewer_connection;
1595 enum lttng_live_viewer_status viewer_status;
1596 enum bt_param_validation_status validation_status;
1597 gchar *validate_error = NULL;
1598
1599 validation_status =
1600 bt_param_validation_validate(params.libObjPtr(), list_sessions_params, &validate_error);
1601 if (validation_status == BT_PARAM_VALIDATION_STATUS_MEMORY_ERROR) {
1602 throw bt2c::MemoryError {};
1603 } else if (validation_status == BT_PARAM_VALIDATION_STATUS_VALIDATION_ERROR) {
1604 bt2c::GCharUP errorFreer {validate_error};
1605
1606 BT_CPPLOGE_APPEND_CAUSE_AND_THROW_SPEC(logger, bt2::Error, "{}", validate_error);
1607 }
1608
1609 url = params[URL_PARAM]->asString().value();
1610
1611 viewer_status = live_viewer_connection_create(url, true, NULL, logger, viewer_connection);
1612 if (viewer_status != LTTNG_LIVE_VIEWER_STATUS_OK) {
1613 if (viewer_status == LTTNG_LIVE_VIEWER_STATUS_ERROR) {
1614 BT_CPPLOGE_APPEND_CAUSE_AND_THROW_SPEC(logger, bt2::Error,
1615 "Failed to create viewer connection");
1616 } else if (viewer_status == LTTNG_LIVE_VIEWER_STATUS_INTERRUPTED) {
1617 throw bt2c::TryAgain {};
1618 } else {
1619 bt_common_abort();
1620 }
1621 }
1622
1623 return live_viewer_connection_list_sessions(viewer_connection.get());
1624 }
1625
1626 static bt2::Value::Shared lttng_live_query_support_info(const bt2::ConstMapValue params,
1627 const bt2c::Logger& logger)
1628 {
1629 struct bt_common_lttng_live_url_parts parts = {};
1630 bt_common_lttng_live_url_parts_deleter partsDeleter {parts};
1631
1632 const auto typeValue = params["type"];
1633 if (!typeValue) {
1634 BT_CPPLOGE_APPEND_CAUSE_AND_THROW_SPEC(logger, bt2::Error,
1635 "Missing expected `type` parameter.");
1636 }
1637
1638 if (!typeValue->isString()) {
1639 BT_CPPLOGE_APPEND_CAUSE_AND_THROW_SPEC(logger, bt2::Error,
1640 "`type` parameter is not a string value.");
1641 }
1642
1643 if (strcmp(typeValue->asString().value(), "string") != 0) {
1644 /* We don't handle file system paths */
1645 return bt2::RealValue::create();
1646 }
1647
1648 const auto inputValue = params["input"];
1649 if (!inputValue) {
1650 BT_CPPLOGE_APPEND_CAUSE_AND_THROW_SPEC(logger, bt2::Error,
1651 "Missing expected `input` parameter.");
1652 }
1653
1654 if (!inputValue->isString()) {
1655 BT_CPPLOGE_APPEND_CAUSE_AND_THROW_SPEC(logger, bt2::Error,
1656 "`input` parameter is not a string value.");
1657 }
1658
1659 parts = bt_common_parse_lttng_live_url(inputValue->asString().value(), NULL, 0);
1660 if (parts.session_name) {
1661 /*
1662 * Looks pretty much like an LTTng live URL: we got the
1663 * session name part, which forms a complete URL.
1664 */
1665 return bt2::RealValue::create(.75);
1666 }
1667
1668 return bt2::RealValue::create();
1669 }
1670
1671 bt_component_class_query_method_status lttng_live_query(bt_self_component_class_source *comp_class,
1672 bt_private_query_executor *priv_query_exec,
1673 const char *object, const bt_value *params,
1674 __attribute__((unused)) void *method_data,
1675 const bt_value **result)
1676 {
1677 try {
1678 bt2c::Logger logger {bt2::SelfComponentClass {comp_class},
1679 bt2::PrivateQueryExecutor {priv_query_exec},
1680 "PLUGIN/SRC.CTF.LTTNG-LIVE/QUERY"};
1681 const bt2::ConstMapValue paramsObj(params);
1682 bt2::Value::Shared resultObj;
1683
1684 if (strcmp(object, "sessions") == 0) {
1685 resultObj = lttng_live_query_list_sessions(paramsObj, logger);
1686 } else if (strcmp(object, "babeltrace.support-info") == 0) {
1687 resultObj = lttng_live_query_support_info(paramsObj, logger);
1688 } else {
1689 BT_CPPLOGI_SPEC(logger, "Unknown query object `{}`", object);
1690 return BT_COMPONENT_CLASS_QUERY_METHOD_STATUS_UNKNOWN_OBJECT;
1691 }
1692
1693 *result = resultObj.release().libObjPtr();
1694
1695 return BT_COMPONENT_CLASS_QUERY_METHOD_STATUS_OK;
1696 } catch (const bt2c::TryAgain&) {
1697 return BT_COMPONENT_CLASS_QUERY_METHOD_STATUS_MEMORY_ERROR;
1698 } catch (const std::bad_alloc&) {
1699 return BT_COMPONENT_CLASS_QUERY_METHOD_STATUS_MEMORY_ERROR;
1700 } catch (const bt2::Error&) {
1701 return BT_COMPONENT_CLASS_QUERY_METHOD_STATUS_ERROR;
1702 }
1703 }
1704
1705 void lttng_live_component_finalize(bt_self_component_source *component)
1706 {
1707 lttng_live_component::UP {static_cast<lttng_live_component *>(
1708 bt_self_component_get_data(bt_self_component_source_as_self_component(component)))};
1709 }
1710
1711 static enum session_not_found_action
1712 parse_session_not_found_action_param(const bt_value *no_session_param)
1713 {
1714 enum session_not_found_action action;
1715 const char *no_session_act_str = bt_value_string_get(no_session_param);
1716
1717 if (strcmp(no_session_act_str, SESS_NOT_FOUND_ACTION_CONTINUE_STR) == 0) {
1718 action = SESSION_NOT_FOUND_ACTION_CONTINUE;
1719 } else if (strcmp(no_session_act_str, SESS_NOT_FOUND_ACTION_FAIL_STR) == 0) {
1720 action = SESSION_NOT_FOUND_ACTION_FAIL;
1721 } else {
1722 BT_ASSERT(strcmp(no_session_act_str, SESS_NOT_FOUND_ACTION_END_STR) == 0);
1723 action = SESSION_NOT_FOUND_ACTION_END;
1724 }
1725
1726 return action;
1727 }
1728
1729 static bt_param_validation_value_descr inputs_elem_descr =
1730 bt_param_validation_value_descr::makeString();
1731
1732 static const char *sess_not_found_action_choices[] = {
1733 SESS_NOT_FOUND_ACTION_CONTINUE_STR,
1734 SESS_NOT_FOUND_ACTION_FAIL_STR,
1735 SESS_NOT_FOUND_ACTION_END_STR,
1736 };
1737
1738 static struct bt_param_validation_map_value_entry_descr params_descr[] = {
1739 {INPUTS_PARAM, BT_PARAM_VALIDATION_MAP_VALUE_ENTRY_MANDATORY,
1740 bt_param_validation_value_descr::makeArray(1, 1, inputs_elem_descr)},
1741 {SESS_NOT_FOUND_ACTION_PARAM, BT_PARAM_VALIDATION_MAP_VALUE_ENTRY_OPTIONAL,
1742 bt_param_validation_value_descr::makeString(sess_not_found_action_choices)},
1743 BT_PARAM_VALIDATION_MAP_VALUE_ENTRY_END};
1744
1745 static bt_component_class_initialize_method_status
1746 lttng_live_component_create(const bt_value *params, bt_self_component_source *self_comp,
1747 lttng_live_component::UP& component)
1748 {
1749 const bt_value *inputs_value;
1750 const bt_value *url_value;
1751 const bt_value *value;
1752 enum bt_param_validation_status validation_status;
1753 gchar *validation_error = NULL;
1754 bt2c::Logger logger {bt2::wrap(self_comp), "PLUGIN/SRC.CTF.LTTNG-LIVE/COMP"};
1755
1756 validation_status = bt_param_validation_validate(params, params_descr, &validation_error);
1757 if (validation_status == BT_PARAM_VALIDATION_STATUS_MEMORY_ERROR) {
1758 return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_MEMORY_ERROR;
1759 } else if (validation_status == BT_PARAM_VALIDATION_STATUS_VALIDATION_ERROR) {
1760 bt2c::GCharUP errorFreer {validation_error};
1761 BT_CPPLOGE_APPEND_CAUSE_SPEC(logger, "{}", validation_error);
1762 return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
1763 }
1764
1765 auto lttng_live =
1766 bt2s::make_unique<lttng_live_component>(std::move(logger), bt2::wrap(self_comp));
1767
1768 lttng_live->max_query_size = MAX_QUERY_SIZE;
1769 lttng_live->has_msg_iter = false;
1770
1771 inputs_value = bt_value_map_borrow_entry_value_const(params, INPUTS_PARAM);
1772 url_value = bt_value_array_borrow_element_by_index_const(inputs_value, 0);
1773 lttng_live->params.url = bt_value_string_get(url_value);
1774
1775 value = bt_value_map_borrow_entry_value_const(params, SESS_NOT_FOUND_ACTION_PARAM);
1776 if (value) {
1777 lttng_live->params.sess_not_found_act = parse_session_not_found_action_param(value);
1778 } else {
1779 BT_CPPLOGI_SPEC(lttng_live->logger,
1780 "Optional `{}` parameter is missing: defaulting to `{}`.",
1781 SESS_NOT_FOUND_ACTION_PARAM, SESS_NOT_FOUND_ACTION_CONTINUE_STR);
1782 lttng_live->params.sess_not_found_act = SESSION_NOT_FOUND_ACTION_CONTINUE;
1783 }
1784
1785 component = std::move(lttng_live);
1786 return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_OK;
1787 }
1788
1789 bt_component_class_initialize_method_status
1790 lttng_live_component_init(bt_self_component_source *self_comp_src,
1791 bt_self_component_source_configuration *, const bt_value *params, void *)
1792 {
1793 try {
1794 lttng_live_component::UP lttng_live;
1795 bt_component_class_initialize_method_status ret;
1796 bt_self_component_add_port_status add_port_status;
1797
1798 ret = lttng_live_component_create(params, self_comp_src, lttng_live);
1799 if (ret != BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_OK) {
1800 return ret;
1801 }
1802
1803 add_port_status =
1804 bt_self_component_source_add_output_port(self_comp_src, "out", NULL, NULL);
1805 if (add_port_status != BT_SELF_COMPONENT_ADD_PORT_STATUS_OK) {
1806 ret = (bt_component_class_initialize_method_status) add_port_status;
1807 return ret;
1808 }
1809
1810 bt_self_component_set_data(bt_self_component_source_as_self_component(self_comp_src),
1811 lttng_live.release());
1812
1813 return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_OK;
1814 } catch (const std::bad_alloc&) {
1815 return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_MEMORY_ERROR;
1816 } catch (const bt2::Error&) {
1817 return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
1818 }
1819 }
This page took 0.064463 seconds and 5 git commands to generate.