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