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