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