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