fix: relayd: unaligned access in trace_chunk_registry_ht_key_hash
[lttng-tools.git] / src / common / consumer / consumer.cpp
1 /*
2 * Copyright (C) 2011 EfficiOS Inc.
3 * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
4 * Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
5 *
6 * SPDX-License-Identifier: GPL-2.0-only
7 *
8 */
9
10 #define _LGPL_SOURCE
11 #include <common/align.hpp>
12 #include <common/common.hpp>
13 #include <common/compat/endian.hpp>
14 #include <common/compat/poll.hpp>
15 #include <common/consumer/consumer-metadata-cache.hpp>
16 #include <common/consumer/consumer-stream.hpp>
17 #include <common/consumer/consumer-testpoint.hpp>
18 #include <common/consumer/consumer-timer.hpp>
19 #include <common/consumer/consumer.hpp>
20 #include <common/dynamic-array.hpp>
21 #include <common/index/ctf-index.hpp>
22 #include <common/index/index.hpp>
23 #include <common/io-hint.hpp>
24 #include <common/kernel-consumer/kernel-consumer.hpp>
25 #include <common/kernel-ctl/kernel-ctl.hpp>
26 #include <common/relayd/relayd.hpp>
27 #include <common/sessiond-comm/relayd.hpp>
28 #include <common/sessiond-comm/sessiond-comm.hpp>
29 #include <common/string-utils/format.hpp>
30 #include <common/time.hpp>
31 #include <common/trace-chunk-registry.hpp>
32 #include <common/trace-chunk.hpp>
33 #include <common/urcu.hpp>
34 #include <common/ust-consumer/ust-consumer.hpp>
35 #include <common/utils.hpp>
36
37 #include <bin/lttng-consumerd/health-consumerd.hpp>
38 #include <fcntl.h>
39 #include <inttypes.h>
40 #include <poll.h>
41 #include <pthread.h>
42 #include <signal.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <sys/mman.h>
46 #include <sys/socket.h>
47 #include <sys/types.h>
48 #include <type_traits>
49 #include <unistd.h>
50
51 lttng_consumer_global_data the_consumer_data;
52
53 enum consumer_channel_action {
54 CONSUMER_CHANNEL_ADD,
55 CONSUMER_CHANNEL_DEL,
56 CONSUMER_CHANNEL_QUIT,
57 };
58
59 namespace {
60 struct consumer_channel_msg {
61 enum consumer_channel_action action;
62 struct lttng_consumer_channel *chan; /* add */
63 uint64_t key; /* del */
64 };
65
66 /*
67 * Global hash table containing respectively metadata and data streams. The
68 * stream element in this ht should only be updated by the metadata poll thread
69 * for the metadata and the data poll thread for the data.
70 */
71 struct lttng_ht *metadata_ht;
72 struct lttng_ht *data_ht;
73 } /* namespace */
74
75 /* Flag used to temporarily pause data consumption from testpoints. */
76 int data_consumption_paused;
77
78 /*
79 * Flag to inform the polling thread to quit when all fd hung up. Updated by
80 * the consumer_thread_receive_fds when it notices that all fds has hung up.
81 * Also updated by the signal handler (consumer_should_exit()). Read by the
82 * polling threads.
83 */
84 int consumer_quit;
85
86 static const char *get_consumer_domain()
87 {
88 switch (the_consumer_data.type) {
89 case LTTNG_CONSUMER_KERNEL:
90 return DEFAULT_KERNEL_TRACE_DIR;
91 case LTTNG_CONSUMER64_UST:
92 /* Fall-through. */
93 case LTTNG_CONSUMER32_UST:
94 return DEFAULT_UST_TRACE_DIR;
95 default:
96 abort();
97 }
98 }
99
100 /*
101 * Notify a thread lttng pipe to poll back again. This usually means that some
102 * global state has changed so we just send back the thread in a poll wait
103 * call.
104 */
105 static void notify_thread_lttng_pipe(struct lttng_pipe *pipe)
106 {
107 struct lttng_consumer_stream *null_stream = nullptr;
108
109 LTTNG_ASSERT(pipe);
110
111 (void) lttng_pipe_write(pipe, &null_stream, sizeof(null_stream)); /* NOLINT sizeof used on a
112 pointer. */
113 }
114
115 static void notify_health_quit_pipe(int *pipe)
116 {
117 ssize_t ret;
118
119 ret = lttng_write(pipe[1], "4", 1);
120 if (ret < 1) {
121 PERROR("write consumer health quit");
122 }
123 }
124
125 static void notify_channel_pipe(struct lttng_consumer_local_data *ctx,
126 struct lttng_consumer_channel *chan,
127 uint64_t key,
128 enum consumer_channel_action action)
129 {
130 struct consumer_channel_msg msg;
131 ssize_t ret;
132
133 memset(&msg, 0, sizeof(msg));
134
135 msg.action = action;
136 msg.chan = chan;
137 msg.key = key;
138 ret = lttng_write(ctx->consumer_channel_pipe[1], &msg, sizeof(msg));
139 if (ret < sizeof(msg)) {
140 PERROR("notify_channel_pipe write error");
141 }
142 }
143
144 void notify_thread_del_channel(struct lttng_consumer_local_data *ctx, uint64_t key)
145 {
146 notify_channel_pipe(ctx, nullptr, key, CONSUMER_CHANNEL_DEL);
147 }
148
149 static int read_channel_pipe(struct lttng_consumer_local_data *ctx,
150 struct lttng_consumer_channel **chan,
151 uint64_t *key,
152 enum consumer_channel_action *action)
153 {
154 struct consumer_channel_msg msg;
155 ssize_t ret;
156
157 ret = lttng_read(ctx->consumer_channel_pipe[0], &msg, sizeof(msg));
158 if (ret < sizeof(msg)) {
159 ret = -1;
160 goto error;
161 }
162 *action = msg.action;
163 *chan = msg.chan;
164 *key = msg.key;
165 error:
166 return (int) ret;
167 }
168
169 /*
170 * Cleanup the stream list of a channel. Those streams are not yet globally
171 * visible
172 */
173 static void clean_channel_stream_list(struct lttng_consumer_channel *channel)
174 {
175 struct lttng_consumer_stream *stream, *stmp;
176
177 LTTNG_ASSERT(channel);
178
179 /* Delete streams that might have been left in the stream list. */
180 cds_list_for_each_entry_safe (stream, stmp, &channel->streams.head, send_node) {
181 /*
182 * Once a stream is added to this list, the buffers were created so we
183 * have a guarantee that this call will succeed. Setting the monitor
184 * mode to 0 so we don't lock nor try to delete the stream from the
185 * global hash table.
186 */
187 stream->monitor = 0;
188 consumer_stream_destroy(stream, nullptr);
189 }
190 }
191
192 /*
193 * Find a stream. The consumer_data.lock must be locked during this
194 * call.
195 */
196 static struct lttng_consumer_stream *find_stream(uint64_t key, struct lttng_ht *ht)
197 {
198 struct lttng_ht_iter iter;
199 struct lttng_ht_node_u64 *node;
200 struct lttng_consumer_stream *stream = nullptr;
201
202 LTTNG_ASSERT(ht);
203
204 /* -1ULL keys are lookup failures */
205 if (key == (uint64_t) -1ULL) {
206 return nullptr;
207 }
208
209 lttng::urcu::read_lock_guard read_lock;
210
211 lttng_ht_lookup(ht, &key, &iter);
212 node = lttng_ht_iter_get_node_u64(&iter);
213 if (node != nullptr) {
214 stream = lttng::utils::container_of(node, &lttng_consumer_stream::node);
215 }
216
217 return stream;
218 }
219
220 static void steal_stream_key(uint64_t key, struct lttng_ht *ht)
221 {
222 struct lttng_consumer_stream *stream;
223
224 lttng::urcu::read_lock_guard read_lock;
225 stream = find_stream(key, ht);
226 if (stream) {
227 stream->key = (uint64_t) -1ULL;
228 /*
229 * We don't want the lookup to match, but we still need
230 * to iterate on this stream when iterating over the hash table. Just
231 * change the node key.
232 */
233 stream->node.key = (uint64_t) -1ULL;
234 }
235 }
236
237 /*
238 * Return a channel object for the given key.
239 *
240 * RCU read side lock MUST be acquired before calling this function and
241 * protects the channel ptr.
242 */
243 struct lttng_consumer_channel *consumer_find_channel(uint64_t key)
244 {
245 struct lttng_ht_iter iter;
246 struct lttng_ht_node_u64 *node;
247 struct lttng_consumer_channel *channel = nullptr;
248
249 ASSERT_RCU_READ_LOCKED();
250
251 /* -1ULL keys are lookup failures */
252 if (key == (uint64_t) -1ULL) {
253 return nullptr;
254 }
255
256 lttng_ht_lookup(the_consumer_data.channel_ht, &key, &iter);
257 node = lttng_ht_iter_get_node_u64(&iter);
258 if (node != nullptr) {
259 channel = lttng::utils::container_of(node, &lttng_consumer_channel::node);
260 }
261
262 return channel;
263 }
264
265 /*
266 * There is a possibility that the consumer does not have enough time between
267 * the close of the channel on the session daemon and the cleanup in here thus
268 * once we have a channel add with an existing key, we know for sure that this
269 * channel will eventually get cleaned up by all streams being closed.
270 *
271 * This function just nullifies the already existing channel key.
272 */
273 static void steal_channel_key(uint64_t key)
274 {
275 struct lttng_consumer_channel *channel;
276
277 lttng::urcu::read_lock_guard read_lock;
278 channel = consumer_find_channel(key);
279 if (channel) {
280 channel->key = (uint64_t) -1ULL;
281 /*
282 * We don't want the lookup to match, but we still need to iterate on
283 * this channel when iterating over the hash table. Just change the
284 * node key.
285 */
286 channel->node.key = (uint64_t) -1ULL;
287 }
288 }
289
290 static void free_channel_rcu(struct rcu_head *head)
291 {
292 struct lttng_ht_node_u64 *node = lttng::utils::container_of(head, &lttng_ht_node_u64::head);
293 struct lttng_consumer_channel *channel =
294 lttng::utils::container_of(node, &lttng_consumer_channel::node);
295
296 switch (the_consumer_data.type) {
297 case LTTNG_CONSUMER_KERNEL:
298 break;
299 case LTTNG_CONSUMER32_UST:
300 case LTTNG_CONSUMER64_UST:
301 lttng_ustconsumer_free_channel(channel);
302 break;
303 default:
304 ERR("Unknown consumer_data type");
305 abort();
306 }
307
308 delete channel;
309 }
310
311 /*
312 * RCU protected relayd socket pair free.
313 */
314 static void free_relayd_rcu(struct rcu_head *head)
315 {
316 struct lttng_ht_node_u64 *node = lttng::utils::container_of(head, &lttng_ht_node_u64::head);
317 struct consumer_relayd_sock_pair *relayd =
318 lttng::utils::container_of(node, &consumer_relayd_sock_pair::node);
319
320 /*
321 * Close all sockets. This is done in the call RCU since we don't want the
322 * socket fds to be reassigned thus potentially creating bad state of the
323 * relayd object.
324 *
325 * We do not have to lock the control socket mutex here since at this stage
326 * there is no one referencing to this relayd object.
327 */
328 (void) relayd_close(&relayd->control_sock);
329 (void) relayd_close(&relayd->data_sock);
330
331 pthread_mutex_destroy(&relayd->ctrl_sock_mutex);
332 free(relayd);
333 }
334
335 /*
336 * Destroy and free relayd socket pair object.
337 */
338 void consumer_destroy_relayd(struct consumer_relayd_sock_pair *relayd)
339 {
340 int ret;
341 struct lttng_ht_iter iter;
342
343 if (relayd == nullptr) {
344 return;
345 }
346
347 DBG("Consumer destroy and close relayd socket pair");
348
349 iter.iter.node = &relayd->node.node;
350 ret = lttng_ht_del(the_consumer_data.relayd_ht, &iter);
351 if (ret != 0) {
352 /* We assume the relayd is being or is destroyed */
353 return;
354 }
355
356 /* RCU free() call */
357 call_rcu(&relayd->node.head, free_relayd_rcu);
358 }
359
360 /*
361 * Remove a channel from the global list protected by a mutex. This function is
362 * also responsible for freeing its data structures.
363 */
364 void consumer_del_channel(struct lttng_consumer_channel *channel)
365 {
366 struct lttng_ht_iter iter;
367
368 DBG("Consumer delete channel key %" PRIu64, channel->key);
369
370 pthread_mutex_lock(&the_consumer_data.lock);
371 pthread_mutex_lock(&channel->lock);
372
373 /* Destroy streams that might have been left in the stream list. */
374 clean_channel_stream_list(channel);
375
376 if (channel->live_timer_enabled == 1) {
377 consumer_timer_live_stop(channel);
378 }
379 if (channel->monitor_timer_enabled == 1) {
380 consumer_timer_monitor_stop(channel);
381 }
382
383 /*
384 * Send a last buffer statistics sample to the session daemon
385 * to ensure it tracks the amount of data consumed by this channel.
386 */
387 sample_and_send_channel_buffer_stats(channel);
388
389 switch (the_consumer_data.type) {
390 case LTTNG_CONSUMER_KERNEL:
391 break;
392 case LTTNG_CONSUMER32_UST:
393 case LTTNG_CONSUMER64_UST:
394 lttng_ustconsumer_del_channel(channel);
395 break;
396 default:
397 ERR("Unknown consumer_data type");
398 abort();
399 goto end;
400 }
401
402 lttng_trace_chunk_put(channel->trace_chunk);
403 channel->trace_chunk = nullptr;
404
405 if (channel->is_published) {
406 int ret;
407
408 lttng::urcu::read_lock_guard read_lock;
409 iter.iter.node = &channel->node.node;
410 ret = lttng_ht_del(the_consumer_data.channel_ht, &iter);
411 LTTNG_ASSERT(!ret);
412
413 iter.iter.node = &channel->channels_by_session_id_ht_node.node;
414 ret = lttng_ht_del(the_consumer_data.channels_by_session_id_ht, &iter);
415 LTTNG_ASSERT(!ret);
416 }
417
418 channel->is_deleted = true;
419 call_rcu(&channel->node.head, free_channel_rcu);
420 end:
421 pthread_mutex_unlock(&channel->lock);
422 pthread_mutex_unlock(&the_consumer_data.lock);
423 }
424
425 /*
426 * Iterate over the relayd hash table and destroy each element. Finally,
427 * destroy the whole hash table.
428 */
429 static void cleanup_relayd_ht()
430 {
431 struct lttng_ht_iter iter;
432 struct consumer_relayd_sock_pair *relayd;
433
434 {
435 lttng::urcu::read_lock_guard read_lock;
436
437 cds_lfht_for_each_entry (
438 the_consumer_data.relayd_ht->ht, &iter.iter, relayd, node.node) {
439 consumer_destroy_relayd(relayd);
440 }
441 }
442
443 lttng_ht_destroy(the_consumer_data.relayd_ht);
444 }
445
446 /*
447 * Update the end point status of all streams having the given network sequence
448 * index (relayd index).
449 *
450 * It's atomically set without having the stream mutex locked which is fine
451 * because we handle the write/read race with a pipe wakeup for each thread.
452 */
453 static void update_endpoint_status_by_netidx(uint64_t net_seq_idx,
454 enum consumer_endpoint_status status)
455 {
456 struct lttng_ht_iter iter;
457 struct lttng_consumer_stream *stream;
458
459 DBG("Consumer set delete flag on stream by idx %" PRIu64, net_seq_idx);
460
461 lttng::urcu::read_lock_guard read_lock;
462
463 /* Let's begin with metadata */
464 cds_lfht_for_each_entry (metadata_ht->ht, &iter.iter, stream, node.node) {
465 if (stream->net_seq_idx == net_seq_idx) {
466 uatomic_set(&stream->endpoint_status, status);
467 stream->chan->metadata_pushed_wait_queue.wake_all();
468
469 DBG("Delete flag set to metadata stream %d", stream->wait_fd);
470 }
471 }
472
473 /* Follow up by the data streams */
474 cds_lfht_for_each_entry (data_ht->ht, &iter.iter, stream, node.node) {
475 if (stream->net_seq_idx == net_seq_idx) {
476 uatomic_set(&stream->endpoint_status, status);
477 DBG("Delete flag set to data stream %d", stream->wait_fd);
478 }
479 }
480 }
481
482 /*
483 * Cleanup a relayd object by flagging every associated streams for deletion,
484 * destroying the object meaning removing it from the relayd hash table,
485 * closing the sockets and freeing the memory in a RCU call.
486 *
487 * If a local data context is available, notify the threads that the streams'
488 * state have changed.
489 */
490 void lttng_consumer_cleanup_relayd(struct consumer_relayd_sock_pair *relayd)
491 {
492 uint64_t netidx;
493
494 LTTNG_ASSERT(relayd);
495
496 DBG("Cleaning up relayd object ID %" PRIu64, relayd->net_seq_idx);
497
498 /* Save the net sequence index before destroying the object */
499 netidx = relayd->net_seq_idx;
500
501 /*
502 * Delete the relayd from the relayd hash table, close the sockets and free
503 * the object in a RCU call.
504 */
505 consumer_destroy_relayd(relayd);
506
507 /* Set inactive endpoint to all streams */
508 update_endpoint_status_by_netidx(netidx, CONSUMER_ENDPOINT_INACTIVE);
509
510 /*
511 * With a local data context, notify the threads that the streams' state
512 * have changed. The write() action on the pipe acts as an "implicit"
513 * memory barrier ordering the updates of the end point status from the
514 * read of this status which happens AFTER receiving this notify.
515 */
516 notify_thread_lttng_pipe(relayd->ctx->consumer_data_pipe);
517 notify_thread_lttng_pipe(relayd->ctx->consumer_metadata_pipe);
518 }
519
520 /*
521 * Flag a relayd socket pair for destruction. Destroy it if the refcount
522 * reaches zero.
523 *
524 * RCU read side lock MUST be aquired before calling this function.
525 */
526 void consumer_flag_relayd_for_destroy(struct consumer_relayd_sock_pair *relayd)
527 {
528 LTTNG_ASSERT(relayd);
529 ASSERT_RCU_READ_LOCKED();
530
531 /* Set destroy flag for this object */
532 uatomic_set(&relayd->destroy_flag, 1);
533
534 /* Destroy the relayd if refcount is 0 */
535 if (uatomic_read(&relayd->refcount) == 0) {
536 consumer_destroy_relayd(relayd);
537 }
538 }
539
540 /*
541 * Completly destroy stream from every visiable data structure and the given
542 * hash table if one.
543 *
544 * One this call returns, the stream object is not longer usable nor visible.
545 */
546 void consumer_del_stream(struct lttng_consumer_stream *stream, struct lttng_ht *ht)
547 {
548 consumer_stream_destroy(stream, ht);
549 }
550
551 /*
552 * XXX naming of del vs destroy is all mixed up.
553 */
554 void consumer_del_stream_for_data(struct lttng_consumer_stream *stream)
555 {
556 consumer_stream_destroy(stream, data_ht);
557 }
558
559 void consumer_del_stream_for_metadata(struct lttng_consumer_stream *stream)
560 {
561 consumer_stream_destroy(stream, metadata_ht);
562 }
563
564 void consumer_stream_update_channel_attributes(struct lttng_consumer_stream *stream,
565 struct lttng_consumer_channel *channel)
566 {
567 stream->channel_read_only_attributes.tracefile_size = channel->tracefile_size;
568 }
569
570 /*
571 * Add a stream to the global list protected by a mutex.
572 */
573 void consumer_add_data_stream(struct lttng_consumer_stream *stream)
574 {
575 struct lttng_ht *ht = data_ht;
576
577 LTTNG_ASSERT(stream);
578 LTTNG_ASSERT(ht);
579
580 DBG3("Adding consumer stream %" PRIu64, stream->key);
581
582 pthread_mutex_lock(&the_consumer_data.lock);
583 pthread_mutex_lock(&stream->chan->lock);
584 pthread_mutex_lock(&stream->chan->timer_lock);
585 pthread_mutex_lock(&stream->lock);
586 lttng::urcu::read_lock_guard read_lock;
587
588 /* Steal stream identifier to avoid having streams with the same key */
589 steal_stream_key(stream->key, ht);
590
591 lttng_ht_add_unique_u64(ht, &stream->node);
592
593 lttng_ht_add_u64(the_consumer_data.stream_per_chan_id_ht, &stream->node_channel_id);
594
595 /*
596 * Add stream to the stream_list_ht of the consumer data. No need to steal
597 * the key since the HT does not use it and we allow to add redundant keys
598 * into this table.
599 */
600 lttng_ht_add_u64(the_consumer_data.stream_list_ht, &stream->node_session_id);
601
602 /*
603 * When nb_init_stream_left reaches 0, we don't need to trigger any action
604 * in terms of destroying the associated channel, because the action that
605 * causes the count to become 0 also causes a stream to be added. The
606 * channel deletion will thus be triggered by the following removal of this
607 * stream.
608 */
609 if (uatomic_read(&stream->chan->nb_init_stream_left) > 0) {
610 /* Increment refcount before decrementing nb_init_stream_left */
611 cmm_smp_wmb();
612 uatomic_dec(&stream->chan->nb_init_stream_left);
613 }
614
615 /* Update consumer data once the node is inserted. */
616 the_consumer_data.stream_count++;
617 the_consumer_data.need_update = 1;
618
619 pthread_mutex_unlock(&stream->lock);
620 pthread_mutex_unlock(&stream->chan->timer_lock);
621 pthread_mutex_unlock(&stream->chan->lock);
622 pthread_mutex_unlock(&the_consumer_data.lock);
623 }
624
625 /*
626 * Add relayd socket to global consumer data hashtable. RCU read side lock MUST
627 * be acquired before calling this.
628 */
629 static int add_relayd(struct consumer_relayd_sock_pair *relayd)
630 {
631 int ret = 0;
632 struct lttng_ht_node_u64 *node;
633 struct lttng_ht_iter iter;
634
635 LTTNG_ASSERT(relayd);
636 ASSERT_RCU_READ_LOCKED();
637
638 lttng_ht_lookup(the_consumer_data.relayd_ht, &relayd->net_seq_idx, &iter);
639 node = lttng_ht_iter_get_node_u64(&iter);
640 if (node != nullptr) {
641 goto end;
642 }
643 lttng_ht_add_unique_u64(the_consumer_data.relayd_ht, &relayd->node);
644
645 end:
646 return ret;
647 }
648
649 /*
650 * Allocate and return a consumer relayd socket.
651 */
652 static struct consumer_relayd_sock_pair *consumer_allocate_relayd_sock_pair(uint64_t net_seq_idx)
653 {
654 struct consumer_relayd_sock_pair *obj = nullptr;
655
656 /* net sequence index of -1 is a failure */
657 if (net_seq_idx == (uint64_t) -1ULL) {
658 goto error;
659 }
660
661 obj = zmalloc<consumer_relayd_sock_pair>();
662 if (obj == nullptr) {
663 PERROR("zmalloc relayd sock");
664 goto error;
665 }
666
667 obj->net_seq_idx = net_seq_idx;
668 obj->refcount = 0;
669 obj->destroy_flag = 0;
670 obj->control_sock.sock.fd = -1;
671 obj->data_sock.sock.fd = -1;
672 lttng_ht_node_init_u64(&obj->node, obj->net_seq_idx);
673 pthread_mutex_init(&obj->ctrl_sock_mutex, nullptr);
674
675 error:
676 return obj;
677 }
678
679 /*
680 * Find a relayd socket pair in the global consumer data.
681 *
682 * Return the object if found else NULL.
683 * RCU read-side lock must be held across this call and while using the
684 * returned object.
685 */
686 struct consumer_relayd_sock_pair *consumer_find_relayd(uint64_t key)
687 {
688 struct lttng_ht_iter iter;
689 struct lttng_ht_node_u64 *node;
690 struct consumer_relayd_sock_pair *relayd = nullptr;
691
692 ASSERT_RCU_READ_LOCKED();
693
694 /* Negative keys are lookup failures */
695 if (key == (uint64_t) -1ULL) {
696 goto error;
697 }
698
699 lttng_ht_lookup(the_consumer_data.relayd_ht, &key, &iter);
700 node = lttng_ht_iter_get_node_u64(&iter);
701 if (node != nullptr) {
702 relayd = lttng::utils::container_of(node, &consumer_relayd_sock_pair::node);
703 }
704
705 error:
706 return relayd;
707 }
708
709 /*
710 * Find a relayd and send the stream
711 *
712 * Returns 0 on success, < 0 on error
713 */
714 int consumer_send_relayd_stream(struct lttng_consumer_stream *stream, char *path)
715 {
716 int ret = 0;
717 struct consumer_relayd_sock_pair *relayd;
718
719 LTTNG_ASSERT(stream);
720 LTTNG_ASSERT(stream->net_seq_idx != -1ULL);
721 LTTNG_ASSERT(path);
722
723 /* The stream is not metadata. Get relayd reference if exists. */
724 lttng::urcu::read_lock_guard read_lock;
725 relayd = consumer_find_relayd(stream->net_seq_idx);
726 if (relayd != nullptr) {
727 /* Add stream on the relayd */
728 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
729 ret = relayd_add_stream(&relayd->control_sock,
730 stream->name,
731 get_consumer_domain(),
732 path,
733 &stream->relayd_stream_id,
734 stream->chan->tracefile_size,
735 stream->chan->tracefile_count,
736 stream->trace_chunk);
737 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
738 if (ret < 0) {
739 ERR("Relayd add stream failed. Cleaning up relayd %" PRIu64 ".",
740 relayd->net_seq_idx);
741 lttng_consumer_cleanup_relayd(relayd);
742 goto end;
743 }
744
745 uatomic_inc(&relayd->refcount);
746 stream->sent_to_relayd = 1;
747 } else {
748 ERR("Stream %" PRIu64 " relayd ID %" PRIu64 " unknown. Can't send it.",
749 stream->key,
750 stream->net_seq_idx);
751 ret = -1;
752 goto end;
753 }
754
755 DBG("Stream %s with key %" PRIu64 " sent to relayd id %" PRIu64,
756 stream->name,
757 stream->key,
758 stream->net_seq_idx);
759
760 end:
761 return ret;
762 }
763
764 /*
765 * Find a relayd and send the streams sent message
766 *
767 * Returns 0 on success, < 0 on error
768 */
769 int consumer_send_relayd_streams_sent(uint64_t net_seq_idx)
770 {
771 int ret = 0;
772 struct consumer_relayd_sock_pair *relayd;
773
774 LTTNG_ASSERT(net_seq_idx != -1ULL);
775
776 /* The stream is not metadata. Get relayd reference if exists. */
777 lttng::urcu::read_lock_guard read_lock;
778 relayd = consumer_find_relayd(net_seq_idx);
779 if (relayd != nullptr) {
780 /* Add stream on the relayd */
781 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
782 ret = relayd_streams_sent(&relayd->control_sock);
783 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
784 if (ret < 0) {
785 ERR("Relayd streams sent failed. Cleaning up relayd %" PRIu64 ".",
786 relayd->net_seq_idx);
787 lttng_consumer_cleanup_relayd(relayd);
788 goto end;
789 }
790 } else {
791 ERR("Relayd ID %" PRIu64 " unknown. Can't send streams_sent.", net_seq_idx);
792 ret = -1;
793 goto end;
794 }
795
796 ret = 0;
797 DBG("All streams sent relayd id %" PRIu64, net_seq_idx);
798
799 end:
800 return ret;
801 }
802
803 /*
804 * Find a relayd and close the stream
805 */
806 void close_relayd_stream(struct lttng_consumer_stream *stream)
807 {
808 struct consumer_relayd_sock_pair *relayd;
809
810 /* The stream is not metadata. Get relayd reference if exists. */
811 lttng::urcu::read_lock_guard read_lock;
812 relayd = consumer_find_relayd(stream->net_seq_idx);
813 if (relayd) {
814 consumer_stream_relayd_close(stream, relayd);
815 }
816 }
817
818 /*
819 * Handle stream for relayd transmission if the stream applies for network
820 * streaming where the net sequence index is set.
821 *
822 * Return destination file descriptor or negative value on error.
823 */
824 static int write_relayd_stream_header(struct lttng_consumer_stream *stream,
825 size_t data_size,
826 unsigned long padding,
827 struct consumer_relayd_sock_pair *relayd)
828 {
829 int outfd = -1, ret;
830 struct lttcomm_relayd_data_hdr data_hdr;
831
832 /* Safety net */
833 LTTNG_ASSERT(stream);
834 LTTNG_ASSERT(relayd);
835
836 /* Reset data header */
837 memset(&data_hdr, 0, sizeof(data_hdr));
838
839 if (stream->metadata_flag) {
840 /* Caller MUST acquire the relayd control socket lock */
841 ret = relayd_send_metadata(&relayd->control_sock, data_size);
842 if (ret < 0) {
843 goto error;
844 }
845
846 /* Metadata are always sent on the control socket. */
847 outfd = relayd->control_sock.sock.fd;
848 } else {
849 /* Set header with stream information */
850 data_hdr.stream_id = htobe64(stream->relayd_stream_id);
851 data_hdr.data_size = htobe32(data_size);
852 data_hdr.padding_size = htobe32(padding);
853
854 /*
855 * Note that net_seq_num below is assigned with the *current* value of
856 * next_net_seq_num and only after that the next_net_seq_num will be
857 * increment. This is why when issuing a command on the relayd using
858 * this next value, 1 should always be substracted in order to compare
859 * the last seen sequence number on the relayd side to the last sent.
860 */
861 data_hdr.net_seq_num = htobe64(stream->next_net_seq_num);
862 /* Other fields are zeroed previously */
863
864 ret = relayd_send_data_hdr(&relayd->data_sock, &data_hdr, sizeof(data_hdr));
865 if (ret < 0) {
866 goto error;
867 }
868
869 ++stream->next_net_seq_num;
870
871 /* Set to go on data socket */
872 outfd = relayd->data_sock.sock.fd;
873 }
874
875 error:
876 return outfd;
877 }
878
879 /*
880 * Write a character on the metadata poll pipe to wake the metadata thread.
881 * Returns 0 on success, -1 on error.
882 */
883 int consumer_metadata_wakeup_pipe(const struct lttng_consumer_channel *channel)
884 {
885 int ret = 0;
886
887 DBG("Waking up metadata poll thread (writing to pipe): channel name = '%s'", channel->name);
888 if (channel->monitor && channel->metadata_stream) {
889 const char dummy = 'c';
890 const ssize_t write_ret =
891 lttng_write(channel->metadata_stream->ust_metadata_poll_pipe[1], &dummy, 1);
892
893 if (write_ret < 1) {
894 if (errno == EWOULDBLOCK) {
895 /*
896 * This is fine, the metadata poll thread
897 * is having a hard time keeping-up, but
898 * it will eventually wake-up and consume
899 * the available data.
900 */
901 ret = 0;
902 } else {
903 PERROR("Failed to write to UST metadata pipe while attempting to wake-up the metadata poll thread");
904 ret = -1;
905 goto end;
906 }
907 }
908 }
909
910 end:
911 return ret;
912 }
913
914 /*
915 * Trigger a dump of the metadata content. Following/during the succesful
916 * completion of this call, the metadata poll thread will start receiving
917 * metadata packets to consume.
918 *
919 * The caller must hold the channel and stream locks.
920 */
921 static int consumer_metadata_stream_dump(struct lttng_consumer_stream *stream)
922 {
923 int ret;
924
925 ASSERT_LOCKED(stream->chan->lock);
926 ASSERT_LOCKED(stream->lock);
927 LTTNG_ASSERT(stream->metadata_flag);
928 LTTNG_ASSERT(stream->chan->trace_chunk);
929
930 switch (the_consumer_data.type) {
931 case LTTNG_CONSUMER_KERNEL:
932 /*
933 * Reset the position of what has been read from the
934 * metadata cache to 0 so we can dump it again.
935 */
936 ret = kernctl_metadata_cache_dump(stream->wait_fd);
937 break;
938 case LTTNG_CONSUMER32_UST:
939 case LTTNG_CONSUMER64_UST:
940 /*
941 * Reset the position pushed from the metadata cache so it
942 * will write from the beginning on the next push.
943 */
944 stream->ust_metadata_pushed = 0;
945 ret = consumer_metadata_wakeup_pipe(stream->chan);
946 break;
947 default:
948 ERR("Unknown consumer_data type");
949 abort();
950 }
951 if (ret < 0) {
952 ERR("Failed to dump the metadata cache");
953 }
954 return ret;
955 }
956
957 static int lttng_consumer_channel_set_trace_chunk(struct lttng_consumer_channel *channel,
958 struct lttng_trace_chunk *new_trace_chunk)
959 {
960 pthread_mutex_lock(&channel->lock);
961 if (channel->is_deleted) {
962 /*
963 * The channel has been logically deleted and should no longer
964 * be used. It has released its reference to its current trace
965 * chunk and should not acquire a new one.
966 *
967 * Return success as there is nothing for the caller to do.
968 */
969 goto end;
970 }
971
972 /*
973 * The acquisition of the reference cannot fail (barring
974 * a severe internal error) since a reference to the published
975 * chunk is already held by the caller.
976 */
977 if (new_trace_chunk) {
978 const bool acquired_reference = lttng_trace_chunk_get(new_trace_chunk);
979
980 LTTNG_ASSERT(acquired_reference);
981 }
982
983 lttng_trace_chunk_put(channel->trace_chunk);
984 channel->trace_chunk = new_trace_chunk;
985 end:
986 pthread_mutex_unlock(&channel->lock);
987 return 0;
988 }
989
990 /*
991 * Allocate and return a new lttng_consumer_channel object using the given key
992 * to initialize the hash table node.
993 *
994 * On error, return NULL.
995 */
996 struct lttng_consumer_channel *consumer_allocate_channel(uint64_t key,
997 uint64_t session_id,
998 const uint64_t *chunk_id,
999 const char *pathname,
1000 const char *name,
1001 uint64_t relayd_id,
1002 enum lttng_event_output output,
1003 uint64_t tracefile_size,
1004 uint64_t tracefile_count,
1005 uint64_t session_id_per_pid,
1006 unsigned int monitor,
1007 unsigned int live_timer_interval,
1008 bool is_in_live_session,
1009 const char *root_shm_path,
1010 const char *shm_path)
1011 {
1012 struct lttng_consumer_channel *channel = nullptr;
1013 struct lttng_trace_chunk *trace_chunk = nullptr;
1014
1015 if (chunk_id) {
1016 trace_chunk = lttng_trace_chunk_registry_find_chunk(
1017 the_consumer_data.chunk_registry, session_id, *chunk_id);
1018 if (!trace_chunk) {
1019 ERR("Failed to find trace chunk reference during creation of channel");
1020 goto end;
1021 }
1022 }
1023
1024 try {
1025 channel = new lttng_consumer_channel;
1026 } catch (const std::bad_alloc& e) {
1027 ERR("Failed to allocate lttng_consumer_channel: %s", e.what());
1028 channel = nullptr;
1029 goto end;
1030 }
1031
1032 channel->key = key;
1033 channel->refcount = 0;
1034 channel->session_id = session_id;
1035 channel->session_id_per_pid = session_id_per_pid;
1036 channel->relayd_id = relayd_id;
1037 channel->tracefile_size = tracefile_size;
1038 channel->tracefile_count = tracefile_count;
1039 channel->monitor = monitor;
1040 channel->live_timer_interval = live_timer_interval;
1041 channel->is_live = is_in_live_session;
1042 pthread_mutex_init(&channel->lock, NULL);
1043 pthread_mutex_init(&channel->timer_lock, NULL);
1044
1045 switch (output) {
1046 case LTTNG_EVENT_SPLICE:
1047 channel->output = CONSUMER_CHANNEL_SPLICE;
1048 break;
1049 case LTTNG_EVENT_MMAP:
1050 channel->output = CONSUMER_CHANNEL_MMAP;
1051 break;
1052 default:
1053 abort();
1054 delete channel;
1055 channel = nullptr;
1056 goto end;
1057 }
1058
1059 /*
1060 * In monitor mode, the streams associated with the channel will be put in
1061 * a special list ONLY owned by this channel. So, the refcount is set to 1
1062 * here meaning that the channel itself has streams that are referenced.
1063 *
1064 * On a channel deletion, once the channel is no longer visible, the
1065 * refcount is decremented and checked for a zero value to delete it. With
1066 * streams in no monitor mode, it will now be safe to destroy the channel.
1067 */
1068 if (!channel->monitor) {
1069 channel->refcount = 1;
1070 }
1071
1072 strncpy(channel->pathname, pathname, sizeof(channel->pathname));
1073 channel->pathname[sizeof(channel->pathname) - 1] = '\0';
1074
1075 strncpy(channel->name, name, sizeof(channel->name));
1076 channel->name[sizeof(channel->name) - 1] = '\0';
1077
1078 if (root_shm_path) {
1079 strncpy(channel->root_shm_path, root_shm_path, sizeof(channel->root_shm_path));
1080 channel->root_shm_path[sizeof(channel->root_shm_path) - 1] = '\0';
1081 }
1082 if (shm_path) {
1083 strncpy(channel->shm_path, shm_path, sizeof(channel->shm_path));
1084 channel->shm_path[sizeof(channel->shm_path) - 1] = '\0';
1085 }
1086
1087 lttng_ht_node_init_u64(&channel->node, channel->key);
1088 lttng_ht_node_init_u64(&channel->channels_by_session_id_ht_node, channel->session_id);
1089
1090 channel->wait_fd = -1;
1091 CDS_INIT_LIST_HEAD(&channel->streams.head);
1092
1093 if (trace_chunk) {
1094 int ret = lttng_consumer_channel_set_trace_chunk(channel, trace_chunk);
1095 if (ret) {
1096 goto error;
1097 }
1098 }
1099
1100 DBG("Allocated channel (key %" PRIu64 ")", channel->key);
1101
1102 end:
1103 lttng_trace_chunk_put(trace_chunk);
1104 return channel;
1105 error:
1106 consumer_del_channel(channel);
1107 channel = nullptr;
1108 goto end;
1109 }
1110
1111 /*
1112 * Add a channel to the global list protected by a mutex.
1113 *
1114 * Always return 0 indicating success.
1115 */
1116 int consumer_add_channel(struct lttng_consumer_channel *channel,
1117 struct lttng_consumer_local_data *ctx)
1118 {
1119 pthread_mutex_lock(&the_consumer_data.lock);
1120 pthread_mutex_lock(&channel->lock);
1121 pthread_mutex_lock(&channel->timer_lock);
1122
1123 /*
1124 * This gives us a guarantee that the channel we are about to add to the
1125 * channel hash table will be unique. See this function comment on the why
1126 * we need to steel the channel key at this stage.
1127 */
1128 steal_channel_key(channel->key);
1129
1130 lttng::urcu::read_lock_guard read_lock;
1131 lttng_ht_add_unique_u64(the_consumer_data.channel_ht, &channel->node);
1132 lttng_ht_add_u64(the_consumer_data.channels_by_session_id_ht,
1133 &channel->channels_by_session_id_ht_node);
1134 channel->is_published = true;
1135
1136 pthread_mutex_unlock(&channel->timer_lock);
1137 pthread_mutex_unlock(&channel->lock);
1138 pthread_mutex_unlock(&the_consumer_data.lock);
1139
1140 if (channel->wait_fd != -1 && channel->type == CONSUMER_CHANNEL_TYPE_DATA) {
1141 notify_channel_pipe(ctx, channel, -1, CONSUMER_CHANNEL_ADD);
1142 }
1143
1144 return 0;
1145 }
1146
1147 /*
1148 * Allocate the pollfd structure and the local view of the out fds to avoid
1149 * doing a lookup in the linked list and concurrency issues when writing is
1150 * needed. Called with consumer_data.lock held.
1151 *
1152 * Returns the number of fds in the structures.
1153 */
1154 static int update_poll_array(struct lttng_consumer_local_data *ctx,
1155 struct pollfd **pollfd,
1156 struct lttng_consumer_stream **local_stream,
1157 struct lttng_ht *ht,
1158 int *nb_inactive_fd)
1159 {
1160 int i = 0;
1161 struct lttng_ht_iter iter;
1162 struct lttng_consumer_stream *stream;
1163
1164 LTTNG_ASSERT(ctx);
1165 LTTNG_ASSERT(ht);
1166 LTTNG_ASSERT(pollfd);
1167 LTTNG_ASSERT(local_stream);
1168
1169 DBG("Updating poll fd array");
1170 *nb_inactive_fd = 0;
1171
1172 {
1173 lttng::urcu::read_lock_guard read_lock;
1174 cds_lfht_for_each_entry (ht->ht, &iter.iter, stream, node.node) {
1175 /*
1176 * Only active streams with an active end point can be added to the
1177 * poll set and local stream storage of the thread.
1178 *
1179 * There is a potential race here for endpoint_status to be updated
1180 * just after the check. However, this is OK since the stream(s) will
1181 * be deleted once the thread is notified that the end point state has
1182 * changed where this function will be called back again.
1183 *
1184 * We track the number of inactive FDs because they still need to be
1185 * closed by the polling thread after a wakeup on the data_pipe or
1186 * metadata_pipe.
1187 */
1188 if (stream->endpoint_status == CONSUMER_ENDPOINT_INACTIVE) {
1189 (*nb_inactive_fd)++;
1190 continue;
1191 }
1192
1193 (*pollfd)[i].fd = stream->wait_fd;
1194 (*pollfd)[i].events = POLLIN | POLLPRI;
1195 local_stream[i] = stream;
1196 i++;
1197 }
1198 }
1199
1200 /*
1201 * Insert the consumer_data_pipe at the end of the array and don't
1202 * increment i so nb_fd is the number of real FD.
1203 */
1204 (*pollfd)[i].fd = lttng_pipe_get_readfd(ctx->consumer_data_pipe);
1205 (*pollfd)[i].events = POLLIN | POLLPRI;
1206
1207 (*pollfd)[i + 1].fd = lttng_pipe_get_readfd(ctx->consumer_wakeup_pipe);
1208 (*pollfd)[i + 1].events = POLLIN | POLLPRI;
1209 return i;
1210 }
1211
1212 /*
1213 * Poll on the should_quit pipe and the command socket return -1 on
1214 * error, 1 if should exit, 0 if data is available on the command socket
1215 */
1216 int lttng_consumer_poll_socket(struct pollfd *consumer_sockpoll)
1217 {
1218 int num_rdy;
1219
1220 restart:
1221 num_rdy = poll(consumer_sockpoll, 2, -1);
1222 if (num_rdy == -1) {
1223 /*
1224 * Restart interrupted system call.
1225 */
1226 if (errno == EINTR) {
1227 goto restart;
1228 }
1229 PERROR("Poll error");
1230 return -1;
1231 }
1232 if (consumer_sockpoll[0].revents & (POLLIN | POLLPRI)) {
1233 DBG("consumer_should_quit wake up");
1234 return 1;
1235 }
1236 return 0;
1237 }
1238
1239 /*
1240 * Set the error socket.
1241 */
1242 void lttng_consumer_set_error_sock(struct lttng_consumer_local_data *ctx, int sock)
1243 {
1244 ctx->consumer_error_socket = sock;
1245 }
1246
1247 /*
1248 * Set the command socket path.
1249 */
1250 void lttng_consumer_set_command_sock_path(struct lttng_consumer_local_data *ctx, char *sock)
1251 {
1252 ctx->consumer_command_sock_path = sock;
1253 }
1254
1255 /*
1256 * Send return code to the session daemon.
1257 * If the socket is not defined, we return 0, it is not a fatal error
1258 */
1259 int lttng_consumer_send_error(struct lttng_consumer_local_data *ctx,
1260 enum lttcomm_return_code error_code)
1261 {
1262 if (ctx->consumer_error_socket > 0) {
1263 const std::int32_t comm_code = std::int32_t(error_code);
1264
1265 static_assert(
1266 sizeof(comm_code) >= sizeof(std::underlying_type<lttcomm_return_code>),
1267 "Fixed-size communication type too small to accomodate lttcomm_return_code");
1268 return lttcomm_send_unix_sock(
1269 ctx->consumer_error_socket, &comm_code, sizeof(comm_code));
1270 }
1271
1272 return 0;
1273 }
1274
1275 /*
1276 * Close all the tracefiles and stream fds and MUST be called when all
1277 * instances are destroyed i.e. when all threads were joined and are ended.
1278 */
1279 void lttng_consumer_cleanup()
1280 {
1281 struct lttng_ht_iter iter;
1282 struct lttng_consumer_channel *channel;
1283 unsigned int trace_chunks_left;
1284
1285 {
1286 lttng::urcu::read_lock_guard read_lock;
1287
1288 cds_lfht_for_each_entry (
1289 the_consumer_data.channel_ht->ht, &iter.iter, channel, node.node) {
1290 consumer_del_channel(channel);
1291 }
1292 }
1293
1294 lttng_ht_destroy(the_consumer_data.channel_ht);
1295 lttng_ht_destroy(the_consumer_data.channels_by_session_id_ht);
1296
1297 cleanup_relayd_ht();
1298
1299 lttng_ht_destroy(the_consumer_data.stream_per_chan_id_ht);
1300
1301 /*
1302 * This HT contains streams that are freed by either the metadata thread or
1303 * the data thread so we do *nothing* on the hash table and simply destroy
1304 * it.
1305 */
1306 lttng_ht_destroy(the_consumer_data.stream_list_ht);
1307
1308 /*
1309 * Trace chunks in the registry may still exist if the session
1310 * daemon has encountered an internal error and could not
1311 * tear down its sessions and/or trace chunks properly.
1312 *
1313 * Release the session daemon's implicit reference to any remaining
1314 * trace chunk and print an error if any trace chunk was found. Note
1315 * that there are _no_ legitimate cases for trace chunks to be left,
1316 * it is a leak. However, it can happen following a crash of the
1317 * session daemon and not emptying the registry would cause an assertion
1318 * to hit.
1319 */
1320 trace_chunks_left =
1321 lttng_trace_chunk_registry_put_each_chunk(the_consumer_data.chunk_registry);
1322 if (trace_chunks_left) {
1323 ERR("%u trace chunks are leaked by lttng-consumerd. "
1324 "This can be caused by an internal error of the session daemon.",
1325 trace_chunks_left);
1326 }
1327 /* Run all callbacks freeing each chunk. */
1328 rcu_barrier();
1329 lttng_trace_chunk_registry_destroy(the_consumer_data.chunk_registry);
1330 }
1331
1332 /*
1333 * Called from signal handler.
1334 */
1335 void lttng_consumer_should_exit(struct lttng_consumer_local_data *ctx)
1336 {
1337 ssize_t ret;
1338
1339 CMM_STORE_SHARED(consumer_quit, 1);
1340 ret = lttng_write(ctx->consumer_should_quit[1], "4", 1);
1341 if (ret < 1) {
1342 PERROR("write consumer quit");
1343 }
1344
1345 DBG("Consumer flag that it should quit");
1346 }
1347
1348 /*
1349 * Flush pending writes to trace output disk file.
1350 */
1351 static void lttng_consumer_sync_trace_file(struct lttng_consumer_stream *stream, off_t orig_offset)
1352 {
1353 int outfd = stream->out_fd;
1354
1355 /*
1356 * This does a blocking write-and-wait on any page that belongs to the
1357 * subbuffer prior to the one we just wrote.
1358 * Don't care about error values, as these are just hints and ways to
1359 * limit the amount of page cache used.
1360 */
1361 if (orig_offset < stream->max_sb_size) {
1362 return;
1363 }
1364 lttng::io::hint_flush_range_dont_need_sync(
1365 outfd, orig_offset - stream->max_sb_size, stream->max_sb_size);
1366 }
1367
1368 /*
1369 * Initialise the necessary environnement :
1370 * - create a new context
1371 * - create the poll_pipe
1372 * - create the should_quit pipe (for signal handler)
1373 * - create the thread pipe (for splice)
1374 *
1375 * Takes a function pointer as argument, this function is called when data is
1376 * available on a buffer. This function is responsible to do the
1377 * kernctl_get_next_subbuf, read the data with mmap or splice depending on the
1378 * buffer configuration and then kernctl_put_next_subbuf at the end.
1379 *
1380 * Returns a pointer to the new context or NULL on error.
1381 */
1382 struct lttng_consumer_local_data *
1383 lttng_consumer_create(enum lttng_consumer_type type,
1384 ssize_t (*buffer_ready)(struct lttng_consumer_stream *stream,
1385 struct lttng_consumer_local_data *ctx,
1386 bool locked_by_caller),
1387 int (*recv_channel)(struct lttng_consumer_channel *channel),
1388 int (*recv_stream)(struct lttng_consumer_stream *stream),
1389 int (*update_stream)(uint64_t stream_key, uint32_t state))
1390 {
1391 int ret;
1392 struct lttng_consumer_local_data *ctx;
1393
1394 LTTNG_ASSERT(the_consumer_data.type == LTTNG_CONSUMER_UNKNOWN ||
1395 the_consumer_data.type == type);
1396 the_consumer_data.type = type;
1397
1398 ctx = zmalloc<lttng_consumer_local_data>();
1399 if (ctx == nullptr) {
1400 PERROR("allocating context");
1401 goto error;
1402 }
1403
1404 ctx->consumer_error_socket = -1;
1405 ctx->consumer_metadata_socket = -1;
1406 pthread_mutex_init(&ctx->metadata_socket_lock, nullptr);
1407 /* assign the callbacks */
1408 ctx->on_buffer_ready = buffer_ready;
1409 ctx->on_recv_channel = recv_channel;
1410 ctx->on_recv_stream = recv_stream;
1411 ctx->on_update_stream = update_stream;
1412
1413 ctx->consumer_data_pipe = lttng_pipe_open(0);
1414 if (!ctx->consumer_data_pipe) {
1415 goto error_poll_pipe;
1416 }
1417
1418 ctx->consumer_wakeup_pipe = lttng_pipe_open(0);
1419 if (!ctx->consumer_wakeup_pipe) {
1420 goto error_wakeup_pipe;
1421 }
1422
1423 ret = pipe(ctx->consumer_should_quit);
1424 if (ret < 0) {
1425 PERROR("Error creating recv pipe");
1426 goto error_quit_pipe;
1427 }
1428
1429 ret = pipe(ctx->consumer_channel_pipe);
1430 if (ret < 0) {
1431 PERROR("Error creating channel pipe");
1432 goto error_channel_pipe;
1433 }
1434
1435 ctx->consumer_metadata_pipe = lttng_pipe_open(0);
1436 if (!ctx->consumer_metadata_pipe) {
1437 goto error_metadata_pipe;
1438 }
1439
1440 ctx->channel_monitor_pipe = -1;
1441
1442 return ctx;
1443
1444 error_metadata_pipe:
1445 utils_close_pipe(ctx->consumer_channel_pipe);
1446 error_channel_pipe:
1447 utils_close_pipe(ctx->consumer_should_quit);
1448 error_quit_pipe:
1449 lttng_pipe_destroy(ctx->consumer_wakeup_pipe);
1450 error_wakeup_pipe:
1451 lttng_pipe_destroy(ctx->consumer_data_pipe);
1452 error_poll_pipe:
1453 free(ctx);
1454 error:
1455 return nullptr;
1456 }
1457
1458 /*
1459 * Iterate over all streams of the hashtable and free them properly.
1460 */
1461 static void destroy_data_stream_ht(struct lttng_ht *ht)
1462 {
1463 struct lttng_ht_iter iter;
1464 struct lttng_consumer_stream *stream;
1465
1466 if (ht == nullptr) {
1467 return;
1468 }
1469
1470 {
1471 lttng::urcu::read_lock_guard read_lock;
1472 cds_lfht_for_each_entry (ht->ht, &iter.iter, stream, node.node) {
1473 /*
1474 * Ignore return value since we are currently cleaning up so any error
1475 * can't be handled.
1476 */
1477 (void) consumer_del_stream(stream, ht);
1478 }
1479 }
1480
1481 lttng_ht_destroy(ht);
1482 }
1483
1484 /*
1485 * Iterate over all streams of the metadata hashtable and free them
1486 * properly.
1487 */
1488 static void destroy_metadata_stream_ht(struct lttng_ht *ht)
1489 {
1490 struct lttng_ht_iter iter;
1491 struct lttng_consumer_stream *stream;
1492
1493 if (ht == nullptr) {
1494 return;
1495 }
1496
1497 {
1498 lttng::urcu::read_lock_guard read_lock;
1499 cds_lfht_for_each_entry (ht->ht, &iter.iter, stream, node.node) {
1500 /*
1501 * Ignore return value since we are currently cleaning up so any error
1502 * can't be handled.
1503 */
1504 (void) consumer_del_metadata_stream(stream, ht);
1505 }
1506 }
1507
1508 lttng_ht_destroy(ht);
1509 }
1510
1511 /*
1512 * Close all fds associated with the instance and free the context.
1513 */
1514 void lttng_consumer_destroy(struct lttng_consumer_local_data *ctx)
1515 {
1516 int ret;
1517
1518 DBG("Consumer destroying it. Closing everything.");
1519
1520 if (!ctx) {
1521 return;
1522 }
1523
1524 destroy_data_stream_ht(data_ht);
1525 destroy_metadata_stream_ht(metadata_ht);
1526
1527 ret = close(ctx->consumer_error_socket);
1528 if (ret) {
1529 PERROR("close");
1530 }
1531 ret = close(ctx->consumer_metadata_socket);
1532 if (ret) {
1533 PERROR("close");
1534 }
1535 utils_close_pipe(ctx->consumer_channel_pipe);
1536 lttng_pipe_destroy(ctx->consumer_data_pipe);
1537 lttng_pipe_destroy(ctx->consumer_metadata_pipe);
1538 lttng_pipe_destroy(ctx->consumer_wakeup_pipe);
1539 utils_close_pipe(ctx->consumer_should_quit);
1540
1541 unlink(ctx->consumer_command_sock_path);
1542 free(ctx);
1543 }
1544
1545 /*
1546 * Write the metadata stream id on the specified file descriptor.
1547 */
1548 static int
1549 write_relayd_metadata_id(int fd, struct lttng_consumer_stream *stream, unsigned long padding)
1550 {
1551 ssize_t ret;
1552 struct lttcomm_relayd_metadata_payload hdr;
1553
1554 hdr.stream_id = htobe64(stream->relayd_stream_id);
1555 hdr.padding_size = htobe32(padding);
1556 ret = lttng_write(fd, (void *) &hdr, sizeof(hdr));
1557 if (ret < sizeof(hdr)) {
1558 /*
1559 * This error means that the fd's end is closed so ignore the PERROR
1560 * not to clubber the error output since this can happen in a normal
1561 * code path.
1562 */
1563 if (errno != EPIPE) {
1564 PERROR("write metadata stream id");
1565 }
1566 DBG3("Consumer failed to write relayd metadata id (errno: %d)", errno);
1567 /*
1568 * Set ret to a negative value because if ret != sizeof(hdr), we don't
1569 * handle writting the missing part so report that as an error and
1570 * don't lie to the caller.
1571 */
1572 ret = -1;
1573 goto end;
1574 }
1575 DBG("Metadata stream id %" PRIu64 " with padding %lu written before data",
1576 stream->relayd_stream_id,
1577 padding);
1578
1579 end:
1580 return (int) ret;
1581 }
1582
1583 /*
1584 * Mmap the ring buffer, read it and write the data to the tracefile. This is a
1585 * core function for writing trace buffers to either the local filesystem or
1586 * the network.
1587 *
1588 * It must be called with the stream and the channel lock held.
1589 *
1590 * Careful review MUST be put if any changes occur!
1591 *
1592 * Returns the number of bytes written
1593 */
1594 ssize_t lttng_consumer_on_read_subbuffer_mmap(struct lttng_consumer_stream *stream,
1595 const struct lttng_buffer_view *buffer,
1596 unsigned long padding)
1597 {
1598 ssize_t ret = 0;
1599 off_t orig_offset = stream->out_fd_offset;
1600 /* Default is on the disk */
1601 int outfd = stream->out_fd;
1602 struct consumer_relayd_sock_pair *relayd = nullptr;
1603 unsigned int relayd_hang_up = 0;
1604 const size_t subbuf_content_size = buffer->size - padding;
1605 size_t write_len;
1606
1607 /* RCU lock for the relayd pointer */
1608 lttng::urcu::read_lock_guard read_lock;
1609 LTTNG_ASSERT(stream->net_seq_idx != (uint64_t) -1ULL || stream->trace_chunk);
1610
1611 /* Flag that the current stream if set for network streaming. */
1612 if (stream->net_seq_idx != (uint64_t) -1ULL) {
1613 relayd = consumer_find_relayd(stream->net_seq_idx);
1614 if (relayd == nullptr) {
1615 ret = -EPIPE;
1616 goto end;
1617 }
1618 }
1619
1620 /* Handle stream on the relayd if the output is on the network */
1621 if (relayd) {
1622 unsigned long netlen = subbuf_content_size;
1623
1624 /*
1625 * Lock the control socket for the complete duration of the function
1626 * since from this point on we will use the socket.
1627 */
1628 if (stream->metadata_flag) {
1629 /* Metadata requires the control socket. */
1630 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
1631 if (stream->reset_metadata_flag) {
1632 ret = relayd_reset_metadata(&relayd->control_sock,
1633 stream->relayd_stream_id,
1634 stream->metadata_version);
1635 if (ret < 0) {
1636 relayd_hang_up = 1;
1637 goto write_error;
1638 }
1639 stream->reset_metadata_flag = 0;
1640 }
1641 netlen += sizeof(struct lttcomm_relayd_metadata_payload);
1642 }
1643
1644 ret = write_relayd_stream_header(stream, netlen, padding, relayd);
1645 if (ret < 0) {
1646 relayd_hang_up = 1;
1647 goto write_error;
1648 }
1649 /* Use the returned socket. */
1650 outfd = ret;
1651
1652 /* Write metadata stream id before payload */
1653 if (stream->metadata_flag) {
1654 ret = write_relayd_metadata_id(outfd, stream, padding);
1655 if (ret < 0) {
1656 relayd_hang_up = 1;
1657 goto write_error;
1658 }
1659 }
1660
1661 write_len = subbuf_content_size;
1662 } else {
1663 /* No streaming; we have to write the full padding. */
1664 if (stream->metadata_flag && stream->reset_metadata_flag) {
1665 ret = utils_truncate_stream_file(stream->out_fd, 0);
1666 if (ret < 0) {
1667 ERR("Reset metadata file");
1668 goto end;
1669 }
1670 stream->reset_metadata_flag = 0;
1671 }
1672
1673 /*
1674 * Check if we need to change the tracefile before writing the packet.
1675 */
1676 if (stream->chan->tracefile_size > 0 &&
1677 (stream->tracefile_size_current + buffer->size) >
1678 stream->chan->tracefile_size) {
1679 ret = consumer_stream_rotate_output_files(stream);
1680 if (ret) {
1681 goto end;
1682 }
1683 outfd = stream->out_fd;
1684 orig_offset = 0;
1685 }
1686 stream->tracefile_size_current += buffer->size;
1687 write_len = buffer->size;
1688 }
1689
1690 /*
1691 * This call guarantee that len or less is returned. It's impossible to
1692 * receive a ret value that is bigger than len.
1693 */
1694 ret = lttng_write(outfd, buffer->data, write_len);
1695 DBG("Consumer mmap write() ret %zd (len %zu)", ret, write_len);
1696 if (ret < 0 || ((size_t) ret != write_len)) {
1697 /*
1698 * Report error to caller if nothing was written else at least send the
1699 * amount written.
1700 */
1701 if (ret < 0) {
1702 ret = -errno;
1703 }
1704 relayd_hang_up = 1;
1705
1706 /* Socket operation failed. We consider the relayd dead */
1707 if (errno == EPIPE) {
1708 /*
1709 * This is possible if the fd is closed on the other side
1710 * (outfd) or any write problem. It can be verbose a bit for a
1711 * normal execution if for instance the relayd is stopped
1712 * abruptly. This can happen so set this to a DBG statement.
1713 */
1714 DBG("Consumer mmap write detected relayd hang up");
1715 } else {
1716 /* Unhandled error, print it and stop function right now. */
1717 PERROR("Error in write mmap (ret %zd != write_len %zu)", ret, write_len);
1718 }
1719 goto write_error;
1720 }
1721 stream->output_written += ret;
1722
1723 /* This call is useless on a socket so better save a syscall. */
1724 if (!relayd) {
1725 /* This won't block, but will start writeout asynchronously */
1726 lttng::io::hint_flush_range_async(outfd, stream->out_fd_offset, write_len);
1727 stream->out_fd_offset += write_len;
1728 lttng_consumer_sync_trace_file(stream, orig_offset);
1729 }
1730
1731 write_error:
1732 /*
1733 * This is a special case that the relayd has closed its socket. Let's
1734 * cleanup the relayd object and all associated streams.
1735 */
1736 if (relayd && relayd_hang_up) {
1737 ERR("Relayd hangup. Cleaning up relayd %" PRIu64 ".", relayd->net_seq_idx);
1738 lttng_consumer_cleanup_relayd(relayd);
1739 }
1740
1741 end:
1742 /* Unlock only if ctrl socket used */
1743 if (relayd && stream->metadata_flag) {
1744 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
1745 }
1746
1747 return ret;
1748 }
1749
1750 /*
1751 * Splice the data from the ring buffer to the tracefile.
1752 *
1753 * It must be called with the stream lock held.
1754 *
1755 * Returns the number of bytes spliced.
1756 */
1757 ssize_t lttng_consumer_on_read_subbuffer_splice(struct lttng_consumer_local_data *ctx,
1758 struct lttng_consumer_stream *stream,
1759 unsigned long len,
1760 unsigned long padding)
1761 {
1762 ssize_t ret = 0, written = 0, ret_splice = 0;
1763 loff_t offset = 0;
1764 off_t orig_offset = stream->out_fd_offset;
1765 int fd = stream->wait_fd;
1766 /* Default is on the disk */
1767 int outfd = stream->out_fd;
1768 struct consumer_relayd_sock_pair *relayd = nullptr;
1769 int *splice_pipe;
1770 unsigned int relayd_hang_up = 0;
1771
1772 switch (the_consumer_data.type) {
1773 case LTTNG_CONSUMER_KERNEL:
1774 break;
1775 case LTTNG_CONSUMER32_UST:
1776 case LTTNG_CONSUMER64_UST:
1777 /* Not supported for user space tracing */
1778 return -ENOSYS;
1779 default:
1780 ERR("Unknown consumer_data type");
1781 abort();
1782 }
1783
1784 /* RCU lock for the relayd pointer */
1785 lttng::urcu::read_lock_guard read_lock;
1786
1787 /* Flag that the current stream if set for network streaming. */
1788 if (stream->net_seq_idx != (uint64_t) -1ULL) {
1789 relayd = consumer_find_relayd(stream->net_seq_idx);
1790 if (relayd == nullptr) {
1791 written = -ret;
1792 goto end;
1793 }
1794 }
1795 splice_pipe = stream->splice_pipe;
1796
1797 /* Write metadata stream id before payload */
1798 if (relayd) {
1799 unsigned long total_len = len;
1800
1801 if (stream->metadata_flag) {
1802 /*
1803 * Lock the control socket for the complete duration of the function
1804 * since from this point on we will use the socket.
1805 */
1806 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
1807
1808 if (stream->reset_metadata_flag) {
1809 ret = relayd_reset_metadata(&relayd->control_sock,
1810 stream->relayd_stream_id,
1811 stream->metadata_version);
1812 if (ret < 0) {
1813 relayd_hang_up = 1;
1814 goto write_error;
1815 }
1816 stream->reset_metadata_flag = 0;
1817 }
1818 ret = write_relayd_metadata_id(splice_pipe[1], stream, padding);
1819 if (ret < 0) {
1820 written = ret;
1821 relayd_hang_up = 1;
1822 goto write_error;
1823 }
1824
1825 total_len += sizeof(struct lttcomm_relayd_metadata_payload);
1826 }
1827
1828 ret = write_relayd_stream_header(stream, total_len, padding, relayd);
1829 if (ret < 0) {
1830 written = ret;
1831 relayd_hang_up = 1;
1832 goto write_error;
1833 }
1834 /* Use the returned socket. */
1835 outfd = ret;
1836 } else {
1837 /* No streaming, we have to set the len with the full padding */
1838 len += padding;
1839
1840 if (stream->metadata_flag && stream->reset_metadata_flag) {
1841 ret = utils_truncate_stream_file(stream->out_fd, 0);
1842 if (ret < 0) {
1843 ERR("Reset metadata file");
1844 goto end;
1845 }
1846 stream->reset_metadata_flag = 0;
1847 }
1848 /*
1849 * Check if we need to change the tracefile before writing the packet.
1850 */
1851 if (stream->chan->tracefile_size > 0 &&
1852 (stream->tracefile_size_current + len) > stream->chan->tracefile_size) {
1853 ret = consumer_stream_rotate_output_files(stream);
1854 if (ret < 0) {
1855 written = ret;
1856 goto end;
1857 }
1858 outfd = stream->out_fd;
1859 orig_offset = 0;
1860 }
1861 stream->tracefile_size_current += len;
1862 }
1863
1864 while (len > 0) {
1865 DBG("splice chan to pipe offset %lu of len %lu (fd : %d, pipe: %d)",
1866 (unsigned long) offset,
1867 len,
1868 fd,
1869 splice_pipe[1]);
1870 ret_splice = splice(
1871 fd, &offset, splice_pipe[1], nullptr, len, SPLICE_F_MOVE | SPLICE_F_MORE);
1872 DBG("splice chan to pipe, ret %zd", ret_splice);
1873 if (ret_splice < 0) {
1874 ret = errno;
1875 written = -ret;
1876 PERROR("Error in relay splice");
1877 goto splice_error;
1878 }
1879
1880 /* Handle stream on the relayd if the output is on the network */
1881 if (relayd && stream->metadata_flag) {
1882 size_t metadata_payload_size =
1883 sizeof(struct lttcomm_relayd_metadata_payload);
1884
1885 /* Update counter to fit the spliced data */
1886 ret_splice += metadata_payload_size;
1887 len += metadata_payload_size;
1888 /*
1889 * We do this so the return value can match the len passed as
1890 * argument to this function.
1891 */
1892 written -= metadata_payload_size;
1893 }
1894
1895 /* Splice data out */
1896 ret_splice = splice(splice_pipe[0],
1897 nullptr,
1898 outfd,
1899 nullptr,
1900 ret_splice,
1901 SPLICE_F_MOVE | SPLICE_F_MORE);
1902 DBG("Consumer splice pipe to file (out_fd: %d), ret %zd", outfd, ret_splice);
1903 if (ret_splice < 0) {
1904 ret = errno;
1905 written = -ret;
1906 relayd_hang_up = 1;
1907 goto write_error;
1908 } else if (ret_splice > len) {
1909 /*
1910 * We don't expect this code path to be executed but you never know
1911 * so this is an extra protection agains a buggy splice().
1912 */
1913 ret = errno;
1914 written += ret_splice;
1915 PERROR("Wrote more data than requested %zd (len: %lu)", ret_splice, len);
1916 goto splice_error;
1917 } else {
1918 /* All good, update current len and continue. */
1919 len -= ret_splice;
1920 }
1921
1922 /* This call is useless on a socket so better save a syscall. */
1923 if (!relayd) {
1924 /* This won't block, but will start writeout asynchronously */
1925 lttng::io::hint_flush_range_async(outfd, stream->out_fd_offset, ret_splice);
1926 stream->out_fd_offset += ret_splice;
1927 }
1928 stream->output_written += ret_splice;
1929 written += ret_splice;
1930 }
1931 if (!relayd) {
1932 lttng_consumer_sync_trace_file(stream, orig_offset);
1933 }
1934 goto end;
1935
1936 write_error:
1937 /*
1938 * This is a special case that the relayd has closed its socket. Let's
1939 * cleanup the relayd object and all associated streams.
1940 */
1941 if (relayd && relayd_hang_up) {
1942 ERR("Relayd hangup. Cleaning up relayd %" PRIu64 ".", relayd->net_seq_idx);
1943 lttng_consumer_cleanup_relayd(relayd);
1944 /* Skip splice error so the consumer does not fail */
1945 goto end;
1946 }
1947
1948 splice_error:
1949 /* send the appropriate error description to sessiond */
1950 switch (ret) {
1951 case EINVAL:
1952 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_EINVAL);
1953 break;
1954 case ENOMEM:
1955 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_ENOMEM);
1956 break;
1957 case ESPIPE:
1958 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_ESPIPE);
1959 break;
1960 }
1961
1962 end:
1963 if (relayd && stream->metadata_flag) {
1964 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
1965 }
1966
1967 return written;
1968 }
1969
1970 /*
1971 * Sample the snapshot positions for a specific fd
1972 *
1973 * Returns 0 on success, < 0 on error
1974 */
1975 int lttng_consumer_sample_snapshot_positions(struct lttng_consumer_stream *stream)
1976 {
1977 switch (the_consumer_data.type) {
1978 case LTTNG_CONSUMER_KERNEL:
1979 return lttng_kconsumer_sample_snapshot_positions(stream);
1980 case LTTNG_CONSUMER32_UST:
1981 case LTTNG_CONSUMER64_UST:
1982 return lttng_ustconsumer_sample_snapshot_positions(stream);
1983 default:
1984 ERR("Unknown consumer_data type");
1985 abort();
1986 return -ENOSYS;
1987 }
1988 }
1989 /*
1990 * Take a snapshot for a specific fd
1991 *
1992 * Returns 0 on success, < 0 on error
1993 */
1994 int lttng_consumer_take_snapshot(struct lttng_consumer_stream *stream)
1995 {
1996 switch (the_consumer_data.type) {
1997 case LTTNG_CONSUMER_KERNEL:
1998 return lttng_kconsumer_take_snapshot(stream);
1999 case LTTNG_CONSUMER32_UST:
2000 case LTTNG_CONSUMER64_UST:
2001 return lttng_ustconsumer_take_snapshot(stream);
2002 default:
2003 ERR("Unknown consumer_data type");
2004 abort();
2005 return -ENOSYS;
2006 }
2007 }
2008
2009 /*
2010 * Get the produced position
2011 *
2012 * Returns 0 on success, < 0 on error
2013 */
2014 int lttng_consumer_get_produced_snapshot(struct lttng_consumer_stream *stream, unsigned long *pos)
2015 {
2016 switch (the_consumer_data.type) {
2017 case LTTNG_CONSUMER_KERNEL:
2018 return lttng_kconsumer_get_produced_snapshot(stream, pos);
2019 case LTTNG_CONSUMER32_UST:
2020 case LTTNG_CONSUMER64_UST:
2021 return lttng_ustconsumer_get_produced_snapshot(stream, pos);
2022 default:
2023 ERR("Unknown consumer_data type");
2024 abort();
2025 return -ENOSYS;
2026 }
2027 }
2028
2029 /*
2030 * Get the consumed position (free-running counter position in bytes).
2031 *
2032 * Returns 0 on success, < 0 on error
2033 */
2034 int lttng_consumer_get_consumed_snapshot(struct lttng_consumer_stream *stream, unsigned long *pos)
2035 {
2036 switch (the_consumer_data.type) {
2037 case LTTNG_CONSUMER_KERNEL:
2038 return lttng_kconsumer_get_consumed_snapshot(stream, pos);
2039 case LTTNG_CONSUMER32_UST:
2040 case LTTNG_CONSUMER64_UST:
2041 return lttng_ustconsumer_get_consumed_snapshot(stream, pos);
2042 default:
2043 ERR("Unknown consumer_data type");
2044 abort();
2045 return -ENOSYS;
2046 }
2047 }
2048
2049 int lttng_consumer_recv_cmd(struct lttng_consumer_local_data *ctx,
2050 int sock,
2051 struct pollfd *consumer_sockpoll)
2052 {
2053 switch (the_consumer_data.type) {
2054 case LTTNG_CONSUMER_KERNEL:
2055 return lttng_kconsumer_recv_cmd(ctx, sock, consumer_sockpoll);
2056 case LTTNG_CONSUMER32_UST:
2057 case LTTNG_CONSUMER64_UST:
2058 return lttng_ustconsumer_recv_cmd(ctx, sock, consumer_sockpoll);
2059 default:
2060 ERR("Unknown consumer_data type");
2061 abort();
2062 return -ENOSYS;
2063 }
2064 }
2065
2066 static void lttng_consumer_close_all_metadata()
2067 {
2068 switch (the_consumer_data.type) {
2069 case LTTNG_CONSUMER_KERNEL:
2070 /*
2071 * The Kernel consumer has a different metadata scheme so we don't
2072 * close anything because the stream will be closed by the session
2073 * daemon.
2074 */
2075 break;
2076 case LTTNG_CONSUMER32_UST:
2077 case LTTNG_CONSUMER64_UST:
2078 /*
2079 * Close all metadata streams. The metadata hash table is passed and
2080 * this call iterates over it by closing all wakeup fd. This is safe
2081 * because at this point we are sure that the metadata producer is
2082 * either dead or blocked.
2083 */
2084 lttng_ustconsumer_close_all_metadata(metadata_ht);
2085 break;
2086 default:
2087 ERR("Unknown consumer_data type");
2088 abort();
2089 }
2090 }
2091
2092 /*
2093 * Clean up a metadata stream and free its memory.
2094 */
2095 void consumer_del_metadata_stream(struct lttng_consumer_stream *stream, struct lttng_ht *ht)
2096 {
2097 struct lttng_consumer_channel *channel = nullptr;
2098 bool free_channel = false;
2099
2100 LTTNG_ASSERT(stream);
2101 /*
2102 * This call should NEVER receive regular stream. It must always be
2103 * metadata stream and this is crucial for data structure synchronization.
2104 */
2105 LTTNG_ASSERT(stream->metadata_flag);
2106
2107 DBG3("Consumer delete metadata stream %d", stream->wait_fd);
2108
2109 pthread_mutex_lock(&the_consumer_data.lock);
2110 /*
2111 * Note that this assumes that a stream's channel is never changed and
2112 * that the stream's lock doesn't need to be taken to sample its
2113 * channel.
2114 */
2115 channel = stream->chan;
2116 pthread_mutex_lock(&channel->lock);
2117 pthread_mutex_lock(&stream->lock);
2118 if (channel->metadata_cache) {
2119 /* Only applicable to userspace consumers. */
2120 pthread_mutex_lock(&channel->metadata_cache->lock);
2121 }
2122
2123 /* Remove any reference to that stream. */
2124 consumer_stream_delete(stream, ht);
2125
2126 /* Close down everything including the relayd if one. */
2127 consumer_stream_close_output(stream);
2128 /* Destroy tracer buffers of the stream. */
2129 consumer_stream_destroy_buffers(stream);
2130
2131 /* Atomically decrement channel refcount since other threads can use it. */
2132 if (!uatomic_sub_return(&channel->refcount, 1) &&
2133 !uatomic_read(&channel->nb_init_stream_left)) {
2134 /* Go for channel deletion! */
2135 free_channel = true;
2136 }
2137 stream->chan = nullptr;
2138
2139 /*
2140 * Nullify the stream reference so it is not used after deletion. The
2141 * channel lock MUST be acquired before being able to check for a NULL
2142 * pointer value.
2143 */
2144 channel->metadata_stream = nullptr;
2145 channel->metadata_pushed_wait_queue.wake_all();
2146
2147 if (channel->metadata_cache) {
2148 pthread_mutex_unlock(&channel->metadata_cache->lock);
2149 }
2150 pthread_mutex_unlock(&stream->lock);
2151 pthread_mutex_unlock(&channel->lock);
2152 pthread_mutex_unlock(&the_consumer_data.lock);
2153
2154 if (free_channel) {
2155 consumer_del_channel(channel);
2156 }
2157
2158 lttng_trace_chunk_put(stream->trace_chunk);
2159 stream->trace_chunk = nullptr;
2160 consumer_stream_free(stream);
2161 }
2162
2163 /*
2164 * Action done with the metadata stream when adding it to the consumer internal
2165 * data structures to handle it.
2166 */
2167 void consumer_add_metadata_stream(struct lttng_consumer_stream *stream)
2168 {
2169 struct lttng_ht *ht = metadata_ht;
2170 struct lttng_ht_iter iter;
2171 struct lttng_ht_node_u64 *node;
2172
2173 LTTNG_ASSERT(stream);
2174 LTTNG_ASSERT(ht);
2175
2176 DBG3("Adding metadata stream %" PRIu64 " to hash table", stream->key);
2177
2178 pthread_mutex_lock(&the_consumer_data.lock);
2179 pthread_mutex_lock(&stream->chan->lock);
2180 pthread_mutex_lock(&stream->chan->timer_lock);
2181 pthread_mutex_lock(&stream->lock);
2182
2183 /*
2184 * From here, refcounts are updated so be _careful_ when returning an error
2185 * after this point.
2186 */
2187
2188 lttng::urcu::read_lock_guard read_lock;
2189
2190 /*
2191 * Lookup the stream just to make sure it does not exist in our internal
2192 * state. This should NEVER happen.
2193 */
2194 lttng_ht_lookup(ht, &stream->key, &iter);
2195 node = lttng_ht_iter_get_node_u64(&iter);
2196 LTTNG_ASSERT(!node);
2197
2198 /*
2199 * When nb_init_stream_left reaches 0, we don't need to trigger any action
2200 * in terms of destroying the associated channel, because the action that
2201 * causes the count to become 0 also causes a stream to be added. The
2202 * channel deletion will thus be triggered by the following removal of this
2203 * stream.
2204 */
2205 if (uatomic_read(&stream->chan->nb_init_stream_left) > 0) {
2206 /* Increment refcount before decrementing nb_init_stream_left */
2207 cmm_smp_wmb();
2208 uatomic_dec(&stream->chan->nb_init_stream_left);
2209 }
2210
2211 lttng_ht_add_unique_u64(ht, &stream->node);
2212
2213 lttng_ht_add_u64(the_consumer_data.stream_per_chan_id_ht, &stream->node_channel_id);
2214
2215 /*
2216 * Add stream to the stream_list_ht of the consumer data. No need to steal
2217 * the key since the HT does not use it and we allow to add redundant keys
2218 * into this table.
2219 */
2220 lttng_ht_add_u64(the_consumer_data.stream_list_ht, &stream->node_session_id);
2221
2222 pthread_mutex_unlock(&stream->lock);
2223 pthread_mutex_unlock(&stream->chan->lock);
2224 pthread_mutex_unlock(&stream->chan->timer_lock);
2225 pthread_mutex_unlock(&the_consumer_data.lock);
2226 }
2227
2228 /*
2229 * Delete data stream that are flagged for deletion (endpoint_status).
2230 */
2231 static void validate_endpoint_status_data_stream()
2232 {
2233 struct lttng_ht_iter iter;
2234 struct lttng_consumer_stream *stream;
2235
2236 DBG("Consumer delete flagged data stream");
2237
2238 {
2239 lttng::urcu::read_lock_guard read_lock;
2240
2241 cds_lfht_for_each_entry (data_ht->ht, &iter.iter, stream, node.node) {
2242 /* Validate delete flag of the stream */
2243 if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
2244 continue;
2245 }
2246 /* Delete it right now */
2247 consumer_del_stream(stream, data_ht);
2248 }
2249 }
2250 }
2251
2252 /*
2253 * Delete metadata stream that are flagged for deletion (endpoint_status).
2254 */
2255 static void validate_endpoint_status_metadata_stream(struct lttng_poll_event *pollset)
2256 {
2257 struct lttng_ht_iter iter;
2258 struct lttng_consumer_stream *stream;
2259
2260 DBG("Consumer delete flagged metadata stream");
2261
2262 LTTNG_ASSERT(pollset);
2263
2264 {
2265 lttng::urcu::read_lock_guard read_lock;
2266 cds_lfht_for_each_entry (metadata_ht->ht, &iter.iter, stream, node.node) {
2267 /* Validate delete flag of the stream */
2268 if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
2269 continue;
2270 }
2271 /*
2272 * Remove from pollset so the metadata thread can continue without
2273 * blocking on a deleted stream.
2274 */
2275 lttng_poll_del(pollset, stream->wait_fd);
2276
2277 /* Delete it right now */
2278 consumer_del_metadata_stream(stream, metadata_ht);
2279 }
2280 }
2281 }
2282
2283 /*
2284 * Thread polls on metadata file descriptor and write them on disk or on the
2285 * network.
2286 */
2287 void *consumer_thread_metadata_poll(void *data)
2288 {
2289 int ret, i, pollfd, err = -1;
2290 uint32_t revents, nb_fd;
2291 struct lttng_consumer_stream *stream = nullptr;
2292 struct lttng_ht_iter iter;
2293 struct lttng_ht_node_u64 *node;
2294 struct lttng_poll_event events;
2295 struct lttng_consumer_local_data *ctx = (lttng_consumer_local_data *) data;
2296 ssize_t len;
2297
2298 rcu_register_thread();
2299
2300 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_METADATA);
2301
2302 if (testpoint(consumerd_thread_metadata)) {
2303 goto error_testpoint;
2304 }
2305
2306 health_code_update();
2307
2308 DBG("Thread metadata poll started");
2309
2310 /* Size is set to 1 for the consumer_metadata pipe */
2311 ret = lttng_poll_create(&events, 2, LTTNG_CLOEXEC);
2312 if (ret < 0) {
2313 ERR("Poll set creation failed");
2314 goto end_poll;
2315 }
2316
2317 ret = lttng_poll_add(&events, lttng_pipe_get_readfd(ctx->consumer_metadata_pipe), LPOLLIN);
2318 if (ret < 0) {
2319 goto end;
2320 }
2321
2322 /* Main loop */
2323 DBG("Metadata main loop started");
2324
2325 while (true) {
2326 restart:
2327 health_code_update();
2328 health_poll_entry();
2329 DBG("Metadata poll wait");
2330 ret = lttng_poll_wait(&events, -1);
2331 DBG("Metadata poll return from wait with %d fd(s)", LTTNG_POLL_GETNB(&events));
2332 health_poll_exit();
2333 DBG("Metadata event caught in thread");
2334 if (ret < 0) {
2335 if (errno == EINTR) {
2336 ERR("Poll EINTR caught");
2337 goto restart;
2338 }
2339 if (LTTNG_POLL_GETNB(&events) == 0) {
2340 err = 0; /* All is OK */
2341 }
2342 goto end;
2343 }
2344
2345 nb_fd = ret;
2346
2347 /* From here, the event is a metadata wait fd */
2348 for (i = 0; i < nb_fd; i++) {
2349 health_code_update();
2350
2351 revents = LTTNG_POLL_GETEV(&events, i);
2352 pollfd = LTTNG_POLL_GETFD(&events, i);
2353
2354 if (pollfd == lttng_pipe_get_readfd(ctx->consumer_metadata_pipe)) {
2355 if (revents & LPOLLIN) {
2356 ssize_t pipe_len;
2357
2358 pipe_len = lttng_pipe_read(ctx->consumer_metadata_pipe,
2359 &stream,
2360 sizeof(stream)); /* NOLINT sizeof
2361 used on a
2362 pointer. */
2363 if (pipe_len < sizeof(stream)) { /* NOLINT sizeof used on a
2364 pointer. */
2365 if (pipe_len < 0) {
2366 PERROR("read metadata stream");
2367 }
2368 /*
2369 * Remove the pipe from the poll set and continue
2370 * the loop since their might be data to consume.
2371 */
2372 lttng_poll_del(
2373 &events,
2374 lttng_pipe_get_readfd(
2375 ctx->consumer_metadata_pipe));
2376 lttng_pipe_read_close(ctx->consumer_metadata_pipe);
2377 continue;
2378 }
2379
2380 /* A NULL stream means that the state has changed. */
2381 if (stream == nullptr) {
2382 /* Check for deleted streams. */
2383 validate_endpoint_status_metadata_stream(&events);
2384 goto restart;
2385 }
2386
2387 DBG("Adding metadata stream %d to poll set",
2388 stream->wait_fd);
2389
2390 /* Add metadata stream to the global poll events list */
2391 lttng_poll_add(
2392 &events, stream->wait_fd, LPOLLIN | LPOLLPRI);
2393 } else if (revents & (LPOLLERR | LPOLLHUP)) {
2394 DBG("Metadata thread pipe hung up");
2395 /*
2396 * Remove the pipe from the poll set and continue the loop
2397 * since their might be data to consume.
2398 */
2399 lttng_poll_del(
2400 &events,
2401 lttng_pipe_get_readfd(ctx->consumer_metadata_pipe));
2402 lttng_pipe_read_close(ctx->consumer_metadata_pipe);
2403 continue;
2404 } else {
2405 ERR("Unexpected poll events %u for sock %d",
2406 revents,
2407 pollfd);
2408 goto end;
2409 }
2410
2411 /* Handle other stream */
2412 continue;
2413 }
2414
2415 lttng::urcu::read_lock_guard read_lock;
2416 {
2417 uint64_t tmp_id = (uint64_t) pollfd;
2418
2419 lttng_ht_lookup(metadata_ht, &tmp_id, &iter);
2420 }
2421 node = lttng_ht_iter_get_node_u64(&iter);
2422 LTTNG_ASSERT(node);
2423
2424 stream = caa_container_of(node, struct lttng_consumer_stream, node);
2425
2426 if (revents & (LPOLLIN | LPOLLPRI)) {
2427 /* Get the data out of the metadata file descriptor */
2428 DBG("Metadata available on fd %d", pollfd);
2429 LTTNG_ASSERT(stream->wait_fd == pollfd);
2430
2431 do {
2432 health_code_update();
2433
2434 len = ctx->on_buffer_ready(stream, ctx, false);
2435 /*
2436 * We don't check the return value here since if we get
2437 * a negative len, it means an error occurred thus we
2438 * simply remove it from the poll set and free the
2439 * stream.
2440 */
2441 } while (len > 0);
2442
2443 /* It's ok to have an unavailable sub-buffer */
2444 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
2445 /* Clean up stream from consumer and free it. */
2446 lttng_poll_del(&events, stream->wait_fd);
2447 consumer_del_metadata_stream(stream, metadata_ht);
2448 }
2449 } else if (revents & (LPOLLERR | LPOLLHUP)) {
2450 DBG("Metadata fd %d is hup|err.", pollfd);
2451 if (!stream->hangup_flush_done &&
2452 (the_consumer_data.type == LTTNG_CONSUMER32_UST ||
2453 the_consumer_data.type == LTTNG_CONSUMER64_UST)) {
2454 DBG("Attempting to flush and consume the UST buffers");
2455 lttng_ustconsumer_on_stream_hangup(stream);
2456
2457 /* We just flushed the stream now read it. */
2458 do {
2459 health_code_update();
2460
2461 len = ctx->on_buffer_ready(stream, ctx, false);
2462 /*
2463 * We don't check the return value here since if we
2464 * get a negative len, it means an error occurred
2465 * thus we simply remove it from the poll set and
2466 * free the stream.
2467 */
2468 } while (len > 0);
2469 }
2470
2471 lttng_poll_del(&events, stream->wait_fd);
2472 /*
2473 * This call update the channel states, closes file descriptors
2474 * and securely free the stream.
2475 */
2476 consumer_del_metadata_stream(stream, metadata_ht);
2477 } else {
2478 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2479 goto end;
2480 }
2481 /* Release RCU lock for the stream looked up */
2482 }
2483 }
2484
2485 /* All is OK */
2486 err = 0;
2487 end:
2488 DBG("Metadata poll thread exiting");
2489
2490 lttng_poll_clean(&events);
2491 end_poll:
2492 error_testpoint:
2493 if (err) {
2494 health_error();
2495 ERR("Health error occurred in %s", __func__);
2496 }
2497 health_unregister(health_consumerd);
2498 rcu_unregister_thread();
2499 return nullptr;
2500 }
2501
2502 /*
2503 * This thread polls the fds in the set to consume the data and write
2504 * it to tracefile if necessary.
2505 */
2506 void *consumer_thread_data_poll(void *data)
2507 {
2508 int num_rdy, high_prio, ret, i, err = -1;
2509 struct pollfd *pollfd = nullptr;
2510 /* local view of the streams */
2511 struct lttng_consumer_stream **local_stream = nullptr, *new_stream = nullptr;
2512 /* local view of consumer_data.fds_count */
2513 int nb_fd = 0;
2514 /* 2 for the consumer_data_pipe and wake up pipe */
2515 const int nb_pipes_fd = 2;
2516 /* Number of FDs with CONSUMER_ENDPOINT_INACTIVE but still open. */
2517 int nb_inactive_fd = 0;
2518 struct lttng_consumer_local_data *ctx = (lttng_consumer_local_data *) data;
2519 ssize_t len;
2520
2521 rcu_register_thread();
2522
2523 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_DATA);
2524
2525 if (testpoint(consumerd_thread_data)) {
2526 goto error_testpoint;
2527 }
2528
2529 health_code_update();
2530
2531 local_stream = zmalloc<lttng_consumer_stream *>();
2532 if (local_stream == nullptr) {
2533 PERROR("local_stream malloc");
2534 goto end;
2535 }
2536
2537 while (true) {
2538 health_code_update();
2539
2540 high_prio = 0;
2541
2542 /*
2543 * the fds set has been updated, we need to update our
2544 * local array as well
2545 */
2546 pthread_mutex_lock(&the_consumer_data.lock);
2547 if (the_consumer_data.need_update) {
2548 free(pollfd);
2549 pollfd = nullptr;
2550
2551 free(local_stream);
2552 local_stream = nullptr;
2553
2554 /* Allocate for all fds */
2555 pollfd =
2556 calloc<struct pollfd>(the_consumer_data.stream_count + nb_pipes_fd);
2557 if (pollfd == nullptr) {
2558 PERROR("pollfd malloc");
2559 pthread_mutex_unlock(&the_consumer_data.lock);
2560 goto end;
2561 }
2562
2563 local_stream = calloc<lttng_consumer_stream *>(
2564 the_consumer_data.stream_count + nb_pipes_fd);
2565 if (local_stream == nullptr) {
2566 PERROR("local_stream malloc");
2567 pthread_mutex_unlock(&the_consumer_data.lock);
2568 goto end;
2569 }
2570 ret = update_poll_array(
2571 ctx, &pollfd, local_stream, data_ht, &nb_inactive_fd);
2572 if (ret < 0) {
2573 ERR("Error in allocating pollfd or local_outfds");
2574 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
2575 pthread_mutex_unlock(&the_consumer_data.lock);
2576 goto end;
2577 }
2578 nb_fd = ret;
2579 the_consumer_data.need_update = 0;
2580 }
2581 pthread_mutex_unlock(&the_consumer_data.lock);
2582
2583 /* No FDs and consumer_quit, consumer_cleanup the thread */
2584 if (nb_fd == 0 && nb_inactive_fd == 0 && CMM_LOAD_SHARED(consumer_quit) == 1) {
2585 err = 0; /* All is OK */
2586 goto end;
2587 }
2588 /* poll on the array of fds */
2589 restart:
2590 DBG("polling on %d fd", nb_fd + nb_pipes_fd);
2591 if (testpoint(consumerd_thread_data_poll)) {
2592 goto end;
2593 }
2594 health_poll_entry();
2595 num_rdy = poll(pollfd, nb_fd + nb_pipes_fd, -1);
2596 health_poll_exit();
2597 DBG("poll num_rdy : %d", num_rdy);
2598 if (num_rdy == -1) {
2599 /*
2600 * Restart interrupted system call.
2601 */
2602 if (errno == EINTR) {
2603 goto restart;
2604 }
2605 PERROR("Poll error");
2606 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
2607 goto end;
2608 } else if (num_rdy == 0) {
2609 DBG("Polling thread timed out");
2610 goto end;
2611 }
2612
2613 if (caa_unlikely(data_consumption_paused)) {
2614 DBG("Data consumption paused, sleeping...");
2615 sleep(1);
2616 goto restart;
2617 }
2618
2619 /*
2620 * If the consumer_data_pipe triggered poll go directly to the
2621 * beginning of the loop to update the array. We want to prioritize
2622 * array update over low-priority reads.
2623 */
2624 if (pollfd[nb_fd].revents & (POLLIN | POLLPRI)) {
2625 ssize_t pipe_readlen;
2626
2627 DBG("consumer_data_pipe wake up");
2628 pipe_readlen = lttng_pipe_read(ctx->consumer_data_pipe,
2629 &new_stream,
2630 sizeof(new_stream)); /* NOLINT sizeof used on
2631 a pointer. */
2632 if (pipe_readlen < sizeof(new_stream)) { /* NOLINT sizeof used on a pointer.
2633 */
2634 PERROR("Consumer data pipe");
2635 /* Continue so we can at least handle the current stream(s). */
2636 continue;
2637 }
2638
2639 /*
2640 * If the stream is NULL, just ignore it. It's also possible that
2641 * the sessiond poll thread changed the consumer_quit state and is
2642 * waking us up to test it.
2643 */
2644 if (new_stream == nullptr) {
2645 validate_endpoint_status_data_stream();
2646 continue;
2647 }
2648
2649 /* Continue to update the local streams and handle prio ones */
2650 continue;
2651 }
2652
2653 /* Handle wakeup pipe. */
2654 if (pollfd[nb_fd + 1].revents & (POLLIN | POLLPRI)) {
2655 char dummy;
2656 ssize_t pipe_readlen;
2657
2658 pipe_readlen =
2659 lttng_pipe_read(ctx->consumer_wakeup_pipe, &dummy, sizeof(dummy));
2660 if (pipe_readlen < 0) {
2661 PERROR("Consumer data wakeup pipe");
2662 }
2663 /* We've been awakened to handle stream(s). */
2664 ctx->has_wakeup = 0;
2665 }
2666
2667 /* Take care of high priority channels first. */
2668 for (i = 0; i < nb_fd; i++) {
2669 health_code_update();
2670
2671 if (local_stream[i] == nullptr) {
2672 continue;
2673 }
2674 if (pollfd[i].revents & POLLPRI) {
2675 DBG("Urgent read on fd %d", pollfd[i].fd);
2676 high_prio = 1;
2677 len = ctx->on_buffer_ready(local_stream[i], ctx, false);
2678 /* it's ok to have an unavailable sub-buffer */
2679 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
2680 /* Clean the stream and free it. */
2681 consumer_del_stream(local_stream[i], data_ht);
2682 local_stream[i] = nullptr;
2683 } else if (len > 0) {
2684 local_stream[i]->has_data_left_to_be_read_before_teardown =
2685 1;
2686 }
2687 }
2688 }
2689
2690 /*
2691 * If we read high prio channel in this loop, try again
2692 * for more high prio data.
2693 */
2694 if (high_prio) {
2695 continue;
2696 }
2697
2698 /* Take care of low priority channels. */
2699 for (i = 0; i < nb_fd; i++) {
2700 health_code_update();
2701
2702 if (local_stream[i] == nullptr) {
2703 continue;
2704 }
2705 if ((pollfd[i].revents & POLLIN) || local_stream[i]->hangup_flush_done ||
2706 local_stream[i]->has_data) {
2707 DBG("Normal read on fd %d", pollfd[i].fd);
2708 len = ctx->on_buffer_ready(local_stream[i], ctx, false);
2709 /* it's ok to have an unavailable sub-buffer */
2710 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
2711 /* Clean the stream and free it. */
2712 consumer_del_stream(local_stream[i], data_ht);
2713 local_stream[i] = nullptr;
2714 } else if (len > 0) {
2715 local_stream[i]->has_data_left_to_be_read_before_teardown =
2716 1;
2717 }
2718 }
2719 }
2720
2721 /* Handle hangup and errors */
2722 for (i = 0; i < nb_fd; i++) {
2723 health_code_update();
2724
2725 if (local_stream[i] == nullptr) {
2726 continue;
2727 }
2728 if (!local_stream[i]->hangup_flush_done &&
2729 (pollfd[i].revents & (POLLHUP | POLLERR | POLLNVAL)) &&
2730 (the_consumer_data.type == LTTNG_CONSUMER32_UST ||
2731 the_consumer_data.type == LTTNG_CONSUMER64_UST)) {
2732 DBG("fd %d is hup|err|nval. Attempting flush and read.",
2733 pollfd[i].fd);
2734 lttng_ustconsumer_on_stream_hangup(local_stream[i]);
2735 /* Attempt read again, for the data we just flushed. */
2736 local_stream[i]->has_data_left_to_be_read_before_teardown = 1;
2737 }
2738 /*
2739 * When a stream's pipe dies (hup/err/nval), an "inactive producer" flush is
2740 * performed. This type of flush ensures that a new packet is produced no
2741 * matter the consumed/produced positions are.
2742 *
2743 * This, in turn, causes the next pass to see that data available for the
2744 * stream. When we come back here, we can be assured that all available
2745 * data has been consumed and we can finally destroy the stream.
2746 *
2747 * If the poll flag is HUP/ERR/NVAL and we have
2748 * read no data in this pass, we can remove the
2749 * stream from its hash table.
2750 */
2751 if ((pollfd[i].revents & POLLHUP)) {
2752 DBG("Polling fd %d tells it has hung up.", pollfd[i].fd);
2753 if (!local_stream[i]->has_data_left_to_be_read_before_teardown) {
2754 consumer_del_stream(local_stream[i], data_ht);
2755 local_stream[i] = nullptr;
2756 }
2757 } else if (pollfd[i].revents & POLLERR) {
2758 ERR("Error returned in polling fd %d.", pollfd[i].fd);
2759 if (!local_stream[i]->has_data_left_to_be_read_before_teardown) {
2760 consumer_del_stream(local_stream[i], data_ht);
2761 local_stream[i] = nullptr;
2762 }
2763 } else if (pollfd[i].revents & POLLNVAL) {
2764 ERR("Polling fd %d tells fd is not open.", pollfd[i].fd);
2765 if (!local_stream[i]->has_data_left_to_be_read_before_teardown) {
2766 consumer_del_stream(local_stream[i], data_ht);
2767 local_stream[i] = nullptr;
2768 }
2769 }
2770 if (local_stream[i] != nullptr) {
2771 local_stream[i]->has_data_left_to_be_read_before_teardown = 0;
2772 }
2773 }
2774 }
2775 /* All is OK */
2776 err = 0;
2777 end:
2778 DBG("polling thread exiting");
2779 free(pollfd);
2780 free(local_stream);
2781
2782 /*
2783 * Close the write side of the pipe so epoll_wait() in
2784 * consumer_thread_metadata_poll can catch it. The thread is monitoring the
2785 * read side of the pipe. If we close them both, epoll_wait strangely does
2786 * not return and could create a endless wait period if the pipe is the
2787 * only tracked fd in the poll set. The thread will take care of closing
2788 * the read side.
2789 */
2790 (void) lttng_pipe_write_close(ctx->consumer_metadata_pipe);
2791
2792 error_testpoint:
2793 if (err) {
2794 health_error();
2795 ERR("Health error occurred in %s", __func__);
2796 }
2797 health_unregister(health_consumerd);
2798
2799 rcu_unregister_thread();
2800 return nullptr;
2801 }
2802
2803 /*
2804 * Close wake-up end of each stream belonging to the channel. This will
2805 * allow the poll() on the stream read-side to detect when the
2806 * write-side (application) finally closes them.
2807 */
2808 static void consumer_close_channel_streams(struct lttng_consumer_channel *channel)
2809 {
2810 struct lttng_ht *ht;
2811 struct lttng_consumer_stream *stream;
2812 struct lttng_ht_iter iter;
2813
2814 ht = the_consumer_data.stream_per_chan_id_ht;
2815
2816 lttng::urcu::read_lock_guard read_lock;
2817 cds_lfht_for_each_entry_duplicate(ht->ht,
2818 ht->hash_fct(&channel->key, lttng_ht_seed),
2819 ht->match_fct,
2820 &channel->key,
2821 &iter.iter,
2822 stream,
2823 node_channel_id.node)
2824 {
2825 /*
2826 * Protect against teardown with mutex.
2827 */
2828 pthread_mutex_lock(&stream->lock);
2829 if (cds_lfht_is_node_deleted(&stream->node.node)) {
2830 goto next;
2831 }
2832 switch (the_consumer_data.type) {
2833 case LTTNG_CONSUMER_KERNEL:
2834 break;
2835 case LTTNG_CONSUMER32_UST:
2836 case LTTNG_CONSUMER64_UST:
2837 if (stream->metadata_flag) {
2838 /* Safe and protected by the stream lock. */
2839 lttng_ustconsumer_close_metadata(stream->chan);
2840 } else {
2841 /*
2842 * Note: a mutex is taken internally within
2843 * liblttng-ust-ctl to protect timer wakeup_fd
2844 * use from concurrent close.
2845 */
2846 lttng_ustconsumer_close_stream_wakeup(stream);
2847 }
2848 break;
2849 default:
2850 ERR("Unknown consumer_data type");
2851 abort();
2852 }
2853 next:
2854 pthread_mutex_unlock(&stream->lock);
2855 }
2856 }
2857
2858 static void destroy_channel_ht(struct lttng_ht *ht)
2859 {
2860 struct lttng_ht_iter iter;
2861 struct lttng_consumer_channel *channel;
2862 int ret;
2863
2864 if (ht == nullptr) {
2865 return;
2866 }
2867
2868 {
2869 lttng::urcu::read_lock_guard read_lock;
2870
2871 cds_lfht_for_each_entry (ht->ht, &iter.iter, channel, wait_fd_node.node) {
2872 ret = lttng_ht_del(ht, &iter);
2873 LTTNG_ASSERT(ret != 0);
2874 }
2875 }
2876
2877 lttng_ht_destroy(ht);
2878 }
2879
2880 /*
2881 * This thread polls the channel fds to detect when they are being
2882 * closed. It closes all related streams if the channel is detected as
2883 * closed. It is currently only used as a shim layer for UST because the
2884 * consumerd needs to keep the per-stream wakeup end of pipes open for
2885 * periodical flush.
2886 */
2887 void *consumer_thread_channel_poll(void *data)
2888 {
2889 int ret, i, pollfd, err = -1;
2890 uint32_t revents, nb_fd;
2891 struct lttng_consumer_channel *chan = nullptr;
2892 struct lttng_ht_iter iter;
2893 struct lttng_ht_node_u64 *node;
2894 struct lttng_poll_event events;
2895 struct lttng_consumer_local_data *ctx = (lttng_consumer_local_data *) data;
2896 struct lttng_ht *channel_ht;
2897
2898 rcu_register_thread();
2899
2900 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_CHANNEL);
2901
2902 if (testpoint(consumerd_thread_channel)) {
2903 goto error_testpoint;
2904 }
2905
2906 health_code_update();
2907
2908 channel_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2909 if (!channel_ht) {
2910 /* ENOMEM at this point. Better to bail out. */
2911 goto end_ht;
2912 }
2913
2914 DBG("Thread channel poll started");
2915
2916 /* Size is set to 1 for the consumer_channel pipe */
2917 ret = lttng_poll_create(&events, 2, LTTNG_CLOEXEC);
2918 if (ret < 0) {
2919 ERR("Poll set creation failed");
2920 goto end_poll;
2921 }
2922
2923 ret = lttng_poll_add(&events, ctx->consumer_channel_pipe[0], LPOLLIN);
2924 if (ret < 0) {
2925 goto end;
2926 }
2927
2928 /* Main loop */
2929 DBG("Channel main loop started");
2930
2931 while (true) {
2932 restart:
2933 health_code_update();
2934 DBG("Channel poll wait");
2935 health_poll_entry();
2936 ret = lttng_poll_wait(&events, -1);
2937 DBG("Channel poll return from wait with %d fd(s)", LTTNG_POLL_GETNB(&events));
2938 health_poll_exit();
2939 DBG("Channel event caught in thread");
2940 if (ret < 0) {
2941 if (errno == EINTR) {
2942 ERR("Poll EINTR caught");
2943 goto restart;
2944 }
2945 if (LTTNG_POLL_GETNB(&events) == 0) {
2946 err = 0; /* All is OK */
2947 }
2948 goto end;
2949 }
2950
2951 nb_fd = ret;
2952
2953 /* From here, the event is a channel wait fd */
2954 for (i = 0; i < nb_fd; i++) {
2955 health_code_update();
2956
2957 revents = LTTNG_POLL_GETEV(&events, i);
2958 pollfd = LTTNG_POLL_GETFD(&events, i);
2959
2960 if (pollfd == ctx->consumer_channel_pipe[0]) {
2961 if (revents & LPOLLIN) {
2962 enum consumer_channel_action action;
2963 uint64_t key;
2964
2965 ret = read_channel_pipe(ctx, &chan, &key, &action);
2966 if (ret <= 0) {
2967 if (ret < 0) {
2968 ERR("Error reading channel pipe");
2969 }
2970 lttng_poll_del(&events,
2971 ctx->consumer_channel_pipe[0]);
2972 continue;
2973 }
2974
2975 switch (action) {
2976 case CONSUMER_CHANNEL_ADD:
2977 {
2978 DBG("Adding channel %d to poll set", chan->wait_fd);
2979
2980 lttng_ht_node_init_u64(&chan->wait_fd_node,
2981 chan->wait_fd);
2982 lttng::urcu::read_lock_guard read_lock;
2983 lttng_ht_add_unique_u64(channel_ht,
2984 &chan->wait_fd_node);
2985 /* Add channel to the global poll events list */
2986 // FIXME: Empty flag on a pipe pollset, this might
2987 // hang on FreeBSD.
2988 lttng_poll_add(&events, chan->wait_fd, 0);
2989 break;
2990 }
2991 case CONSUMER_CHANNEL_DEL:
2992 {
2993 /*
2994 * This command should never be called if the
2995 * channel has streams monitored by either the data
2996 * or metadata thread. The consumer only notify this
2997 * thread with a channel del. command if it receives
2998 * a destroy channel command from the session daemon
2999 * that send it if a command prior to the
3000 * GET_CHANNEL failed.
3001 */
3002
3003 lttng::urcu::read_lock_guard read_lock;
3004 chan = consumer_find_channel(key);
3005 if (!chan) {
3006 ERR("UST consumer get channel key %" PRIu64
3007 " not found for del channel",
3008 key);
3009 break;
3010 }
3011 lttng_poll_del(&events, chan->wait_fd);
3012 iter.iter.node = &chan->wait_fd_node.node;
3013 ret = lttng_ht_del(channel_ht, &iter);
3014 LTTNG_ASSERT(ret == 0);
3015
3016 switch (the_consumer_data.type) {
3017 case LTTNG_CONSUMER_KERNEL:
3018 break;
3019 case LTTNG_CONSUMER32_UST:
3020 case LTTNG_CONSUMER64_UST:
3021 health_code_update();
3022 /* Destroy streams that might have been left
3023 * in the stream list. */
3024 clean_channel_stream_list(chan);
3025 break;
3026 default:
3027 ERR("Unknown consumer_data type");
3028 abort();
3029 }
3030
3031 /*
3032 * Release our own refcount. Force channel deletion
3033 * even if streams were not initialized.
3034 */
3035 if (!uatomic_sub_return(&chan->refcount, 1)) {
3036 consumer_del_channel(chan);
3037 }
3038 goto restart;
3039 }
3040 case CONSUMER_CHANNEL_QUIT:
3041 /*
3042 * Remove the pipe from the poll set and continue
3043 * the loop since their might be data to consume.
3044 */
3045 lttng_poll_del(&events,
3046 ctx->consumer_channel_pipe[0]);
3047 continue;
3048 default:
3049 ERR("Unknown action");
3050 break;
3051 }
3052 } else if (revents & (LPOLLERR | LPOLLHUP)) {
3053 DBG("Channel thread pipe hung up");
3054 /*
3055 * Remove the pipe from the poll set and continue the loop
3056 * since their might be data to consume.
3057 */
3058 lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
3059 continue;
3060 } else {
3061 ERR("Unexpected poll events %u for sock %d",
3062 revents,
3063 pollfd);
3064 goto end;
3065 }
3066
3067 /* Handle other stream */
3068 continue;
3069 }
3070
3071 lttng::urcu::read_lock_guard read_lock;
3072 {
3073 uint64_t tmp_id = (uint64_t) pollfd;
3074
3075 lttng_ht_lookup(channel_ht, &tmp_id, &iter);
3076 }
3077 node = lttng_ht_iter_get_node_u64(&iter);
3078 LTTNG_ASSERT(node);
3079
3080 chan = caa_container_of(node, struct lttng_consumer_channel, wait_fd_node);
3081
3082 /* Check for error event */
3083 if (revents & (LPOLLERR | LPOLLHUP)) {
3084 DBG("Channel fd %d is hup|err.", pollfd);
3085
3086 lttng_poll_del(&events, chan->wait_fd);
3087 ret = lttng_ht_del(channel_ht, &iter);
3088 LTTNG_ASSERT(ret == 0);
3089
3090 /*
3091 * This will close the wait fd for each stream associated to
3092 * this channel AND monitored by the data/metadata thread thus
3093 * will be clean by the right thread.
3094 */
3095 consumer_close_channel_streams(chan);
3096
3097 /* Release our own refcount */
3098 if (!uatomic_sub_return(&chan->refcount, 1) &&
3099 !uatomic_read(&chan->nb_init_stream_left)) {
3100 consumer_del_channel(chan);
3101 }
3102 } else {
3103 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3104 goto end;
3105 }
3106
3107 /* Release RCU lock for the channel looked up */
3108 }
3109 }
3110
3111 /* All is OK */
3112 err = 0;
3113 end:
3114 lttng_poll_clean(&events);
3115 end_poll:
3116 destroy_channel_ht(channel_ht);
3117 end_ht:
3118 error_testpoint:
3119 DBG("Channel poll thread exiting");
3120 if (err) {
3121 health_error();
3122 ERR("Health error occurred in %s", __func__);
3123 }
3124 health_unregister(health_consumerd);
3125 rcu_unregister_thread();
3126 return nullptr;
3127 }
3128
3129 static int set_metadata_socket(struct lttng_consumer_local_data *ctx,
3130 struct pollfd *sockpoll,
3131 int client_socket)
3132 {
3133 int ret;
3134
3135 LTTNG_ASSERT(ctx);
3136 LTTNG_ASSERT(sockpoll);
3137
3138 ret = lttng_consumer_poll_socket(sockpoll);
3139 if (ret) {
3140 goto error;
3141 }
3142 DBG("Metadata connection on client_socket");
3143
3144 /* Blocking call, waiting for transmission */
3145 ctx->consumer_metadata_socket = lttcomm_accept_unix_sock(client_socket);
3146 if (ctx->consumer_metadata_socket < 0) {
3147 WARN("On accept metadata");
3148 ret = -1;
3149 goto error;
3150 }
3151 ret = 0;
3152
3153 error:
3154 return ret;
3155 }
3156
3157 /*
3158 * This thread listens on the consumerd socket and receives the file
3159 * descriptors from the session daemon.
3160 */
3161 void *consumer_thread_sessiond_poll(void *data)
3162 {
3163 int sock = -1, client_socket, ret, err = -1;
3164 /*
3165 * structure to poll for incoming data on communication socket avoids
3166 * making blocking sockets.
3167 */
3168 struct pollfd consumer_sockpoll[2];
3169 struct lttng_consumer_local_data *ctx = (lttng_consumer_local_data *) data;
3170
3171 rcu_register_thread();
3172
3173 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_SESSIOND);
3174
3175 if (testpoint(consumerd_thread_sessiond)) {
3176 goto error_testpoint;
3177 }
3178
3179 health_code_update();
3180
3181 DBG("Creating command socket %s", ctx->consumer_command_sock_path);
3182 unlink(ctx->consumer_command_sock_path);
3183 client_socket = lttcomm_create_unix_sock(ctx->consumer_command_sock_path);
3184 if (client_socket < 0) {
3185 ERR("Cannot create command socket");
3186 goto end;
3187 }
3188
3189 ret = lttcomm_listen_unix_sock(client_socket);
3190 if (ret < 0) {
3191 goto end;
3192 }
3193
3194 DBG("Sending ready command to lttng-sessiond");
3195 ret = lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_COMMAND_SOCK_READY);
3196 /* return < 0 on error, but == 0 is not fatal */
3197 if (ret < 0) {
3198 ERR("Error sending ready command to lttng-sessiond");
3199 goto end;
3200 }
3201
3202 /* prepare the FDs to poll : to client socket and the should_quit pipe */
3203 consumer_sockpoll[0].fd = ctx->consumer_should_quit[0];
3204 consumer_sockpoll[0].events = POLLIN | POLLPRI;
3205 consumer_sockpoll[1].fd = client_socket;
3206 consumer_sockpoll[1].events = POLLIN | POLLPRI;
3207
3208 ret = lttng_consumer_poll_socket(consumer_sockpoll);
3209 if (ret) {
3210 if (ret > 0) {
3211 /* should exit */
3212 err = 0;
3213 }
3214 goto end;
3215 }
3216 DBG("Connection on client_socket");
3217
3218 /* Blocking call, waiting for transmission */
3219 sock = lttcomm_accept_unix_sock(client_socket);
3220 if (sock < 0) {
3221 WARN("On accept");
3222 goto end;
3223 }
3224
3225 /*
3226 * Setup metadata socket which is the second socket connection on the
3227 * command unix socket.
3228 */
3229 ret = set_metadata_socket(ctx, consumer_sockpoll, client_socket);
3230 if (ret) {
3231 if (ret > 0) {
3232 /* should exit */
3233 err = 0;
3234 }
3235 goto end;
3236 }
3237
3238 /* This socket is not useful anymore. */
3239 ret = close(client_socket);
3240 if (ret < 0) {
3241 PERROR("close client_socket");
3242 }
3243 client_socket = -1;
3244
3245 /* update the polling structure to poll on the established socket */
3246 consumer_sockpoll[1].fd = sock;
3247 consumer_sockpoll[1].events = POLLIN | POLLPRI;
3248
3249 while (true) {
3250 health_code_update();
3251
3252 health_poll_entry();
3253 ret = lttng_consumer_poll_socket(consumer_sockpoll);
3254 health_poll_exit();
3255 if (ret) {
3256 if (ret > 0) {
3257 /* should exit */
3258 err = 0;
3259 }
3260 goto end;
3261 }
3262 DBG("Incoming command on sock");
3263 ret = lttng_consumer_recv_cmd(ctx, sock, consumer_sockpoll);
3264 if (ret <= 0) {
3265 /*
3266 * This could simply be a session daemon quitting. Don't output
3267 * ERR() here.
3268 */
3269 DBG("Communication interrupted on command socket");
3270 err = 0;
3271 goto end;
3272 }
3273 if (CMM_LOAD_SHARED(consumer_quit)) {
3274 DBG("consumer_thread_receive_fds received quit from signal");
3275 err = 0; /* All is OK */
3276 goto end;
3277 }
3278 DBG("Received command on sock");
3279 }
3280 /* All is OK */
3281 err = 0;
3282
3283 end:
3284 DBG("Consumer thread sessiond poll exiting");
3285
3286 /*
3287 * Close metadata streams since the producer is the session daemon which
3288 * just died.
3289 *
3290 * NOTE: for now, this only applies to the UST tracer.
3291 */
3292 lttng_consumer_close_all_metadata();
3293
3294 /*
3295 * when all fds have hung up, the polling thread
3296 * can exit cleanly
3297 */
3298 CMM_STORE_SHARED(consumer_quit, 1);
3299
3300 /*
3301 * Notify the data poll thread to poll back again and test the
3302 * consumer_quit state that we just set so to quit gracefully.
3303 */
3304 notify_thread_lttng_pipe(ctx->consumer_data_pipe);
3305
3306 notify_channel_pipe(ctx, nullptr, -1, CONSUMER_CHANNEL_QUIT);
3307
3308 notify_health_quit_pipe(health_quit_pipe);
3309
3310 /* Cleaning up possibly open sockets. */
3311 if (sock >= 0) {
3312 ret = close(sock);
3313 if (ret < 0) {
3314 PERROR("close sock sessiond poll");
3315 }
3316 }
3317 if (client_socket >= 0) {
3318 ret = close(client_socket);
3319 if (ret < 0) {
3320 PERROR("close client_socket sessiond poll");
3321 }
3322 }
3323
3324 error_testpoint:
3325 if (err) {
3326 health_error();
3327 ERR("Health error occurred in %s", __func__);
3328 }
3329 health_unregister(health_consumerd);
3330
3331 rcu_unregister_thread();
3332 return nullptr;
3333 }
3334
3335 static int post_consume(struct lttng_consumer_stream *stream,
3336 const struct stream_subbuffer *subbuffer,
3337 struct lttng_consumer_local_data *ctx)
3338 {
3339 size_t i;
3340 int ret = 0;
3341 const size_t count =
3342 lttng_dynamic_array_get_count(&stream->read_subbuffer_ops.post_consume_cbs);
3343
3344 for (i = 0; i < count; i++) {
3345 const post_consume_cb op = *(post_consume_cb *) lttng_dynamic_array_get_element(
3346 &stream->read_subbuffer_ops.post_consume_cbs, i);
3347
3348 ret = op(stream, subbuffer, ctx);
3349 if (ret) {
3350 goto end;
3351 }
3352 }
3353 end:
3354 return ret;
3355 }
3356
3357 ssize_t lttng_consumer_read_subbuffer(struct lttng_consumer_stream *stream,
3358 struct lttng_consumer_local_data *ctx,
3359 bool locked_by_caller)
3360 {
3361 ssize_t ret, written_bytes = 0;
3362 int rotation_ret;
3363 struct stream_subbuffer subbuffer = {};
3364 enum get_next_subbuffer_status get_next_status;
3365
3366 if (!locked_by_caller) {
3367 stream->read_subbuffer_ops.lock(stream);
3368 } else {
3369 stream->read_subbuffer_ops.assert_locked(stream);
3370 }
3371
3372 if (stream->read_subbuffer_ops.on_wake_up) {
3373 ret = stream->read_subbuffer_ops.on_wake_up(stream);
3374 if (ret) {
3375 goto end;
3376 }
3377 }
3378
3379 /*
3380 * If the stream was flagged to be ready for rotation before we extract
3381 * the next packet, rotate it now.
3382 */
3383 if (stream->rotate_ready) {
3384 DBG("Rotate stream before consuming data");
3385 ret = lttng_consumer_rotate_stream(stream);
3386 if (ret < 0) {
3387 ERR("Stream rotation error before consuming data");
3388 goto end;
3389 }
3390 }
3391
3392 get_next_status = stream->read_subbuffer_ops.get_next_subbuffer(stream, &subbuffer);
3393 switch (get_next_status) {
3394 case GET_NEXT_SUBBUFFER_STATUS_OK:
3395 break;
3396 case GET_NEXT_SUBBUFFER_STATUS_NO_DATA:
3397 /* Not an error. */
3398 ret = 0;
3399 goto sleep_stream;
3400 case GET_NEXT_SUBBUFFER_STATUS_ERROR:
3401 ret = -1;
3402 goto end;
3403 default:
3404 abort();
3405 }
3406
3407 ret = stream->read_subbuffer_ops.pre_consume_subbuffer(stream, &subbuffer);
3408 if (ret) {
3409 goto error_put_subbuf;
3410 }
3411
3412 written_bytes = stream->read_subbuffer_ops.consume_subbuffer(ctx, stream, &subbuffer);
3413 if (written_bytes <= 0) {
3414 ERR("Error consuming subbuffer: (%zd)", written_bytes);
3415 ret = (int) written_bytes;
3416 goto error_put_subbuf;
3417 }
3418
3419 ret = stream->read_subbuffer_ops.put_next_subbuffer(stream, &subbuffer);
3420 if (ret) {
3421 goto end;
3422 }
3423
3424 ret = post_consume(stream, &subbuffer, ctx);
3425 if (ret) {
3426 goto end;
3427 }
3428
3429 /*
3430 * After extracting the packet, we check if the stream is now ready to
3431 * be rotated and perform the action immediately.
3432 *
3433 * Don't overwrite `ret` as callers expect the number of bytes
3434 * consumed to be returned on success.
3435 */
3436 rotation_ret = lttng_consumer_stream_is_rotate_ready(stream);
3437 if (rotation_ret == 1) {
3438 rotation_ret = lttng_consumer_rotate_stream(stream);
3439 if (rotation_ret < 0) {
3440 ret = rotation_ret;
3441 ERR("Stream rotation error after consuming data");
3442 goto end;
3443 }
3444
3445 } else if (rotation_ret < 0) {
3446 ret = rotation_ret;
3447 ERR("Failed to check if stream was ready to rotate after consuming data");
3448 goto end;
3449 }
3450
3451 sleep_stream:
3452 if (stream->read_subbuffer_ops.on_sleep) {
3453 stream->read_subbuffer_ops.on_sleep(stream, ctx);
3454 }
3455
3456 ret = written_bytes;
3457 end:
3458 if (!locked_by_caller) {
3459 stream->read_subbuffer_ops.unlock(stream);
3460 }
3461
3462 return ret;
3463 error_put_subbuf:
3464 (void) stream->read_subbuffer_ops.put_next_subbuffer(stream, &subbuffer);
3465 goto end;
3466 }
3467
3468 int lttng_consumer_on_recv_stream(struct lttng_consumer_stream *stream)
3469 {
3470 switch (the_consumer_data.type) {
3471 case LTTNG_CONSUMER_KERNEL:
3472 return lttng_kconsumer_on_recv_stream(stream);
3473 case LTTNG_CONSUMER32_UST:
3474 case LTTNG_CONSUMER64_UST:
3475 return lttng_ustconsumer_on_recv_stream(stream);
3476 default:
3477 ERR("Unknown consumer_data type");
3478 abort();
3479 return -ENOSYS;
3480 }
3481 }
3482
3483 /*
3484 * Allocate and set consumer data hash tables.
3485 */
3486 int lttng_consumer_init()
3487 {
3488 the_consumer_data.channel_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3489 if (!the_consumer_data.channel_ht) {
3490 goto error;
3491 }
3492
3493 the_consumer_data.channels_by_session_id_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3494 if (!the_consumer_data.channels_by_session_id_ht) {
3495 goto error;
3496 }
3497
3498 the_consumer_data.relayd_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3499 if (!the_consumer_data.relayd_ht) {
3500 goto error;
3501 }
3502
3503 the_consumer_data.stream_list_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3504 if (!the_consumer_data.stream_list_ht) {
3505 goto error;
3506 }
3507
3508 the_consumer_data.stream_per_chan_id_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3509 if (!the_consumer_data.stream_per_chan_id_ht) {
3510 goto error;
3511 }
3512
3513 data_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3514 if (!data_ht) {
3515 goto error;
3516 }
3517
3518 metadata_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3519 if (!metadata_ht) {
3520 goto error;
3521 }
3522
3523 the_consumer_data.chunk_registry = lttng_trace_chunk_registry_create();
3524 if (!the_consumer_data.chunk_registry) {
3525 goto error;
3526 }
3527
3528 return 0;
3529
3530 error:
3531 return -1;
3532 }
3533
3534 /*
3535 * Process the ADD_RELAYD command receive by a consumer.
3536 *
3537 * This will create a relayd socket pair and add it to the relayd hash table.
3538 * The caller MUST acquire a RCU read side lock before calling it.
3539 */
3540 void consumer_add_relayd_socket(uint64_t net_seq_idx,
3541 int sock_type,
3542 struct lttng_consumer_local_data *ctx,
3543 int sock,
3544 struct pollfd *consumer_sockpoll,
3545 uint64_t sessiond_id,
3546 uint64_t relayd_session_id,
3547 uint32_t relayd_version_major,
3548 uint32_t relayd_version_minor,
3549 enum lttcomm_sock_proto relayd_socket_protocol)
3550 {
3551 int fd = -1, ret = -1, relayd_created = 0;
3552 enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
3553 struct consumer_relayd_sock_pair *relayd = nullptr;
3554
3555 LTTNG_ASSERT(ctx);
3556 LTTNG_ASSERT(sock >= 0);
3557 ASSERT_RCU_READ_LOCKED();
3558
3559 DBG("Consumer adding relayd socket (idx: %" PRIu64 ")", net_seq_idx);
3560
3561 /* Get relayd reference if exists. */
3562 relayd = consumer_find_relayd(net_seq_idx);
3563 if (relayd == nullptr) {
3564 LTTNG_ASSERT(sock_type == LTTNG_STREAM_CONTROL);
3565 /* Not found. Allocate one. */
3566 relayd = consumer_allocate_relayd_sock_pair(net_seq_idx);
3567 if (relayd == nullptr) {
3568 ret_code = LTTCOMM_CONSUMERD_ENOMEM;
3569 goto error;
3570 } else {
3571 relayd->sessiond_session_id = sessiond_id;
3572 relayd_created = 1;
3573 }
3574
3575 /*
3576 * This code path MUST continue to the consumer send status message to
3577 * we can notify the session daemon and continue our work without
3578 * killing everything.
3579 */
3580 } else {
3581 /*
3582 * relayd key should never be found for control socket.
3583 */
3584 LTTNG_ASSERT(sock_type != LTTNG_STREAM_CONTROL);
3585 }
3586
3587 /* First send a status message before receiving the fds. */
3588 ret = consumer_send_status_msg(sock, LTTCOMM_CONSUMERD_SUCCESS);
3589 if (ret < 0) {
3590 /* Somehow, the session daemon is not responding anymore. */
3591 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_FATAL);
3592 goto error_nosignal;
3593 }
3594
3595 /* Poll on consumer socket. */
3596 ret = lttng_consumer_poll_socket(consumer_sockpoll);
3597 if (ret) {
3598 /* Needing to exit in the middle of a command: error. */
3599 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
3600 goto error_nosignal;
3601 }
3602
3603 /* Get relayd socket from session daemon */
3604 ret = lttcomm_recv_fds_unix_sock(sock, &fd, 1);
3605 if (ret != sizeof(fd)) {
3606 fd = -1; /* Just in case it gets set with an invalid value. */
3607
3608 /*
3609 * Failing to receive FDs might indicate a major problem such as
3610 * reaching a fd limit during the receive where the kernel returns a
3611 * MSG_CTRUNC and fails to cleanup the fd in the queue. Any case, we
3612 * don't take any chances and stop everything.
3613 *
3614 * XXX: Feature request #558 will fix that and avoid this possible
3615 * issue when reaching the fd limit.
3616 */
3617 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_ERROR_RECV_FD);
3618 ret_code = LTTCOMM_CONSUMERD_ERROR_RECV_FD;
3619 goto error;
3620 }
3621
3622 /* Copy socket information and received FD */
3623 switch (sock_type) {
3624 case LTTNG_STREAM_CONTROL:
3625 /* Copy received lttcomm socket */
3626 ret = lttcomm_populate_sock_from_open_socket(
3627 &relayd->control_sock.sock, fd, relayd_socket_protocol);
3628
3629 /* Assign version values. */
3630 relayd->control_sock.major = relayd_version_major;
3631 relayd->control_sock.minor = relayd_version_minor;
3632
3633 relayd->relayd_session_id = relayd_session_id;
3634
3635 break;
3636 case LTTNG_STREAM_DATA:
3637 /* Copy received lttcomm socket */
3638 ret = lttcomm_populate_sock_from_open_socket(
3639 &relayd->data_sock.sock, fd, relayd_socket_protocol);
3640 /* Assign version values. */
3641 relayd->data_sock.major = relayd_version_major;
3642 relayd->data_sock.minor = relayd_version_minor;
3643 break;
3644 default:
3645 ERR("Unknown relayd socket type (%d)", sock_type);
3646 ret_code = LTTCOMM_CONSUMERD_FATAL;
3647 goto error;
3648 }
3649
3650 if (ret < 0) {
3651 ret_code = LTTCOMM_CONSUMERD_FATAL;
3652 goto error;
3653 }
3654
3655 DBG("Consumer %s socket created successfully with net idx %" PRIu64 " (fd: %d)",
3656 sock_type == LTTNG_STREAM_CONTROL ? "control" : "data",
3657 relayd->net_seq_idx,
3658 fd);
3659 /*
3660 * We gave the ownership of the fd to the relayd structure. Set the
3661 * fd to -1 so we don't call close() on it in the error path below.
3662 */
3663 fd = -1;
3664
3665 /* We successfully added the socket. Send status back. */
3666 ret = consumer_send_status_msg(sock, ret_code);
3667 if (ret < 0) {
3668 /* Somehow, the session daemon is not responding anymore. */
3669 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_FATAL);
3670 goto error_nosignal;
3671 }
3672
3673 /*
3674 * Add relayd socket pair to consumer data hashtable. If object already
3675 * exists or on error, the function gracefully returns.
3676 */
3677 relayd->ctx = ctx;
3678 add_relayd(relayd);
3679
3680 /* All good! */
3681 return;
3682
3683 error:
3684 if (consumer_send_status_msg(sock, ret_code) < 0) {
3685 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_FATAL);
3686 }
3687
3688 error_nosignal:
3689 /* Close received socket if valid. */
3690 if (fd >= 0) {
3691 if (close(fd)) {
3692 PERROR("close received socket");
3693 }
3694 }
3695
3696 if (relayd_created) {
3697 free(relayd);
3698 }
3699 }
3700
3701 /*
3702 * Search for a relayd associated to the session id and return the reference.
3703 *
3704 * A rcu read side lock MUST be acquire before calling this function and locked
3705 * until the relayd object is no longer necessary.
3706 */
3707 static struct consumer_relayd_sock_pair *find_relayd_by_session_id(uint64_t id)
3708 {
3709 struct lttng_ht_iter iter;
3710 struct consumer_relayd_sock_pair *relayd = nullptr;
3711
3712 ASSERT_RCU_READ_LOCKED();
3713
3714 /* Iterate over all relayd since they are indexed by net_seq_idx. */
3715 cds_lfht_for_each_entry (the_consumer_data.relayd_ht->ht, &iter.iter, relayd, node.node) {
3716 /*
3717 * Check by sessiond id which is unique here where the relayd session
3718 * id might not be when having multiple relayd.
3719 */
3720 if (relayd->sessiond_session_id == id) {
3721 /* Found the relayd. There can be only one per id. */
3722 goto found;
3723 }
3724 }
3725
3726 return nullptr;
3727
3728 found:
3729 return relayd;
3730 }
3731
3732 /*
3733 * Check if for a given session id there is still data needed to be extract
3734 * from the buffers.
3735 *
3736 * Return 1 if data is pending or else 0 meaning ready to be read.
3737 */
3738 int consumer_data_pending(uint64_t id)
3739 {
3740 int ret;
3741 struct lttng_ht_iter iter;
3742 struct lttng_ht *ht;
3743 struct lttng_consumer_stream *stream;
3744 struct consumer_relayd_sock_pair *relayd = nullptr;
3745 int (*data_pending)(struct lttng_consumer_stream *);
3746
3747 DBG("Consumer data pending command on session id %" PRIu64, id);
3748
3749 lttng::urcu::read_lock_guard read_lock;
3750 pthread_mutex_lock(&the_consumer_data.lock);
3751
3752 switch (the_consumer_data.type) {
3753 case LTTNG_CONSUMER_KERNEL:
3754 data_pending = lttng_kconsumer_data_pending;
3755 break;
3756 case LTTNG_CONSUMER32_UST:
3757 case LTTNG_CONSUMER64_UST:
3758 data_pending = lttng_ustconsumer_data_pending;
3759 break;
3760 default:
3761 ERR("Unknown consumer data type");
3762 abort();
3763 }
3764
3765 /* Ease our life a bit */
3766 ht = the_consumer_data.stream_list_ht;
3767
3768 cds_lfht_for_each_entry_duplicate(ht->ht,
3769 ht->hash_fct(&id, lttng_ht_seed),
3770 ht->match_fct,
3771 &id,
3772 &iter.iter,
3773 stream,
3774 node_session_id.node)
3775 {
3776 pthread_mutex_lock(&stream->lock);
3777
3778 /*
3779 * A removed node from the hash table indicates that the stream has
3780 * been deleted thus having a guarantee that the buffers are closed
3781 * on the consumer side. However, data can still be transmitted
3782 * over the network so don't skip the relayd check.
3783 */
3784 ret = cds_lfht_is_node_deleted(&stream->node.node);
3785 if (!ret) {
3786 /* Check the stream if there is data in the buffers. */
3787 ret = data_pending(stream);
3788 if (ret == 1) {
3789 pthread_mutex_unlock(&stream->lock);
3790 goto data_pending;
3791 }
3792 }
3793
3794 pthread_mutex_unlock(&stream->lock);
3795 }
3796
3797 relayd = find_relayd_by_session_id(id);
3798 if (relayd) {
3799 unsigned int is_data_inflight = 0;
3800
3801 /* Send init command for data pending. */
3802 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
3803 ret = relayd_begin_data_pending(&relayd->control_sock, relayd->relayd_session_id);
3804 if (ret < 0) {
3805 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3806 /* Communication error thus the relayd so no data pending. */
3807 goto data_not_pending;
3808 }
3809
3810 cds_lfht_for_each_entry_duplicate(ht->ht,
3811 ht->hash_fct(&id, lttng_ht_seed),
3812 ht->match_fct,
3813 &id,
3814 &iter.iter,
3815 stream,
3816 node_session_id.node)
3817 {
3818 if (stream->metadata_flag) {
3819 ret = relayd_quiescent_control(&relayd->control_sock,
3820 stream->relayd_stream_id);
3821 } else {
3822 ret = relayd_data_pending(&relayd->control_sock,
3823 stream->relayd_stream_id,
3824 stream->next_net_seq_num - 1);
3825 }
3826
3827 if (ret == 1) {
3828 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3829 goto data_pending;
3830 } else if (ret < 0) {
3831 ERR("Relayd data pending failed. Cleaning up relayd %" PRIu64 ".",
3832 relayd->net_seq_idx);
3833 lttng_consumer_cleanup_relayd(relayd);
3834 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3835 goto data_not_pending;
3836 }
3837 }
3838
3839 /* Send end command for data pending. */
3840 ret = relayd_end_data_pending(
3841 &relayd->control_sock, relayd->relayd_session_id, &is_data_inflight);
3842 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3843 if (ret < 0) {
3844 ERR("Relayd end data pending failed. Cleaning up relayd %" PRIu64 ".",
3845 relayd->net_seq_idx);
3846 lttng_consumer_cleanup_relayd(relayd);
3847 goto data_not_pending;
3848 }
3849 if (is_data_inflight) {
3850 goto data_pending;
3851 }
3852 }
3853
3854 /*
3855 * Finding _no_ node in the hash table and no inflight data means that the
3856 * stream(s) have been removed thus data is guaranteed to be available for
3857 * analysis from the trace files.
3858 */
3859
3860 data_not_pending:
3861 /* Data is available to be read by a viewer. */
3862 pthread_mutex_unlock(&the_consumer_data.lock);
3863 return 0;
3864
3865 data_pending:
3866 /* Data is still being extracted from buffers. */
3867 pthread_mutex_unlock(&the_consumer_data.lock);
3868 return 1;
3869 }
3870
3871 /*
3872 * Send a ret code status message to the sessiond daemon.
3873 *
3874 * Return the sendmsg() return value.
3875 */
3876 int consumer_send_status_msg(int sock, int ret_code)
3877 {
3878 struct lttcomm_consumer_status_msg msg;
3879
3880 memset(&msg, 0, sizeof(msg));
3881 msg.ret_code = (lttcomm_return_code) ret_code;
3882
3883 return lttcomm_send_unix_sock(sock, &msg, sizeof(msg));
3884 }
3885
3886 /*
3887 * Send a channel status message to the sessiond daemon.
3888 *
3889 * Return the sendmsg() return value.
3890 */
3891 int consumer_send_status_channel(int sock, struct lttng_consumer_channel *channel)
3892 {
3893 struct lttcomm_consumer_status_channel msg;
3894
3895 LTTNG_ASSERT(sock >= 0);
3896
3897 memset(&msg, 0, sizeof(msg));
3898 if (!channel) {
3899 msg.ret_code = LTTCOMM_CONSUMERD_CHANNEL_FAIL;
3900 } else {
3901 msg.ret_code = LTTCOMM_CONSUMERD_SUCCESS;
3902 msg.key = channel->key;
3903 msg.stream_count = channel->streams.count;
3904 }
3905
3906 return lttcomm_send_unix_sock(sock, &msg, sizeof(msg));
3907 }
3908
3909 unsigned long consumer_get_consume_start_pos(unsigned long consumed_pos,
3910 unsigned long produced_pos,
3911 uint64_t nb_packets_per_stream,
3912 uint64_t max_sb_size)
3913 {
3914 unsigned long start_pos;
3915
3916 if (!nb_packets_per_stream) {
3917 return consumed_pos; /* Grab everything */
3918 }
3919 start_pos = produced_pos - lttng_offset_align_floor(produced_pos, max_sb_size);
3920 start_pos -= max_sb_size * nb_packets_per_stream;
3921 if ((long) (start_pos - consumed_pos) < 0) {
3922 return consumed_pos; /* Grab everything */
3923 }
3924 return start_pos;
3925 }
3926
3927 /* Stream lock must be held by the caller. */
3928 static int sample_stream_positions(struct lttng_consumer_stream *stream,
3929 unsigned long *produced,
3930 unsigned long *consumed)
3931 {
3932 int ret;
3933
3934 ASSERT_LOCKED(stream->lock);
3935
3936 ret = lttng_consumer_sample_snapshot_positions(stream);
3937 if (ret < 0) {
3938 ERR("Failed to sample snapshot positions");
3939 goto end;
3940 }
3941
3942 ret = lttng_consumer_get_produced_snapshot(stream, produced);
3943 if (ret < 0) {
3944 ERR("Failed to sample produced position");
3945 goto end;
3946 }
3947
3948 ret = lttng_consumer_get_consumed_snapshot(stream, consumed);
3949 if (ret < 0) {
3950 ERR("Failed to sample consumed position");
3951 goto end;
3952 }
3953
3954 end:
3955 return ret;
3956 }
3957
3958 /*
3959 * Sample the rotate position for all the streams of a channel. If a stream
3960 * is already at the rotate position (produced == consumed), we flag it as
3961 * ready for rotation. The rotation of ready streams occurs after we have
3962 * replied to the session daemon that we have finished sampling the positions.
3963 * Must be called with RCU read-side lock held to ensure existence of channel.
3964 *
3965 * Returns 0 on success, < 0 on error
3966 */
3967 int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
3968 uint64_t key,
3969 uint64_t relayd_id)
3970 {
3971 int ret;
3972 struct lttng_consumer_stream *stream;
3973 struct lttng_ht_iter iter;
3974 struct lttng_ht *ht = the_consumer_data.stream_per_chan_id_ht;
3975 struct lttng_dynamic_array stream_rotation_positions;
3976 uint64_t next_chunk_id, stream_count = 0;
3977 enum lttng_trace_chunk_status chunk_status;
3978 const bool is_local_trace = relayd_id == -1ULL;
3979 struct consumer_relayd_sock_pair *relayd = nullptr;
3980 bool rotating_to_new_chunk = true;
3981 /* Array of `struct lttng_consumer_stream *` */
3982 struct lttng_dynamic_pointer_array streams_packet_to_open;
3983 size_t stream_idx;
3984
3985 ASSERT_RCU_READ_LOCKED();
3986
3987 DBG("Consumer sample rotate position for channel %" PRIu64, key);
3988
3989 lttng_dynamic_array_init(&stream_rotation_positions,
3990 sizeof(struct relayd_stream_rotation_position),
3991 nullptr);
3992 lttng_dynamic_pointer_array_init(&streams_packet_to_open, nullptr);
3993
3994 lttng::urcu::read_lock_guard read_lock;
3995
3996 pthread_mutex_lock(&channel->lock);
3997 LTTNG_ASSERT(channel->trace_chunk);
3998 chunk_status = lttng_trace_chunk_get_id(channel->trace_chunk, &next_chunk_id);
3999 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4000 ret = -1;
4001 goto end_unlock_channel;
4002 }
4003
4004 cds_lfht_for_each_entry_duplicate(ht->ht,
4005 ht->hash_fct(&channel->key, lttng_ht_seed),
4006 ht->match_fct,
4007 &channel->key,
4008 &iter.iter,
4009 stream,
4010 node_channel_id.node)
4011 {
4012 unsigned long produced_pos = 0, consumed_pos = 0;
4013
4014 health_code_update();
4015
4016 /*
4017 * Lock stream because we are about to change its state.
4018 */
4019 pthread_mutex_lock(&stream->lock);
4020
4021 if (stream->trace_chunk == stream->chan->trace_chunk) {
4022 rotating_to_new_chunk = false;
4023 }
4024
4025 /*
4026 * Do not flush a packet when rotating from a NULL trace
4027 * chunk. The stream has no means to output data, and the prior
4028 * rotation which rotated to NULL performed that side-effect
4029 * already. No new data can be produced when a stream has no
4030 * associated trace chunk (e.g. a stop followed by a rotate).
4031 */
4032 if (stream->trace_chunk) {
4033 bool flush_active;
4034
4035 if (stream->metadata_flag) {
4036 /*
4037 * Don't produce an empty metadata packet,
4038 * simply close the current one.
4039 *
4040 * Metadata is regenerated on every trace chunk
4041 * switch; there is no concern that no data was
4042 * produced.
4043 */
4044 flush_active = true;
4045 } else {
4046 /*
4047 * Only flush an empty packet if the "packet
4048 * open" could not be performed on transition
4049 * to a new trace chunk and no packets were
4050 * consumed within the chunk's lifetime.
4051 */
4052 if (stream->opened_packet_in_current_trace_chunk) {
4053 flush_active = true;
4054 } else {
4055 /*
4056 * Stream could have been full at the
4057 * time of rotation, but then have had
4058 * no activity at all.
4059 *
4060 * It is important to flush a packet
4061 * to prevent 0-length files from being
4062 * produced as most viewers choke on
4063 * them.
4064 *
4065 * Unfortunately viewers will not be
4066 * able to know that tracing was active
4067 * for this stream during this trace
4068 * chunk's lifetime.
4069 */
4070 ret = sample_stream_positions(
4071 stream, &produced_pos, &consumed_pos);
4072 if (ret) {
4073 goto end_unlock_stream;
4074 }
4075
4076 /*
4077 * Don't flush an empty packet if data
4078 * was produced; it will be consumed
4079 * before the rotation completes.
4080 */
4081 flush_active = produced_pos != consumed_pos;
4082 if (!flush_active) {
4083 const char *trace_chunk_name;
4084 uint64_t trace_chunk_id;
4085
4086 chunk_status = lttng_trace_chunk_get_name(
4087 stream->trace_chunk,
4088 &trace_chunk_name,
4089 nullptr);
4090 if (chunk_status == LTTNG_TRACE_CHUNK_STATUS_NONE) {
4091 trace_chunk_name = "none";
4092 }
4093
4094 /*
4095 * Consumer trace chunks are
4096 * never anonymous.
4097 */
4098 chunk_status = lttng_trace_chunk_get_id(
4099 stream->trace_chunk, &trace_chunk_id);
4100 LTTNG_ASSERT(chunk_status ==
4101 LTTNG_TRACE_CHUNK_STATUS_OK);
4102
4103 DBG("Unable to open packet for stream during trace chunk's lifetime. "
4104 "Flushing an empty packet to prevent an empty file from being created: "
4105 "stream id = %" PRIu64
4106 ", trace chunk name = `%s`, trace chunk id = %" PRIu64,
4107 stream->key,
4108 trace_chunk_name,
4109 trace_chunk_id);
4110 }
4111 }
4112 }
4113
4114 /*
4115 * Close the current packet before sampling the
4116 * ring buffer positions.
4117 */
4118 ret = consumer_stream_flush_buffer(stream, flush_active);
4119 if (ret < 0) {
4120 ERR("Failed to flush stream %" PRIu64 " during channel rotation",
4121 stream->key);
4122 goto end_unlock_stream;
4123 }
4124 }
4125
4126 ret = lttng_consumer_take_snapshot(stream);
4127 if (ret < 0 && ret != -ENODATA && ret != -EAGAIN) {
4128 ERR("Failed to sample snapshot position during channel rotation");
4129 goto end_unlock_stream;
4130 }
4131 if (!ret) {
4132 ret = lttng_consumer_get_produced_snapshot(stream, &produced_pos);
4133 if (ret < 0) {
4134 ERR("Failed to sample produced position during channel rotation");
4135 goto end_unlock_stream;
4136 }
4137
4138 ret = lttng_consumer_get_consumed_snapshot(stream, &consumed_pos);
4139 if (ret < 0) {
4140 ERR("Failed to sample consumed position during channel rotation");
4141 goto end_unlock_stream;
4142 }
4143 }
4144 /*
4145 * Align produced position on the start-of-packet boundary of the first
4146 * packet going into the next trace chunk.
4147 */
4148 produced_pos = lttng_align_floor(produced_pos, stream->max_sb_size);
4149 if (consumed_pos == produced_pos) {
4150 DBG("Set rotate ready for stream %" PRIu64 " produced = %lu consumed = %lu",
4151 stream->key,
4152 produced_pos,
4153 consumed_pos);
4154 stream->rotate_ready = true;
4155 } else {
4156 DBG("Different consumed and produced positions "
4157 "for stream %" PRIu64 " produced = %lu consumed = %lu",
4158 stream->key,
4159 produced_pos,
4160 consumed_pos);
4161 }
4162 /*
4163 * The rotation position is based on the packet_seq_num of the
4164 * packet following the last packet that was consumed for this
4165 * stream, incremented by the offset between produced and
4166 * consumed positions. This rotation position is a lower bound
4167 * (inclusive) at which the next trace chunk starts. Since it
4168 * is a lower bound, it is OK if the packet_seq_num does not
4169 * correspond exactly to the same packet identified by the
4170 * consumed_pos, which can happen in overwrite mode.
4171 */
4172 if (stream->sequence_number_unavailable) {
4173 /*
4174 * Rotation should never be performed on a session which
4175 * interacts with a pre-2.8 lttng-modules, which does
4176 * not implement packet sequence number.
4177 */
4178 ERR("Failure to rotate stream %" PRIu64 ": sequence number unavailable",
4179 stream->key);
4180 ret = -1;
4181 goto end_unlock_stream;
4182 }
4183 stream->rotate_position = stream->last_sequence_number + 1 +
4184 ((produced_pos - consumed_pos) / stream->max_sb_size);
4185 DBG("Set rotation position for stream %" PRIu64 " at position %" PRIu64,
4186 stream->key,
4187 stream->rotate_position);
4188
4189 if (!is_local_trace) {
4190 /*
4191 * The relay daemon control protocol expects a rotation
4192 * position as "the sequence number of the first packet
4193 * _after_ the current trace chunk".
4194 */
4195 const struct relayd_stream_rotation_position position = {
4196 .stream_id = stream->relayd_stream_id,
4197 .rotate_at_seq_num = stream->rotate_position,
4198 };
4199
4200 ret = lttng_dynamic_array_add_element(&stream_rotation_positions,
4201 &position);
4202 if (ret) {
4203 ERR("Failed to allocate stream rotation position");
4204 goto end_unlock_stream;
4205 }
4206 stream_count++;
4207 }
4208
4209 stream->opened_packet_in_current_trace_chunk = false;
4210
4211 if (rotating_to_new_chunk && !stream->metadata_flag) {
4212 /*
4213 * Attempt to flush an empty packet as close to the
4214 * rotation point as possible. In the event where a
4215 * stream remains inactive after the rotation point,
4216 * this ensures that the new trace chunk has a
4217 * beginning timestamp set at the begining of the
4218 * trace chunk instead of only creating an empty
4219 * packet when the trace chunk is stopped.
4220 *
4221 * This indicates to the viewers that the stream
4222 * was being recorded, but more importantly it
4223 * allows viewers to determine a useable trace
4224 * intersection.
4225 *
4226 * This presents a problem in the case where the
4227 * ring-buffer is completely full.
4228 *
4229 * Consider the following scenario:
4230 * - The consumption of data is slow (slow network,
4231 * for instance),
4232 * - The ring buffer is full,
4233 * - A rotation is initiated,
4234 * - The flush below does nothing (no space left to
4235 * open a new packet),
4236 * - The other streams rotate very soon, and new
4237 * data is produced in the new chunk,
4238 * - This stream completes its rotation long after the
4239 * rotation was initiated
4240 * - The session is stopped before any event can be
4241 * produced in this stream's buffers.
4242 *
4243 * The resulting trace chunk will have a single packet
4244 * temporaly at the end of the trace chunk for this
4245 * stream making the stream intersection more narrow
4246 * than it should be.
4247 *
4248 * To work-around this, an empty flush is performed
4249 * after the first consumption of a packet during a
4250 * rotation if open_packet fails. The idea is that
4251 * consuming a packet frees enough space to switch
4252 * packets in this scenario and allows the tracer to
4253 * "stamp" the beginning of the new trace chunk at the
4254 * earliest possible point.
4255 *
4256 * The packet open is performed after the channel
4257 * rotation to ensure that no attempt to open a packet
4258 * is performed in a stream that has no active trace
4259 * chunk.
4260 */
4261 ret = lttng_dynamic_pointer_array_add_pointer(&streams_packet_to_open,
4262 stream);
4263 if (ret) {
4264 PERROR("Failed to add a stream pointer to array of streams in which to open a packet");
4265 ret = -1;
4266 goto end_unlock_stream;
4267 }
4268 }
4269
4270 pthread_mutex_unlock(&stream->lock);
4271 }
4272 stream = nullptr;
4273
4274 if (!is_local_trace) {
4275 relayd = consumer_find_relayd(relayd_id);
4276 if (!relayd) {
4277 ERR("Failed to find relayd %" PRIu64, relayd_id);
4278 ret = -1;
4279 goto end_unlock_channel;
4280 }
4281
4282 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
4283 ret = relayd_rotate_streams(&relayd->control_sock,
4284 stream_count,
4285 rotating_to_new_chunk ? &next_chunk_id : nullptr,
4286 (const struct relayd_stream_rotation_position *)
4287 stream_rotation_positions.buffer.data);
4288 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
4289 if (ret < 0) {
4290 ERR("Relayd rotate stream failed. Cleaning up relayd %" PRIu64,
4291 relayd->net_seq_idx);
4292 lttng_consumer_cleanup_relayd(relayd);
4293 goto end_unlock_channel;
4294 }
4295 }
4296
4297 for (stream_idx = 0;
4298 stream_idx < lttng_dynamic_pointer_array_get_count(&streams_packet_to_open);
4299 stream_idx++) {
4300 enum consumer_stream_open_packet_status status;
4301
4302 stream = (lttng_consumer_stream *) lttng_dynamic_pointer_array_get_pointer(
4303 &streams_packet_to_open, stream_idx);
4304
4305 pthread_mutex_lock(&stream->lock);
4306 status = consumer_stream_open_packet(stream);
4307 pthread_mutex_unlock(&stream->lock);
4308 switch (status) {
4309 case CONSUMER_STREAM_OPEN_PACKET_STATUS_OPENED:
4310 DBG("Opened a packet after a rotation: stream id = %" PRIu64
4311 ", channel name = %s, session id = %" PRIu64,
4312 stream->key,
4313 stream->chan->name,
4314 stream->chan->session_id);
4315 break;
4316 case CONSUMER_STREAM_OPEN_PACKET_STATUS_NO_SPACE:
4317 /*
4318 * Can't open a packet as there is no space left
4319 * in the buffer. A new packet will be opened
4320 * once one has been consumed.
4321 */
4322 DBG("No space left to open a packet after a rotation: stream id = %" PRIu64
4323 ", channel name = %s, session id = %" PRIu64,
4324 stream->key,
4325 stream->chan->name,
4326 stream->chan->session_id);
4327 break;
4328 case CONSUMER_STREAM_OPEN_PACKET_STATUS_ERROR:
4329 /* Logged by callee. */
4330 ret = -1;
4331 goto end_unlock_channel;
4332 default:
4333 abort();
4334 }
4335 }
4336
4337 pthread_mutex_unlock(&channel->lock);
4338 ret = 0;
4339 goto end;
4340
4341 end_unlock_stream:
4342 pthread_mutex_unlock(&stream->lock);
4343 end_unlock_channel:
4344 pthread_mutex_unlock(&channel->lock);
4345 end:
4346 lttng_dynamic_array_reset(&stream_rotation_positions);
4347 lttng_dynamic_pointer_array_reset(&streams_packet_to_open);
4348 return ret;
4349 }
4350
4351 static int consumer_clear_buffer(struct lttng_consumer_stream *stream)
4352 {
4353 int ret = 0;
4354 unsigned long consumed_pos_before, consumed_pos_after;
4355
4356 ret = lttng_consumer_sample_snapshot_positions(stream);
4357 if (ret < 0) {
4358 ERR("Taking snapshot positions");
4359 goto end;
4360 }
4361
4362 ret = lttng_consumer_get_consumed_snapshot(stream, &consumed_pos_before);
4363 if (ret < 0) {
4364 ERR("Consumed snapshot position");
4365 goto end;
4366 }
4367
4368 switch (the_consumer_data.type) {
4369 case LTTNG_CONSUMER_KERNEL:
4370 ret = kernctl_buffer_clear(stream->wait_fd);
4371 if (ret < 0) {
4372 ERR("Failed to clear kernel stream (ret = %d)", ret);
4373 goto end;
4374 }
4375 break;
4376 case LTTNG_CONSUMER32_UST:
4377 case LTTNG_CONSUMER64_UST:
4378 ret = lttng_ustconsumer_clear_buffer(stream);
4379 if (ret < 0) {
4380 ERR("Failed to clear ust stream (ret = %d)", ret);
4381 goto end;
4382 }
4383 break;
4384 default:
4385 ERR("Unknown consumer_data type");
4386 abort();
4387 }
4388
4389 ret = lttng_consumer_sample_snapshot_positions(stream);
4390 if (ret < 0) {
4391 ERR("Taking snapshot positions");
4392 goto end;
4393 }
4394 ret = lttng_consumer_get_consumed_snapshot(stream, &consumed_pos_after);
4395 if (ret < 0) {
4396 ERR("Consumed snapshot position");
4397 goto end;
4398 }
4399 DBG("clear: before: %lu after: %lu", consumed_pos_before, consumed_pos_after);
4400 end:
4401 return ret;
4402 }
4403
4404 static int consumer_clear_stream(struct lttng_consumer_stream *stream)
4405 {
4406 int ret;
4407
4408 ret = consumer_stream_flush_buffer(stream, true);
4409 if (ret < 0) {
4410 ERR("Failed to flush stream %" PRIu64 " during channel clear", stream->key);
4411 ret = LTTCOMM_CONSUMERD_FATAL;
4412 goto error;
4413 }
4414
4415 ret = consumer_clear_buffer(stream);
4416 if (ret < 0) {
4417 ERR("Failed to clear stream %" PRIu64 " during channel clear", stream->key);
4418 ret = LTTCOMM_CONSUMERD_FATAL;
4419 goto error;
4420 }
4421
4422 ret = LTTCOMM_CONSUMERD_SUCCESS;
4423 error:
4424 return ret;
4425 }
4426
4427 static int consumer_clear_unmonitored_channel(struct lttng_consumer_channel *channel)
4428 {
4429 int ret;
4430 struct lttng_consumer_stream *stream;
4431
4432 lttng::urcu::read_lock_guard read_lock;
4433 pthread_mutex_lock(&channel->lock);
4434 cds_list_for_each_entry (stream, &channel->streams.head, send_node) {
4435 health_code_update();
4436 pthread_mutex_lock(&stream->lock);
4437 ret = consumer_clear_stream(stream);
4438 if (ret) {
4439 goto error_unlock;
4440 }
4441 pthread_mutex_unlock(&stream->lock);
4442 }
4443 pthread_mutex_unlock(&channel->lock);
4444 return 0;
4445
4446 error_unlock:
4447 pthread_mutex_unlock(&stream->lock);
4448 pthread_mutex_unlock(&channel->lock);
4449 return ret;
4450 }
4451
4452 /*
4453 * Check if a stream is ready to be rotated after extracting it.
4454 *
4455 * Return 1 if it is ready for rotation, 0 if it is not, a negative value on
4456 * error. Stream lock must be held.
4457 */
4458 int lttng_consumer_stream_is_rotate_ready(struct lttng_consumer_stream *stream)
4459 {
4460 DBG("Check is rotate ready for stream %" PRIu64 " ready %u rotate_position %" PRIu64
4461 " last_sequence_number %" PRIu64,
4462 stream->key,
4463 stream->rotate_ready,
4464 stream->rotate_position,
4465 stream->last_sequence_number);
4466 if (stream->rotate_ready) {
4467 return 1;
4468 }
4469
4470 /*
4471 * If packet seq num is unavailable, it means we are interacting
4472 * with a pre-2.8 lttng-modules which does not implement the
4473 * sequence number. Rotation should never be used by sessiond in this
4474 * scenario.
4475 */
4476 if (stream->sequence_number_unavailable) {
4477 ERR("Internal error: rotation used on stream %" PRIu64
4478 " with unavailable sequence number",
4479 stream->key);
4480 return -1;
4481 }
4482
4483 if (stream->rotate_position == -1ULL || stream->last_sequence_number == -1ULL) {
4484 return 0;
4485 }
4486
4487 /*
4488 * Rotate position not reached yet. The stream rotate position is
4489 * the position of the next packet belonging to the next trace chunk,
4490 * but consumerd considers rotation ready when reaching the last
4491 * packet of the current chunk, hence the "rotate_position - 1".
4492 */
4493
4494 DBG("Check is rotate ready for stream %" PRIu64 " last_sequence_number %" PRIu64
4495 " rotate_position %" PRIu64,
4496 stream->key,
4497 stream->last_sequence_number,
4498 stream->rotate_position);
4499 if (stream->last_sequence_number >= stream->rotate_position - 1) {
4500 return 1;
4501 }
4502
4503 return 0;
4504 }
4505
4506 /*
4507 * Reset the state for a stream after a rotation occurred.
4508 */
4509 void lttng_consumer_reset_stream_rotate_state(struct lttng_consumer_stream *stream)
4510 {
4511 DBG("lttng_consumer_reset_stream_rotate_state for stream %" PRIu64, stream->key);
4512 stream->rotate_position = -1ULL;
4513 stream->rotate_ready = false;
4514 }
4515
4516 /*
4517 * Perform the rotation a local stream file.
4518 */
4519 static int rotate_local_stream(struct lttng_consumer_stream *stream)
4520 {
4521 int ret = 0;
4522
4523 DBG("Rotate local stream: stream key %" PRIu64 ", channel key %" PRIu64,
4524 stream->key,
4525 stream->chan->key);
4526 stream->tracefile_size_current = 0;
4527 stream->tracefile_count_current = 0;
4528
4529 if (stream->out_fd >= 0) {
4530 ret = close(stream->out_fd);
4531 if (ret) {
4532 PERROR("Failed to close stream out_fd of channel \"%s\"",
4533 stream->chan->name);
4534 }
4535 stream->out_fd = -1;
4536 }
4537
4538 if (stream->index_file) {
4539 lttng_index_file_put(stream->index_file);
4540 stream->index_file = nullptr;
4541 }
4542
4543 if (!stream->trace_chunk) {
4544 goto end;
4545 }
4546
4547 ret = consumer_stream_create_output_files(stream, true);
4548 end:
4549 return ret;
4550 }
4551
4552 /*
4553 * Performs the stream rotation for the rotate session feature if needed.
4554 * It must be called with the channel and stream locks held.
4555 *
4556 * Return 0 on success, a negative number of error.
4557 */
4558 int lttng_consumer_rotate_stream(struct lttng_consumer_stream *stream)
4559 {
4560 int ret;
4561
4562 DBG("Consumer rotate stream %" PRIu64, stream->key);
4563
4564 /*
4565 * Update the stream's 'current' chunk to the session's (channel)
4566 * now-current chunk.
4567 */
4568 lttng_trace_chunk_put(stream->trace_chunk);
4569 if (stream->chan->trace_chunk == stream->trace_chunk) {
4570 /*
4571 * A channel can be rotated and not have a "next" chunk
4572 * to transition to. In that case, the channel's "current chunk"
4573 * has not been closed yet, but it has not been updated to
4574 * a "next" trace chunk either. Hence, the stream, like its
4575 * parent channel, becomes part of no chunk and can't output
4576 * anything until a new trace chunk is created.
4577 */
4578 stream->trace_chunk = nullptr;
4579 } else if (stream->chan->trace_chunk && !lttng_trace_chunk_get(stream->chan->trace_chunk)) {
4580 ERR("Failed to acquire a reference to channel's trace chunk during stream rotation");
4581 ret = -1;
4582 goto error;
4583 } else {
4584 /*
4585 * Update the stream's trace chunk to its parent channel's
4586 * current trace chunk.
4587 */
4588 stream->trace_chunk = stream->chan->trace_chunk;
4589 }
4590
4591 if (stream->net_seq_idx == (uint64_t) -1ULL) {
4592 ret = rotate_local_stream(stream);
4593 if (ret < 0) {
4594 ERR("Failed to rotate stream, ret = %i", ret);
4595 goto error;
4596 }
4597 }
4598
4599 if (stream->metadata_flag && stream->trace_chunk) {
4600 /*
4601 * If the stream has transitioned to a new trace
4602 * chunk, the metadata should be re-dumped to the
4603 * newest chunk.
4604 *
4605 * However, it is possible for a stream to transition to
4606 * a "no-chunk" state. This can happen if a rotation
4607 * occurs on an inactive session. In such cases, the metadata
4608 * regeneration will happen when the next trace chunk is
4609 * created.
4610 */
4611 ret = consumer_metadata_stream_dump(stream);
4612 if (ret) {
4613 goto error;
4614 }
4615 }
4616 lttng_consumer_reset_stream_rotate_state(stream);
4617
4618 ret = 0;
4619
4620 error:
4621 return ret;
4622 }
4623
4624 /*
4625 * Rotate all the ready streams now.
4626 *
4627 * This is especially important for low throughput streams that have already
4628 * been consumed, we cannot wait for their next packet to perform the
4629 * rotation.
4630 * Need to be called with RCU read-side lock held to ensure existence of
4631 * channel.
4632 *
4633 * Returns 0 on success, < 0 on error
4634 */
4635 int lttng_consumer_rotate_ready_streams(struct lttng_consumer_channel *channel, uint64_t key)
4636 {
4637 int ret;
4638 struct lttng_consumer_stream *stream;
4639 struct lttng_ht_iter iter;
4640 struct lttng_ht *ht = the_consumer_data.stream_per_chan_id_ht;
4641
4642 ASSERT_RCU_READ_LOCKED();
4643
4644 lttng::urcu::read_lock_guard read_lock;
4645
4646 DBG("Consumer rotate ready streams in channel %" PRIu64, key);
4647
4648 cds_lfht_for_each_entry_duplicate(ht->ht,
4649 ht->hash_fct(&channel->key, lttng_ht_seed),
4650 ht->match_fct,
4651 &channel->key,
4652 &iter.iter,
4653 stream,
4654 node_channel_id.node)
4655 {
4656 health_code_update();
4657
4658 pthread_mutex_lock(&stream->chan->lock);
4659 pthread_mutex_lock(&stream->lock);
4660
4661 if (!stream->rotate_ready) {
4662 pthread_mutex_unlock(&stream->lock);
4663 pthread_mutex_unlock(&stream->chan->lock);
4664 continue;
4665 }
4666 DBG("Consumer rotate ready stream %" PRIu64, stream->key);
4667
4668 ret = lttng_consumer_rotate_stream(stream);
4669 pthread_mutex_unlock(&stream->lock);
4670 pthread_mutex_unlock(&stream->chan->lock);
4671 if (ret) {
4672 goto end;
4673 }
4674 }
4675
4676 ret = 0;
4677
4678 end:
4679 return ret;
4680 }
4681
4682 enum lttcomm_return_code lttng_consumer_init_command(struct lttng_consumer_local_data *ctx,
4683 const lttng_uuid& sessiond_uuid)
4684 {
4685 enum lttcomm_return_code ret;
4686 char uuid_str[LTTNG_UUID_STR_LEN];
4687
4688 if (ctx->sessiond_uuid.is_set) {
4689 ret = LTTCOMM_CONSUMERD_ALREADY_SET;
4690 goto end;
4691 }
4692
4693 ctx->sessiond_uuid.is_set = true;
4694 ctx->sessiond_uuid.value = sessiond_uuid;
4695 ret = LTTCOMM_CONSUMERD_SUCCESS;
4696 lttng_uuid_to_str(sessiond_uuid, uuid_str);
4697 DBG("Received session daemon UUID: %s", uuid_str);
4698 end:
4699 return ret;
4700 }
4701
4702 enum lttcomm_return_code
4703 lttng_consumer_create_trace_chunk(const uint64_t *relayd_id,
4704 uint64_t session_id,
4705 uint64_t chunk_id,
4706 time_t chunk_creation_timestamp,
4707 const char *chunk_override_name,
4708 const struct lttng_credentials *credentials,
4709 struct lttng_directory_handle *chunk_directory_handle)
4710 {
4711 int ret;
4712 enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
4713 struct lttng_trace_chunk *created_chunk = nullptr, *published_chunk = nullptr;
4714 enum lttng_trace_chunk_status chunk_status;
4715 char relayd_id_buffer[MAX_INT_DEC_LEN(*relayd_id)];
4716 char creation_timestamp_buffer[ISO8601_STR_LEN];
4717 const char *relayd_id_str = "(none)";
4718 const char *creation_timestamp_str;
4719 struct lttng_ht_iter iter;
4720 struct lttng_consumer_channel *channel;
4721
4722 if (relayd_id) {
4723 /* Only used for logging purposes. */
4724 ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer), "%" PRIu64, *relayd_id);
4725 if (ret > 0 && ret < sizeof(relayd_id_buffer)) {
4726 relayd_id_str = relayd_id_buffer;
4727 } else {
4728 relayd_id_str = "(formatting error)";
4729 }
4730 }
4731
4732 /* Local protocol error. */
4733 LTTNG_ASSERT(chunk_creation_timestamp);
4734 ret = time_to_iso8601_str(chunk_creation_timestamp,
4735 creation_timestamp_buffer,
4736 sizeof(creation_timestamp_buffer));
4737 creation_timestamp_str = !ret ? creation_timestamp_buffer : "(formatting error)";
4738
4739 DBG("Consumer create trace chunk command: relay_id = %s"
4740 ", session_id = %" PRIu64 ", chunk_id = %" PRIu64 ", chunk_override_name = %s"
4741 ", chunk_creation_timestamp = %s",
4742 relayd_id_str,
4743 session_id,
4744 chunk_id,
4745 chunk_override_name ?: "(none)",
4746 creation_timestamp_str);
4747
4748 /*
4749 * The trace chunk registry, as used by the consumer daemon, implicitly
4750 * owns the trace chunks. This is only needed in the consumer since
4751 * the consumer has no notion of a session beyond session IDs being
4752 * used to identify other objects.
4753 *
4754 * The lttng_trace_chunk_registry_publish() call below provides a
4755 * reference which is not released; it implicitly becomes the session
4756 * daemon's reference to the chunk in the consumer daemon.
4757 *
4758 * The lifetime of trace chunks in the consumer daemon is managed by
4759 * the session daemon through the LTTNG_CONSUMER_CREATE_TRACE_CHUNK
4760 * and LTTNG_CONSUMER_DESTROY_TRACE_CHUNK commands.
4761 */
4762 created_chunk = lttng_trace_chunk_create(chunk_id, chunk_creation_timestamp, nullptr);
4763 if (!created_chunk) {
4764 ERR("Failed to create trace chunk");
4765 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4766 goto error;
4767 }
4768
4769 if (chunk_override_name) {
4770 chunk_status = lttng_trace_chunk_override_name(created_chunk, chunk_override_name);
4771 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4772 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4773 goto error;
4774 }
4775 }
4776
4777 if (chunk_directory_handle) {
4778 chunk_status = lttng_trace_chunk_set_credentials(created_chunk, credentials);
4779 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4780 ERR("Failed to set trace chunk credentials");
4781 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4782 goto error;
4783 }
4784 /*
4785 * The consumer daemon has no ownership of the chunk output
4786 * directory.
4787 */
4788 chunk_status = lttng_trace_chunk_set_as_user(created_chunk, chunk_directory_handle);
4789 chunk_directory_handle = nullptr;
4790 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4791 ERR("Failed to set trace chunk's directory handle");
4792 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4793 goto error;
4794 }
4795 }
4796
4797 published_chunk = lttng_trace_chunk_registry_publish_chunk(
4798 the_consumer_data.chunk_registry, session_id, created_chunk);
4799 lttng_trace_chunk_put(created_chunk);
4800 created_chunk = nullptr;
4801 if (!published_chunk) {
4802 ERR("Failed to publish trace chunk");
4803 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4804 goto error;
4805 }
4806
4807 {
4808 lttng::urcu::read_lock_guard read_lock;
4809 cds_lfht_for_each_entry_duplicate(
4810 the_consumer_data.channels_by_session_id_ht->ht,
4811 the_consumer_data.channels_by_session_id_ht->hash_fct(&session_id,
4812 lttng_ht_seed),
4813 the_consumer_data.channels_by_session_id_ht->match_fct,
4814 &session_id,
4815 &iter.iter,
4816 channel,
4817 channels_by_session_id_ht_node.node)
4818 {
4819 ret = lttng_consumer_channel_set_trace_chunk(channel, published_chunk);
4820 if (ret) {
4821 /*
4822 * Roll-back the creation of this chunk.
4823 *
4824 * This is important since the session daemon will
4825 * assume that the creation of this chunk failed and
4826 * will never ask for it to be closed, resulting
4827 * in a leak and an inconsistent state for some
4828 * channels.
4829 */
4830 enum lttcomm_return_code close_ret;
4831 char path[LTTNG_PATH_MAX];
4832
4833 DBG("Failed to set new trace chunk on existing channels, rolling back");
4834 close_ret =
4835 lttng_consumer_close_trace_chunk(relayd_id,
4836 session_id,
4837 chunk_id,
4838 chunk_creation_timestamp,
4839 nullptr,
4840 path);
4841 if (close_ret != LTTCOMM_CONSUMERD_SUCCESS) {
4842 ERR("Failed to roll-back the creation of new chunk: session_id = %" PRIu64
4843 ", chunk_id = %" PRIu64,
4844 session_id,
4845 chunk_id);
4846 }
4847
4848 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4849 break;
4850 }
4851 }
4852 }
4853
4854 if (relayd_id) {
4855 struct consumer_relayd_sock_pair *relayd;
4856
4857 relayd = consumer_find_relayd(*relayd_id);
4858 if (relayd) {
4859 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
4860 ret = relayd_create_trace_chunk(&relayd->control_sock, published_chunk);
4861 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
4862 } else {
4863 ERR("Failed to find relay daemon socket: relayd_id = %" PRIu64, *relayd_id);
4864 }
4865
4866 if (!relayd || ret) {
4867 enum lttcomm_return_code close_ret;
4868 char path[LTTNG_PATH_MAX];
4869
4870 close_ret = lttng_consumer_close_trace_chunk(relayd_id,
4871 session_id,
4872 chunk_id,
4873 chunk_creation_timestamp,
4874 nullptr,
4875 path);
4876 if (close_ret != LTTCOMM_CONSUMERD_SUCCESS) {
4877 ERR("Failed to roll-back the creation of new chunk: session_id = %" PRIu64
4878 ", chunk_id = %" PRIu64,
4879 session_id,
4880 chunk_id);
4881 }
4882
4883 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4884 goto error_unlock;
4885 }
4886 }
4887 error_unlock:
4888 error:
4889 /* Release the reference returned by the "publish" operation. */
4890 lttng_trace_chunk_put(published_chunk);
4891 lttng_trace_chunk_put(created_chunk);
4892 return ret_code;
4893 }
4894
4895 enum lttcomm_return_code
4896 lttng_consumer_close_trace_chunk(const uint64_t *relayd_id,
4897 uint64_t session_id,
4898 uint64_t chunk_id,
4899 time_t chunk_close_timestamp,
4900 const enum lttng_trace_chunk_command_type *close_command,
4901 char *path)
4902 {
4903 enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
4904 struct lttng_trace_chunk *chunk;
4905 char relayd_id_buffer[MAX_INT_DEC_LEN(*relayd_id)];
4906 const char *relayd_id_str = "(none)";
4907 const char *close_command_name = "none";
4908 struct lttng_ht_iter iter;
4909 struct lttng_consumer_channel *channel;
4910 enum lttng_trace_chunk_status chunk_status;
4911
4912 if (relayd_id) {
4913 int ret;
4914
4915 /* Only used for logging purposes. */
4916 ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer), "%" PRIu64, *relayd_id);
4917 if (ret > 0 && ret < sizeof(relayd_id_buffer)) {
4918 relayd_id_str = relayd_id_buffer;
4919 } else {
4920 relayd_id_str = "(formatting error)";
4921 }
4922 }
4923 if (close_command) {
4924 close_command_name = lttng_trace_chunk_command_type_get_name(*close_command);
4925 }
4926
4927 DBG("Consumer close trace chunk command: relayd_id = %s"
4928 ", session_id = %" PRIu64 ", chunk_id = %" PRIu64 ", close command = %s",
4929 relayd_id_str,
4930 session_id,
4931 chunk_id,
4932 close_command_name);
4933
4934 chunk = lttng_trace_chunk_registry_find_chunk(
4935 the_consumer_data.chunk_registry, session_id, chunk_id);
4936 if (!chunk) {
4937 ERR("Failed to find chunk: session_id = %" PRIu64 ", chunk_id = %" PRIu64,
4938 session_id,
4939 chunk_id);
4940 ret_code = LTTCOMM_CONSUMERD_UNKNOWN_TRACE_CHUNK;
4941 goto end;
4942 }
4943
4944 chunk_status = lttng_trace_chunk_set_close_timestamp(chunk, chunk_close_timestamp);
4945 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4946 ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
4947 goto end;
4948 }
4949
4950 if (close_command) {
4951 chunk_status = lttng_trace_chunk_set_close_command(chunk, *close_command);
4952 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4953 ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
4954 goto end;
4955 }
4956 }
4957
4958 /*
4959 * chunk is now invalid to access as we no longer hold a reference to
4960 * it; it is only kept around to compare it (by address) to the
4961 * current chunk found in the session's channels.
4962 */
4963 {
4964 lttng::urcu::read_lock_guard read_lock;
4965 cds_lfht_for_each_entry (
4966 the_consumer_data.channel_ht->ht, &iter.iter, channel, node.node) {
4967 int ret;
4968
4969 /*
4970 * Only change the channel's chunk to NULL if it still
4971 * references the chunk being closed. The channel may
4972 * reference a newer channel in the case of a session
4973 * rotation. When a session rotation occurs, the "next"
4974 * chunk is created before the "current" chunk is closed.
4975 */
4976 if (channel->trace_chunk != chunk) {
4977 continue;
4978 }
4979 ret = lttng_consumer_channel_set_trace_chunk(channel, nullptr);
4980 if (ret) {
4981 /*
4982 * Attempt to close the chunk on as many channels as
4983 * possible.
4984 */
4985 ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
4986 }
4987 }
4988 }
4989 if (relayd_id) {
4990 int ret;
4991 struct consumer_relayd_sock_pair *relayd;
4992
4993 relayd = consumer_find_relayd(*relayd_id);
4994 if (relayd) {
4995 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
4996 ret = relayd_close_trace_chunk(&relayd->control_sock, chunk, path);
4997 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
4998 } else {
4999 ERR("Failed to find relay daemon socket: relayd_id = %" PRIu64, *relayd_id);
5000 }
5001
5002 if (!relayd || ret) {
5003 ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
5004 goto error_unlock;
5005 }
5006 }
5007 error_unlock:
5008 end:
5009 /*
5010 * Release the reference returned by the "find" operation and
5011 * the session daemon's implicit reference to the chunk.
5012 */
5013 lttng_trace_chunk_put(chunk);
5014 lttng_trace_chunk_put(chunk);
5015
5016 return ret_code;
5017 }
5018
5019 enum lttcomm_return_code
5020 lttng_consumer_trace_chunk_exists(const uint64_t *relayd_id, uint64_t session_id, uint64_t chunk_id)
5021 {
5022 int ret;
5023 enum lttcomm_return_code ret_code;
5024 char relayd_id_buffer[MAX_INT_DEC_LEN(*relayd_id)];
5025 const char *relayd_id_str = "(none)";
5026 const bool is_local_trace = !relayd_id;
5027 struct consumer_relayd_sock_pair *relayd = nullptr;
5028 bool chunk_exists_local, chunk_exists_remote;
5029 lttng::urcu::read_lock_guard read_lock;
5030
5031 if (relayd_id) {
5032 /* Only used for logging purposes. */
5033 ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer), "%" PRIu64, *relayd_id);
5034 if (ret > 0 && ret < sizeof(relayd_id_buffer)) {
5035 relayd_id_str = relayd_id_buffer;
5036 } else {
5037 relayd_id_str = "(formatting error)";
5038 }
5039 }
5040
5041 DBG("Consumer trace chunk exists command: relayd_id = %s"
5042 ", chunk_id = %" PRIu64,
5043 relayd_id_str,
5044 chunk_id);
5045 ret = lttng_trace_chunk_registry_chunk_exists(
5046 the_consumer_data.chunk_registry, session_id, chunk_id, &chunk_exists_local);
5047 if (ret) {
5048 /* Internal error. */
5049 ERR("Failed to query the existence of a trace chunk");
5050 ret_code = LTTCOMM_CONSUMERD_FATAL;
5051 goto end;
5052 }
5053 DBG("Trace chunk %s locally", chunk_exists_local ? "exists" : "does not exist");
5054 if (chunk_exists_local) {
5055 ret_code = LTTCOMM_CONSUMERD_TRACE_CHUNK_EXISTS_LOCAL;
5056 goto end;
5057 } else if (is_local_trace) {
5058 ret_code = LTTCOMM_CONSUMERD_UNKNOWN_TRACE_CHUNK;
5059 goto end;
5060 }
5061
5062 relayd = consumer_find_relayd(*relayd_id);
5063 if (!relayd) {
5064 ERR("Failed to find relayd %" PRIu64, *relayd_id);
5065 ret_code = LTTCOMM_CONSUMERD_INVALID_PARAMETERS;
5066 goto end_rcu_unlock;
5067 }
5068 DBG("Looking up existence of trace chunk on relay daemon");
5069 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
5070 ret = relayd_trace_chunk_exists(&relayd->control_sock, chunk_id, &chunk_exists_remote);
5071 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
5072 if (ret < 0) {
5073 ERR("Failed to look-up the existence of trace chunk on relay daemon");
5074 ret_code = LTTCOMM_CONSUMERD_RELAYD_FAIL;
5075 goto end_rcu_unlock;
5076 }
5077
5078 ret_code = chunk_exists_remote ? LTTCOMM_CONSUMERD_TRACE_CHUNK_EXISTS_REMOTE :
5079 LTTCOMM_CONSUMERD_UNKNOWN_TRACE_CHUNK;
5080 DBG("Trace chunk %s on relay daemon", chunk_exists_remote ? "exists" : "does not exist");
5081
5082 end_rcu_unlock:
5083 end:
5084 return ret_code;
5085 }
5086
5087 static int consumer_clear_monitored_channel(struct lttng_consumer_channel *channel)
5088 {
5089 struct lttng_ht *ht;
5090 struct lttng_consumer_stream *stream;
5091 struct lttng_ht_iter iter;
5092 int ret;
5093
5094 ht = the_consumer_data.stream_per_chan_id_ht;
5095
5096 lttng::urcu::read_lock_guard read_lock;
5097 cds_lfht_for_each_entry_duplicate(ht->ht,
5098 ht->hash_fct(&channel->key, lttng_ht_seed),
5099 ht->match_fct,
5100 &channel->key,
5101 &iter.iter,
5102 stream,
5103 node_channel_id.node)
5104 {
5105 /*
5106 * Protect against teardown with mutex.
5107 */
5108 pthread_mutex_lock(&stream->lock);
5109 if (cds_lfht_is_node_deleted(&stream->node.node)) {
5110 goto next;
5111 }
5112 ret = consumer_clear_stream(stream);
5113 if (ret) {
5114 goto error_unlock;
5115 }
5116 next:
5117 pthread_mutex_unlock(&stream->lock);
5118 }
5119 return LTTCOMM_CONSUMERD_SUCCESS;
5120
5121 error_unlock:
5122 pthread_mutex_unlock(&stream->lock);
5123 return ret;
5124 }
5125
5126 int lttng_consumer_clear_channel(struct lttng_consumer_channel *channel)
5127 {
5128 int ret;
5129
5130 DBG("Consumer clear channel %" PRIu64, channel->key);
5131
5132 if (channel->type == CONSUMER_CHANNEL_TYPE_METADATA) {
5133 /*
5134 * Nothing to do for the metadata channel/stream.
5135 * Snapshot mechanism already take care of the metadata
5136 * handling/generation, and monitored channels only need to
5137 * have their data stream cleared..
5138 */
5139 ret = LTTCOMM_CONSUMERD_SUCCESS;
5140 goto end;
5141 }
5142
5143 if (!channel->monitor) {
5144 ret = consumer_clear_unmonitored_channel(channel);
5145 } else {
5146 ret = consumer_clear_monitored_channel(channel);
5147 }
5148 end:
5149 return ret;
5150 }
5151
5152 enum lttcomm_return_code lttng_consumer_open_channel_packets(struct lttng_consumer_channel *channel)
5153 {
5154 struct lttng_consumer_stream *stream;
5155 enum lttcomm_return_code ret = LTTCOMM_CONSUMERD_SUCCESS;
5156
5157 if (channel->metadata_stream) {
5158 ERR("Open channel packets command attempted on a metadata channel");
5159 ret = LTTCOMM_CONSUMERD_INVALID_PARAMETERS;
5160 goto end;
5161 }
5162
5163 {
5164 lttng::urcu::read_lock_guard read_lock;
5165 cds_list_for_each_entry (stream, &channel->streams.head, send_node) {
5166 enum consumer_stream_open_packet_status status;
5167
5168 pthread_mutex_lock(&stream->lock);
5169 if (cds_lfht_is_node_deleted(&stream->node.node)) {
5170 goto next;
5171 }
5172
5173 status = consumer_stream_open_packet(stream);
5174 switch (status) {
5175 case CONSUMER_STREAM_OPEN_PACKET_STATUS_OPENED:
5176 DBG("Opened a packet in \"open channel packets\" command: stream id = %" PRIu64
5177 ", channel name = %s, session id = %" PRIu64,
5178 stream->key,
5179 stream->chan->name,
5180 stream->chan->session_id);
5181 stream->opened_packet_in_current_trace_chunk = true;
5182 break;
5183 case CONSUMER_STREAM_OPEN_PACKET_STATUS_NO_SPACE:
5184 DBG("No space left to open a packet in \"open channel packets\" command: stream id = %" PRIu64
5185 ", channel name = %s, session id = %" PRIu64,
5186 stream->key,
5187 stream->chan->name,
5188 stream->chan->session_id);
5189 break;
5190 case CONSUMER_STREAM_OPEN_PACKET_STATUS_ERROR:
5191 /*
5192 * Only unexpected internal errors can lead to this
5193 * failing. Report an unknown error.
5194 */
5195 ERR("Failed to flush empty buffer in \"open channel packets\" command: stream id = %" PRIu64
5196 ", channel id = %" PRIu64 ", channel name = %s"
5197 ", session id = %" PRIu64,
5198 stream->key,
5199 channel->key,
5200 channel->name,
5201 channel->session_id);
5202 ret = LTTCOMM_CONSUMERD_UNKNOWN_ERROR;
5203 goto error_unlock;
5204 default:
5205 abort();
5206 }
5207
5208 next:
5209 pthread_mutex_unlock(&stream->lock);
5210 }
5211 }
5212 end_rcu_unlock:
5213 end:
5214 return ret;
5215
5216 error_unlock:
5217 pthread_mutex_unlock(&stream->lock);
5218 goto end_rcu_unlock;
5219 }
5220
5221 void lttng_consumer_sigbus_handle(void *addr)
5222 {
5223 lttng_ustconsumer_sigbus_handle(addr);
5224 }
This page took 0.174309 seconds and 4 git commands to generate.