src.ctf.fs: make ctf_fs_ds_index_create return a unique_ptr
[babeltrace.git] / src / plugins / ctf / fs-src / fs.cpp
CommitLineData
7a278c8e 1/*
0235b0db 2 * SPDX-License-Identifier: MIT
7a278c8e 3 *
1a9f7075 4 * Copyright 2015-2017 Philippe Proulx <pproulx@efficios.com>
f3bc2010 5 * Copyright 2016 Jérémie Galarneau <jeremie.galarneau@efficios.com>
7a278c8e 6 *
0235b0db 7 * Babeltrace CTF file system Reader Component
7a278c8e
JG
8 */
9
c802cacb
SM
10#include <glib.h>
11#include <inttypes.h>
c802cacb
SM
12
13#include <babeltrace2/babeltrace.h>
14
c802cacb 15#include "common/assert.h"
578e048b 16#include "common/common.h"
6162e6b7 17#include "common/uuid.h"
945312a2 18#include "cpp-common/bt2s/make-unique.hpp"
c802cacb
SM
19
20#include "plugins/common/param-validation/param-validation.h"
21
5656cea5
PP
22#include "../common/src/metadata/tsdl/ctf-meta-configure-ir-trace.hpp"
23#include "../common/src/msg-iter/msg-iter.hpp"
c802cacb
SM
24#include "data-stream-file.hpp"
25#include "file.hpp"
26#include "fs.hpp"
27#include "metadata.hpp"
087cd0f5 28#include "query.hpp"
e7a4393b 29
4164020e
SM
30struct tracer_info
31{
32 const char *name;
33 int64_t major;
34 int64_t minor;
35 int64_t patch;
626cc488
FD
36};
37
4164020e 38static void ctf_fs_msg_iter_data_destroy(struct ctf_fs_msg_iter_data *msg_iter_data)
94cf822e 39{
4164020e
SM
40 if (!msg_iter_data) {
41 return;
42 }
94cf822e 43
4164020e
SM
44 if (msg_iter_data->msg_iter) {
45 ctf_msg_iter_destroy(msg_iter_data->msg_iter);
46 }
6de92955 47
4164020e
SM
48 if (msg_iter_data->msg_iter_medops_data) {
49 ctf_fs_ds_group_medops_data_destroy(msg_iter_data->msg_iter_medops_data);
50 }
94cf822e 51
afb0f12b 52 delete msg_iter_data;
fc917f65
PP
53}
54
4164020e
SM
55static bt_message_iterator_class_next_method_status
56ctf_fs_iterator_next_one(struct ctf_fs_msg_iter_data *msg_iter_data, const bt_message **out_msg)
ea0b4b9e 57{
4164020e
SM
58 bt_message_iterator_class_next_method_status status;
59 enum ctf_msg_iter_status msg_iter_status;
4164020e
SM
60
61 msg_iter_status = ctf_msg_iter_get_next_message(msg_iter_data->msg_iter, out_msg);
62
63 switch (msg_iter_status) {
64 case CTF_MSG_ITER_STATUS_OK:
65 /* Cool, message has been written to *out_msg. */
66 status = BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_OK;
67 break;
68
69 case CTF_MSG_ITER_STATUS_EOF:
70 status = BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_END;
71 break;
72
73 case CTF_MSG_ITER_STATUS_AGAIN:
74 /*
75 * Should not make it this far as this is
76 * medium-specific; there is nothing for the user to do
77 * and it should have been handled upstream.
78 */
79 bt_common_abort();
80
81 case CTF_MSG_ITER_STATUS_ERROR:
0f5c5d5c
SM
82 BT_CPPLOGE_APPEND_CAUSE_SPEC(msg_iter_data->logger,
83 "Failed to get next message from CTF message iterator.");
4164020e
SM
84 status = BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_ERROR;
85 break;
86
87 case CTF_MSG_ITER_STATUS_MEMORY_ERROR:
0f5c5d5c
SM
88 BT_CPPLOGE_APPEND_CAUSE_SPEC(msg_iter_data->logger,
89 "Failed to get next message from CTF message iterator.");
4164020e
SM
90 status = BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_MEMORY_ERROR;
91 break;
92
93 default:
94 bt_common_abort();
95 }
96
97 return status;
d4393e08
PP
98}
99
4164020e
SM
100bt_message_iterator_class_next_method_status
101ctf_fs_iterator_next(bt_self_message_iterator *iterator, bt_message_array_const msgs,
102 uint64_t capacity, uint64_t *count)
d4393e08 103{
1e690349
SM
104 try {
105 bt_message_iterator_class_next_method_status status;
106 struct ctf_fs_msg_iter_data *msg_iter_data =
107 (struct ctf_fs_msg_iter_data *) bt_self_message_iterator_get_data(iterator);
108 uint64_t i = 0;
4164020e 109
1e690349
SM
110 if (G_UNLIKELY(msg_iter_data->next_saved_error)) {
111 /*
4164020e
SM
112 * Last time we were called, we hit an error but had some
113 * messages to deliver, so we stashed the error here. Return
114 * it now.
115 */
1e690349
SM
116 BT_CURRENT_THREAD_MOVE_ERROR_AND_RESET(msg_iter_data->next_saved_error);
117 status = msg_iter_data->next_saved_status;
118 goto end;
4164020e 119 }
4164020e 120
1e690349
SM
121 do {
122 status = ctf_fs_iterator_next_one(msg_iter_data, &msgs[i]);
123 if (status == BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_OK) {
124 i++;
125 }
126 } while (i < capacity && status == BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_OK);
127
128 if (i > 0) {
129 /*
4164020e
SM
130 * Even if ctf_fs_iterator_next_one() returned something
131 * else than BT_MESSAGE_ITERATOR_NEXT_METHOD_STATUS_OK, we
132 * accumulated message objects in the output
133 * message array, so we need to return
134 * BT_MESSAGE_ITERATOR_NEXT_METHOD_STATUS_OK so that they are
e7401568 135 * transferred to downstream. This other status occurs
4164020e
SM
136 * again the next time muxer_msg_iter_do_next() is
137 * called, possibly without any accumulated
138 * message, in which case we'll return it.
139 */
1e690349
SM
140 if (status < 0) {
141 /*
4164020e
SM
142 * Save this error for the next _next call. Assume that
143 * this component always appends error causes when
144 * returning an error status code, which will cause the
145 * current thread error to be non-NULL.
146 */
1e690349
SM
147 msg_iter_data->next_saved_error = bt_current_thread_take_error();
148 BT_ASSERT(msg_iter_data->next_saved_error);
149 msg_iter_data->next_saved_status = status;
150 }
4164020e 151
1e690349
SM
152 *count = i;
153 status = BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_OK;
154 }
d4393e08 155
cbca1c06 156end:
1e690349
SM
157 return status;
158 return status;
159 } catch (const std::bad_alloc&) {
160 return BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_MEMORY_ERROR;
161 } catch (const bt2::Error&) {
162 return BT_MESSAGE_ITERATOR_CLASS_NEXT_METHOD_STATUS_ERROR;
163 }
ea0b4b9e 164}
bfd20a42 165
a3f0c7db 166bt_message_iterator_class_seek_beginning_method_status
d24d5663 167ctf_fs_iterator_seek_beginning(bt_self_message_iterator *it)
6a9bb5e9 168{
1e690349
SM
169 try {
170 struct ctf_fs_msg_iter_data *msg_iter_data =
171 (struct ctf_fs_msg_iter_data *) bt_self_message_iterator_get_data(it);
6a9bb5e9 172
1e690349 173 BT_ASSERT(msg_iter_data);
6a9bb5e9 174
1e690349
SM
175 ctf_msg_iter_reset(msg_iter_data->msg_iter);
176 ctf_fs_ds_group_medops_data_reset(msg_iter_data->msg_iter_medops_data);
f6e68e70 177
1e690349
SM
178 return BT_MESSAGE_ITERATOR_CLASS_SEEK_BEGINNING_METHOD_STATUS_OK;
179 } catch (const std::bad_alloc&) {
180 return BT_MESSAGE_ITERATOR_CLASS_SEEK_BEGINNING_METHOD_STATUS_MEMORY_ERROR;
181 } catch (const bt2::Error&) {
182 return BT_MESSAGE_ITERATOR_CLASS_SEEK_BEGINNING_METHOD_STATUS_ERROR;
183 }
6a9bb5e9
PP
184}
185
d6e69534 186void ctf_fs_iterator_finalize(bt_self_message_iterator *it)
760051fa 187{
4164020e
SM
188 ctf_fs_msg_iter_data_destroy(
189 (struct ctf_fs_msg_iter_data *) bt_self_message_iterator_get_data(it));
760051fa
JG
190}
191
4164020e
SM
192static bt_message_iterator_class_initialize_method_status
193ctf_msg_iter_medium_status_to_msg_iter_initialize_status(enum ctf_msg_iter_medium_status status)
1b7b1ef9 194{
4164020e
SM
195 switch (status) {
196 case CTF_MSG_ITER_MEDIUM_STATUS_EOF:
197 case CTF_MSG_ITER_MEDIUM_STATUS_AGAIN:
198 case CTF_MSG_ITER_MEDIUM_STATUS_ERROR:
199 return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
200 case CTF_MSG_ITER_MEDIUM_STATUS_MEMORY_ERROR:
201 return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_MEMORY_ERROR;
202 case CTF_MSG_ITER_MEDIUM_STATUS_OK:
203 return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_OK;
204 }
205
206 bt_common_abort();
1b7b1ef9
SM
207}
208
4164020e
SM
209bt_message_iterator_class_initialize_method_status
210ctf_fs_iterator_init(bt_self_message_iterator *self_msg_iter,
211 bt_self_message_iterator_configuration *config,
212 bt_self_component_port_output *self_port)
4c1456f0 213{
1e690349
SM
214 try {
215 struct ctf_fs_port_data *port_data;
216 bt_message_iterator_class_initialize_method_status status;
217 enum ctf_msg_iter_medium_status medium_status;
218
219 port_data = (struct ctf_fs_port_data *) bt_self_component_port_get_data(
220 bt_self_component_port_output_as_self_component_port(self_port));
221 BT_ASSERT(port_data);
222
223 ctf_fs_msg_iter_data *msg_iter_data = new ctf_fs_msg_iter_data {self_msg_iter};
224 msg_iter_data->ds_file_group = port_data->ds_file_group;
225
226 medium_status = ctf_fs_ds_group_medops_data_create(msg_iter_data->ds_file_group,
227 self_msg_iter, msg_iter_data->logger,
228 &msg_iter_data->msg_iter_medops_data);
229 BT_ASSERT(medium_status == CTF_MSG_ITER_MEDIUM_STATUS_OK ||
230 medium_status == CTF_MSG_ITER_MEDIUM_STATUS_ERROR ||
231 medium_status == CTF_MSG_ITER_MEDIUM_STATUS_MEMORY_ERROR);
232 if (medium_status != CTF_MSG_ITER_MEDIUM_STATUS_OK) {
233 BT_CPPLOGE_APPEND_CAUSE_SPEC(msg_iter_data->logger,
234 "Failed to create ctf_fs_ds_group_medops");
235 status = ctf_msg_iter_medium_status_to_msg_iter_initialize_status(medium_status);
236 goto error;
237 }
4164020e 238
1e690349
SM
239 msg_iter_data->msg_iter = ctf_msg_iter_create(
240 msg_iter_data->ds_file_group->ctf_fs_trace->metadata->tc,
241 bt_common_get_page_size(static_cast<int>(msg_iter_data->logger.level())) * 8,
242 ctf_fs_ds_group_medops, msg_iter_data->msg_iter_medops_data, self_msg_iter,
243 msg_iter_data->logger);
244 if (!msg_iter_data->msg_iter) {
245 BT_CPPLOGE_APPEND_CAUSE_SPEC(msg_iter_data->logger,
246 "Cannot create a CTF message iterator.");
247 status = BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_MEMORY_ERROR;
248 goto error;
249 }
4164020e 250
1e690349 251 /*
4164020e
SM
252 * This iterator can seek forward if its stream class has a default
253 * clock class.
254 */
1e690349
SM
255 if (msg_iter_data->ds_file_group->sc->default_clock_class) {
256 bt_self_message_iterator_configuration_set_can_seek_forward(config, true);
257 }
4164020e 258
1e690349
SM
259 bt_self_message_iterator_set_data(self_msg_iter, msg_iter_data);
260 msg_iter_data = NULL;
4164020e 261
1e690349
SM
262 status = BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_OK;
263 goto end;
5b29e799 264
4f1f88a6 265error:
1e690349 266 bt_self_message_iterator_set_data(self_msg_iter, NULL);
4f1f88a6 267
760051fa 268end:
1e690349
SM
269 ctf_fs_msg_iter_data_destroy(msg_iter_data);
270 return status;
271 } catch (const std::bad_alloc&) {
272 return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_MEMORY_ERROR;
273 } catch (const bt2::Error&) {
274 return BT_MESSAGE_ITERATOR_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
275 }
760051fa
JG
276}
277
4164020e 278static void ctf_fs_trace_destroy(struct ctf_fs_trace *ctf_fs_trace)
a0cd55ad 279{
4164020e
SM
280 if (!ctf_fs_trace) {
281 return;
282 }
a0cd55ad 283
4164020e 284 BT_TRACE_PUT_REF_AND_RESET(ctf_fs_trace->trace);
a0cd55ad 285
4164020e
SM
286 if (ctf_fs_trace->path) {
287 g_string_free(ctf_fs_trace->path, TRUE);
288 }
a0cd55ad 289
4164020e
SM
290 if (ctf_fs_trace->metadata) {
291 ctf_fs_metadata_fini(ctf_fs_trace->metadata);
afb0f12b 292 delete ctf_fs_trace->metadata;
4164020e 293 }
a0cd55ad 294
afb0f12b 295 delete ctf_fs_trace;
a0cd55ad
SM
296}
297
7df773f2
SM
298void ctf_fs_trace_deleter::operator()(ctf_fs_trace * const trace) noexcept
299{
300 ctf_fs_trace_destroy(trace);
301}
302
1a9f7075 303void ctf_fs_destroy(struct ctf_fs_component *ctf_fs)
760051fa 304{
4164020e
SM
305 if (!ctf_fs) {
306 return;
307 }
4f1f88a6 308
afb0f12b 309 delete ctf_fs;
1a9f7075
PP
310}
311
f340a3e8
SM
312void ctf_fs_component_deleter::operator()(ctf_fs_component *comp)
313{
314 ctf_fs_destroy(comp);
315}
316
f340a3e8 317ctf_fs_component::UP ctf_fs_component_create(const bt2c::Logger& parentLogger)
a4792757 318{
945312a2 319 return ctf_fs_component::UP {new ctf_fs_component {parentLogger}};
f280892e
SM
320}
321
322void ctf_fs_finalize(bt_self_component_source *component)
323{
4164020e
SM
324 ctf_fs_destroy((struct ctf_fs_component *) bt_self_component_get_data(
325 bt_self_component_source_as_self_component(component)));
5b29e799
JG
326}
327
49b956cc 328bt2c::GCharUP ctf_fs_make_port_name(struct ctf_fs_ds_file_group *ds_file_group)
547eacf1 329{
4164020e
SM
330 GString *name = g_string_new(NULL);
331
332 /*
333 * The unique port name is generated by concatenating unique identifiers
334 * for:
335 *
336 * - the trace
337 * - the stream class
338 * - the stream
339 */
340
341 /* For the trace, use the uuid if present, else the path. */
342 if (ds_file_group->ctf_fs_trace->metadata->tc->is_uuid_set) {
343 char uuid_str[BT_UUID_STR_LEN + 1];
344
345 bt_uuid_to_str(ds_file_group->ctf_fs_trace->metadata->tc->uuid, uuid_str);
346 g_string_assign(name, uuid_str);
347 } else {
348 g_string_assign(name, ds_file_group->ctf_fs_trace->path->str);
349 }
350
351 /*
352 * For the stream class, use the id if present. We can omit this field
353 * otherwise, as there will only be a single stream class.
354 */
355 if (ds_file_group->sc->id != UINT64_C(-1)) {
356 g_string_append_printf(name, " | %" PRIu64, ds_file_group->sc->id);
357 }
358
359 /* For the stream, use the id if present, else, use the path. */
360 if (ds_file_group->stream_id != UINT64_C(-1)) {
361 g_string_append_printf(name, " | %" PRIu64, ds_file_group->stream_id);
362 } else {
f3d74124
SM
363 BT_ASSERT(ds_file_group->ds_file_infos.size() == 1);
364 const auto& ds_file_info = *ds_file_group->ds_file_infos[0];
365 g_string_append_printf(name, " | %s", ds_file_info.path.c_str());
4164020e
SM
366 }
367
49b956cc 368 return bt2c::GCharUP {g_string_free(name, FALSE)};
547eacf1
PP
369}
370
ce11b8c4 371static int create_one_port_for_trace(struct ctf_fs_component *ctf_fs,
4164020e
SM
372 struct ctf_fs_ds_file_group *ds_file_group,
373 bt_self_component_source *self_comp_src)
5b29e799 374{
4164020e 375 int ret = 0;
945312a2 376 ctf_fs_port_data::UP port_data;
4164020e 377
49b956cc 378 bt2c::GCharUP port_name = ctf_fs_make_port_name(ds_file_group);
4164020e
SM
379 if (!port_name) {
380 goto error;
381 }
382
49b956cc 383 BT_CPPLOGI_SPEC(ctf_fs->logger, "Creating one port named `{}`", port_name.get());
4164020e
SM
384
385 /* Create output port for this file */
945312a2 386 port_data = bt2s::make_unique<ctf_fs_port_data>();
4164020e
SM
387 port_data->ctf_fs = ctf_fs;
388 port_data->ds_file_group = ds_file_group;
945312a2
SM
389 ret = bt_self_component_source_add_output_port(self_comp_src, port_name.get(), port_data.get(),
390 NULL);
4164020e
SM
391 if (ret) {
392 goto error;
393 }
394
945312a2 395 ctf_fs->port_data.emplace_back(std::move(port_data));
4164020e 396 goto end;
4f1f88a6
PP
397
398error:
4164020e 399 ret = -1;
4f1f88a6
PP
400
401end:
4164020e 402 return ret;
5b29e799
JG
403}
404
4164020e
SM
405static int create_ports_for_trace(struct ctf_fs_component *ctf_fs,
406 struct ctf_fs_trace *ctf_fs_trace,
407 bt_self_component_source *self_comp_src)
94cf822e 408{
4164020e 409 int ret = 0;
4164020e
SM
410
411 /* Create one output port for each stream file group */
cdf7de78
SM
412 for (const auto& ds_file_group : ctf_fs_trace->ds_file_groups) {
413 ret = create_one_port_for_trace(ctf_fs, ds_file_group.get(), self_comp_src);
4164020e 414 if (ret) {
0f5c5d5c 415 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs->logger, "Cannot create output port.");
4164020e
SM
416 goto end;
417 }
418 }
94cf822e
PP
419
420end:
4164020e 421 return ret;
94cf822e
PP
422}
423
8bf7105e 424/* Replace by g_ptr_array_insert when we depend on glib >= 2.40. */
4164020e 425static void array_insert(GPtrArray *array, gpointer element, size_t pos)
8bf7105e 426{
4164020e 427 size_t original_array_len = array->len;
8bf7105e 428
4164020e
SM
429 /* Allocate an unused element at the end of the array. */
430 g_ptr_array_add(array, NULL);
8bf7105e 431
4164020e
SM
432 /* If we are not inserting at the end, move the elements by one. */
433 if (pos < original_array_len) {
434 memmove(&(array->pdata[pos + 1]), &(array->pdata[pos]),
435 (original_array_len - pos) * sizeof(gpointer));
436 }
8bf7105e 437
4164020e
SM
438 /* Insert the value. */
439 array->pdata[pos] = element;
8bf7105e
MJ
440}
441
41a65f30
SM
442/*
443 * Insert ds_file_info in ds_file_group's list of ds_file_infos at the right
444 * place to keep it sorted.
445 */
446
4164020e 447static void ds_file_group_insert_ds_file_info_sorted(struct ctf_fs_ds_file_group *ds_file_group,
f3d74124 448 ctf_fs_ds_file_info::UP ds_file_info)
41a65f30 449{
4164020e 450 /* Find the spot where to insert this ds_file_info. */
f3d74124 451 auto it = ds_file_group->ds_file_infos.begin();
41a65f30 452
f3d74124
SM
453 for (; it != ds_file_group->ds_file_infos.end(); ++it) {
454 const ctf_fs_ds_file_info& other_ds_file_info = **it;
455
456 if (ds_file_info->begin_ns < other_ds_file_info.begin_ns) {
4164020e
SM
457 break;
458 }
459 }
41a65f30 460
f3d74124 461 ds_file_group->ds_file_infos.insert(it, std::move(ds_file_info));
41a65f30
SM
462}
463
4164020e
SM
464static bool ds_index_entries_equal(const struct ctf_fs_ds_index_entry *left,
465 const struct ctf_fs_ds_index_entry *right)
1505f33a 466{
ef7d7ac2 467 if (left->packetSize != right->packetSize) {
4164020e
SM
468 return false;
469 }
1505f33a 470
4164020e
SM
471 if (left->timestamp_begin != right->timestamp_begin) {
472 return false;
473 }
1505f33a 474
4164020e
SM
475 if (left->timestamp_end != right->timestamp_end) {
476 return false;
477 }
1505f33a 478
4164020e
SM
479 if (left->packet_seq_num != right->packet_seq_num) {
480 return false;
481 }
1505f33a 482
4164020e 483 return true;
1505f33a
SM
484}
485
486/*
487 * Insert `entry` into `index`, without duplication.
488 *
489 * The entry is inserted only if there isn't an identical entry already.
490 *
491 * In any case, the ownership of `entry` is transferred to this function. So if
492 * the entry is not inserted, it is freed.
493 */
494
4164020e
SM
495static void ds_index_insert_ds_index_entry_sorted(struct ctf_fs_ds_index *index,
496 struct ctf_fs_ds_index_entry *entry)
7ed5243a 497{
4164020e
SM
498 guint i;
499 struct ctf_fs_ds_index_entry *other_entry = NULL;
500
501 /* Find the spot where to insert this index entry. */
502 for (i = 0; i < index->entries->len; i++) {
503 other_entry = (struct ctf_fs_ds_index_entry *) g_ptr_array_index(index->entries, i);
504
505 if (entry->timestamp_begin_ns <= other_entry->timestamp_begin_ns) {
506 break;
507 }
508 }
509
510 /*
511 * Insert the entry only if a duplicate doesn't already exist.
512 *
513 * There can be duplicate packets if reading multiple overlapping
514 * snapshots of the same trace. We then want the index to contain
515 * a reference to only one copy of that packet.
516 */
517 if (i == index->entries->len || !ds_index_entries_equal(entry, other_entry)) {
518 array_insert(index->entries, entry, i);
519 } else {
afb0f12b 520 delete entry;
4164020e 521 }
ce75de14
SM
522}
523
4164020e 524static void merge_ctf_fs_ds_indexes(struct ctf_fs_ds_index *dest, struct ctf_fs_ds_index *src)
ce75de14 525{
4164020e 526 guint i;
ce75de14 527
4164020e
SM
528 for (i = 0; i < src->entries->len; i++) {
529 struct ctf_fs_ds_index_entry *entry =
530 (struct ctf_fs_ds_index_entry *) g_ptr_array_index(src->entries, i);
ce75de14 531
4164020e 532 /*
ce75de14 533 * Ownership of the ctf_fs_ds_index_entry is transferred to
1505f33a 534 * ds_index_insert_ds_index_entry_sorted.
ce75de14 535 */
4164020e
SM
536 g_ptr_array_index(src->entries, i) = NULL;
537 ds_index_insert_ds_index_entry_sorted(dest, entry);
538 }
7ed5243a
FD
539}
540
4164020e 541static int add_ds_file_to_ds_file_group(struct ctf_fs_trace *ctf_fs_trace, const char *path)
94cf822e 542{
4164020e
SM
543 int64_t stream_instance_id = -1;
544 int64_t begin_ns = -1;
545 struct ctf_fs_ds_file_group *ds_file_group = NULL;
fe2e19c4 546 ctf_fs_ds_file_group::UP new_ds_file_group;
4164020e 547 int ret;
4164020e 548 struct ctf_fs_ds_file *ds_file = NULL;
f3d74124 549 ctf_fs_ds_file_info::UP ds_file_info;
4164020e
SM
550 struct ctf_fs_ds_index *index = NULL;
551 struct ctf_msg_iter *msg_iter = NULL;
552 struct ctf_stream_class *sc = NULL;
553 struct ctf_msg_iter_packet_properties props;
4164020e
SM
554
555 /*
556 * Create a temporary ds_file to read some properties about the data
557 * stream file.
558 */
0f5c5d5c 559 ds_file = ctf_fs_ds_file_create(ctf_fs_trace, NULL, path, ctf_fs_trace->logger);
4164020e
SM
560 if (!ds_file) {
561 goto error;
562 }
563
564 /* Create a temporary iterator to read the ds_file. */
0f5c5d5c
SM
565 msg_iter = ctf_msg_iter_create(
566 ctf_fs_trace->metadata->tc,
567 bt_common_get_page_size(static_cast<int>(ctf_fs_trace->logger.level())) * 8,
568 ctf_fs_ds_file_medops, ds_file, nullptr, ctf_fs_trace->logger);
4164020e 569 if (!msg_iter) {
0f5c5d5c 570 BT_CPPLOGE_STR_SPEC(ctf_fs_trace->logger, "Cannot create a CTF message iterator.");
4164020e
SM
571 goto error;
572 }
573
574 ctf_msg_iter_set_dry_run(msg_iter, true);
575
576 ret = ctf_msg_iter_get_packet_properties(msg_iter, &props);
577 if (ret) {
0f5c5d5c
SM
578 BT_CPPLOGE_APPEND_CAUSE_SPEC(
579 ctf_fs_trace->logger,
580 "Cannot get stream file's first packet's header and context fields (`{}`).", path);
4164020e
SM
581 goto error;
582 }
583
584 sc = ctf_trace_class_borrow_stream_class_by_id(ds_file->metadata->tc, props.stream_class_id);
585 BT_ASSERT(sc);
586 stream_instance_id = props.data_stream_id;
587
588 if (props.snapshots.beginning_clock != UINT64_C(-1)) {
589 BT_ASSERT(sc->default_clock_class);
590 ret = bt_util_clock_cycles_to_ns_from_origin(
591 props.snapshots.beginning_clock, sc->default_clock_class->frequency,
592 sc->default_clock_class->offset_seconds, sc->default_clock_class->offset_cycles,
593 &begin_ns);
594 if (ret) {
0f5c5d5c
SM
595 BT_CPPLOGE_APPEND_CAUSE_SPEC(
596 ctf_fs_trace->logger,
597 "Cannot convert clock cycles to nanoseconds from origin (`{}`).", path);
4164020e
SM
598 goto error;
599 }
600 }
601
f3d74124 602 ds_file_info = ctf_fs_ds_file_info_create(path, begin_ns);
4164020e
SM
603 if (!ds_file_info) {
604 goto error;
605 }
606
441fa755 607 index = ctf_fs_ds_file_build_index(ds_file, ds_file_info.get(), msg_iter).release();
4164020e 608 if (!index) {
0f5c5d5c
SM
609 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs_trace->logger, "Failed to index CTF stream file \'{}\'",
610 ds_file->file->path->str);
4164020e
SM
611 goto error;
612 }
613
614 if (begin_ns == -1) {
615 /*
616 * No beginning timestamp to sort the stream files
617 * within a stream file group, so consider that this
618 * file must be the only one within its group.
619 */
620 stream_instance_id = -1;
621 }
622
623 if (stream_instance_id == -1) {
624 /*
625 * No stream instance ID or no beginning timestamp:
626 * create a unique stream file group for this stream
627 * file because, even if there's a stream instance ID,
628 * there's no timestamp to order the file within its
629 * group.
630 */
fe2e19c4
SM
631 new_ds_file_group = ctf_fs_ds_file_group_create(ctf_fs_trace, sc, UINT64_C(-1), index);
632
4164020e
SM
633 /* Ownership of index is transferred. */
634 index = NULL;
635
fe2e19c4 636 if (!new_ds_file_group) {
4164020e
SM
637 goto error;
638 }
639
f3d74124 640 ds_file_group_insert_ds_file_info_sorted(new_ds_file_group.get(), std::move(ds_file_info));
cdf7de78 641 ctf_fs_trace->ds_file_groups.emplace_back(std::move(new_ds_file_group));
4164020e
SM
642 goto end;
643 }
644
645 BT_ASSERT(stream_instance_id != -1);
646 BT_ASSERT(begin_ns != -1);
647
648 /* Find an existing stream file group with this ID */
cdf7de78
SM
649 for (const auto& candidate : ctf_fs_trace->ds_file_groups) {
650 if (candidate->sc == sc && candidate->stream_id == stream_instance_id) {
651 ds_file_group = candidate.get();
4164020e
SM
652 break;
653 }
4164020e
SM
654 }
655
656 if (!ds_file_group) {
fe2e19c4
SM
657 new_ds_file_group =
658 ctf_fs_ds_file_group_create(ctf_fs_trace, sc, stream_instance_id, index);
4164020e
SM
659 /* Ownership of index is transferred. */
660 index = NULL;
fe2e19c4 661 if (!new_ds_file_group) {
4164020e
SM
662 goto error;
663 }
664
fe2e19c4 665 ds_file_group = new_ds_file_group.get();
cdf7de78 666 ctf_fs_trace->ds_file_groups.emplace_back(std::move(new_ds_file_group));
4164020e
SM
667 } else {
668 merge_ctf_fs_ds_indexes(ds_file_group->index, index);
669 }
670
f3d74124 671 ds_file_group_insert_ds_file_info_sorted(ds_file_group, std::move(ds_file_info));
4164020e
SM
672
673 goto end;
94cf822e
PP
674
675error:
4164020e 676 ret = -1;
94cf822e
PP
677
678end:
4164020e 679 ctf_fs_ds_file_destroy(ds_file);
6de92955 680
4164020e
SM
681 if (msg_iter) {
682 ctf_msg_iter_destroy(msg_iter);
683 }
6de92955 684
4164020e
SM
685 ctf_fs_ds_index_destroy(index);
686 return ret;
94cf822e
PP
687}
688
4164020e 689static int create_ds_file_groups(struct ctf_fs_trace *ctf_fs_trace)
e7a4393b 690{
4164020e
SM
691 int ret = 0;
692 const char *basename;
693 GError *error = NULL;
694 GDir *dir = NULL;
4164020e
SM
695
696 /* Check each file in the path directory, except specific ones */
697 dir = g_dir_open(ctf_fs_trace->path->str, 0, &error);
698 if (!dir) {
0f5c5d5c
SM
699 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs_trace->logger,
700 "Cannot open directory `{}`: {} (code {})",
701 ctf_fs_trace->path->str, error->message, error->code);
4164020e
SM
702 goto error;
703 }
704
705 while ((basename = g_dir_read_name(dir))) {
706 struct ctf_fs_file *file;
707
708 if (strcmp(basename, CTF_FS_METADATA_FILENAME) == 0) {
709 /* Ignore the metadata stream. */
0f5c5d5c
SM
710 BT_CPPLOGI_SPEC(ctf_fs_trace->logger,
711 "Ignoring metadata file `{}" G_DIR_SEPARATOR_S "{}`",
712 ctf_fs_trace->path->str, basename);
4164020e
SM
713 continue;
714 }
715
716 if (basename[0] == '.') {
0f5c5d5c
SM
717 BT_CPPLOGI_SPEC(ctf_fs_trace->logger,
718 "Ignoring hidden file `{}" G_DIR_SEPARATOR_S "{}`",
719 ctf_fs_trace->path->str, basename);
4164020e
SM
720 continue;
721 }
722
723 /* Create the file. */
0f5c5d5c 724 file = ctf_fs_file_create(ctf_fs_trace->logger);
4164020e 725 if (!file) {
0f5c5d5c
SM
726 BT_CPPLOGE_APPEND_CAUSE_SPEC(
727 ctf_fs_trace->logger,
728 "Cannot create stream file object for file `{}" G_DIR_SEPARATOR_S "{}`",
4164020e
SM
729 ctf_fs_trace->path->str, basename);
730 goto error;
731 }
732
733 /* Create full path string. */
734 g_string_append_printf(file->path, "%s" G_DIR_SEPARATOR_S "%s", ctf_fs_trace->path->str,
735 basename);
736 if (!g_file_test(file->path->str, G_FILE_TEST_IS_REGULAR)) {
0f5c5d5c
SM
737 BT_CPPLOGI_SPEC(ctf_fs_trace->logger, "Ignoring non-regular file `{}`",
738 file->path->str);
4164020e
SM
739 ctf_fs_file_destroy(file);
740 file = NULL;
741 continue;
742 }
743
744 ret = ctf_fs_file_open(file, "rb");
745 if (ret) {
0f5c5d5c
SM
746 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs_trace->logger, "Cannot open stream file `{}`",
747 file->path->str);
4164020e
SM
748 goto error;
749 }
750
751 if (file->size == 0) {
752 /* Skip empty stream. */
0f5c5d5c 753 BT_CPPLOGI_SPEC(ctf_fs_trace->logger, "Ignoring empty file `{}`", file->path->str);
4164020e
SM
754 ctf_fs_file_destroy(file);
755 continue;
756 }
757
758 ret = add_ds_file_to_ds_file_group(ctf_fs_trace, file->path->str);
759 if (ret) {
0f5c5d5c
SM
760 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs_trace->logger,
761 "Cannot add stream file `{}` to stream file group",
762 file->path->str);
4164020e
SM
763 ctf_fs_file_destroy(file);
764 goto error;
765 }
766
767 ctf_fs_file_destroy(file);
768 }
769
770 goto end;
4f1f88a6 771
e7a4393b 772error:
4164020e 773 ret = -1;
4f1f88a6 774
e7a4393b 775end:
4164020e
SM
776 if (dir) {
777 g_dir_close(dir);
778 dir = NULL;
779 }
4f1f88a6 780
4164020e
SM
781 if (error) {
782 g_error_free(error);
783 }
5b29e799 784
4164020e 785 return ret;
5b29e799
JG
786}
787
0f5c5d5c 788static int set_trace_name(bt_trace *trace, const char *name_suffix, const bt2c::Logger& logger)
862ca4ed 789{
4164020e
SM
790 int ret = 0;
791 const bt_value *val;
792 GString *name;
793
794 name = g_string_new(NULL);
795 if (!name) {
0f5c5d5c 796 BT_CPPLOGE_STR_SPEC(logger, "Failed to allocate a GString.");
4164020e
SM
797 ret = -1;
798 goto end;
799 }
800
801 /*
802 * Check if we have a trace environment string value named `hostname`.
803 * If so, use it as the trace name's prefix.
804 */
805 val = bt_trace_borrow_environment_entry_value_by_name_const(trace, "hostname");
806 if (val && bt_value_is_string(val)) {
807 g_string_append(name, bt_value_string_get(val));
808
809 if (name_suffix) {
810 g_string_append_c(name, G_DIR_SEPARATOR);
811 }
812 }
813
814 if (name_suffix) {
815 g_string_append(name, name_suffix);
816 }
817
818 ret = bt_trace_set_name(trace, name->str);
819 if (ret) {
820 goto end;
821 }
822
823 goto end;
862ca4ed
PP
824
825end:
4164020e
SM
826 if (name) {
827 g_string_free(name, TRUE);
828 }
862ca4ed 829
4164020e 830 return ret;
862ca4ed
PP
831}
832
2ca337f1
SM
833static ctf_fs_trace::UP ctf_fs_trace_create(const char *path, const char *name,
834 const ctf::src::ClkClsCfg& clkClsCfg,
835 bt_self_component *selfComp,
836 const bt2c::Logger& parentLogger)
1a9f7075 837{
4164020e
SM
838 int ret;
839
2ca337f1 840 ctf_fs_trace::UP ctf_fs_trace {new struct ctf_fs_trace(parentLogger)};
4164020e
SM
841 ctf_fs_trace->path = g_string_new(path);
842 if (!ctf_fs_trace->path) {
843 goto error;
844 }
845
afb0f12b 846 ctf_fs_trace->metadata = new ctf_fs_metadata;
4164020e 847 ctf_fs_metadata_init(ctf_fs_trace->metadata);
4164020e 848
2ca337f1 849 ret = ctf_fs_metadata_set_trace_class(selfComp, ctf_fs_trace.get(), clkClsCfg);
4164020e
SM
850 if (ret) {
851 goto error;
852 }
853
854 if (ctf_fs_trace->metadata->trace_class) {
855 ctf_fs_trace->trace = bt_trace_create(ctf_fs_trace->metadata->trace_class);
856 if (!ctf_fs_trace->trace) {
857 goto error;
858 }
859 }
860
861 if (ctf_fs_trace->trace) {
862 ret = ctf_trace_class_configure_ir_trace(ctf_fs_trace->metadata->tc, ctf_fs_trace->trace);
863 if (ret) {
864 goto error;
865 }
866
0f5c5d5c 867 ret = set_trace_name(ctf_fs_trace->trace, name, ctf_fs_trace->logger);
4164020e
SM
868 if (ret) {
869 goto error;
870 }
871 }
872
2ca337f1 873 ret = create_ds_file_groups(ctf_fs_trace.get());
4164020e
SM
874 if (ret) {
875 goto error;
876 }
877
878 goto end;
1a9f7075
PP
879
880error:
2ca337f1 881 ctf_fs_trace.reset();
44c440bc 882
1a9f7075 883end:
4164020e 884 return ctf_fs_trace;
1a9f7075
PP
885}
886
4164020e 887static int path_is_ctf_trace(const char *path)
1a9f7075 888{
4164020e
SM
889 GString *metadata_path = g_string_new(NULL);
890 int ret = 0;
1a9f7075 891
4164020e
SM
892 if (!metadata_path) {
893 ret = -1;
894 goto end;
895 }
1a9f7075 896
4164020e 897 g_string_printf(metadata_path, "%s" G_DIR_SEPARATOR_S "%s", path, CTF_FS_METADATA_FILENAME);
1a9f7075 898
4164020e
SM
899 if (g_file_test(metadata_path->str, G_FILE_TEST_IS_REGULAR)) {
900 ret = 1;
901 goto end;
902 }
1a9f7075
PP
903
904end:
4164020e
SM
905 g_string_free(metadata_path, TRUE);
906 return ret;
1a9f7075
PP
907}
908
a0cd55ad 909/* Helper for ctf_fs_component_create_ctf_fs_trace, to handle a single path. */
f280892e 910
4164020e
SM
911static int ctf_fs_component_create_ctf_fs_trace_one_path(struct ctf_fs_component *ctf_fs,
912 const char *path_param,
a4c955d9
SM
913 const char *trace_name,
914 std::vector<ctf_fs_trace::UP>& traces,
0f5c5d5c 915 bt_self_component *selfComp)
1a9f7075 916{
2ca337f1 917 ctf_fs_trace::UP ctf_fs_trace;
4164020e
SM
918 int ret;
919 GString *norm_path;
4164020e
SM
920
921 norm_path = bt_common_normalize_path(path_param, NULL);
922 if (!norm_path) {
0f5c5d5c 923 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs->logger, "Failed to normalize path: `{}`.", path_param);
4164020e
SM
924 goto error;
925 }
926
927 ret = path_is_ctf_trace(norm_path->str);
928 if (ret < 0) {
0f5c5d5c
SM
929 BT_CPPLOGE_APPEND_CAUSE_SPEC(
930 ctf_fs->logger, "Failed to check if path is a CTF trace: path={}", norm_path->str);
4164020e
SM
931 goto error;
932 } else if (ret == 0) {
0f5c5d5c
SM
933 BT_CPPLOGE_APPEND_CAUSE_SPEC(
934 ctf_fs->logger, "Path is not a CTF trace (does not contain a metadata file): `{}`.",
935 norm_path->str);
4164020e
SM
936 goto error;
937 }
938
939 // FIXME: Remove or ifdef for __MINGW32__
940 if (strcmp(norm_path->str, "/") == 0) {
0f5c5d5c 941 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs->logger, "Opening a trace in `/` is not supported.");
4164020e
SM
942 ret = -1;
943 goto end;
944 }
945
c942e7a2
SM
946 ctf_fs_trace = ctf_fs_trace_create(norm_path->str, trace_name, ctf_fs->clkClsCfg, selfComp,
947 ctf_fs->logger);
4164020e 948 if (!ctf_fs_trace) {
0f5c5d5c
SM
949 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs->logger, "Cannot create trace for `{}`.",
950 norm_path->str);
4164020e
SM
951 goto error;
952 }
953
a4c955d9 954 traces.emplace_back(std::move(ctf_fs_trace));
4164020e
SM
955
956 ret = 0;
957 goto end;
1a9f7075
PP
958
959error:
4164020e 960 ret = -1;
1a9f7075
PP
961
962end:
4164020e
SM
963 if (norm_path) {
964 g_string_free(norm_path, TRUE);
965 }
4bd72b60 966
4164020e 967 return ret;
1a9f7075
PP
968}
969
41a65f30
SM
970/*
971 * Count the number of stream and event classes defined by this trace's metadata.
972 *
973 * This is used to determine which metadata is the "latest", out of multiple
974 * traces sharing the same UUID. It is assumed that amongst all these metadatas,
975 * a bigger metadata is a superset of a smaller metadata. Therefore, it is
976 * enough to just count the classes.
977 */
978
4164020e 979static unsigned int metadata_count_stream_and_event_classes(struct ctf_fs_trace *trace)
41a65f30 980{
4164020e
SM
981 unsigned int num = trace->metadata->tc->stream_classes->len;
982 guint i;
41a65f30 983
4164020e
SM
984 for (i = 0; i < trace->metadata->tc->stream_classes->len; i++) {
985 struct ctf_stream_class *sc =
986 (struct ctf_stream_class *) trace->metadata->tc->stream_classes->pdata[i];
987 num += sc->event_classes->len;
988 }
41a65f30 989
4164020e 990 return num;
41a65f30
SM
991}
992
993/*
994 * Merge the src ds_file_group into dest. This consists of merging their
995 * ds_file_infos, making sure to keep the result sorted.
996 */
997
4164020e 998static void merge_ctf_fs_ds_file_groups(struct ctf_fs_ds_file_group *dest,
cdf7de78 999 ctf_fs_ds_file_group::UP src)
41a65f30 1000{
f3d74124
SM
1001 for (auto& ds_file_info : src->ds_file_infos) {
1002 ds_file_group_insert_ds_file_info_sorted(dest, std::move(ds_file_info));
4164020e 1003 }
41a65f30 1004
4164020e
SM
1005 /* Merge both indexes. */
1006 merge_ctf_fs_ds_indexes(dest->index, src->index);
7ed5243a 1007}
a4c955d9 1008
41a65f30
SM
1009/* Merge src_trace's data stream file groups into dest_trace's. */
1010
4164020e 1011static int merge_matching_ctf_fs_ds_file_groups(struct ctf_fs_trace *dest_trace,
a4c955d9 1012 ctf_fs_trace::UP src_trace)
41a65f30 1013{
cdf7de78
SM
1014 std::vector<ctf_fs_ds_file_group::UP>& dest = dest_trace->ds_file_groups;
1015 std::vector<ctf_fs_ds_file_group::UP>& src = src_trace->ds_file_groups;
4164020e
SM
1016 int ret = 0;
1017
1018 /*
1019 * Save the initial length of dest: we only want to check against the
1020 * original elements in the inner loop.
1021 */
cdf7de78 1022 size_t dest_len = dest.size();
4164020e 1023
cdf7de78 1024 for (auto& src_group : src) {
4164020e
SM
1025 struct ctf_fs_ds_file_group *dest_group = NULL;
1026
1027 /* A stream instance without ID can't match a stream in the other trace. */
1028 if (src_group->stream_id != -1) {
4164020e 1029 /* Let's search for a matching ds_file_group in the destination. */
cdf7de78
SM
1030 for (size_t d_i = 0; d_i < dest_len; ++d_i) {
1031 ctf_fs_ds_file_group *candidate_dest = dest[d_i].get();
4164020e
SM
1032
1033 /* Can't match a stream instance without ID. */
1034 if (candidate_dest->stream_id == -1) {
1035 continue;
1036 }
1037
1038 /*
1039 * If the two groups have the same stream instance id
1040 * and belong to the same stream class (stream instance
1041 * ids are per-stream class), they represent the same
1042 * stream instance.
1043 */
1044 if (candidate_dest->stream_id != src_group->stream_id ||
1045 candidate_dest->sc->id != src_group->sc->id) {
1046 continue;
1047 }
1048
1049 dest_group = candidate_dest;
1050 break;
1051 }
1052 }
1053
1054 /*
1055 * Didn't find a friend in dest to merge our src_group into?
1056 * Create a new empty one. This can happen if a stream was
1057 * active in the source trace chunk but not in the destination
1058 * trace chunk.
1059 */
1060 if (!dest_group) {
1061 struct ctf_stream_class *sc;
4164020e
SM
1062
1063 sc = ctf_trace_class_borrow_stream_class_by_id(dest_trace->metadata->tc,
1064 src_group->sc->id);
1065 BT_ASSERT(sc);
1066
441fa755 1067 auto index = ctf_fs_ds_index_create(dest_trace->logger).release();
4164020e
SM
1068 if (!index) {
1069 ret = -1;
1070 goto end;
1071 }
1072
fe2e19c4
SM
1073 auto new_dest_group =
1074 ctf_fs_ds_file_group_create(dest_trace, sc, src_group->stream_id, index);
1075
4164020e
SM
1076 /* Ownership of index is transferred. */
1077 index = NULL;
fe2e19c4 1078 if (!new_dest_group) {
4164020e
SM
1079 ret = -1;
1080 goto end;
1081 }
1082
fe2e19c4 1083 dest_group = new_dest_group.get();
cdf7de78 1084 dest_trace->ds_file_groups.emplace_back(std::move(new_dest_group));
4164020e
SM
1085 }
1086
1087 BT_ASSERT(dest_group);
cdf7de78 1088 merge_ctf_fs_ds_file_groups(dest_group, std::move(src_group));
4164020e 1089 }
54ef52bd
FD
1090
1091end:
4164020e 1092 return ret;
41a65f30
SM
1093}
1094
1095/*
1096 * Collapse the given traces, which must all share the same UUID, in a single
1097 * one.
1098 *
1099 * The trace with the most expansive metadata is chosen and all other traces
a4c955d9
SM
1100 * are merged into that one. On return, the elements of `traces` are nullptr
1101 * and the merged trace is placed in `out_trace`.
41a65f30
SM
1102 */
1103
a4c955d9 1104static int merge_ctf_fs_traces(std::vector<ctf_fs_trace::UP> traces, ctf_fs_trace::UP& out_trace)
41a65f30 1105{
4164020e
SM
1106 unsigned int winner_count;
1107 struct ctf_fs_trace *winner;
1108 guint i, winner_i;
1109 int ret = 0;
1110
a4c955d9 1111 BT_ASSERT(traces.size() >= 2);
4164020e 1112
a4c955d9
SM
1113 winner_count = metadata_count_stream_and_event_classes(traces[0].get());
1114 winner = traces[0].get();
4164020e
SM
1115 winner_i = 0;
1116
1117 /* Find the trace with the largest metadata. */
a4c955d9
SM
1118 for (i = 1; i < traces.size(); i++) {
1119 ctf_fs_trace *candidate = traces[i].get();
4164020e
SM
1120 unsigned int candidate_count;
1121
4164020e
SM
1122 /* A bit of sanity check. */
1123 BT_ASSERT(bt_uuid_compare(winner->metadata->tc->uuid, candidate->metadata->tc->uuid) == 0);
1124
1125 candidate_count = metadata_count_stream_and_event_classes(candidate);
1126
1127 if (candidate_count > winner_count) {
1128 winner_count = candidate_count;
1129 winner = candidate;
1130 winner_i = i;
1131 }
1132 }
1133
1134 /* Merge all the other traces in the winning trace. */
a4c955d9 1135 for (ctf_fs_trace::UP& trace : traces) {
4164020e 1136 /* Don't merge the winner into itself. */
a4c955d9 1137 if (trace.get() == winner) {
4164020e
SM
1138 continue;
1139 }
1140
1141 /* Merge trace's data stream file groups into winner's. */
a4c955d9 1142 ret = merge_matching_ctf_fs_ds_file_groups(winner, std::move(trace));
4164020e
SM
1143 if (ret) {
1144 goto end;
1145 }
1146 }
1147
1148 /*
1149 * Move the winner out of the array, into `*out_trace`.
1150 */
a4c955d9 1151 out_trace = std::move(traces[winner_i]);
54ef52bd
FD
1152
1153end:
4164020e 1154 return ret;
41a65f30
SM
1155}
1156
4164020e
SM
1157enum target_event
1158{
1159 FIRST_EVENT,
1160 LAST_EVENT,
1719bf64
FD
1161};
1162
4164020e
SM
1163static int decode_clock_snapshot_after_event(struct ctf_fs_trace *ctf_fs_trace,
1164 struct ctf_clock_class *default_cc,
1165 struct ctf_fs_ds_index_entry *index_entry,
1166 enum target_event target_event, uint64_t *cs,
1167 int64_t *ts_ns)
1719bf64 1168{
4164020e
SM
1169 enum ctf_msg_iter_status iter_status = CTF_MSG_ITER_STATUS_OK;
1170 struct ctf_fs_ds_file *ds_file = NULL;
1171 struct ctf_msg_iter *msg_iter = NULL;
4164020e
SM
1172 int ret = 0;
1173
1174 BT_ASSERT(ctf_fs_trace);
1175 BT_ASSERT(index_entry);
1176 BT_ASSERT(index_entry->path);
1177
0f5c5d5c 1178 ds_file = ctf_fs_ds_file_create(ctf_fs_trace, NULL, index_entry->path, ctf_fs_trace->logger);
4164020e 1179 if (!ds_file) {
0f5c5d5c 1180 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs_trace->logger, "Failed to create a ctf_fs_ds_file");
4164020e
SM
1181 ret = -1;
1182 goto end;
1183 }
1184
1185 BT_ASSERT(ctf_fs_trace->metadata);
1186 BT_ASSERT(ctf_fs_trace->metadata->tc);
1187
0f5c5d5c
SM
1188 msg_iter = ctf_msg_iter_create(
1189 ctf_fs_trace->metadata->tc,
1190 bt_common_get_page_size(static_cast<int>(ctf_fs_trace->logger.level())) * 8,
1191 ctf_fs_ds_file_medops, ds_file, NULL, ctf_fs_trace->logger);
4164020e
SM
1192 if (!msg_iter) {
1193 /* ctf_msg_iter_create() logs errors. */
1194 ret = -1;
1195 goto end;
1196 }
1197
1198 /*
1199 * Turn on dry run mode to prevent the creation and usage of Babeltrace
1200 * library objects (bt_field, bt_message_*, etc.).
1201 */
1202 ctf_msg_iter_set_dry_run(msg_iter, true);
1203
1204 /* Seek to the beginning of the target packet. */
ef7d7ac2 1205 iter_status = ctf_msg_iter_seek(msg_iter, index_entry->offset.bytes());
4164020e
SM
1206 if (iter_status) {
1207 /* ctf_msg_iter_seek() logs errors. */
1208 ret = -1;
1209 goto end;
1210 }
1211
1212 switch (target_event) {
1213 case FIRST_EVENT:
1214 /*
1215 * Start to decode the packet until we reach the end of
1216 * the first event. To extract the first event's clock
1217 * snapshot.
1218 */
1219 iter_status = ctf_msg_iter_curr_packet_first_event_clock_snapshot(msg_iter, cs);
1220 break;
1221 case LAST_EVENT:
1222 /* Decode the packet to extract the last event's clock snapshot. */
1223 iter_status = ctf_msg_iter_curr_packet_last_event_clock_snapshot(msg_iter, cs);
1224 break;
1225 default:
1226 bt_common_abort();
1227 }
1228 if (iter_status) {
1229 ret = -1;
1230 goto end;
1231 }
1232
1233 /* Convert clock snapshot to timestamp. */
1234 ret = bt_util_clock_cycles_to_ns_from_origin(
1235 *cs, default_cc->frequency, default_cc->offset_seconds, default_cc->offset_cycles, ts_ns);
1236 if (ret) {
0f5c5d5c
SM
1237 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs_trace->logger,
1238 "Failed to convert clock snapshot to timestamp");
4164020e
SM
1239 goto end;
1240 }
1719bf64
FD
1241
1242end:
4164020e
SM
1243 if (ds_file) {
1244 ctf_fs_ds_file_destroy(ds_file);
1245 }
1246 if (msg_iter) {
1247 ctf_msg_iter_destroy(msg_iter);
1248 }
1249
1250 return ret;
1719bf64
FD
1251}
1252
4164020e
SM
1253static int decode_packet_first_event_timestamp(struct ctf_fs_trace *ctf_fs_trace,
1254 struct ctf_clock_class *default_cc,
1255 struct ctf_fs_ds_index_entry *index_entry,
1256 uint64_t *cs, int64_t *ts_ns)
c43092a5 1257{
4164020e
SM
1258 return decode_clock_snapshot_after_event(ctf_fs_trace, default_cc, index_entry, FIRST_EVENT, cs,
1259 ts_ns);
c43092a5
FD
1260}
1261
4164020e
SM
1262static int decode_packet_last_event_timestamp(struct ctf_fs_trace *ctf_fs_trace,
1263 struct ctf_clock_class *default_cc,
1264 struct ctf_fs_ds_index_entry *index_entry,
1265 uint64_t *cs, int64_t *ts_ns)
1719bf64 1266{
4164020e
SM
1267 return decode_clock_snapshot_after_event(ctf_fs_trace, default_cc, index_entry, LAST_EVENT, cs,
1268 ts_ns);
1719bf64
FD
1269}
1270
1271/*
1272 * Fix up packet index entries for lttng's "event-after-packet" bug.
1273 * Some buggy lttng tracer versions may emit events with a timestamp that is
1274 * larger (after) than the timestamp_end of the their packets.
1275 *
1276 * To fix up this erroneous data we do the following:
1277 * 1. If it's not the stream file's last packet: set the packet index entry's
1278 * end time to the next packet's beginning time.
1279 * 2. If it's the stream file's last packet, set the packet index entry's end
1280 * time to the packet's last event's time, if any, or to the packet's
1281 * beginning time otherwise.
1282 *
1283 * Known buggy tracer versions:
1284 * - before lttng-ust 2.11.0
1285 * - before lttng-module 2.11.0
1286 * - before lttng-module 2.10.10
1287 * - before lttng-module 2.9.13
1288 */
4164020e 1289static int fix_index_lttng_event_after_packet_bug(struct ctf_fs_trace *trace)
1719bf64 1290{
4164020e 1291 int ret = 0;
4164020e 1292
cdf7de78 1293 for (const auto& ds_file_group : trace->ds_file_groups) {
4164020e
SM
1294 guint entry_i;
1295 struct ctf_clock_class *default_cc;
1296 struct ctf_fs_ds_index_entry *last_entry;
1297 struct ctf_fs_ds_index *index;
1298
4164020e
SM
1299 BT_ASSERT(ds_file_group);
1300 index = ds_file_group->index;
1301
1302 BT_ASSERT(index);
1303 BT_ASSERT(index->entries);
1304 BT_ASSERT(index->entries->len > 0);
1305
1306 /*
1307 * Iterate over all entries but the last one. The last one is
1308 * fixed differently after.
1309 */
1310 for (entry_i = 0; entry_i < index->entries->len - 1; entry_i++) {
1311 struct ctf_fs_ds_index_entry *curr_entry, *next_entry;
1312
1313 curr_entry = (ctf_fs_ds_index_entry *) g_ptr_array_index(index->entries, entry_i);
1314 next_entry = (ctf_fs_ds_index_entry *) g_ptr_array_index(index->entries, entry_i + 1);
1315
1316 /*
1317 * 1. Set the current index entry `end` timestamp to
1318 * the next index entry `begin` timestamp.
1319 */
1320 curr_entry->timestamp_end = next_entry->timestamp_begin;
1321 curr_entry->timestamp_end_ns = next_entry->timestamp_begin_ns;
1322 }
1323
1324 /*
1325 * 2. Fix the last entry by decoding the last event of the last
1326 * packet.
1327 */
1328 last_entry =
1329 (ctf_fs_ds_index_entry *) g_ptr_array_index(index->entries, index->entries->len - 1);
1330 BT_ASSERT(last_entry);
1331
1332 BT_ASSERT(ds_file_group->sc->default_clock_class);
1333 default_cc = ds_file_group->sc->default_clock_class;
1334
1335 /*
1336 * Decode packet to read the timestamp of the last event of the
1337 * entry.
1338 */
1339 ret = decode_packet_last_event_timestamp(trace, default_cc, last_entry,
1340 &last_entry->timestamp_end,
1341 &last_entry->timestamp_end_ns);
1342 if (ret) {
0f5c5d5c
SM
1343 BT_CPPLOGE_APPEND_CAUSE_SPEC(
1344 trace->logger,
4164020e
SM
1345 "Failed to decode stream's last packet to get its last event's clock snapshot.");
1346 goto end;
1347 }
1348 }
1719bf64
FD
1349
1350end:
4164020e 1351 return ret;
1719bf64
FD
1352}
1353
c43092a5
FD
1354/*
1355 * Fix up packet index entries for barectf's "event-before-packet" bug.
1356 * Some buggy barectf tracer versions may emit events with a timestamp that is
1357 * less than the timestamp_begin of the their packets.
1358 *
1359 * To fix up this erroneous data we do the following:
1360 * 1. Starting at the second index entry, set the timestamp_begin of the
1361 * current entry to the timestamp of the first event of the packet.
1362 * 2. Set the previous entry's timestamp_end to the timestamp_begin of the
1363 * current packet.
1364 *
1365 * Known buggy tracer versions:
1366 * - before barectf 2.3.1
1367 */
4164020e 1368static int fix_index_barectf_event_before_packet_bug(struct ctf_fs_trace *trace)
c43092a5 1369{
4164020e 1370 int ret = 0;
4164020e 1371
cdf7de78 1372 for (const auto& ds_file_group : trace->ds_file_groups) {
4164020e
SM
1373 guint entry_i;
1374 struct ctf_clock_class *default_cc;
4164020e
SM
1375 struct ctf_fs_ds_index *index = ds_file_group->index;
1376
1377 BT_ASSERT(index);
1378 BT_ASSERT(index->entries);
1379 BT_ASSERT(index->entries->len > 0);
1380
1381 BT_ASSERT(ds_file_group->sc->default_clock_class);
1382 default_cc = ds_file_group->sc->default_clock_class;
1383
1384 /*
1385 * 1. Iterate over the index, starting from the second entry
1386 * (index = 1).
1387 */
1388 for (entry_i = 1; entry_i < index->entries->len; entry_i++) {
1389 ctf_fs_ds_index_entry *prev_entry =
1390 (ctf_fs_ds_index_entry *) g_ptr_array_index(index->entries, entry_i - 1);
1391 ctf_fs_ds_index_entry *curr_entry =
1392 (ctf_fs_ds_index_entry *) g_ptr_array_index(index->entries, entry_i);
1393 /*
1394 * 2. Set the current entry `begin` timestamp to the
1395 * timestamp of the first event of the current packet.
1396 */
1397 ret = decode_packet_first_event_timestamp(trace, default_cc, curr_entry,
1398 &curr_entry->timestamp_begin,
1399 &curr_entry->timestamp_begin_ns);
1400 if (ret) {
0f5c5d5c
SM
1401 BT_CPPLOGE_APPEND_CAUSE_SPEC(trace->logger,
1402 "Failed to decode first event's clock snapshot");
4164020e
SM
1403 goto end;
1404 }
1405
1406 /*
1407 * 3. Set the previous entry `end` timestamp to the
1408 * timestamp of the first event of the current packet.
1409 */
1410 prev_entry->timestamp_end = curr_entry->timestamp_begin;
1411 prev_entry->timestamp_end_ns = curr_entry->timestamp_begin_ns;
1412 }
1413 }
c43092a5 1414end:
4164020e 1415 return ret;
c43092a5
FD
1416}
1417
aada78b5
FD
1418/*
1419 * When using the lttng-crash feature it's likely that the last packets of each
1420 * stream have their timestamp_end set to zero. This is caused by the fact that
1421 * the tracer crashed and was not able to properly close the packets.
1422 *
1423 * To fix up this erroneous data we do the following:
1424 * For each index entry, if the entry's timestamp_end is 0 and the
1425 * timestamp_begin is not 0:
1426 * - If it's the stream file's last packet: set the packet index entry's end
1427 * time to the packet's last event's time, if any, or to the packet's
1428 * beginning time otherwise.
1429 * - If it's not the stream file's last packet: set the packet index
1430 * entry's end time to the next packet's beginning time.
1431 *
1432 * Affected versions:
1433 * - All current and future lttng-ust and lttng-modules versions.
1434 */
4164020e 1435static int fix_index_lttng_crash_quirk(struct ctf_fs_trace *trace)
aada78b5 1436{
4164020e 1437 int ret = 0;
4164020e 1438
cdf7de78 1439 for (const auto& ds_file_group : trace->ds_file_groups) {
4164020e
SM
1440 guint entry_idx;
1441 struct ctf_clock_class *default_cc;
1442 struct ctf_fs_ds_index *index;
1443
4164020e
SM
1444 BT_ASSERT(ds_file_group);
1445 index = ds_file_group->index;
1446
1447 BT_ASSERT(ds_file_group->sc->default_clock_class);
1448 default_cc = ds_file_group->sc->default_clock_class;
1449
1450 BT_ASSERT(index);
1451 BT_ASSERT(index->entries);
1452 BT_ASSERT(index->entries->len > 0);
1453
1454 ctf_fs_ds_index_entry *last_entry =
1455 (ctf_fs_ds_index_entry *) g_ptr_array_index(index->entries, index->entries->len - 1);
1456 BT_ASSERT(last_entry);
1457
1458 /* 1. Fix the last entry first. */
1459 if (last_entry->timestamp_end == 0 && last_entry->timestamp_begin != 0) {
1460 /*
1461 * Decode packet to read the timestamp of the
1462 * last event of the stream file.
1463 */
1464 ret = decode_packet_last_event_timestamp(trace, default_cc, last_entry,
1465 &last_entry->timestamp_end,
1466 &last_entry->timestamp_end_ns);
1467 if (ret) {
0f5c5d5c
SM
1468 BT_CPPLOGE_APPEND_CAUSE_SPEC(trace->logger,
1469 "Failed to decode last event's clock snapshot");
4164020e
SM
1470 goto end;
1471 }
1472 }
1473
1474 /* Iterate over all entries but the last one. */
1475 for (entry_idx = 0; entry_idx < index->entries->len - 1; entry_idx++) {
1476 ctf_fs_ds_index_entry *curr_entry =
1477 (ctf_fs_ds_index_entry *) g_ptr_array_index(index->entries, entry_idx);
1478 ctf_fs_ds_index_entry *next_entry =
1479 (ctf_fs_ds_index_entry *) g_ptr_array_index(index->entries, entry_idx + 1);
1480
1481 if (curr_entry->timestamp_end == 0 && curr_entry->timestamp_begin != 0) {
1482 /*
1483 * 2. Set the current index entry `end` timestamp to
1484 * the next index entry `begin` timestamp.
1485 */
1486 curr_entry->timestamp_end = next_entry->timestamp_begin;
1487 curr_entry->timestamp_end_ns = next_entry->timestamp_begin_ns;
1488 }
1489 }
1490 }
aada78b5
FD
1491
1492end:
4164020e 1493 return ret;
aada78b5
FD
1494}
1495
626cc488
FD
1496/*
1497 * Extract the tracer information necessary to compare versions.
1498 * Returns 0 on success, and -1 if the extraction is not successful because the
1499 * necessary fields are absents in the trace metadata.
1500 */
4164020e 1501static int extract_tracer_info(struct ctf_fs_trace *trace, struct tracer_info *current_tracer_info)
626cc488 1502{
4164020e
SM
1503 int ret = 0;
1504 struct ctf_trace_class_env_entry *entry;
1505
1506 /* Clear the current_tracer_info struct */
1507 memset(current_tracer_info, 0, sizeof(*current_tracer_info));
1508
1509 /*
1510 * To compare 2 tracer versions, at least the tracer name and it's
1511 * major version are needed. If one of these is missing, consider it an
1512 * extraction failure.
1513 */
1514 entry = ctf_trace_class_borrow_env_entry_by_name(trace->metadata->tc, "tracer_name");
1515 if (!entry || entry->type != CTF_TRACE_CLASS_ENV_ENTRY_TYPE_STR) {
1516 goto missing_bare_minimum;
1517 }
1518
1519 /* Set tracer name. */
1520 current_tracer_info->name = entry->value.str->str;
1521
1522 entry = ctf_trace_class_borrow_env_entry_by_name(trace->metadata->tc, "tracer_major");
1523 if (!entry || entry->type != CTF_TRACE_CLASS_ENV_ENTRY_TYPE_INT) {
1524 goto missing_bare_minimum;
1525 }
1526
1527 /* Set major version number. */
1528 current_tracer_info->major = entry->value.i;
1529
1530 entry = ctf_trace_class_borrow_env_entry_by_name(trace->metadata->tc, "tracer_minor");
1531 if (!entry || entry->type != CTF_TRACE_CLASS_ENV_ENTRY_TYPE_INT) {
1532 goto end;
1533 }
1534
1535 /* Set minor version number. */
1536 current_tracer_info->minor = entry->value.i;
1537
1538 entry = ctf_trace_class_borrow_env_entry_by_name(trace->metadata->tc, "tracer_patch");
1539 if (!entry) {
1540 /*
1541 * If `tracer_patch` doesn't exist `tracer_patchlevel` might.
1542 * For example, `lttng-modules` uses entry name
1543 * `tracer_patchlevel`.
1544 */
1545 entry = ctf_trace_class_borrow_env_entry_by_name(trace->metadata->tc, "tracer_patchlevel");
1546 }
1547
1548 if (!entry || entry->type != CTF_TRACE_CLASS_ENV_ENTRY_TYPE_INT) {
1549 goto end;
1550 }
1551
1552 /* Set patch version number. */
1553 current_tracer_info->patch = entry->value.i;
1554
1555 goto end;
626cc488
FD
1556
1557missing_bare_minimum:
4164020e 1558 ret = -1;
626cc488 1559end:
4164020e 1560 return ret;
626cc488
FD
1561}
1562
4164020e 1563static bool is_tracer_affected_by_lttng_event_after_packet_bug(struct tracer_info *curr_tracer_info)
1719bf64 1564{
4164020e
SM
1565 bool is_affected = false;
1566
1567 if (strcmp(curr_tracer_info->name, "lttng-ust") == 0) {
1568 if (curr_tracer_info->major < 2) {
1569 is_affected = true;
1570 } else if (curr_tracer_info->major == 2) {
1571 /* fixed in lttng-ust 2.11.0 */
1572 if (curr_tracer_info->minor < 11) {
1573 is_affected = true;
1574 }
1575 }
1576 } else if (strcmp(curr_tracer_info->name, "lttng-modules") == 0) {
1577 if (curr_tracer_info->major < 2) {
1578 is_affected = true;
1579 } else if (curr_tracer_info->major == 2) {
1580 /* fixed in lttng-modules 2.11.0 */
1581 if (curr_tracer_info->minor == 10) {
1582 /* fixed in lttng-modules 2.10.10 */
1583 if (curr_tracer_info->patch < 10) {
1584 is_affected = true;
1585 }
1586 } else if (curr_tracer_info->minor == 9) {
1587 /* fixed in lttng-modules 2.9.13 */
1588 if (curr_tracer_info->patch < 13) {
1589 is_affected = true;
1590 }
1591 } else if (curr_tracer_info->minor < 9) {
1592 is_affected = true;
1593 }
1594 }
1595 }
1596
1597 return is_affected;
1719bf64
FD
1598}
1599
4164020e
SM
1600static bool
1601is_tracer_affected_by_barectf_event_before_packet_bug(struct tracer_info *curr_tracer_info)
c43092a5 1602{
4164020e
SM
1603 bool is_affected = false;
1604
1605 if (strcmp(curr_tracer_info->name, "barectf") == 0) {
1606 if (curr_tracer_info->major < 2) {
1607 is_affected = true;
1608 } else if (curr_tracer_info->major == 2) {
1609 if (curr_tracer_info->minor < 3) {
1610 is_affected = true;
1611 } else if (curr_tracer_info->minor == 3) {
1612 /* fixed in barectf 2.3.1 */
1613 if (curr_tracer_info->patch < 1) {
1614 is_affected = true;
1615 }
1616 }
1617 }
1618 }
1619
1620 return is_affected;
c43092a5
FD
1621}
1622
4164020e 1623static bool is_tracer_affected_by_lttng_crash_quirk(struct tracer_info *curr_tracer_info)
aada78b5 1624{
4164020e 1625 bool is_affected = false;
aada78b5 1626
4164020e
SM
1627 /* All LTTng tracer may be affected by this lttng crash quirk. */
1628 if (strcmp(curr_tracer_info->name, "lttng-ust") == 0) {
1629 is_affected = true;
1630 } else if (strcmp(curr_tracer_info->name, "lttng-modules") == 0) {
1631 is_affected = true;
1632 }
aada78b5 1633
4164020e 1634 return is_affected;
aada78b5
FD
1635}
1636
1719bf64
FD
1637/*
1638 * Looks for trace produced by known buggy tracers and fix up the index
1639 * produced earlier.
1640 */
0f5c5d5c 1641static int fix_packet_index_tracer_bugs(ctf_fs_trace *trace)
1719bf64 1642{
4164020e
SM
1643 int ret = 0;
1644 struct tracer_info current_tracer_info;
4164020e 1645
0f5c5d5c 1646 ret = extract_tracer_info(trace, &current_tracer_info);
4164020e
SM
1647 if (ret) {
1648 /*
1649 * A trace may not have all the necessary environment
1650 * entries to do the tracer version comparison.
1651 * At least, the tracer name and major version number
1652 * are needed. Failing to extract these entries is not
1653 * an error.
1654 */
1655 ret = 0;
0f5c5d5c
SM
1656 BT_CPPLOGI_STR_SPEC(
1657 trace->logger,
1658 "Cannot extract tracer information necessary to compare with buggy versions.");
4164020e 1659 goto end;
4164020e
SM
1660 }
1661
1662 /* Check if the trace may be affected by old tracer bugs. */
1663 if (is_tracer_affected_by_lttng_event_after_packet_bug(&current_tracer_info)) {
0f5c5d5c
SM
1664 BT_CPPLOGI_STR_SPEC(
1665 trace->logger,
1666 "Trace may be affected by LTTng tracer packet timestamp bug. Fixing up.");
1667 ret = fix_index_lttng_event_after_packet_bug(trace);
4164020e 1668 if (ret) {
0f5c5d5c
SM
1669 BT_CPPLOGE_APPEND_CAUSE_SPEC(trace->logger,
1670 "Failed to fix LTTng event-after-packet bug.");
4164020e
SM
1671 goto end;
1672 }
0f5c5d5c 1673 trace->metadata->tc->quirks.lttng_event_after_packet = true;
4164020e
SM
1674 }
1675
1676 if (is_tracer_affected_by_barectf_event_before_packet_bug(&current_tracer_info)) {
0f5c5d5c
SM
1677 BT_CPPLOGI_STR_SPEC(
1678 trace->logger,
1679 "Trace may be affected by barectf tracer packet timestamp bug. Fixing up.");
1680 ret = fix_index_barectf_event_before_packet_bug(trace);
4164020e 1681 if (ret) {
0f5c5d5c
SM
1682 BT_CPPLOGE_APPEND_CAUSE_SPEC(trace->logger,
1683 "Failed to fix barectf event-before-packet bug.");
4164020e
SM
1684 goto end;
1685 }
0f5c5d5c 1686 trace->metadata->tc->quirks.barectf_event_before_packet = true;
4164020e
SM
1687 }
1688
1689 if (is_tracer_affected_by_lttng_crash_quirk(&current_tracer_info)) {
0f5c5d5c 1690 ret = fix_index_lttng_crash_quirk(trace);
4164020e 1691 if (ret) {
0f5c5d5c
SM
1692 BT_CPPLOGE_APPEND_CAUSE_SPEC(trace->logger,
1693 "Failed to fix lttng-crash timestamp quirks.");
4164020e
SM
1694 goto end;
1695 }
0f5c5d5c 1696 trace->metadata->tc->quirks.lttng_crash = true;
4164020e 1697 }
a0cd55ad 1698
1719bf64 1699end:
4164020e 1700 return ret;
1719bf64
FD
1701}
1702
cdf7de78
SM
1703static bool compare_ds_file_groups_by_first_path(const ctf_fs_ds_file_group::UP& ds_file_group_a,
1704 const ctf_fs_ds_file_group::UP& ds_file_group_b)
e9b3611f 1705{
f3d74124
SM
1706 BT_ASSERT(!ds_file_group_a->ds_file_infos.empty());
1707 BT_ASSERT(!ds_file_group_b->ds_file_infos.empty());
087cd0f5 1708
f3d74124
SM
1709 const auto& first_ds_file_info_a = *ds_file_group_a->ds_file_infos[0];
1710 const auto& first_ds_file_info_b = *ds_file_group_b->ds_file_infos[0];
087cd0f5 1711
f3d74124 1712 return first_ds_file_info_a.path < first_ds_file_info_b.path;
e9b3611f
PP
1713}
1714
4164020e 1715static gint compare_strings(gconstpointer p_a, gconstpointer p_b)
7b69723d 1716{
4164020e
SM
1717 const char *a = *((const char **) p_a);
1718 const char *b = *((const char **) p_b);
7b69723d 1719
4164020e 1720 return strcmp(a, b);
7b69723d
SM
1721}
1722
4164020e
SM
1723int ctf_fs_component_create_ctf_fs_trace(struct ctf_fs_component *ctf_fs,
1724 const bt_value *paths_value,
1725 const bt_value *trace_name_value,
0f5c5d5c 1726 bt_self_component *selfComp)
f280892e 1727{
4164020e
SM
1728 int ret = 0;
1729 uint64_t i;
4164020e 1730 GPtrArray *paths = NULL;
a4c955d9 1731 std::vector<ctf_fs_trace::UP> traces;
4164020e
SM
1732 const char *trace_name;
1733
1734 BT_ASSERT(bt_value_get_type(paths_value) == BT_VALUE_TYPE_ARRAY);
1735 BT_ASSERT(!bt_value_array_is_empty(paths_value));
1736
4164020e
SM
1737 paths = g_ptr_array_new_with_free_func(g_free);
1738 if (!paths) {
0f5c5d5c 1739 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs->logger, "Failed to allocate a GPtrArray.");
4164020e
SM
1740 goto error;
1741 }
1742
1743 trace_name = trace_name_value ? bt_value_string_get(trace_name_value) : NULL;
1744
1745 /*
1746 * Create a sorted array of the paths, to make the execution of this
1747 * component deterministic.
1748 */
1749 for (i = 0; i < bt_value_array_get_length(paths_value); i++) {
1750 const bt_value *path_value = bt_value_array_borrow_element_by_index_const(paths_value, i);
1751 const char *input = bt_value_string_get(path_value);
1752 gchar *input_copy;
1753
1754 input_copy = g_strdup(input);
1755 if (!input_copy) {
0f5c5d5c 1756 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs->logger, "Failed to copy a string.");
4164020e
SM
1757 goto error;
1758 }
1759
1760 g_ptr_array_add(paths, input_copy);
1761 }
1762
1763 g_ptr_array_sort(paths, compare_strings);
1764
1765 /* Create a separate ctf_fs_trace object for each path. */
1766 for (i = 0; i < paths->len; i++) {
1767 const char *path = (const char *) g_ptr_array_index(paths, i);
1768
1769 ret = ctf_fs_component_create_ctf_fs_trace_one_path(ctf_fs, path, trace_name, traces,
0f5c5d5c 1770 selfComp);
4164020e
SM
1771 if (ret) {
1772 goto end;
1773 }
1774 }
1775
a4c955d9
SM
1776 if (traces.size() > 1) {
1777 ctf_fs_trace *first_trace = traces[0].get();
4164020e 1778 const uint8_t *first_trace_uuid = first_trace->metadata->tc->uuid;
4164020e
SM
1779
1780 /*
1781 * We have more than one trace, they must all share the same
1782 * UUID, verify that.
1783 */
a4c955d9
SM
1784 for (i = 0; i < traces.size(); i++) {
1785 ctf_fs_trace *this_trace = traces[i].get();
4164020e
SM
1786 const uint8_t *this_trace_uuid = this_trace->metadata->tc->uuid;
1787
1788 if (!this_trace->metadata->tc->is_uuid_set) {
0f5c5d5c
SM
1789 BT_CPPLOGE_APPEND_CAUSE_SPEC(
1790 ctf_fs->logger,
1791 "Multiple traces given, but a trace does not have a UUID: path={}",
4164020e
SM
1792 this_trace->path->str);
1793 goto error;
1794 }
1795
1796 if (bt_uuid_compare(first_trace_uuid, this_trace_uuid) != 0) {
1797 char first_trace_uuid_str[BT_UUID_STR_LEN + 1];
1798 char this_trace_uuid_str[BT_UUID_STR_LEN + 1];
1799
1800 bt_uuid_to_str(first_trace_uuid, first_trace_uuid_str);
1801 bt_uuid_to_str(this_trace_uuid, this_trace_uuid_str);
1802
0f5c5d5c
SM
1803 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs->logger,
1804 "Multiple traces given, but UUIDs don't match: "
1805 "first-trace-uuid={}, first-trace-path={}, "
1806 "trace-uuid={}, trace-path={}",
1807 first_trace_uuid_str, first_trace->path->str,
1808 this_trace_uuid_str, this_trace->path->str);
4164020e
SM
1809 goto error;
1810 }
1811 }
1812
a4c955d9 1813 ret = merge_ctf_fs_traces(std::move(traces), ctf_fs->trace);
4164020e 1814 if (ret) {
0f5c5d5c
SM
1815 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs->logger,
1816 "Failed to merge traces with the same UUID.");
4164020e
SM
1817 goto error;
1818 }
4164020e
SM
1819 } else {
1820 /* Just one trace, it may or may not have a UUID, both are fine. */
a4c955d9 1821 ctf_fs->trace = std::move(traces[0]);
4164020e
SM
1822 }
1823
7df773f2 1824 ret = fix_packet_index_tracer_bugs(ctf_fs->trace.get());
4164020e 1825 if (ret) {
0f5c5d5c 1826 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs->logger, "Failed to fix packet index tracer bugs.");
4164020e
SM
1827 }
1828
1829 /*
1830 * Sort data stream file groups by first data stream file info
1831 * path to get a deterministic order. This order influences the
1832 * order of the output ports. It also influences the order of
1833 * the automatic stream IDs if the trace's packet headers do not
1834 * contain a `stream_instance_id` field, in which case the data
1835 * stream file to stream ID association is always the same,
1836 * whatever the build and the system.
1837 *
1838 * Having a deterministic order here can help debugging and
1839 * testing.
1840 */
cdf7de78
SM
1841 std::sort(ctf_fs->trace->ds_file_groups.begin(), ctf_fs->trace->ds_file_groups.end(),
1842 compare_ds_file_groups_by_first_path);
4164020e 1843 goto end;
a0cd55ad 1844error:
4164020e 1845 ret = -1;
a0cd55ad 1846
f280892e 1847end:
4164020e
SM
1848 if (paths) {
1849 g_ptr_array_free(paths, TRUE);
1850 }
7b69723d 1851
4164020e 1852 return ret;
f280892e
SM
1853}
1854
4164020e 1855static GString *get_stream_instance_unique_name(struct ctf_fs_ds_file_group *ds_file_group)
a38d7650 1856{
4164020e
SM
1857 GString *name;
1858 struct ctf_fs_ds_file_info *ds_file_info;
1859
1860 name = g_string_new(NULL);
1861 if (!name) {
1862 goto end;
1863 }
1864
1865 /*
1866 * If there's more than one stream file in the stream file
1867 * group, the first (earliest) stream file's path is used as
1868 * the stream's unique name.
1869 */
f3d74124
SM
1870 BT_ASSERT(!ds_file_group->ds_file_infos.empty());
1871 ds_file_info = ds_file_group->ds_file_infos[0].get();
4d199954 1872 g_string_assign(name, ds_file_info->path.c_str());
a38d7650
SM
1873
1874end:
4164020e 1875 return name;
a38d7650
SM
1876}
1877
f280892e
SM
1878/* Create the IR stream objects for ctf_fs_trace. */
1879
4164020e 1880static int create_streams_for_trace(struct ctf_fs_trace *ctf_fs_trace)
f280892e 1881{
4164020e
SM
1882 int ret;
1883 GString *name = NULL;
4164020e 1884
cdf7de78
SM
1885 for (const auto& ds_file_group : ctf_fs_trace->ds_file_groups) {
1886 name = get_stream_instance_unique_name(ds_file_group.get());
4164020e
SM
1887
1888 if (!name) {
1889 goto error;
1890 }
1891
f0940b01
SM
1892 BT_ASSERT(ds_file_group->sc->ir_sc);
1893 BT_ASSERT(ctf_fs_trace->trace);
1894
1895 if (ds_file_group->stream_id == UINT64_C(-1)) {
1896 /* No stream ID: use 0 */
1897 ds_file_group->stream = bt_stream_create_with_id(
1898 ds_file_group->sc->ir_sc, ctf_fs_trace->trace, ctf_fs_trace->next_stream_id);
1899 ctf_fs_trace->next_stream_id++;
4164020e 1900 } else {
f0940b01
SM
1901 /* Specific stream ID */
1902 ds_file_group->stream = bt_stream_create_with_id(
1903 ds_file_group->sc->ir_sc, ctf_fs_trace->trace, (uint64_t) ds_file_group->stream_id);
4164020e
SM
1904 }
1905
1906 if (!ds_file_group->stream) {
0f5c5d5c
SM
1907 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs_trace->logger,
1908 "Cannot create stream for DS file group: "
1909 "addr={}, stream-name=\"{}\"",
1910 fmt::ptr(ds_file_group), name->str);
4164020e
SM
1911 goto error;
1912 }
1913
1914 ret = bt_stream_set_name(ds_file_group->stream, name->str);
1915 if (ret) {
0f5c5d5c
SM
1916 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs_trace->logger,
1917 "Cannot set stream's name: "
1918 "addr={}, stream-name=\"{}\"",
1919 fmt::ptr(ds_file_group->stream), name->str);
4164020e
SM
1920 goto error;
1921 }
1922
1923 g_string_free(name, TRUE);
1924 name = NULL;
1925 }
1926
1927 ret = 0;
1928 goto end;
f280892e
SM
1929
1930error:
4164020e 1931 ret = -1;
f280892e
SM
1932
1933end:
1934
4164020e
SM
1935 if (name) {
1936 g_string_free(name, TRUE);
1937 }
1938 return ret;
f280892e
SM
1939}
1940
88730e42
SM
1941static const bt_param_validation_value_descr inputs_elem_descr =
1942 bt_param_validation_value_descr::makeString();
087cd0f5
SM
1943
1944static bt_param_validation_map_value_entry_descr fs_params_entries_descr[] = {
88730e42
SM
1945 {"inputs", BT_PARAM_VALIDATION_MAP_VALUE_ENTRY_MANDATORY,
1946 bt_param_validation_value_descr::makeArray(1, BT_PARAM_VALIDATION_INFINITE,
1947 inputs_elem_descr)},
1948 {"trace-name", BT_PARAM_VALIDATION_MAP_VALUE_ENTRY_OPTIONAL,
1949 bt_param_validation_value_descr::makeString()},
1950 {"clock-class-offset-s", BT_PARAM_VALIDATION_MAP_VALUE_ENTRY_OPTIONAL,
1951 bt_param_validation_value_descr::makeSignedInteger()},
1952 {"clock-class-offset-ns", BT_PARAM_VALIDATION_MAP_VALUE_ENTRY_OPTIONAL,
1953 bt_param_validation_value_descr::makeSignedInteger()},
1954 {"force-clock-class-origin-unix-epoch", BT_PARAM_VALIDATION_MAP_VALUE_ENTRY_OPTIONAL,
1955 bt_param_validation_value_descr::makeBool()},
4164020e
SM
1956 BT_PARAM_VALIDATION_MAP_VALUE_ENTRY_END};
1957
1958bool read_src_fs_parameters(const bt_value *params, const bt_value **inputs,
0f5c5d5c 1959 const bt_value **trace_name, struct ctf_fs_component *ctf_fs)
4164020e
SM
1960{
1961 bool ret;
1962 const bt_value *value;
4164020e
SM
1963 enum bt_param_validation_status validate_value_status;
1964 gchar *error = NULL;
1965
1966 validate_value_status = bt_param_validation_validate(params, fs_params_entries_descr, &error);
1967 if (validate_value_status != BT_PARAM_VALIDATION_STATUS_OK) {
0f5c5d5c 1968 BT_CPPLOGE_APPEND_CAUSE_SPEC(ctf_fs->logger, "{}", error);
4164020e
SM
1969 ret = false;
1970 goto end;
1971 }
1972
1973 /* inputs parameter */
1974 *inputs = bt_value_map_borrow_entry_value_const(params, "inputs");
1975
1976 /* clock-class-offset-s parameter */
1977 value = bt_value_map_borrow_entry_value_const(params, "clock-class-offset-s");
1978 if (value) {
c942e7a2 1979 ctf_fs->clkClsCfg.offsetSec = bt_value_integer_signed_get(value);
4164020e
SM
1980 }
1981
1982 /* clock-class-offset-ns parameter */
1983 value = bt_value_map_borrow_entry_value_const(params, "clock-class-offset-ns");
1984 if (value) {
c942e7a2 1985 ctf_fs->clkClsCfg.offsetNanoSec = bt_value_integer_signed_get(value);
4164020e
SM
1986 }
1987
1988 /* force-clock-class-origin-unix-epoch parameter */
1989 value = bt_value_map_borrow_entry_value_const(params, "force-clock-class-origin-unix-epoch");
1990 if (value) {
c942e7a2 1991 ctf_fs->clkClsCfg.forceOriginIsUnixEpoch = bt_value_bool_get(value);
4164020e
SM
1992 }
1993
1994 /* trace-name parameter */
1995 *trace_name = bt_value_map_borrow_entry_value_const(params, "trace-name");
1996
1997 ret = true;
d907165c
SM
1998
1999end:
4164020e
SM
2000 g_free(error);
2001 return ret;
d907165c
SM
2002}
2003
f340a3e8
SM
2004static ctf_fs_component::UP ctf_fs_create(const bt_value *params,
2005 bt_self_component_source *self_comp_src)
56a1cced 2006{
4164020e
SM
2007 const bt_value *inputs_value;
2008 const bt_value *trace_name_value;
2009 bt_self_component *self_comp = bt_self_component_source_as_self_component(self_comp_src);
56a1cced 2010
f340a3e8 2011 ctf_fs_component::UP ctf_fs = ctf_fs_component_create(
0f5c5d5c 2012 bt2c::Logger {bt2::SelfSourceComponent {self_comp_src}, "PLUGIN/SRC.CTF.FS/COMP"});
4164020e 2013 if (!ctf_fs) {
f340a3e8 2014 return nullptr;
4164020e 2015 }
f280892e 2016
f340a3e8
SM
2017 if (!read_src_fs_parameters(params, &inputs_value, &trace_name_value, ctf_fs.get())) {
2018 return nullptr;
4164020e 2019 }
56a1cced 2020
f340a3e8
SM
2021 if (ctf_fs_component_create_ctf_fs_trace(ctf_fs.get(), inputs_value, trace_name_value,
2022 self_comp)) {
2023 return nullptr;
4164020e 2024 }
4f1f88a6 2025
7df773f2 2026 if (create_streams_for_trace(ctf_fs->trace.get())) {
f340a3e8 2027 return nullptr;
4164020e 2028 }
f280892e 2029
7df773f2 2030 if (create_ports_for_trace(ctf_fs.get(), ctf_fs->trace.get(), self_comp_src)) {
f340a3e8 2031 return nullptr;
4164020e 2032 }
4f1f88a6 2033
4164020e 2034 return ctf_fs;
56a1cced
JG
2035}
2036
50b9f4b5
SM
2037bt_component_class_initialize_method_status ctf_fs_init(bt_self_component_source *self_comp_src,
2038 bt_self_component_source_configuration *,
2039 const bt_value *params, void *)
ea0b4b9e 2040{
1e690349 2041 try {
1e690349
SM
2042 bt_component_class_initialize_method_status ret =
2043 BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_OK;
2044
f340a3e8 2045 ctf_fs_component::UP ctf_fs = ctf_fs_create(params, self_comp_src);
1e690349
SM
2046 if (!ctf_fs) {
2047 ret = BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
2048 }
ea0b4b9e 2049
f340a3e8
SM
2050 bt_self_component_set_data(bt_self_component_source_as_self_component(self_comp_src),
2051 ctf_fs.release());
1e690349
SM
2052 return ret;
2053 } catch (const std::bad_alloc&) {
2054 return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_MEMORY_ERROR;
2055 } catch (const bt2::Error&) {
2056 return BT_COMPONENT_CLASS_INITIALIZE_METHOD_STATUS_ERROR;
4164020e 2057 }
ea0b4b9e 2058}
33f93973 2059
0f5c5d5c 2060bt_component_class_query_method_status ctf_fs_query(bt_self_component_class_source *comp_class_src,
4164020e
SM
2061 bt_private_query_executor *priv_query_exec,
2062 const char *object, const bt_value *params,
2063 __attribute__((unused)) void *method_data,
2064 const bt_value **result)
33f93973 2065{
1e690349 2066 try {
1e690349
SM
2067 bt2c::Logger logger {bt2::SelfComponentClass {comp_class_src},
2068 bt2::PrivateQueryExecutor {priv_query_exec},
2069 "PLUGIN/SRC.CTF.FS/QUERY"};
c02af779
SM
2070 bt2::ConstMapValue paramsObj(params);
2071 bt2::Value::Shared resultObj;
1e690349
SM
2072
2073 if (strcmp(object, "metadata-info") == 0) {
c02af779 2074 resultObj = metadata_info_query(paramsObj, logger);
1e690349 2075 } else if (strcmp(object, "babeltrace.trace-infos") == 0) {
c02af779 2076 resultObj = trace_infos_query(paramsObj, logger);
1e690349 2077 } else if (!strcmp(object, "babeltrace.support-info")) {
c02af779 2078 resultObj = support_info_query(paramsObj, logger);
1e690349
SM
2079 } else {
2080 BT_CPPLOGE_SPEC(logger, "Unknown query object `{}`", object);
c02af779 2081 return BT_COMPONENT_CLASS_QUERY_METHOD_STATUS_UNKNOWN_OBJECT;
1e690349 2082 }
c02af779
SM
2083
2084 *result = resultObj.release().libObjPtr();
2085
2086 return BT_COMPONENT_CLASS_QUERY_METHOD_STATUS_OK;
1e690349
SM
2087 } catch (const std::bad_alloc&) {
2088 return BT_COMPONENT_CLASS_QUERY_METHOD_STATUS_MEMORY_ERROR;
2089 } catch (const bt2::Error&) {
2090 return BT_COMPONENT_CLASS_QUERY_METHOD_STATUS_ERROR;
2091 }
33f93973 2092}
This page took 0.29559 seconds and 4 git commands to generate.