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