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