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