consumerd: on_sleep not called on stream when no data is available
[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_stream *stream,
1588 const struct lttng_buffer_view *buffer,
1589 unsigned long padding)
1590 {
1591 ssize_t ret = 0;
1592 off_t orig_offset = stream->out_fd_offset;
1593 /* Default is on the disk */
1594 int outfd = stream->out_fd;
1595 struct consumer_relayd_sock_pair *relayd = NULL;
1596 unsigned int relayd_hang_up = 0;
1597 const size_t subbuf_content_size = buffer->size - padding;
1598 size_t write_len;
1599
1600 /* RCU lock for the relayd pointer */
1601 rcu_read_lock();
1602 assert(stream->net_seq_idx != (uint64_t) -1ULL ||
1603 stream->trace_chunk);
1604
1605 /* Flag that the current stream if set for network streaming. */
1606 if (stream->net_seq_idx != (uint64_t) -1ULL) {
1607 relayd = consumer_find_relayd(stream->net_seq_idx);
1608 if (relayd == NULL) {
1609 ret = -EPIPE;
1610 goto end;
1611 }
1612 }
1613
1614 /* Handle stream on the relayd if the output is on the network */
1615 if (relayd) {
1616 unsigned long netlen = subbuf_content_size;
1617
1618 /*
1619 * Lock the control socket for the complete duration of the function
1620 * since from this point on we will use the socket.
1621 */
1622 if (stream->metadata_flag) {
1623 /* Metadata requires the control socket. */
1624 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
1625 if (stream->reset_metadata_flag) {
1626 ret = relayd_reset_metadata(&relayd->control_sock,
1627 stream->relayd_stream_id,
1628 stream->metadata_version);
1629 if (ret < 0) {
1630 relayd_hang_up = 1;
1631 goto write_error;
1632 }
1633 stream->reset_metadata_flag = 0;
1634 }
1635 netlen += sizeof(struct lttcomm_relayd_metadata_payload);
1636 }
1637
1638 ret = write_relayd_stream_header(stream, netlen, padding, relayd);
1639 if (ret < 0) {
1640 relayd_hang_up = 1;
1641 goto write_error;
1642 }
1643 /* Use the returned socket. */
1644 outfd = ret;
1645
1646 /* Write metadata stream id before payload */
1647 if (stream->metadata_flag) {
1648 ret = write_relayd_metadata_id(outfd, stream, padding);
1649 if (ret < 0) {
1650 relayd_hang_up = 1;
1651 goto write_error;
1652 }
1653 }
1654
1655 write_len = subbuf_content_size;
1656 } else {
1657 /* No streaming; we have to write the full padding. */
1658 if (stream->metadata_flag && stream->reset_metadata_flag) {
1659 ret = utils_truncate_stream_file(stream->out_fd, 0);
1660 if (ret < 0) {
1661 ERR("Reset metadata file");
1662 goto end;
1663 }
1664 stream->reset_metadata_flag = 0;
1665 }
1666
1667 /*
1668 * Check if we need to change the tracefile before writing the packet.
1669 */
1670 if (stream->chan->tracefile_size > 0 &&
1671 (stream->tracefile_size_current + buffer->size) >
1672 stream->chan->tracefile_size) {
1673 ret = consumer_stream_rotate_output_files(stream);
1674 if (ret) {
1675 goto end;
1676 }
1677 outfd = stream->out_fd;
1678 orig_offset = 0;
1679 }
1680 stream->tracefile_size_current += buffer->size;
1681 write_len = buffer->size;
1682 }
1683
1684 /*
1685 * This call guarantee that len or less is returned. It's impossible to
1686 * receive a ret value that is bigger than len.
1687 */
1688 ret = lttng_write(outfd, buffer->data, write_len);
1689 DBG("Consumer mmap write() ret %zd (len %zu)", ret, write_len);
1690 if (ret < 0 || ((size_t) ret != write_len)) {
1691 /*
1692 * Report error to caller if nothing was written else at least send the
1693 * amount written.
1694 */
1695 if (ret < 0) {
1696 ret = -errno;
1697 }
1698 relayd_hang_up = 1;
1699
1700 /* Socket operation failed. We consider the relayd dead */
1701 if (errno == EPIPE) {
1702 /*
1703 * This is possible if the fd is closed on the other side
1704 * (outfd) or any write problem. It can be verbose a bit for a
1705 * normal execution if for instance the relayd is stopped
1706 * abruptly. This can happen so set this to a DBG statement.
1707 */
1708 DBG("Consumer mmap write detected relayd hang up");
1709 } else {
1710 /* Unhandled error, print it and stop function right now. */
1711 PERROR("Error in write mmap (ret %zd != write_len %zu)", ret,
1712 write_len);
1713 }
1714 goto write_error;
1715 }
1716 stream->output_written += ret;
1717
1718 /* This call is useless on a socket so better save a syscall. */
1719 if (!relayd) {
1720 /* This won't block, but will start writeout asynchronously */
1721 lttng_sync_file_range(outfd, stream->out_fd_offset, write_len,
1722 SYNC_FILE_RANGE_WRITE);
1723 stream->out_fd_offset += write_len;
1724 lttng_consumer_sync_trace_file(stream, orig_offset);
1725 }
1726
1727 write_error:
1728 /*
1729 * This is a special case that the relayd has closed its socket. Let's
1730 * cleanup the relayd object and all associated streams.
1731 */
1732 if (relayd && relayd_hang_up) {
1733 ERR("Relayd hangup. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
1734 lttng_consumer_cleanup_relayd(relayd);
1735 }
1736
1737 end:
1738 /* Unlock only if ctrl socket used */
1739 if (relayd && stream->metadata_flag) {
1740 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
1741 }
1742
1743 rcu_read_unlock();
1744 return ret;
1745 }
1746
1747 /*
1748 * Splice the data from the ring buffer to the tracefile.
1749 *
1750 * It must be called with the stream lock held.
1751 *
1752 * Returns the number of bytes spliced.
1753 */
1754 ssize_t lttng_consumer_on_read_subbuffer_splice(
1755 struct lttng_consumer_local_data *ctx,
1756 struct lttng_consumer_stream *stream, unsigned long len,
1757 unsigned long padding)
1758 {
1759 ssize_t ret = 0, written = 0, ret_splice = 0;
1760 loff_t offset = 0;
1761 off_t orig_offset = stream->out_fd_offset;
1762 int fd = stream->wait_fd;
1763 /* Default is on the disk */
1764 int outfd = stream->out_fd;
1765 struct consumer_relayd_sock_pair *relayd = NULL;
1766 int *splice_pipe;
1767 unsigned int relayd_hang_up = 0;
1768
1769 switch (consumer_data.type) {
1770 case LTTNG_CONSUMER_KERNEL:
1771 break;
1772 case LTTNG_CONSUMER32_UST:
1773 case LTTNG_CONSUMER64_UST:
1774 /* Not supported for user space tracing */
1775 return -ENOSYS;
1776 default:
1777 ERR("Unknown consumer_data type");
1778 assert(0);
1779 }
1780
1781 /* RCU lock for the relayd pointer */
1782 rcu_read_lock();
1783
1784 /* Flag that the current stream if set for network streaming. */
1785 if (stream->net_seq_idx != (uint64_t) -1ULL) {
1786 relayd = consumer_find_relayd(stream->net_seq_idx);
1787 if (relayd == NULL) {
1788 written = -ret;
1789 goto end;
1790 }
1791 }
1792 splice_pipe = stream->splice_pipe;
1793
1794 /* Write metadata stream id before payload */
1795 if (relayd) {
1796 unsigned long total_len = len;
1797
1798 if (stream->metadata_flag) {
1799 /*
1800 * Lock the control socket for the complete duration of the function
1801 * since from this point on we will use the socket.
1802 */
1803 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
1804
1805 if (stream->reset_metadata_flag) {
1806 ret = relayd_reset_metadata(&relayd->control_sock,
1807 stream->relayd_stream_id,
1808 stream->metadata_version);
1809 if (ret < 0) {
1810 relayd_hang_up = 1;
1811 goto write_error;
1812 }
1813 stream->reset_metadata_flag = 0;
1814 }
1815 ret = write_relayd_metadata_id(splice_pipe[1], stream,
1816 padding);
1817 if (ret < 0) {
1818 written = ret;
1819 relayd_hang_up = 1;
1820 goto write_error;
1821 }
1822
1823 total_len += sizeof(struct lttcomm_relayd_metadata_payload);
1824 }
1825
1826 ret = write_relayd_stream_header(stream, total_len, padding, relayd);
1827 if (ret < 0) {
1828 written = ret;
1829 relayd_hang_up = 1;
1830 goto write_error;
1831 }
1832 /* Use the returned socket. */
1833 outfd = ret;
1834 } else {
1835 /* No streaming, we have to set the len with the full padding */
1836 len += padding;
1837
1838 if (stream->metadata_flag && stream->reset_metadata_flag) {
1839 ret = utils_truncate_stream_file(stream->out_fd, 0);
1840 if (ret < 0) {
1841 ERR("Reset metadata file");
1842 goto end;
1843 }
1844 stream->reset_metadata_flag = 0;
1845 }
1846 /*
1847 * Check if we need to change the tracefile before writing the packet.
1848 */
1849 if (stream->chan->tracefile_size > 0 &&
1850 (stream->tracefile_size_current + len) >
1851 stream->chan->tracefile_size) {
1852 ret = consumer_stream_rotate_output_files(stream);
1853 if (ret < 0) {
1854 written = ret;
1855 goto end;
1856 }
1857 outfd = stream->out_fd;
1858 orig_offset = 0;
1859 }
1860 stream->tracefile_size_current += len;
1861 }
1862
1863 while (len > 0) {
1864 DBG("splice chan to pipe offset %lu of len %lu (fd : %d, pipe: %d)",
1865 (unsigned long)offset, len, fd, splice_pipe[1]);
1866 ret_splice = splice(fd, &offset, splice_pipe[1], NULL, len,
1867 SPLICE_F_MOVE | SPLICE_F_MORE);
1868 DBG("splice chan to pipe, ret %zd", ret_splice);
1869 if (ret_splice < 0) {
1870 ret = errno;
1871 written = -ret;
1872 PERROR("Error in relay splice");
1873 goto splice_error;
1874 }
1875
1876 /* Handle stream on the relayd if the output is on the network */
1877 if (relayd && stream->metadata_flag) {
1878 size_t metadata_payload_size =
1879 sizeof(struct lttcomm_relayd_metadata_payload);
1880
1881 /* Update counter to fit the spliced data */
1882 ret_splice += metadata_payload_size;
1883 len += metadata_payload_size;
1884 /*
1885 * We do this so the return value can match the len passed as
1886 * argument to this function.
1887 */
1888 written -= metadata_payload_size;
1889 }
1890
1891 /* Splice data out */
1892 ret_splice = splice(splice_pipe[0], NULL, outfd, NULL,
1893 ret_splice, SPLICE_F_MOVE | SPLICE_F_MORE);
1894 DBG("Consumer splice pipe to file (out_fd: %d), ret %zd",
1895 outfd, ret_splice);
1896 if (ret_splice < 0) {
1897 ret = errno;
1898 written = -ret;
1899 relayd_hang_up = 1;
1900 goto write_error;
1901 } else if (ret_splice > len) {
1902 /*
1903 * We don't expect this code path to be executed but you never know
1904 * so this is an extra protection agains a buggy splice().
1905 */
1906 ret = errno;
1907 written += ret_splice;
1908 PERROR("Wrote more data than requested %zd (len: %lu)", ret_splice,
1909 len);
1910 goto splice_error;
1911 } else {
1912 /* All good, update current len and continue. */
1913 len -= ret_splice;
1914 }
1915
1916 /* This call is useless on a socket so better save a syscall. */
1917 if (!relayd) {
1918 /* This won't block, but will start writeout asynchronously */
1919 lttng_sync_file_range(outfd, stream->out_fd_offset, ret_splice,
1920 SYNC_FILE_RANGE_WRITE);
1921 stream->out_fd_offset += ret_splice;
1922 }
1923 stream->output_written += ret_splice;
1924 written += ret_splice;
1925 }
1926 if (!relayd) {
1927 lttng_consumer_sync_trace_file(stream, orig_offset);
1928 }
1929 goto end;
1930
1931 write_error:
1932 /*
1933 * This is a special case that the relayd has closed its socket. Let's
1934 * cleanup the relayd object and all associated streams.
1935 */
1936 if (relayd && relayd_hang_up) {
1937 ERR("Relayd hangup. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
1938 lttng_consumer_cleanup_relayd(relayd);
1939 /* Skip splice error so the consumer does not fail */
1940 goto end;
1941 }
1942
1943 splice_error:
1944 /* send the appropriate error description to sessiond */
1945 switch (ret) {
1946 case EINVAL:
1947 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_EINVAL);
1948 break;
1949 case ENOMEM:
1950 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_ENOMEM);
1951 break;
1952 case ESPIPE:
1953 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_ESPIPE);
1954 break;
1955 }
1956
1957 end:
1958 if (relayd && stream->metadata_flag) {
1959 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
1960 }
1961
1962 rcu_read_unlock();
1963 return written;
1964 }
1965
1966 /*
1967 * Sample the snapshot positions for a specific fd
1968 *
1969 * Returns 0 on success, < 0 on error
1970 */
1971 int lttng_consumer_sample_snapshot_positions(struct lttng_consumer_stream *stream)
1972 {
1973 switch (consumer_data.type) {
1974 case LTTNG_CONSUMER_KERNEL:
1975 return lttng_kconsumer_sample_snapshot_positions(stream);
1976 case LTTNG_CONSUMER32_UST:
1977 case LTTNG_CONSUMER64_UST:
1978 return lttng_ustconsumer_sample_snapshot_positions(stream);
1979 default:
1980 ERR("Unknown consumer_data type");
1981 assert(0);
1982 return -ENOSYS;
1983 }
1984 }
1985 /*
1986 * Take a snapshot for a specific fd
1987 *
1988 * Returns 0 on success, < 0 on error
1989 */
1990 int lttng_consumer_take_snapshot(struct lttng_consumer_stream *stream)
1991 {
1992 switch (consumer_data.type) {
1993 case LTTNG_CONSUMER_KERNEL:
1994 return lttng_kconsumer_take_snapshot(stream);
1995 case LTTNG_CONSUMER32_UST:
1996 case LTTNG_CONSUMER64_UST:
1997 return lttng_ustconsumer_take_snapshot(stream);
1998 default:
1999 ERR("Unknown consumer_data type");
2000 assert(0);
2001 return -ENOSYS;
2002 }
2003 }
2004
2005 /*
2006 * Get the produced position
2007 *
2008 * Returns 0 on success, < 0 on error
2009 */
2010 int lttng_consumer_get_produced_snapshot(struct lttng_consumer_stream *stream,
2011 unsigned long *pos)
2012 {
2013 switch (consumer_data.type) {
2014 case LTTNG_CONSUMER_KERNEL:
2015 return lttng_kconsumer_get_produced_snapshot(stream, pos);
2016 case LTTNG_CONSUMER32_UST:
2017 case LTTNG_CONSUMER64_UST:
2018 return lttng_ustconsumer_get_produced_snapshot(stream, pos);
2019 default:
2020 ERR("Unknown consumer_data type");
2021 assert(0);
2022 return -ENOSYS;
2023 }
2024 }
2025
2026 /*
2027 * Get the consumed position (free-running counter position in bytes).
2028 *
2029 * Returns 0 on success, < 0 on error
2030 */
2031 int lttng_consumer_get_consumed_snapshot(struct lttng_consumer_stream *stream,
2032 unsigned long *pos)
2033 {
2034 switch (consumer_data.type) {
2035 case LTTNG_CONSUMER_KERNEL:
2036 return lttng_kconsumer_get_consumed_snapshot(stream, pos);
2037 case LTTNG_CONSUMER32_UST:
2038 case LTTNG_CONSUMER64_UST:
2039 return lttng_ustconsumer_get_consumed_snapshot(stream, pos);
2040 default:
2041 ERR("Unknown consumer_data type");
2042 assert(0);
2043 return -ENOSYS;
2044 }
2045 }
2046
2047 int lttng_consumer_recv_cmd(struct lttng_consumer_local_data *ctx,
2048 int sock, struct pollfd *consumer_sockpoll)
2049 {
2050 switch (consumer_data.type) {
2051 case LTTNG_CONSUMER_KERNEL:
2052 return lttng_kconsumer_recv_cmd(ctx, sock, consumer_sockpoll);
2053 case LTTNG_CONSUMER32_UST:
2054 case LTTNG_CONSUMER64_UST:
2055 return lttng_ustconsumer_recv_cmd(ctx, sock, consumer_sockpoll);
2056 default:
2057 ERR("Unknown consumer_data type");
2058 assert(0);
2059 return -ENOSYS;
2060 }
2061 }
2062
2063 void lttng_consumer_close_all_metadata(void)
2064 {
2065 switch (consumer_data.type) {
2066 case LTTNG_CONSUMER_KERNEL:
2067 /*
2068 * The Kernel consumer has a different metadata scheme so we don't
2069 * close anything because the stream will be closed by the session
2070 * daemon.
2071 */
2072 break;
2073 case LTTNG_CONSUMER32_UST:
2074 case LTTNG_CONSUMER64_UST:
2075 /*
2076 * Close all metadata streams. The metadata hash table is passed and
2077 * this call iterates over it by closing all wakeup fd. This is safe
2078 * because at this point we are sure that the metadata producer is
2079 * either dead or blocked.
2080 */
2081 lttng_ustconsumer_close_all_metadata(metadata_ht);
2082 break;
2083 default:
2084 ERR("Unknown consumer_data type");
2085 assert(0);
2086 }
2087 }
2088
2089 /*
2090 * Clean up a metadata stream and free its memory.
2091 */
2092 void consumer_del_metadata_stream(struct lttng_consumer_stream *stream,
2093 struct lttng_ht *ht)
2094 {
2095 struct lttng_consumer_channel *channel = NULL;
2096 bool free_channel = false;
2097
2098 assert(stream);
2099 /*
2100 * This call should NEVER receive regular stream. It must always be
2101 * metadata stream and this is crucial for data structure synchronization.
2102 */
2103 assert(stream->metadata_flag);
2104
2105 DBG3("Consumer delete metadata stream %d", stream->wait_fd);
2106
2107 pthread_mutex_lock(&consumer_data.lock);
2108 /*
2109 * Note that this assumes that a stream's channel is never changed and
2110 * that the stream's lock doesn't need to be taken to sample its
2111 * channel.
2112 */
2113 channel = stream->chan;
2114 pthread_mutex_lock(&channel->lock);
2115 pthread_mutex_lock(&stream->lock);
2116 if (channel->metadata_cache) {
2117 /* Only applicable to userspace consumers. */
2118 pthread_mutex_lock(&channel->metadata_cache->lock);
2119 }
2120
2121 /* Remove any reference to that stream. */
2122 consumer_stream_delete(stream, ht);
2123
2124 /* Close down everything including the relayd if one. */
2125 consumer_stream_close(stream);
2126 /* Destroy tracer buffers of the stream. */
2127 consumer_stream_destroy_buffers(stream);
2128
2129 /* Atomically decrement channel refcount since other threads can use it. */
2130 if (!uatomic_sub_return(&channel->refcount, 1)
2131 && !uatomic_read(&channel->nb_init_stream_left)) {
2132 /* Go for channel deletion! */
2133 free_channel = true;
2134 }
2135 stream->chan = NULL;
2136
2137 /*
2138 * Nullify the stream reference so it is not used after deletion. The
2139 * channel lock MUST be acquired before being able to check for a NULL
2140 * pointer value.
2141 */
2142 channel->metadata_stream = NULL;
2143
2144 if (channel->metadata_cache) {
2145 pthread_mutex_unlock(&channel->metadata_cache->lock);
2146 }
2147 pthread_mutex_unlock(&stream->lock);
2148 pthread_mutex_unlock(&channel->lock);
2149 pthread_mutex_unlock(&consumer_data.lock);
2150
2151 if (free_channel) {
2152 consumer_del_channel(channel);
2153 }
2154
2155 lttng_trace_chunk_put(stream->trace_chunk);
2156 stream->trace_chunk = NULL;
2157 consumer_stream_free(stream);
2158 }
2159
2160 /*
2161 * Action done with the metadata stream when adding it to the consumer internal
2162 * data structures to handle it.
2163 */
2164 void consumer_add_metadata_stream(struct lttng_consumer_stream *stream)
2165 {
2166 struct lttng_ht *ht = metadata_ht;
2167 struct lttng_ht_iter iter;
2168 struct lttng_ht_node_u64 *node;
2169
2170 assert(stream);
2171 assert(ht);
2172
2173 DBG3("Adding metadata stream %" PRIu64 " to hash table", stream->key);
2174
2175 pthread_mutex_lock(&consumer_data.lock);
2176 pthread_mutex_lock(&stream->chan->lock);
2177 pthread_mutex_lock(&stream->chan->timer_lock);
2178 pthread_mutex_lock(&stream->lock);
2179
2180 /*
2181 * From here, refcounts are updated so be _careful_ when returning an error
2182 * after this point.
2183 */
2184
2185 rcu_read_lock();
2186
2187 /*
2188 * Lookup the stream just to make sure it does not exist in our internal
2189 * state. This should NEVER happen.
2190 */
2191 lttng_ht_lookup(ht, &stream->key, &iter);
2192 node = lttng_ht_iter_get_node_u64(&iter);
2193 assert(!node);
2194
2195 /*
2196 * When nb_init_stream_left reaches 0, we don't need to trigger any action
2197 * in terms of destroying the associated channel, because the action that
2198 * causes the count to become 0 also causes a stream to be added. The
2199 * channel deletion will thus be triggered by the following removal of this
2200 * stream.
2201 */
2202 if (uatomic_read(&stream->chan->nb_init_stream_left) > 0) {
2203 /* Increment refcount before decrementing nb_init_stream_left */
2204 cmm_smp_wmb();
2205 uatomic_dec(&stream->chan->nb_init_stream_left);
2206 }
2207
2208 lttng_ht_add_unique_u64(ht, &stream->node);
2209
2210 lttng_ht_add_u64(consumer_data.stream_per_chan_id_ht,
2211 &stream->node_channel_id);
2212
2213 /*
2214 * Add stream to the stream_list_ht of the consumer data. No need to steal
2215 * the key since the HT does not use it and we allow to add redundant keys
2216 * into this table.
2217 */
2218 lttng_ht_add_u64(consumer_data.stream_list_ht, &stream->node_session_id);
2219
2220 rcu_read_unlock();
2221
2222 pthread_mutex_unlock(&stream->lock);
2223 pthread_mutex_unlock(&stream->chan->lock);
2224 pthread_mutex_unlock(&stream->chan->timer_lock);
2225 pthread_mutex_unlock(&consumer_data.lock);
2226 }
2227
2228 /*
2229 * Delete data stream that are flagged for deletion (endpoint_status).
2230 */
2231 static void validate_endpoint_status_data_stream(void)
2232 {
2233 struct lttng_ht_iter iter;
2234 struct lttng_consumer_stream *stream;
2235
2236 DBG("Consumer delete flagged data stream");
2237
2238 rcu_read_lock();
2239 cds_lfht_for_each_entry(data_ht->ht, &iter.iter, stream, node.node) {
2240 /* Validate delete flag of the stream */
2241 if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
2242 continue;
2243 }
2244 /* Delete it right now */
2245 consumer_del_stream(stream, data_ht);
2246 }
2247 rcu_read_unlock();
2248 }
2249
2250 /*
2251 * Delete metadata stream that are flagged for deletion (endpoint_status).
2252 */
2253 static void validate_endpoint_status_metadata_stream(
2254 struct lttng_poll_event *pollset)
2255 {
2256 struct lttng_ht_iter iter;
2257 struct lttng_consumer_stream *stream;
2258
2259 DBG("Consumer delete flagged metadata stream");
2260
2261 assert(pollset);
2262
2263 rcu_read_lock();
2264 cds_lfht_for_each_entry(metadata_ht->ht, &iter.iter, stream, node.node) {
2265 /* Validate delete flag of the stream */
2266 if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
2267 continue;
2268 }
2269 /*
2270 * Remove from pollset so the metadata thread can continue without
2271 * blocking on a deleted stream.
2272 */
2273 lttng_poll_del(pollset, stream->wait_fd);
2274
2275 /* Delete it right now */
2276 consumer_del_metadata_stream(stream, metadata_ht);
2277 }
2278 rcu_read_unlock();
2279 }
2280
2281 /*
2282 * Thread polls on metadata file descriptor and write them on disk or on the
2283 * network.
2284 */
2285 void *consumer_thread_metadata_poll(void *data)
2286 {
2287 int ret, i, pollfd, err = -1;
2288 uint32_t revents, nb_fd;
2289 struct lttng_consumer_stream *stream = NULL;
2290 struct lttng_ht_iter iter;
2291 struct lttng_ht_node_u64 *node;
2292 struct lttng_poll_event events;
2293 struct lttng_consumer_local_data *ctx = data;
2294 ssize_t len;
2295
2296 rcu_register_thread();
2297
2298 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_METADATA);
2299
2300 if (testpoint(consumerd_thread_metadata)) {
2301 goto error_testpoint;
2302 }
2303
2304 health_code_update();
2305
2306 DBG("Thread metadata poll started");
2307
2308 /* Size is set to 1 for the consumer_metadata pipe */
2309 ret = lttng_poll_create(&events, 2, LTTNG_CLOEXEC);
2310 if (ret < 0) {
2311 ERR("Poll set creation failed");
2312 goto end_poll;
2313 }
2314
2315 ret = lttng_poll_add(&events,
2316 lttng_pipe_get_readfd(ctx->consumer_metadata_pipe), LPOLLIN);
2317 if (ret < 0) {
2318 goto end;
2319 }
2320
2321 /* Main loop */
2322 DBG("Metadata main loop started");
2323
2324 while (1) {
2325 restart:
2326 health_code_update();
2327 health_poll_entry();
2328 DBG("Metadata poll wait");
2329 ret = lttng_poll_wait(&events, -1);
2330 DBG("Metadata poll return from wait with %d fd(s)",
2331 LTTNG_POLL_GETNB(&events));
2332 health_poll_exit();
2333 DBG("Metadata event caught in thread");
2334 if (ret < 0) {
2335 if (errno == EINTR) {
2336 ERR("Poll EINTR caught");
2337 goto restart;
2338 }
2339 if (LTTNG_POLL_GETNB(&events) == 0) {
2340 err = 0; /* All is OK */
2341 }
2342 goto end;
2343 }
2344
2345 nb_fd = ret;
2346
2347 /* From here, the event is a metadata wait fd */
2348 for (i = 0; i < nb_fd; i++) {
2349 health_code_update();
2350
2351 revents = LTTNG_POLL_GETEV(&events, i);
2352 pollfd = LTTNG_POLL_GETFD(&events, i);
2353
2354 if (pollfd == lttng_pipe_get_readfd(ctx->consumer_metadata_pipe)) {
2355 if (revents & LPOLLIN) {
2356 ssize_t pipe_len;
2357
2358 pipe_len = lttng_pipe_read(ctx->consumer_metadata_pipe,
2359 &stream, sizeof(stream));
2360 if (pipe_len < sizeof(stream)) {
2361 if (pipe_len < 0) {
2362 PERROR("read metadata stream");
2363 }
2364 /*
2365 * Remove the pipe from the poll set and continue the loop
2366 * since their might be data to consume.
2367 */
2368 lttng_poll_del(&events,
2369 lttng_pipe_get_readfd(ctx->consumer_metadata_pipe));
2370 lttng_pipe_read_close(ctx->consumer_metadata_pipe);
2371 continue;
2372 }
2373
2374 /* A NULL stream means that the state has changed. */
2375 if (stream == NULL) {
2376 /* Check for deleted streams. */
2377 validate_endpoint_status_metadata_stream(&events);
2378 goto restart;
2379 }
2380
2381 DBG("Adding metadata stream %d to poll set",
2382 stream->wait_fd);
2383
2384 /* Add metadata stream to the global poll events list */
2385 lttng_poll_add(&events, stream->wait_fd,
2386 LPOLLIN | LPOLLPRI | LPOLLHUP);
2387 } else if (revents & (LPOLLERR | LPOLLHUP)) {
2388 DBG("Metadata thread pipe hung up");
2389 /*
2390 * Remove the pipe from the poll set and continue the loop
2391 * since their might be data to consume.
2392 */
2393 lttng_poll_del(&events,
2394 lttng_pipe_get_readfd(ctx->consumer_metadata_pipe));
2395 lttng_pipe_read_close(ctx->consumer_metadata_pipe);
2396 continue;
2397 } else {
2398 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2399 goto end;
2400 }
2401
2402 /* Handle other stream */
2403 continue;
2404 }
2405
2406 rcu_read_lock();
2407 {
2408 uint64_t tmp_id = (uint64_t) pollfd;
2409
2410 lttng_ht_lookup(metadata_ht, &tmp_id, &iter);
2411 }
2412 node = lttng_ht_iter_get_node_u64(&iter);
2413 assert(node);
2414
2415 stream = caa_container_of(node, struct lttng_consumer_stream,
2416 node);
2417
2418 if (revents & (LPOLLIN | LPOLLPRI)) {
2419 /* Get the data out of the metadata file descriptor */
2420 DBG("Metadata available on fd %d", pollfd);
2421 assert(stream->wait_fd == pollfd);
2422
2423 do {
2424 health_code_update();
2425
2426 len = ctx->on_buffer_ready(stream, ctx, false);
2427 /*
2428 * We don't check the return value here since if we get
2429 * a negative len, it means an error occurred thus we
2430 * simply remove it from the poll set and free the
2431 * stream.
2432 */
2433 } while (len > 0);
2434
2435 /* It's ok to have an unavailable sub-buffer */
2436 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
2437 /* Clean up stream from consumer and free it. */
2438 lttng_poll_del(&events, stream->wait_fd);
2439 consumer_del_metadata_stream(stream, metadata_ht);
2440 }
2441 } else if (revents & (LPOLLERR | LPOLLHUP)) {
2442 DBG("Metadata fd %d is hup|err.", pollfd);
2443 if (!stream->hangup_flush_done
2444 && (consumer_data.type == LTTNG_CONSUMER32_UST
2445 || consumer_data.type == LTTNG_CONSUMER64_UST)) {
2446 DBG("Attempting to flush and consume the UST buffers");
2447 lttng_ustconsumer_on_stream_hangup(stream);
2448
2449 /* We just flushed the stream now read it. */
2450 do {
2451 health_code_update();
2452
2453 len = ctx->on_buffer_ready(stream, ctx, false);
2454 /*
2455 * We don't check the return value here since if we get
2456 * a negative len, it means an error occurred thus we
2457 * simply remove it from the poll set and free the
2458 * stream.
2459 */
2460 } while (len > 0);
2461 }
2462
2463 lttng_poll_del(&events, stream->wait_fd);
2464 /*
2465 * This call update the channel states, closes file descriptors
2466 * and securely free the stream.
2467 */
2468 consumer_del_metadata_stream(stream, metadata_ht);
2469 } else {
2470 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2471 rcu_read_unlock();
2472 goto end;
2473 }
2474 /* Release RCU lock for the stream looked up */
2475 rcu_read_unlock();
2476 }
2477 }
2478
2479 /* All is OK */
2480 err = 0;
2481 end:
2482 DBG("Metadata poll thread exiting");
2483
2484 lttng_poll_clean(&events);
2485 end_poll:
2486 error_testpoint:
2487 if (err) {
2488 health_error();
2489 ERR("Health error occurred in %s", __func__);
2490 }
2491 health_unregister(health_consumerd);
2492 rcu_unregister_thread();
2493 return NULL;
2494 }
2495
2496 /*
2497 * This thread polls the fds in the set to consume the data and write
2498 * it to tracefile if necessary.
2499 */
2500 void *consumer_thread_data_poll(void *data)
2501 {
2502 int num_rdy, num_hup, high_prio, ret, i, err = -1;
2503 struct pollfd *pollfd = NULL;
2504 /* local view of the streams */
2505 struct lttng_consumer_stream **local_stream = NULL, *new_stream = NULL;
2506 /* local view of consumer_data.fds_count */
2507 int nb_fd = 0;
2508 /* 2 for the consumer_data_pipe and wake up pipe */
2509 const int nb_pipes_fd = 2;
2510 /* Number of FDs with CONSUMER_ENDPOINT_INACTIVE but still open. */
2511 int nb_inactive_fd = 0;
2512 struct lttng_consumer_local_data *ctx = data;
2513 ssize_t len;
2514
2515 rcu_register_thread();
2516
2517 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_DATA);
2518
2519 if (testpoint(consumerd_thread_data)) {
2520 goto error_testpoint;
2521 }
2522
2523 health_code_update();
2524
2525 local_stream = zmalloc(sizeof(struct lttng_consumer_stream *));
2526 if (local_stream == NULL) {
2527 PERROR("local_stream malloc");
2528 goto end;
2529 }
2530
2531 while (1) {
2532 health_code_update();
2533
2534 high_prio = 0;
2535 num_hup = 0;
2536
2537 /*
2538 * the fds set has been updated, we need to update our
2539 * local array as well
2540 */
2541 pthread_mutex_lock(&consumer_data.lock);
2542 if (consumer_data.need_update) {
2543 free(pollfd);
2544 pollfd = NULL;
2545
2546 free(local_stream);
2547 local_stream = NULL;
2548
2549 /* Allocate for all fds */
2550 pollfd = zmalloc((consumer_data.stream_count + nb_pipes_fd) * sizeof(struct pollfd));
2551 if (pollfd == NULL) {
2552 PERROR("pollfd malloc");
2553 pthread_mutex_unlock(&consumer_data.lock);
2554 goto end;
2555 }
2556
2557 local_stream = zmalloc((consumer_data.stream_count + nb_pipes_fd) *
2558 sizeof(struct lttng_consumer_stream *));
2559 if (local_stream == NULL) {
2560 PERROR("local_stream malloc");
2561 pthread_mutex_unlock(&consumer_data.lock);
2562 goto end;
2563 }
2564 ret = update_poll_array(ctx, &pollfd, local_stream,
2565 data_ht, &nb_inactive_fd);
2566 if (ret < 0) {
2567 ERR("Error in allocating pollfd or local_outfds");
2568 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
2569 pthread_mutex_unlock(&consumer_data.lock);
2570 goto end;
2571 }
2572 nb_fd = ret;
2573 consumer_data.need_update = 0;
2574 }
2575 pthread_mutex_unlock(&consumer_data.lock);
2576
2577 /* No FDs and consumer_quit, consumer_cleanup the thread */
2578 if (nb_fd == 0 && nb_inactive_fd == 0 &&
2579 CMM_LOAD_SHARED(consumer_quit) == 1) {
2580 err = 0; /* All is OK */
2581 goto end;
2582 }
2583 /* poll on the array of fds */
2584 restart:
2585 DBG("polling on %d fd", nb_fd + nb_pipes_fd);
2586 if (testpoint(consumerd_thread_data_poll)) {
2587 goto end;
2588 }
2589 health_poll_entry();
2590 num_rdy = poll(pollfd, nb_fd + nb_pipes_fd, -1);
2591 health_poll_exit();
2592 DBG("poll num_rdy : %d", num_rdy);
2593 if (num_rdy == -1) {
2594 /*
2595 * Restart interrupted system call.
2596 */
2597 if (errno == EINTR) {
2598 goto restart;
2599 }
2600 PERROR("Poll error");
2601 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
2602 goto end;
2603 } else if (num_rdy == 0) {
2604 DBG("Polling thread timed out");
2605 goto end;
2606 }
2607
2608 if (caa_unlikely(data_consumption_paused)) {
2609 DBG("Data consumption paused, sleeping...");
2610 sleep(1);
2611 goto restart;
2612 }
2613
2614 /*
2615 * If the consumer_data_pipe triggered poll go directly to the
2616 * beginning of the loop to update the array. We want to prioritize
2617 * array update over low-priority reads.
2618 */
2619 if (pollfd[nb_fd].revents & (POLLIN | POLLPRI)) {
2620 ssize_t pipe_readlen;
2621
2622 DBG("consumer_data_pipe wake up");
2623 pipe_readlen = lttng_pipe_read(ctx->consumer_data_pipe,
2624 &new_stream, sizeof(new_stream));
2625 if (pipe_readlen < sizeof(new_stream)) {
2626 PERROR("Consumer data pipe");
2627 /* Continue so we can at least handle the current stream(s). */
2628 continue;
2629 }
2630
2631 /*
2632 * If the stream is NULL, just ignore it. It's also possible that
2633 * the sessiond poll thread changed the consumer_quit state and is
2634 * waking us up to test it.
2635 */
2636 if (new_stream == NULL) {
2637 validate_endpoint_status_data_stream();
2638 continue;
2639 }
2640
2641 /* Continue to update the local streams and handle prio ones */
2642 continue;
2643 }
2644
2645 /* Handle wakeup pipe. */
2646 if (pollfd[nb_fd + 1].revents & (POLLIN | POLLPRI)) {
2647 char dummy;
2648 ssize_t pipe_readlen;
2649
2650 pipe_readlen = lttng_pipe_read(ctx->consumer_wakeup_pipe, &dummy,
2651 sizeof(dummy));
2652 if (pipe_readlen < 0) {
2653 PERROR("Consumer data wakeup pipe");
2654 }
2655 /* We've been awakened to handle stream(s). */
2656 ctx->has_wakeup = 0;
2657 }
2658
2659 /* Take care of high priority channels first. */
2660 for (i = 0; i < nb_fd; i++) {
2661 health_code_update();
2662
2663 if (local_stream[i] == NULL) {
2664 continue;
2665 }
2666 if (pollfd[i].revents & POLLPRI) {
2667 DBG("Urgent read on fd %d", pollfd[i].fd);
2668 high_prio = 1;
2669 len = ctx->on_buffer_ready(local_stream[i], ctx, false);
2670 /* it's ok to have an unavailable sub-buffer */
2671 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
2672 /* Clean the stream and free it. */
2673 consumer_del_stream(local_stream[i], data_ht);
2674 local_stream[i] = NULL;
2675 } else if (len > 0) {
2676 local_stream[i]->data_read = 1;
2677 }
2678 }
2679 }
2680
2681 /*
2682 * If we read high prio channel in this loop, try again
2683 * for more high prio data.
2684 */
2685 if (high_prio) {
2686 continue;
2687 }
2688
2689 /* Take care of low priority channels. */
2690 for (i = 0; i < nb_fd; i++) {
2691 health_code_update();
2692
2693 if (local_stream[i] == NULL) {
2694 continue;
2695 }
2696 if ((pollfd[i].revents & POLLIN) ||
2697 local_stream[i]->hangup_flush_done ||
2698 local_stream[i]->has_data) {
2699 DBG("Normal read on fd %d", pollfd[i].fd);
2700 len = ctx->on_buffer_ready(local_stream[i], ctx, false);
2701 /* it's ok to have an unavailable sub-buffer */
2702 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
2703 /* Clean the stream and free it. */
2704 consumer_del_stream(local_stream[i], data_ht);
2705 local_stream[i] = NULL;
2706 } else if (len > 0) {
2707 local_stream[i]->data_read = 1;
2708 }
2709 }
2710 }
2711
2712 /* Handle hangup and errors */
2713 for (i = 0; i < nb_fd; i++) {
2714 health_code_update();
2715
2716 if (local_stream[i] == NULL) {
2717 continue;
2718 }
2719 if (!local_stream[i]->hangup_flush_done
2720 && (pollfd[i].revents & (POLLHUP | POLLERR | POLLNVAL))
2721 && (consumer_data.type == LTTNG_CONSUMER32_UST
2722 || consumer_data.type == LTTNG_CONSUMER64_UST)) {
2723 DBG("fd %d is hup|err|nval. Attempting flush and read.",
2724 pollfd[i].fd);
2725 lttng_ustconsumer_on_stream_hangup(local_stream[i]);
2726 /* Attempt read again, for the data we just flushed. */
2727 local_stream[i]->data_read = 1;
2728 }
2729 /*
2730 * If the poll flag is HUP/ERR/NVAL and we have
2731 * read no data in this pass, we can remove the
2732 * stream from its hash table.
2733 */
2734 if ((pollfd[i].revents & POLLHUP)) {
2735 DBG("Polling fd %d tells it has hung up.", pollfd[i].fd);
2736 if (!local_stream[i]->data_read) {
2737 consumer_del_stream(local_stream[i], data_ht);
2738 local_stream[i] = NULL;
2739 num_hup++;
2740 }
2741 } else if (pollfd[i].revents & POLLERR) {
2742 ERR("Error returned in polling fd %d.", pollfd[i].fd);
2743 if (!local_stream[i]->data_read) {
2744 consumer_del_stream(local_stream[i], data_ht);
2745 local_stream[i] = NULL;
2746 num_hup++;
2747 }
2748 } else if (pollfd[i].revents & POLLNVAL) {
2749 ERR("Polling fd %d tells fd is not open.", pollfd[i].fd);
2750 if (!local_stream[i]->data_read) {
2751 consumer_del_stream(local_stream[i], data_ht);
2752 local_stream[i] = NULL;
2753 num_hup++;
2754 }
2755 }
2756 if (local_stream[i] != NULL) {
2757 local_stream[i]->data_read = 0;
2758 }
2759 }
2760 }
2761 /* All is OK */
2762 err = 0;
2763 end:
2764 DBG("polling thread exiting");
2765 free(pollfd);
2766 free(local_stream);
2767
2768 /*
2769 * Close the write side of the pipe so epoll_wait() in
2770 * consumer_thread_metadata_poll can catch it. The thread is monitoring the
2771 * read side of the pipe. If we close them both, epoll_wait strangely does
2772 * not return and could create a endless wait period if the pipe is the
2773 * only tracked fd in the poll set. The thread will take care of closing
2774 * the read side.
2775 */
2776 (void) lttng_pipe_write_close(ctx->consumer_metadata_pipe);
2777
2778 error_testpoint:
2779 if (err) {
2780 health_error();
2781 ERR("Health error occurred in %s", __func__);
2782 }
2783 health_unregister(health_consumerd);
2784
2785 rcu_unregister_thread();
2786 return NULL;
2787 }
2788
2789 /*
2790 * Close wake-up end of each stream belonging to the channel. This will
2791 * allow the poll() on the stream read-side to detect when the
2792 * write-side (application) finally closes them.
2793 */
2794 static
2795 void consumer_close_channel_streams(struct lttng_consumer_channel *channel)
2796 {
2797 struct lttng_ht *ht;
2798 struct lttng_consumer_stream *stream;
2799 struct lttng_ht_iter iter;
2800
2801 ht = consumer_data.stream_per_chan_id_ht;
2802
2803 rcu_read_lock();
2804 cds_lfht_for_each_entry_duplicate(ht->ht,
2805 ht->hash_fct(&channel->key, lttng_ht_seed),
2806 ht->match_fct, &channel->key,
2807 &iter.iter, stream, node_channel_id.node) {
2808 /*
2809 * Protect against teardown with mutex.
2810 */
2811 pthread_mutex_lock(&stream->lock);
2812 if (cds_lfht_is_node_deleted(&stream->node.node)) {
2813 goto next;
2814 }
2815 switch (consumer_data.type) {
2816 case LTTNG_CONSUMER_KERNEL:
2817 break;
2818 case LTTNG_CONSUMER32_UST:
2819 case LTTNG_CONSUMER64_UST:
2820 if (stream->metadata_flag) {
2821 /* Safe and protected by the stream lock. */
2822 lttng_ustconsumer_close_metadata(stream->chan);
2823 } else {
2824 /*
2825 * Note: a mutex is taken internally within
2826 * liblttng-ust-ctl to protect timer wakeup_fd
2827 * use from concurrent close.
2828 */
2829 lttng_ustconsumer_close_stream_wakeup(stream);
2830 }
2831 break;
2832 default:
2833 ERR("Unknown consumer_data type");
2834 assert(0);
2835 }
2836 next:
2837 pthread_mutex_unlock(&stream->lock);
2838 }
2839 rcu_read_unlock();
2840 }
2841
2842 static void destroy_channel_ht(struct lttng_ht *ht)
2843 {
2844 struct lttng_ht_iter iter;
2845 struct lttng_consumer_channel *channel;
2846 int ret;
2847
2848 if (ht == NULL) {
2849 return;
2850 }
2851
2852 rcu_read_lock();
2853 cds_lfht_for_each_entry(ht->ht, &iter.iter, channel, wait_fd_node.node) {
2854 ret = lttng_ht_del(ht, &iter);
2855 assert(ret != 0);
2856 }
2857 rcu_read_unlock();
2858
2859 lttng_ht_destroy(ht);
2860 }
2861
2862 /*
2863 * This thread polls the channel fds to detect when they are being
2864 * closed. It closes all related streams if the channel is detected as
2865 * closed. It is currently only used as a shim layer for UST because the
2866 * consumerd needs to keep the per-stream wakeup end of pipes open for
2867 * periodical flush.
2868 */
2869 void *consumer_thread_channel_poll(void *data)
2870 {
2871 int ret, i, pollfd, err = -1;
2872 uint32_t revents, nb_fd;
2873 struct lttng_consumer_channel *chan = NULL;
2874 struct lttng_ht_iter iter;
2875 struct lttng_ht_node_u64 *node;
2876 struct lttng_poll_event events;
2877 struct lttng_consumer_local_data *ctx = data;
2878 struct lttng_ht *channel_ht;
2879
2880 rcu_register_thread();
2881
2882 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_CHANNEL);
2883
2884 if (testpoint(consumerd_thread_channel)) {
2885 goto error_testpoint;
2886 }
2887
2888 health_code_update();
2889
2890 channel_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2891 if (!channel_ht) {
2892 /* ENOMEM at this point. Better to bail out. */
2893 goto end_ht;
2894 }
2895
2896 DBG("Thread channel poll started");
2897
2898 /* Size is set to 1 for the consumer_channel pipe */
2899 ret = lttng_poll_create(&events, 2, LTTNG_CLOEXEC);
2900 if (ret < 0) {
2901 ERR("Poll set creation failed");
2902 goto end_poll;
2903 }
2904
2905 ret = lttng_poll_add(&events, ctx->consumer_channel_pipe[0], LPOLLIN);
2906 if (ret < 0) {
2907 goto end;
2908 }
2909
2910 /* Main loop */
2911 DBG("Channel main loop started");
2912
2913 while (1) {
2914 restart:
2915 health_code_update();
2916 DBG("Channel poll wait");
2917 health_poll_entry();
2918 ret = lttng_poll_wait(&events, -1);
2919 DBG("Channel poll return from wait with %d fd(s)",
2920 LTTNG_POLL_GETNB(&events));
2921 health_poll_exit();
2922 DBG("Channel event caught in thread");
2923 if (ret < 0) {
2924 if (errno == EINTR) {
2925 ERR("Poll EINTR caught");
2926 goto restart;
2927 }
2928 if (LTTNG_POLL_GETNB(&events) == 0) {
2929 err = 0; /* All is OK */
2930 }
2931 goto end;
2932 }
2933
2934 nb_fd = ret;
2935
2936 /* From here, the event is a channel wait fd */
2937 for (i = 0; i < nb_fd; i++) {
2938 health_code_update();
2939
2940 revents = LTTNG_POLL_GETEV(&events, i);
2941 pollfd = LTTNG_POLL_GETFD(&events, i);
2942
2943 if (pollfd == ctx->consumer_channel_pipe[0]) {
2944 if (revents & LPOLLIN) {
2945 enum consumer_channel_action action;
2946 uint64_t key;
2947
2948 ret = read_channel_pipe(ctx, &chan, &key, &action);
2949 if (ret <= 0) {
2950 if (ret < 0) {
2951 ERR("Error reading channel pipe");
2952 }
2953 lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
2954 continue;
2955 }
2956
2957 switch (action) {
2958 case CONSUMER_CHANNEL_ADD:
2959 DBG("Adding channel %d to poll set",
2960 chan->wait_fd);
2961
2962 lttng_ht_node_init_u64(&chan->wait_fd_node,
2963 chan->wait_fd);
2964 rcu_read_lock();
2965 lttng_ht_add_unique_u64(channel_ht,
2966 &chan->wait_fd_node);
2967 rcu_read_unlock();
2968 /* Add channel to the global poll events list */
2969 lttng_poll_add(&events, chan->wait_fd,
2970 LPOLLERR | LPOLLHUP);
2971 break;
2972 case CONSUMER_CHANNEL_DEL:
2973 {
2974 /*
2975 * This command should never be called if the channel
2976 * has streams monitored by either the data or metadata
2977 * thread. The consumer only notify this thread with a
2978 * channel del. command if it receives a destroy
2979 * channel command from the session daemon that send it
2980 * if a command prior to the GET_CHANNEL failed.
2981 */
2982
2983 rcu_read_lock();
2984 chan = consumer_find_channel(key);
2985 if (!chan) {
2986 rcu_read_unlock();
2987 ERR("UST consumer get channel key %" PRIu64 " not found for del channel", key);
2988 break;
2989 }
2990 lttng_poll_del(&events, chan->wait_fd);
2991 iter.iter.node = &chan->wait_fd_node.node;
2992 ret = lttng_ht_del(channel_ht, &iter);
2993 assert(ret == 0);
2994
2995 switch (consumer_data.type) {
2996 case LTTNG_CONSUMER_KERNEL:
2997 break;
2998 case LTTNG_CONSUMER32_UST:
2999 case LTTNG_CONSUMER64_UST:
3000 health_code_update();
3001 /* Destroy streams that might have been left in the stream list. */
3002 clean_channel_stream_list(chan);
3003 break;
3004 default:
3005 ERR("Unknown consumer_data type");
3006 assert(0);
3007 }
3008
3009 /*
3010 * Release our own refcount. Force channel deletion even if
3011 * streams were not initialized.
3012 */
3013 if (!uatomic_sub_return(&chan->refcount, 1)) {
3014 consumer_del_channel(chan);
3015 }
3016 rcu_read_unlock();
3017 goto restart;
3018 }
3019 case CONSUMER_CHANNEL_QUIT:
3020 /*
3021 * Remove the pipe from the poll set and continue the loop
3022 * since their might be data to consume.
3023 */
3024 lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
3025 continue;
3026 default:
3027 ERR("Unknown action");
3028 break;
3029 }
3030 } else if (revents & (LPOLLERR | LPOLLHUP)) {
3031 DBG("Channel thread pipe hung up");
3032 /*
3033 * Remove the pipe from the poll set and continue the loop
3034 * since their might be data to consume.
3035 */
3036 lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
3037 continue;
3038 } else {
3039 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3040 goto end;
3041 }
3042
3043 /* Handle other stream */
3044 continue;
3045 }
3046
3047 rcu_read_lock();
3048 {
3049 uint64_t tmp_id = (uint64_t) pollfd;
3050
3051 lttng_ht_lookup(channel_ht, &tmp_id, &iter);
3052 }
3053 node = lttng_ht_iter_get_node_u64(&iter);
3054 assert(node);
3055
3056 chan = caa_container_of(node, struct lttng_consumer_channel,
3057 wait_fd_node);
3058
3059 /* Check for error event */
3060 if (revents & (LPOLLERR | LPOLLHUP)) {
3061 DBG("Channel fd %d is hup|err.", pollfd);
3062
3063 lttng_poll_del(&events, chan->wait_fd);
3064 ret = lttng_ht_del(channel_ht, &iter);
3065 assert(ret == 0);
3066
3067 /*
3068 * This will close the wait fd for each stream associated to
3069 * this channel AND monitored by the data/metadata thread thus
3070 * will be clean by the right thread.
3071 */
3072 consumer_close_channel_streams(chan);
3073
3074 /* Release our own refcount */
3075 if (!uatomic_sub_return(&chan->refcount, 1)
3076 && !uatomic_read(&chan->nb_init_stream_left)) {
3077 consumer_del_channel(chan);
3078 }
3079 } else {
3080 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3081 rcu_read_unlock();
3082 goto end;
3083 }
3084
3085 /* Release RCU lock for the channel looked up */
3086 rcu_read_unlock();
3087 }
3088 }
3089
3090 /* All is OK */
3091 err = 0;
3092 end:
3093 lttng_poll_clean(&events);
3094 end_poll:
3095 destroy_channel_ht(channel_ht);
3096 end_ht:
3097 error_testpoint:
3098 DBG("Channel poll thread exiting");
3099 if (err) {
3100 health_error();
3101 ERR("Health error occurred in %s", __func__);
3102 }
3103 health_unregister(health_consumerd);
3104 rcu_unregister_thread();
3105 return NULL;
3106 }
3107
3108 static int set_metadata_socket(struct lttng_consumer_local_data *ctx,
3109 struct pollfd *sockpoll, int client_socket)
3110 {
3111 int ret;
3112
3113 assert(ctx);
3114 assert(sockpoll);
3115
3116 ret = lttng_consumer_poll_socket(sockpoll);
3117 if (ret) {
3118 goto error;
3119 }
3120 DBG("Metadata connection on client_socket");
3121
3122 /* Blocking call, waiting for transmission */
3123 ctx->consumer_metadata_socket = lttcomm_accept_unix_sock(client_socket);
3124 if (ctx->consumer_metadata_socket < 0) {
3125 WARN("On accept metadata");
3126 ret = -1;
3127 goto error;
3128 }
3129 ret = 0;
3130
3131 error:
3132 return ret;
3133 }
3134
3135 /*
3136 * This thread listens on the consumerd socket and receives the file
3137 * descriptors from the session daemon.
3138 */
3139 void *consumer_thread_sessiond_poll(void *data)
3140 {
3141 int sock = -1, client_socket, ret, err = -1;
3142 /*
3143 * structure to poll for incoming data on communication socket avoids
3144 * making blocking sockets.
3145 */
3146 struct pollfd consumer_sockpoll[2];
3147 struct lttng_consumer_local_data *ctx = data;
3148
3149 rcu_register_thread();
3150
3151 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_SESSIOND);
3152
3153 if (testpoint(consumerd_thread_sessiond)) {
3154 goto error_testpoint;
3155 }
3156
3157 health_code_update();
3158
3159 DBG("Creating command socket %s", ctx->consumer_command_sock_path);
3160 unlink(ctx->consumer_command_sock_path);
3161 client_socket = lttcomm_create_unix_sock(ctx->consumer_command_sock_path);
3162 if (client_socket < 0) {
3163 ERR("Cannot create command socket");
3164 goto end;
3165 }
3166
3167 ret = lttcomm_listen_unix_sock(client_socket);
3168 if (ret < 0) {
3169 goto end;
3170 }
3171
3172 DBG("Sending ready command to lttng-sessiond");
3173 ret = lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_COMMAND_SOCK_READY);
3174 /* return < 0 on error, but == 0 is not fatal */
3175 if (ret < 0) {
3176 ERR("Error sending ready command to lttng-sessiond");
3177 goto end;
3178 }
3179
3180 /* prepare the FDs to poll : to client socket and the should_quit pipe */
3181 consumer_sockpoll[0].fd = ctx->consumer_should_quit[0];
3182 consumer_sockpoll[0].events = POLLIN | POLLPRI;
3183 consumer_sockpoll[1].fd = client_socket;
3184 consumer_sockpoll[1].events = POLLIN | POLLPRI;
3185
3186 ret = lttng_consumer_poll_socket(consumer_sockpoll);
3187 if (ret) {
3188 if (ret > 0) {
3189 /* should exit */
3190 err = 0;
3191 }
3192 goto end;
3193 }
3194 DBG("Connection on client_socket");
3195
3196 /* Blocking call, waiting for transmission */
3197 sock = lttcomm_accept_unix_sock(client_socket);
3198 if (sock < 0) {
3199 WARN("On accept");
3200 goto end;
3201 }
3202
3203 /*
3204 * Setup metadata socket which is the second socket connection on the
3205 * command unix socket.
3206 */
3207 ret = set_metadata_socket(ctx, consumer_sockpoll, client_socket);
3208 if (ret) {
3209 if (ret > 0) {
3210 /* should exit */
3211 err = 0;
3212 }
3213 goto end;
3214 }
3215
3216 /* This socket is not useful anymore. */
3217 ret = close(client_socket);
3218 if (ret < 0) {
3219 PERROR("close client_socket");
3220 }
3221 client_socket = -1;
3222
3223 /* update the polling structure to poll on the established socket */
3224 consumer_sockpoll[1].fd = sock;
3225 consumer_sockpoll[1].events = POLLIN | POLLPRI;
3226
3227 while (1) {
3228 health_code_update();
3229
3230 health_poll_entry();
3231 ret = lttng_consumer_poll_socket(consumer_sockpoll);
3232 health_poll_exit();
3233 if (ret) {
3234 if (ret > 0) {
3235 /* should exit */
3236 err = 0;
3237 }
3238 goto end;
3239 }
3240 DBG("Incoming command on sock");
3241 ret = lttng_consumer_recv_cmd(ctx, sock, consumer_sockpoll);
3242 if (ret <= 0) {
3243 /*
3244 * This could simply be a session daemon quitting. Don't output
3245 * ERR() here.
3246 */
3247 DBG("Communication interrupted on command socket");
3248 err = 0;
3249 goto end;
3250 }
3251 if (CMM_LOAD_SHARED(consumer_quit)) {
3252 DBG("consumer_thread_receive_fds received quit from signal");
3253 err = 0; /* All is OK */
3254 goto end;
3255 }
3256 DBG("received command on sock");
3257 }
3258 /* All is OK */
3259 err = 0;
3260
3261 end:
3262 DBG("Consumer thread sessiond poll exiting");
3263
3264 /*
3265 * Close metadata streams since the producer is the session daemon which
3266 * just died.
3267 *
3268 * NOTE: for now, this only applies to the UST tracer.
3269 */
3270 lttng_consumer_close_all_metadata();
3271
3272 /*
3273 * when all fds have hung up, the polling thread
3274 * can exit cleanly
3275 */
3276 CMM_STORE_SHARED(consumer_quit, 1);
3277
3278 /*
3279 * Notify the data poll thread to poll back again and test the
3280 * consumer_quit state that we just set so to quit gracefully.
3281 */
3282 notify_thread_lttng_pipe(ctx->consumer_data_pipe);
3283
3284 notify_channel_pipe(ctx, NULL, -1, CONSUMER_CHANNEL_QUIT);
3285
3286 notify_health_quit_pipe(health_quit_pipe);
3287
3288 /* Cleaning up possibly open sockets. */
3289 if (sock >= 0) {
3290 ret = close(sock);
3291 if (ret < 0) {
3292 PERROR("close sock sessiond poll");
3293 }
3294 }
3295 if (client_socket >= 0) {
3296 ret = close(client_socket);
3297 if (ret < 0) {
3298 PERROR("close client_socket sessiond poll");
3299 }
3300 }
3301
3302 error_testpoint:
3303 if (err) {
3304 health_error();
3305 ERR("Health error occurred in %s", __func__);
3306 }
3307 health_unregister(health_consumerd);
3308
3309 rcu_unregister_thread();
3310 return NULL;
3311 }
3312
3313 ssize_t lttng_consumer_read_subbuffer(struct lttng_consumer_stream *stream,
3314 struct lttng_consumer_local_data *ctx,
3315 bool locked_by_caller)
3316 {
3317 ssize_t ret, written_bytes;
3318 int rotation_ret;
3319 struct stream_subbuffer subbuffer = {};
3320
3321 if (!locked_by_caller) {
3322 stream->read_subbuffer_ops.lock(stream);
3323 }
3324
3325 if (stream->read_subbuffer_ops.on_wake_up) {
3326 ret = stream->read_subbuffer_ops.on_wake_up(stream);
3327 if (ret) {
3328 goto end;
3329 }
3330 }
3331
3332 /*
3333 * If the stream was flagged to be ready for rotation before we extract
3334 * the next packet, rotate it now.
3335 */
3336 if (stream->rotate_ready) {
3337 DBG("Rotate stream before consuming data");
3338 ret = lttng_consumer_rotate_stream(ctx, stream);
3339 if (ret < 0) {
3340 ERR("Stream rotation error before consuming data");
3341 goto end;
3342 }
3343 }
3344
3345 ret = stream->read_subbuffer_ops.get_next_subbuffer(stream, &subbuffer);
3346 if (ret) {
3347 if (ret == -ENODATA) {
3348 /* Not an error. */
3349 ret = 0;
3350 goto sleep_stream;
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 stream_sleep:
3417 if (stream->read_subbuffer_ops.on_sleep) {
3418 stream->read_subbuffer_ops.on_sleep(stream, ctx);
3419 }
3420
3421 ret = written_bytes;
3422 end:
3423 if (!locked_by_caller) {
3424 stream->read_subbuffer_ops.unlock(stream);
3425 }
3426
3427 return ret;
3428 error_put_subbuf:
3429 (void) stream->read_subbuffer_ops.put_next_subbuffer(stream, &subbuffer);
3430 goto end;
3431 }
3432
3433 int lttng_consumer_on_recv_stream(struct lttng_consumer_stream *stream)
3434 {
3435 switch (consumer_data.type) {
3436 case LTTNG_CONSUMER_KERNEL:
3437 return lttng_kconsumer_on_recv_stream(stream);
3438 case LTTNG_CONSUMER32_UST:
3439 case LTTNG_CONSUMER64_UST:
3440 return lttng_ustconsumer_on_recv_stream(stream);
3441 default:
3442 ERR("Unknown consumer_data type");
3443 assert(0);
3444 return -ENOSYS;
3445 }
3446 }
3447
3448 /*
3449 * Allocate and set consumer data hash tables.
3450 */
3451 int lttng_consumer_init(void)
3452 {
3453 consumer_data.channel_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3454 if (!consumer_data.channel_ht) {
3455 goto error;
3456 }
3457
3458 consumer_data.channels_by_session_id_ht =
3459 lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3460 if (!consumer_data.channels_by_session_id_ht) {
3461 goto error;
3462 }
3463
3464 consumer_data.relayd_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3465 if (!consumer_data.relayd_ht) {
3466 goto error;
3467 }
3468
3469 consumer_data.stream_list_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3470 if (!consumer_data.stream_list_ht) {
3471 goto error;
3472 }
3473
3474 consumer_data.stream_per_chan_id_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3475 if (!consumer_data.stream_per_chan_id_ht) {
3476 goto error;
3477 }
3478
3479 data_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3480 if (!data_ht) {
3481 goto error;
3482 }
3483
3484 metadata_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3485 if (!metadata_ht) {
3486 goto error;
3487 }
3488
3489 consumer_data.chunk_registry = lttng_trace_chunk_registry_create();
3490 if (!consumer_data.chunk_registry) {
3491 goto error;
3492 }
3493
3494 return 0;
3495
3496 error:
3497 return -1;
3498 }
3499
3500 /*
3501 * Process the ADD_RELAYD command receive by a consumer.
3502 *
3503 * This will create a relayd socket pair and add it to the relayd hash table.
3504 * The caller MUST acquire a RCU read side lock before calling it.
3505 */
3506 void consumer_add_relayd_socket(uint64_t net_seq_idx, int sock_type,
3507 struct lttng_consumer_local_data *ctx, int sock,
3508 struct pollfd *consumer_sockpoll,
3509 struct lttcomm_relayd_sock *relayd_sock, uint64_t sessiond_id,
3510 uint64_t relayd_session_id)
3511 {
3512 int fd = -1, ret = -1, relayd_created = 0;
3513 enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
3514 struct consumer_relayd_sock_pair *relayd = NULL;
3515
3516 assert(ctx);
3517 assert(relayd_sock);
3518
3519 DBG("Consumer adding relayd socket (idx: %" PRIu64 ")", net_seq_idx);
3520
3521 /* Get relayd reference if exists. */
3522 relayd = consumer_find_relayd(net_seq_idx);
3523 if (relayd == NULL) {
3524 assert(sock_type == LTTNG_STREAM_CONTROL);
3525 /* Not found. Allocate one. */
3526 relayd = consumer_allocate_relayd_sock_pair(net_seq_idx);
3527 if (relayd == NULL) {
3528 ret_code = LTTCOMM_CONSUMERD_ENOMEM;
3529 goto error;
3530 } else {
3531 relayd->sessiond_session_id = sessiond_id;
3532 relayd_created = 1;
3533 }
3534
3535 /*
3536 * This code path MUST continue to the consumer send status message to
3537 * we can notify the session daemon and continue our work without
3538 * killing everything.
3539 */
3540 } else {
3541 /*
3542 * relayd key should never be found for control socket.
3543 */
3544 assert(sock_type != LTTNG_STREAM_CONTROL);
3545 }
3546
3547 /* First send a status message before receiving the fds. */
3548 ret = consumer_send_status_msg(sock, LTTCOMM_CONSUMERD_SUCCESS);
3549 if (ret < 0) {
3550 /* Somehow, the session daemon is not responding anymore. */
3551 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_FATAL);
3552 goto error_nosignal;
3553 }
3554
3555 /* Poll on consumer socket. */
3556 ret = lttng_consumer_poll_socket(consumer_sockpoll);
3557 if (ret) {
3558 /* Needing to exit in the middle of a command: error. */
3559 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
3560 goto error_nosignal;
3561 }
3562
3563 /* Get relayd socket from session daemon */
3564 ret = lttcomm_recv_fds_unix_sock(sock, &fd, 1);
3565 if (ret != sizeof(fd)) {
3566 fd = -1; /* Just in case it gets set with an invalid value. */
3567
3568 /*
3569 * Failing to receive FDs might indicate a major problem such as
3570 * reaching a fd limit during the receive where the kernel returns a
3571 * MSG_CTRUNC and fails to cleanup the fd in the queue. Any case, we
3572 * don't take any chances and stop everything.
3573 *
3574 * XXX: Feature request #558 will fix that and avoid this possible
3575 * issue when reaching the fd limit.
3576 */
3577 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_ERROR_RECV_FD);
3578 ret_code = LTTCOMM_CONSUMERD_ERROR_RECV_FD;
3579 goto error;
3580 }
3581
3582 /* Copy socket information and received FD */
3583 switch (sock_type) {
3584 case LTTNG_STREAM_CONTROL:
3585 /* Copy received lttcomm socket */
3586 lttcomm_copy_sock(&relayd->control_sock.sock, &relayd_sock->sock);
3587 ret = lttcomm_create_sock(&relayd->control_sock.sock);
3588 /* Handle create_sock error. */
3589 if (ret < 0) {
3590 ret_code = LTTCOMM_CONSUMERD_ENOMEM;
3591 goto error;
3592 }
3593 /*
3594 * Close the socket created internally by
3595 * lttcomm_create_sock, so we can replace it by the one
3596 * received from sessiond.
3597 */
3598 if (close(relayd->control_sock.sock.fd)) {
3599 PERROR("close");
3600 }
3601
3602 /* Assign new file descriptor */
3603 relayd->control_sock.sock.fd = fd;
3604 /* Assign version values. */
3605 relayd->control_sock.major = relayd_sock->major;
3606 relayd->control_sock.minor = relayd_sock->minor;
3607
3608 relayd->relayd_session_id = relayd_session_id;
3609
3610 break;
3611 case LTTNG_STREAM_DATA:
3612 /* Copy received lttcomm socket */
3613 lttcomm_copy_sock(&relayd->data_sock.sock, &relayd_sock->sock);
3614 ret = lttcomm_create_sock(&relayd->data_sock.sock);
3615 /* Handle create_sock error. */
3616 if (ret < 0) {
3617 ret_code = LTTCOMM_CONSUMERD_ENOMEM;
3618 goto error;
3619 }
3620 /*
3621 * Close the socket created internally by
3622 * lttcomm_create_sock, so we can replace it by the one
3623 * received from sessiond.
3624 */
3625 if (close(relayd->data_sock.sock.fd)) {
3626 PERROR("close");
3627 }
3628
3629 /* Assign new file descriptor */
3630 relayd->data_sock.sock.fd = fd;
3631 /* Assign version values. */
3632 relayd->data_sock.major = relayd_sock->major;
3633 relayd->data_sock.minor = relayd_sock->minor;
3634 break;
3635 default:
3636 ERR("Unknown relayd socket type (%d)", sock_type);
3637 ret_code = LTTCOMM_CONSUMERD_FATAL;
3638 goto error;
3639 }
3640
3641 DBG("Consumer %s socket created successfully with net idx %" PRIu64 " (fd: %d)",
3642 sock_type == LTTNG_STREAM_CONTROL ? "control" : "data",
3643 relayd->net_seq_idx, fd);
3644 /*
3645 * We gave the ownership of the fd to the relayd structure. Set the
3646 * fd to -1 so we don't call close() on it in the error path below.
3647 */
3648 fd = -1;
3649
3650 /* We successfully added the socket. Send status back. */
3651 ret = consumer_send_status_msg(sock, ret_code);
3652 if (ret < 0) {
3653 /* Somehow, the session daemon is not responding anymore. */
3654 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_FATAL);
3655 goto error_nosignal;
3656 }
3657
3658 /*
3659 * Add relayd socket pair to consumer data hashtable. If object already
3660 * exists or on error, the function gracefully returns.
3661 */
3662 relayd->ctx = ctx;
3663 add_relayd(relayd);
3664
3665 /* All good! */
3666 return;
3667
3668 error:
3669 if (consumer_send_status_msg(sock, ret_code) < 0) {
3670 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_FATAL);
3671 }
3672
3673 error_nosignal:
3674 /* Close received socket if valid. */
3675 if (fd >= 0) {
3676 if (close(fd)) {
3677 PERROR("close received socket");
3678 }
3679 }
3680
3681 if (relayd_created) {
3682 free(relayd);
3683 }
3684 }
3685
3686 /*
3687 * Search for a relayd associated to the session id and return the reference.
3688 *
3689 * A rcu read side lock MUST be acquire before calling this function and locked
3690 * until the relayd object is no longer necessary.
3691 */
3692 static struct consumer_relayd_sock_pair *find_relayd_by_session_id(uint64_t id)
3693 {
3694 struct lttng_ht_iter iter;
3695 struct consumer_relayd_sock_pair *relayd = NULL;
3696
3697 /* Iterate over all relayd since they are indexed by net_seq_idx. */
3698 cds_lfht_for_each_entry(consumer_data.relayd_ht->ht, &iter.iter, relayd,
3699 node.node) {
3700 /*
3701 * Check by sessiond id which is unique here where the relayd session
3702 * id might not be when having multiple relayd.
3703 */
3704 if (relayd->sessiond_session_id == id) {
3705 /* Found the relayd. There can be only one per id. */
3706 goto found;
3707 }
3708 }
3709
3710 return NULL;
3711
3712 found:
3713 return relayd;
3714 }
3715
3716 /*
3717 * Check if for a given session id there is still data needed to be extract
3718 * from the buffers.
3719 *
3720 * Return 1 if data is pending or else 0 meaning ready to be read.
3721 */
3722 int consumer_data_pending(uint64_t id)
3723 {
3724 int ret;
3725 struct lttng_ht_iter iter;
3726 struct lttng_ht *ht;
3727 struct lttng_consumer_stream *stream;
3728 struct consumer_relayd_sock_pair *relayd = NULL;
3729 int (*data_pending)(struct lttng_consumer_stream *);
3730
3731 DBG("Consumer data pending command on session id %" PRIu64, id);
3732
3733 rcu_read_lock();
3734 pthread_mutex_lock(&consumer_data.lock);
3735
3736 switch (consumer_data.type) {
3737 case LTTNG_CONSUMER_KERNEL:
3738 data_pending = lttng_kconsumer_data_pending;
3739 break;
3740 case LTTNG_CONSUMER32_UST:
3741 case LTTNG_CONSUMER64_UST:
3742 data_pending = lttng_ustconsumer_data_pending;
3743 break;
3744 default:
3745 ERR("Unknown consumer data type");
3746 assert(0);
3747 }
3748
3749 /* Ease our life a bit */
3750 ht = consumer_data.stream_list_ht;
3751
3752 cds_lfht_for_each_entry_duplicate(ht->ht,
3753 ht->hash_fct(&id, lttng_ht_seed),
3754 ht->match_fct, &id,
3755 &iter.iter, stream, node_session_id.node) {
3756 pthread_mutex_lock(&stream->lock);
3757
3758 /*
3759 * A removed node from the hash table indicates that the stream has
3760 * been deleted thus having a guarantee that the buffers are closed
3761 * on the consumer side. However, data can still be transmitted
3762 * over the network so don't skip the relayd check.
3763 */
3764 ret = cds_lfht_is_node_deleted(&stream->node.node);
3765 if (!ret) {
3766 /* Check the stream if there is data in the buffers. */
3767 ret = data_pending(stream);
3768 if (ret == 1) {
3769 pthread_mutex_unlock(&stream->lock);
3770 goto data_pending;
3771 }
3772 }
3773
3774 pthread_mutex_unlock(&stream->lock);
3775 }
3776
3777 relayd = find_relayd_by_session_id(id);
3778 if (relayd) {
3779 unsigned int is_data_inflight = 0;
3780
3781 /* Send init command for data pending. */
3782 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
3783 ret = relayd_begin_data_pending(&relayd->control_sock,
3784 relayd->relayd_session_id);
3785 if (ret < 0) {
3786 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3787 /* Communication error thus the relayd so no data pending. */
3788 goto data_not_pending;
3789 }
3790
3791 cds_lfht_for_each_entry_duplicate(ht->ht,
3792 ht->hash_fct(&id, lttng_ht_seed),
3793 ht->match_fct, &id,
3794 &iter.iter, stream, node_session_id.node) {
3795 if (stream->metadata_flag) {
3796 ret = relayd_quiescent_control(&relayd->control_sock,
3797 stream->relayd_stream_id);
3798 } else {
3799 ret = relayd_data_pending(&relayd->control_sock,
3800 stream->relayd_stream_id,
3801 stream->next_net_seq_num - 1);
3802 }
3803
3804 if (ret == 1) {
3805 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3806 goto data_pending;
3807 } else if (ret < 0) {
3808 ERR("Relayd data pending failed. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
3809 lttng_consumer_cleanup_relayd(relayd);
3810 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3811 goto data_not_pending;
3812 }
3813 }
3814
3815 /* Send end command for data pending. */
3816 ret = relayd_end_data_pending(&relayd->control_sock,
3817 relayd->relayd_session_id, &is_data_inflight);
3818 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3819 if (ret < 0) {
3820 ERR("Relayd end data pending failed. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
3821 lttng_consumer_cleanup_relayd(relayd);
3822 goto data_not_pending;
3823 }
3824 if (is_data_inflight) {
3825 goto data_pending;
3826 }
3827 }
3828
3829 /*
3830 * Finding _no_ node in the hash table and no inflight data means that the
3831 * stream(s) have been removed thus data is guaranteed to be available for
3832 * analysis from the trace files.
3833 */
3834
3835 data_not_pending:
3836 /* Data is available to be read by a viewer. */
3837 pthread_mutex_unlock(&consumer_data.lock);
3838 rcu_read_unlock();
3839 return 0;
3840
3841 data_pending:
3842 /* Data is still being extracted from buffers. */
3843 pthread_mutex_unlock(&consumer_data.lock);
3844 rcu_read_unlock();
3845 return 1;
3846 }
3847
3848 /*
3849 * Send a ret code status message to the sessiond daemon.
3850 *
3851 * Return the sendmsg() return value.
3852 */
3853 int consumer_send_status_msg(int sock, int ret_code)
3854 {
3855 struct lttcomm_consumer_status_msg msg;
3856
3857 memset(&msg, 0, sizeof(msg));
3858 msg.ret_code = ret_code;
3859
3860 return lttcomm_send_unix_sock(sock, &msg, sizeof(msg));
3861 }
3862
3863 /*
3864 * Send a channel status message to the sessiond daemon.
3865 *
3866 * Return the sendmsg() return value.
3867 */
3868 int consumer_send_status_channel(int sock,
3869 struct lttng_consumer_channel *channel)
3870 {
3871 struct lttcomm_consumer_status_channel msg;
3872
3873 assert(sock >= 0);
3874
3875 memset(&msg, 0, sizeof(msg));
3876 if (!channel) {
3877 msg.ret_code = LTTCOMM_CONSUMERD_CHANNEL_FAIL;
3878 } else {
3879 msg.ret_code = LTTCOMM_CONSUMERD_SUCCESS;
3880 msg.key = channel->key;
3881 msg.stream_count = channel->streams.count;
3882 }
3883
3884 return lttcomm_send_unix_sock(sock, &msg, sizeof(msg));
3885 }
3886
3887 unsigned long consumer_get_consume_start_pos(unsigned long consumed_pos,
3888 unsigned long produced_pos, uint64_t nb_packets_per_stream,
3889 uint64_t max_sb_size)
3890 {
3891 unsigned long start_pos;
3892
3893 if (!nb_packets_per_stream) {
3894 return consumed_pos; /* Grab everything */
3895 }
3896 start_pos = produced_pos - offset_align_floor(produced_pos, max_sb_size);
3897 start_pos -= max_sb_size * nb_packets_per_stream;
3898 if ((long) (start_pos - consumed_pos) < 0) {
3899 return consumed_pos; /* Grab everything */
3900 }
3901 return start_pos;
3902 }
3903
3904 static
3905 int consumer_flush_buffer(struct lttng_consumer_stream *stream, int producer_active)
3906 {
3907 int ret = 0;
3908
3909 switch (consumer_data.type) {
3910 case LTTNG_CONSUMER_KERNEL:
3911 if (producer_active) {
3912 ret = kernctl_buffer_flush(stream->wait_fd);
3913 if (ret < 0) {
3914 ERR("Failed to flush kernel stream");
3915 goto end;
3916 }
3917 } else {
3918 ret = kernctl_buffer_flush_empty(stream->wait_fd);
3919 if (ret < 0) {
3920 ERR("Failed to flush kernel stream");
3921 goto end;
3922 }
3923 }
3924 break;
3925 case LTTNG_CONSUMER32_UST:
3926 case LTTNG_CONSUMER64_UST:
3927 lttng_ustconsumer_flush_buffer(stream, producer_active);
3928 break;
3929 default:
3930 ERR("Unknown consumer_data type");
3931 abort();
3932 }
3933
3934 end:
3935 return ret;
3936 }
3937
3938 /*
3939 * Sample the rotate position for all the streams of a channel. If a stream
3940 * is already at the rotate position (produced == consumed), we flag it as
3941 * ready for rotation. The rotation of ready streams occurs after we have
3942 * replied to the session daemon that we have finished sampling the positions.
3943 * Must be called with RCU read-side lock held to ensure existence of channel.
3944 *
3945 * Returns 0 on success, < 0 on error
3946 */
3947 int lttng_consumer_rotate_channel(struct lttng_consumer_channel *channel,
3948 uint64_t key, uint64_t relayd_id, uint32_t metadata,
3949 struct lttng_consumer_local_data *ctx)
3950 {
3951 int ret;
3952 struct lttng_consumer_stream *stream;
3953 struct lttng_ht_iter iter;
3954 struct lttng_ht *ht = consumer_data.stream_per_chan_id_ht;
3955 struct lttng_dynamic_array stream_rotation_positions;
3956 uint64_t next_chunk_id, stream_count = 0;
3957 enum lttng_trace_chunk_status chunk_status;
3958 const bool is_local_trace = relayd_id == -1ULL;
3959 struct consumer_relayd_sock_pair *relayd = NULL;
3960 bool rotating_to_new_chunk = true;
3961
3962 DBG("Consumer sample rotate position for channel %" PRIu64, key);
3963
3964 lttng_dynamic_array_init(&stream_rotation_positions,
3965 sizeof(struct relayd_stream_rotation_position), NULL);
3966
3967 rcu_read_lock();
3968
3969 pthread_mutex_lock(&channel->lock);
3970 assert(channel->trace_chunk);
3971 chunk_status = lttng_trace_chunk_get_id(channel->trace_chunk,
3972 &next_chunk_id);
3973 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
3974 ret = -1;
3975 goto end_unlock_channel;
3976 }
3977
3978 cds_lfht_for_each_entry_duplicate(ht->ht,
3979 ht->hash_fct(&channel->key, lttng_ht_seed),
3980 ht->match_fct, &channel->key, &iter.iter,
3981 stream, node_channel_id.node) {
3982 unsigned long produced_pos = 0, consumed_pos = 0;
3983
3984 health_code_update();
3985
3986 /*
3987 * Lock stream because we are about to change its state.
3988 */
3989 pthread_mutex_lock(&stream->lock);
3990
3991 if (stream->trace_chunk == stream->chan->trace_chunk) {
3992 rotating_to_new_chunk = false;
3993 }
3994
3995 /*
3996 * Do not flush an empty packet when rotating from a NULL trace
3997 * chunk. The stream has no means to output data, and the prior
3998 * rotation which rotated to NULL performed that side-effect already.
3999 */
4000 if (stream->trace_chunk) {
4001 /*
4002 * For metadata stream, do an active flush, which does not
4003 * produce empty packets. For data streams, empty-flush;
4004 * ensures we have at least one packet in each stream per trace
4005 * chunk, even if no data was produced.
4006 */
4007 ret = consumer_flush_buffer(stream, stream->metadata_flag ? 1 : 0);
4008 if (ret < 0) {
4009 ERR("Failed to flush stream %" PRIu64 " during channel rotation",
4010 stream->key);
4011 goto end_unlock_stream;
4012 }
4013 }
4014
4015 ret = lttng_consumer_take_snapshot(stream);
4016 if (ret < 0 && ret != -ENODATA && ret != -EAGAIN) {
4017 ERR("Failed to sample snapshot position during channel rotation");
4018 goto end_unlock_stream;
4019 }
4020 if (!ret) {
4021 ret = lttng_consumer_get_produced_snapshot(stream,
4022 &produced_pos);
4023 if (ret < 0) {
4024 ERR("Failed to sample produced position during channel rotation");
4025 goto end_unlock_stream;
4026 }
4027
4028 ret = lttng_consumer_get_consumed_snapshot(stream,
4029 &consumed_pos);
4030 if (ret < 0) {
4031 ERR("Failed to sample consumed position during channel rotation");
4032 goto end_unlock_stream;
4033 }
4034 }
4035 /*
4036 * Align produced position on the start-of-packet boundary of the first
4037 * packet going into the next trace chunk.
4038 */
4039 produced_pos = ALIGN_FLOOR(produced_pos, stream->max_sb_size);
4040 if (consumed_pos == produced_pos) {
4041 stream->rotate_ready = true;
4042 }
4043 /*
4044 * The rotation position is based on the packet_seq_num of the
4045 * packet following the last packet that was consumed for this
4046 * stream, incremented by the offset between produced and
4047 * consumed positions. This rotation position is a lower bound
4048 * (inclusive) at which the next trace chunk starts. Since it
4049 * is a lower bound, it is OK if the packet_seq_num does not
4050 * correspond exactly to the same packet identified by the
4051 * consumed_pos, which can happen in overwrite mode.
4052 */
4053 if (stream->sequence_number_unavailable) {
4054 /*
4055 * Rotation should never be performed on a session which
4056 * interacts with a pre-2.8 lttng-modules, which does
4057 * not implement packet sequence number.
4058 */
4059 ERR("Failure to rotate stream %" PRIu64 ": sequence number unavailable",
4060 stream->key);
4061 ret = -1;
4062 goto end_unlock_stream;
4063 }
4064 stream->rotate_position = stream->last_sequence_number + 1 +
4065 ((produced_pos - consumed_pos) / stream->max_sb_size);
4066
4067 if (!is_local_trace) {
4068 /*
4069 * The relay daemon control protocol expects a rotation
4070 * position as "the sequence number of the first packet
4071 * _after_ the current trace chunk".
4072 */
4073 const struct relayd_stream_rotation_position position = {
4074 .stream_id = stream->relayd_stream_id,
4075 .rotate_at_seq_num = stream->rotate_position,
4076 };
4077
4078 ret = lttng_dynamic_array_add_element(
4079 &stream_rotation_positions,
4080 &position);
4081 if (ret) {
4082 ERR("Failed to allocate stream rotation position");
4083 goto end_unlock_stream;
4084 }
4085 stream_count++;
4086 }
4087 pthread_mutex_unlock(&stream->lock);
4088 }
4089 stream = NULL;
4090 pthread_mutex_unlock(&channel->lock);
4091
4092 if (is_local_trace) {
4093 ret = 0;
4094 goto end;
4095 }
4096
4097 relayd = consumer_find_relayd(relayd_id);
4098 if (!relayd) {
4099 ERR("Failed to find relayd %" PRIu64, relayd_id);
4100 ret = -1;
4101 goto end;
4102 }
4103
4104 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
4105 ret = relayd_rotate_streams(&relayd->control_sock, stream_count,
4106 rotating_to_new_chunk ? &next_chunk_id : NULL,
4107 (const struct relayd_stream_rotation_position *)
4108 stream_rotation_positions.buffer.data);
4109 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
4110 if (ret < 0) {
4111 ERR("Relayd rotate stream failed. Cleaning up relayd %" PRIu64,
4112 relayd->net_seq_idx);
4113 lttng_consumer_cleanup_relayd(relayd);
4114 goto end;
4115 }
4116
4117 ret = 0;
4118 goto end;
4119
4120 end_unlock_stream:
4121 pthread_mutex_unlock(&stream->lock);
4122 end_unlock_channel:
4123 pthread_mutex_unlock(&channel->lock);
4124 end:
4125 rcu_read_unlock();
4126 lttng_dynamic_array_reset(&stream_rotation_positions);
4127 return ret;
4128 }
4129
4130 /*
4131 * Check if a stream is ready to be rotated after extracting it.
4132 *
4133 * Return 1 if it is ready for rotation, 0 if it is not, a negative value on
4134 * error. Stream lock must be held.
4135 */
4136 int lttng_consumer_stream_is_rotate_ready(struct lttng_consumer_stream *stream)
4137 {
4138 if (stream->rotate_ready) {
4139 return 1;
4140 }
4141
4142 /*
4143 * If packet seq num is unavailable, it means we are interacting
4144 * with a pre-2.8 lttng-modules which does not implement the
4145 * sequence number. Rotation should never be used by sessiond in this
4146 * scenario.
4147 */
4148 if (stream->sequence_number_unavailable) {
4149 ERR("Internal error: rotation used on stream %" PRIu64
4150 " with unavailable sequence number",
4151 stream->key);
4152 return -1;
4153 }
4154
4155 if (stream->rotate_position == -1ULL ||
4156 stream->last_sequence_number == -1ULL) {
4157 return 0;
4158 }
4159
4160 /*
4161 * Rotate position not reached yet. The stream rotate position is
4162 * the position of the next packet belonging to the next trace chunk,
4163 * but consumerd considers rotation ready when reaching the last
4164 * packet of the current chunk, hence the "rotate_position - 1".
4165 */
4166 if (stream->last_sequence_number >= stream->rotate_position - 1) {
4167 return 1;
4168 }
4169
4170 return 0;
4171 }
4172
4173 /*
4174 * Reset the state for a stream after a rotation occurred.
4175 */
4176 void lttng_consumer_reset_stream_rotate_state(struct lttng_consumer_stream *stream)
4177 {
4178 stream->rotate_position = -1ULL;
4179 stream->rotate_ready = false;
4180 }
4181
4182 /*
4183 * Perform the rotation a local stream file.
4184 */
4185 static
4186 int rotate_local_stream(struct lttng_consumer_local_data *ctx,
4187 struct lttng_consumer_stream *stream)
4188 {
4189 int ret = 0;
4190
4191 DBG("Rotate local stream: stream key %" PRIu64 ", channel key %" PRIu64,
4192 stream->key,
4193 stream->chan->key);
4194 stream->tracefile_size_current = 0;
4195 stream->tracefile_count_current = 0;
4196
4197 if (stream->out_fd >= 0) {
4198 ret = close(stream->out_fd);
4199 if (ret) {
4200 PERROR("Failed to close stream out_fd of channel \"%s\"",
4201 stream->chan->name);
4202 }
4203 stream->out_fd = -1;
4204 }
4205
4206 if (stream->index_file) {
4207 lttng_index_file_put(stream->index_file);
4208 stream->index_file = NULL;
4209 }
4210
4211 if (!stream->trace_chunk) {
4212 goto end;
4213 }
4214
4215 ret = consumer_stream_create_output_files(stream, true);
4216 end:
4217 return ret;
4218 }
4219
4220 /*
4221 * Performs the stream rotation for the rotate session feature if needed.
4222 * It must be called with the channel and stream locks held.
4223 *
4224 * Return 0 on success, a negative number of error.
4225 */
4226 int lttng_consumer_rotate_stream(struct lttng_consumer_local_data *ctx,
4227 struct lttng_consumer_stream *stream)
4228 {
4229 int ret;
4230
4231 DBG("Consumer rotate stream %" PRIu64, stream->key);
4232
4233 /*
4234 * Update the stream's 'current' chunk to the session's (channel)
4235 * now-current chunk.
4236 */
4237 lttng_trace_chunk_put(stream->trace_chunk);
4238 if (stream->chan->trace_chunk == stream->trace_chunk) {
4239 /*
4240 * A channel can be rotated and not have a "next" chunk
4241 * to transition to. In that case, the channel's "current chunk"
4242 * has not been closed yet, but it has not been updated to
4243 * a "next" trace chunk either. Hence, the stream, like its
4244 * parent channel, becomes part of no chunk and can't output
4245 * anything until a new trace chunk is created.
4246 */
4247 stream->trace_chunk = NULL;
4248 } else if (stream->chan->trace_chunk &&
4249 !lttng_trace_chunk_get(stream->chan->trace_chunk)) {
4250 ERR("Failed to acquire a reference to channel's trace chunk during stream rotation");
4251 ret = -1;
4252 goto error;
4253 } else {
4254 /*
4255 * Update the stream's trace chunk to its parent channel's
4256 * current trace chunk.
4257 */
4258 stream->trace_chunk = stream->chan->trace_chunk;
4259 }
4260
4261 if (stream->net_seq_idx == (uint64_t) -1ULL) {
4262 ret = rotate_local_stream(ctx, stream);
4263 if (ret < 0) {
4264 ERR("Failed to rotate stream, ret = %i", ret);
4265 goto error;
4266 }
4267 }
4268
4269 if (stream->metadata_flag && stream->trace_chunk) {
4270 /*
4271 * If the stream has transitioned to a new trace
4272 * chunk, the metadata should be re-dumped to the
4273 * newest chunk.
4274 *
4275 * However, it is possible for a stream to transition to
4276 * a "no-chunk" state. This can happen if a rotation
4277 * occurs on an inactive session. In such cases, the metadata
4278 * regeneration will happen when the next trace chunk is
4279 * created.
4280 */
4281 ret = consumer_metadata_stream_dump(stream);
4282 if (ret) {
4283 goto error;
4284 }
4285 }
4286 lttng_consumer_reset_stream_rotate_state(stream);
4287
4288 ret = 0;
4289
4290 error:
4291 return ret;
4292 }
4293
4294 /*
4295 * Rotate all the ready streams now.
4296 *
4297 * This is especially important for low throughput streams that have already
4298 * been consumed, we cannot wait for their next packet to perform the
4299 * rotation.
4300 * Need to be called with RCU read-side lock held to ensure existence of
4301 * channel.
4302 *
4303 * Returns 0 on success, < 0 on error
4304 */
4305 int lttng_consumer_rotate_ready_streams(struct lttng_consumer_channel *channel,
4306 uint64_t key, struct lttng_consumer_local_data *ctx)
4307 {
4308 int ret;
4309 struct lttng_consumer_stream *stream;
4310 struct lttng_ht_iter iter;
4311 struct lttng_ht *ht = consumer_data.stream_per_chan_id_ht;
4312
4313 rcu_read_lock();
4314
4315 DBG("Consumer rotate ready streams in channel %" PRIu64, key);
4316
4317 cds_lfht_for_each_entry_duplicate(ht->ht,
4318 ht->hash_fct(&channel->key, lttng_ht_seed),
4319 ht->match_fct, &channel->key, &iter.iter,
4320 stream, node_channel_id.node) {
4321 health_code_update();
4322
4323 pthread_mutex_lock(&stream->chan->lock);
4324 pthread_mutex_lock(&stream->lock);
4325
4326 if (!stream->rotate_ready) {
4327 pthread_mutex_unlock(&stream->lock);
4328 pthread_mutex_unlock(&stream->chan->lock);
4329 continue;
4330 }
4331 DBG("Consumer rotate ready stream %" PRIu64, stream->key);
4332
4333 ret = lttng_consumer_rotate_stream(ctx, stream);
4334 pthread_mutex_unlock(&stream->lock);
4335 pthread_mutex_unlock(&stream->chan->lock);
4336 if (ret) {
4337 goto end;
4338 }
4339 }
4340
4341 ret = 0;
4342
4343 end:
4344 rcu_read_unlock();
4345 return ret;
4346 }
4347
4348 enum lttcomm_return_code lttng_consumer_init_command(
4349 struct lttng_consumer_local_data *ctx,
4350 const lttng_uuid sessiond_uuid)
4351 {
4352 enum lttcomm_return_code ret;
4353 char uuid_str[UUID_STR_LEN];
4354
4355 if (ctx->sessiond_uuid.is_set) {
4356 ret = LTTCOMM_CONSUMERD_ALREADY_SET;
4357 goto end;
4358 }
4359
4360 ctx->sessiond_uuid.is_set = true;
4361 memcpy(ctx->sessiond_uuid.value, sessiond_uuid, sizeof(lttng_uuid));
4362 ret = LTTCOMM_CONSUMERD_SUCCESS;
4363 lttng_uuid_to_str(sessiond_uuid, uuid_str);
4364 DBG("Received session daemon UUID: %s", uuid_str);
4365 end:
4366 return ret;
4367 }
4368
4369 enum lttcomm_return_code lttng_consumer_create_trace_chunk(
4370 const uint64_t *relayd_id, uint64_t session_id,
4371 uint64_t chunk_id,
4372 time_t chunk_creation_timestamp,
4373 const char *chunk_override_name,
4374 const struct lttng_credentials *credentials,
4375 struct lttng_directory_handle *chunk_directory_handle)
4376 {
4377 int ret;
4378 enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
4379 struct lttng_trace_chunk *created_chunk = NULL, *published_chunk = NULL;
4380 enum lttng_trace_chunk_status chunk_status;
4381 char relayd_id_buffer[MAX_INT_DEC_LEN(*relayd_id)];
4382 char creation_timestamp_buffer[ISO8601_STR_LEN];
4383 const char *relayd_id_str = "(none)";
4384 const char *creation_timestamp_str;
4385 struct lttng_ht_iter iter;
4386 struct lttng_consumer_channel *channel;
4387
4388 if (relayd_id) {
4389 /* Only used for logging purposes. */
4390 ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer),
4391 "%" PRIu64, *relayd_id);
4392 if (ret > 0 && ret < sizeof(relayd_id_buffer)) {
4393 relayd_id_str = relayd_id_buffer;
4394 } else {
4395 relayd_id_str = "(formatting error)";
4396 }
4397 }
4398
4399 /* Local protocol error. */
4400 assert(chunk_creation_timestamp);
4401 ret = time_to_iso8601_str(chunk_creation_timestamp,
4402 creation_timestamp_buffer,
4403 sizeof(creation_timestamp_buffer));
4404 creation_timestamp_str = !ret ? creation_timestamp_buffer :
4405 "(formatting error)";
4406
4407 DBG("Consumer create trace chunk command: relay_id = %s"
4408 ", session_id = %" PRIu64 ", chunk_id = %" PRIu64
4409 ", chunk_override_name = %s"
4410 ", chunk_creation_timestamp = %s",
4411 relayd_id_str, session_id, chunk_id,
4412 chunk_override_name ? : "(none)",
4413 creation_timestamp_str);
4414
4415 /*
4416 * The trace chunk registry, as used by the consumer daemon, implicitly
4417 * owns the trace chunks. This is only needed in the consumer since
4418 * the consumer has no notion of a session beyond session IDs being
4419 * used to identify other objects.
4420 *
4421 * The lttng_trace_chunk_registry_publish() call below provides a
4422 * reference which is not released; it implicitly becomes the session
4423 * daemon's reference to the chunk in the consumer daemon.
4424 *
4425 * The lifetime of trace chunks in the consumer daemon is managed by
4426 * the session daemon through the LTTNG_CONSUMER_CREATE_TRACE_CHUNK
4427 * and LTTNG_CONSUMER_DESTROY_TRACE_CHUNK commands.
4428 */
4429 created_chunk = lttng_trace_chunk_create(chunk_id,
4430 chunk_creation_timestamp);
4431 if (!created_chunk) {
4432 ERR("Failed to create trace chunk");
4433 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4434 goto error;
4435 }
4436
4437 if (chunk_override_name) {
4438 chunk_status = lttng_trace_chunk_override_name(created_chunk,
4439 chunk_override_name);
4440 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4441 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4442 goto error;
4443 }
4444 }
4445
4446 if (chunk_directory_handle) {
4447 chunk_status = lttng_trace_chunk_set_credentials(created_chunk,
4448 credentials);
4449 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4450 ERR("Failed to set trace chunk credentials");
4451 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4452 goto error;
4453 }
4454 /*
4455 * The consumer daemon has no ownership of the chunk output
4456 * directory.
4457 */
4458 chunk_status = lttng_trace_chunk_set_as_user(created_chunk,
4459 chunk_directory_handle);
4460 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4461 ERR("Failed to set trace chunk's directory handle");
4462 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4463 goto error;
4464 }
4465 }
4466
4467 published_chunk = lttng_trace_chunk_registry_publish_chunk(
4468 consumer_data.chunk_registry, session_id,
4469 created_chunk);
4470 lttng_trace_chunk_put(created_chunk);
4471 created_chunk = NULL;
4472 if (!published_chunk) {
4473 ERR("Failed to publish trace chunk");
4474 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4475 goto error;
4476 }
4477
4478 rcu_read_lock();
4479 cds_lfht_for_each_entry_duplicate(consumer_data.channels_by_session_id_ht->ht,
4480 consumer_data.channels_by_session_id_ht->hash_fct(
4481 &session_id, lttng_ht_seed),
4482 consumer_data.channels_by_session_id_ht->match_fct,
4483 &session_id, &iter.iter, channel,
4484 channels_by_session_id_ht_node.node) {
4485 ret = lttng_consumer_channel_set_trace_chunk(channel,
4486 published_chunk);
4487 if (ret) {
4488 /*
4489 * Roll-back the creation of this chunk.
4490 *
4491 * This is important since the session daemon will
4492 * assume that the creation of this chunk failed and
4493 * will never ask for it to be closed, resulting
4494 * in a leak and an inconsistent state for some
4495 * channels.
4496 */
4497 enum lttcomm_return_code close_ret;
4498 char path[LTTNG_PATH_MAX];
4499
4500 DBG("Failed to set new trace chunk on existing channels, rolling back");
4501 close_ret = lttng_consumer_close_trace_chunk(relayd_id,
4502 session_id, chunk_id,
4503 chunk_creation_timestamp, NULL,
4504 path);
4505 if (close_ret != LTTCOMM_CONSUMERD_SUCCESS) {
4506 ERR("Failed to roll-back the creation of new chunk: session_id = %" PRIu64 ", chunk_id = %" PRIu64,
4507 session_id, chunk_id);
4508 }
4509
4510 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4511 break;
4512 }
4513 }
4514
4515 if (relayd_id) {
4516 struct consumer_relayd_sock_pair *relayd;
4517
4518 relayd = consumer_find_relayd(*relayd_id);
4519 if (relayd) {
4520 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
4521 ret = relayd_create_trace_chunk(
4522 &relayd->control_sock, published_chunk);
4523 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
4524 } else {
4525 ERR("Failed to find relay daemon socket: relayd_id = %" PRIu64, *relayd_id);
4526 }
4527
4528 if (!relayd || ret) {
4529 enum lttcomm_return_code close_ret;
4530 char path[LTTNG_PATH_MAX];
4531
4532 close_ret = lttng_consumer_close_trace_chunk(relayd_id,
4533 session_id,
4534 chunk_id,
4535 chunk_creation_timestamp,
4536 NULL, path);
4537 if (close_ret != LTTCOMM_CONSUMERD_SUCCESS) {
4538 ERR("Failed to roll-back the creation of new chunk: session_id = %" PRIu64 ", chunk_id = %" PRIu64,
4539 session_id,
4540 chunk_id);
4541 }
4542
4543 ret_code = LTTCOMM_CONSUMERD_CREATE_TRACE_CHUNK_FAILED;
4544 goto error_unlock;
4545 }
4546 }
4547 error_unlock:
4548 rcu_read_unlock();
4549 error:
4550 /* Release the reference returned by the "publish" operation. */
4551 lttng_trace_chunk_put(published_chunk);
4552 lttng_trace_chunk_put(created_chunk);
4553 return ret_code;
4554 }
4555
4556 enum lttcomm_return_code lttng_consumer_close_trace_chunk(
4557 const uint64_t *relayd_id, uint64_t session_id,
4558 uint64_t chunk_id, time_t chunk_close_timestamp,
4559 const enum lttng_trace_chunk_command_type *close_command,
4560 char *path)
4561 {
4562 enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
4563 struct lttng_trace_chunk *chunk;
4564 char relayd_id_buffer[MAX_INT_DEC_LEN(*relayd_id)];
4565 const char *relayd_id_str = "(none)";
4566 const char *close_command_name = "none";
4567 struct lttng_ht_iter iter;
4568 struct lttng_consumer_channel *channel;
4569 enum lttng_trace_chunk_status chunk_status;
4570
4571 if (relayd_id) {
4572 int ret;
4573
4574 /* Only used for logging purposes. */
4575 ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer),
4576 "%" PRIu64, *relayd_id);
4577 if (ret > 0 && ret < sizeof(relayd_id_buffer)) {
4578 relayd_id_str = relayd_id_buffer;
4579 } else {
4580 relayd_id_str = "(formatting error)";
4581 }
4582 }
4583 if (close_command) {
4584 close_command_name = lttng_trace_chunk_command_type_get_name(
4585 *close_command);
4586 }
4587
4588 DBG("Consumer close trace chunk command: relayd_id = %s"
4589 ", session_id = %" PRIu64 ", chunk_id = %" PRIu64
4590 ", close command = %s",
4591 relayd_id_str, session_id, chunk_id,
4592 close_command_name);
4593
4594 chunk = lttng_trace_chunk_registry_find_chunk(
4595 consumer_data.chunk_registry, session_id, chunk_id);
4596 if (!chunk) {
4597 ERR("Failed to find chunk: session_id = %" PRIu64
4598 ", chunk_id = %" PRIu64,
4599 session_id, chunk_id);
4600 ret_code = LTTCOMM_CONSUMERD_UNKNOWN_TRACE_CHUNK;
4601 goto end;
4602 }
4603
4604 chunk_status = lttng_trace_chunk_set_close_timestamp(chunk,
4605 chunk_close_timestamp);
4606 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4607 ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
4608 goto end;
4609 }
4610
4611 if (close_command) {
4612 chunk_status = lttng_trace_chunk_set_close_command(
4613 chunk, *close_command);
4614 if (chunk_status != LTTNG_TRACE_CHUNK_STATUS_OK) {
4615 ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
4616 goto end;
4617 }
4618 }
4619
4620 /*
4621 * chunk is now invalid to access as we no longer hold a reference to
4622 * it; it is only kept around to compare it (by address) to the
4623 * current chunk found in the session's channels.
4624 */
4625 rcu_read_lock();
4626 cds_lfht_for_each_entry(consumer_data.channel_ht->ht, &iter.iter,
4627 channel, node.node) {
4628 int ret;
4629
4630 /*
4631 * Only change the channel's chunk to NULL if it still
4632 * references the chunk being closed. The channel may
4633 * reference a newer channel in the case of a session
4634 * rotation. When a session rotation occurs, the "next"
4635 * chunk is created before the "current" chunk is closed.
4636 */
4637 if (channel->trace_chunk != chunk) {
4638 continue;
4639 }
4640 ret = lttng_consumer_channel_set_trace_chunk(channel, NULL);
4641 if (ret) {
4642 /*
4643 * Attempt to close the chunk on as many channels as
4644 * possible.
4645 */
4646 ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
4647 }
4648 }
4649
4650 if (relayd_id) {
4651 int ret;
4652 struct consumer_relayd_sock_pair *relayd;
4653
4654 relayd = consumer_find_relayd(*relayd_id);
4655 if (relayd) {
4656 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
4657 ret = relayd_close_trace_chunk(
4658 &relayd->control_sock, chunk,
4659 path);
4660 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
4661 } else {
4662 ERR("Failed to find relay daemon socket: relayd_id = %" PRIu64,
4663 *relayd_id);
4664 }
4665
4666 if (!relayd || ret) {
4667 ret_code = LTTCOMM_CONSUMERD_CLOSE_TRACE_CHUNK_FAILED;
4668 goto error_unlock;
4669 }
4670 }
4671 error_unlock:
4672 rcu_read_unlock();
4673 end:
4674 /*
4675 * Release the reference returned by the "find" operation and
4676 * the session daemon's implicit reference to the chunk.
4677 */
4678 lttng_trace_chunk_put(chunk);
4679 lttng_trace_chunk_put(chunk);
4680
4681 return ret_code;
4682 }
4683
4684 enum lttcomm_return_code lttng_consumer_trace_chunk_exists(
4685 const uint64_t *relayd_id, uint64_t session_id,
4686 uint64_t chunk_id)
4687 {
4688 int ret;
4689 enum lttcomm_return_code ret_code;
4690 char relayd_id_buffer[MAX_INT_DEC_LEN(*relayd_id)];
4691 const char *relayd_id_str = "(none)";
4692 const bool is_local_trace = !relayd_id;
4693 struct consumer_relayd_sock_pair *relayd = NULL;
4694 bool chunk_exists_local, chunk_exists_remote;
4695
4696 if (relayd_id) {
4697 int ret;
4698
4699 /* Only used for logging purposes. */
4700 ret = snprintf(relayd_id_buffer, sizeof(relayd_id_buffer),
4701 "%" PRIu64, *relayd_id);
4702 if (ret > 0 && ret < sizeof(relayd_id_buffer)) {
4703 relayd_id_str = relayd_id_buffer;
4704 } else {
4705 relayd_id_str = "(formatting error)";
4706 }
4707 }
4708
4709 DBG("Consumer trace chunk exists command: relayd_id = %s"
4710 ", chunk_id = %" PRIu64, relayd_id_str,
4711 chunk_id);
4712 ret = lttng_trace_chunk_registry_chunk_exists(
4713 consumer_data.chunk_registry, session_id,
4714 chunk_id, &chunk_exists_local);
4715 if (ret) {
4716 /* Internal error. */
4717 ERR("Failed to query the existence of a trace chunk");
4718 ret_code = LTTCOMM_CONSUMERD_FATAL;
4719 goto end;
4720 }
4721 DBG("Trace chunk %s locally",
4722 chunk_exists_local ? "exists" : "does not exist");
4723 if (chunk_exists_local) {
4724 ret_code = LTTCOMM_CONSUMERD_TRACE_CHUNK_EXISTS_LOCAL;
4725 goto end;
4726 } else if (is_local_trace) {
4727 ret_code = LTTCOMM_CONSUMERD_UNKNOWN_TRACE_CHUNK;
4728 goto end;
4729 }
4730
4731 rcu_read_lock();
4732 relayd = consumer_find_relayd(*relayd_id);
4733 if (!relayd) {
4734 ERR("Failed to find relayd %" PRIu64, *relayd_id);
4735 ret_code = LTTCOMM_CONSUMERD_INVALID_PARAMETERS;
4736 goto end_rcu_unlock;
4737 }
4738 DBG("Looking up existence of trace chunk on relay daemon");
4739 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
4740 ret = relayd_trace_chunk_exists(&relayd->control_sock, chunk_id,
4741 &chunk_exists_remote);
4742 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
4743 if (ret < 0) {
4744 ERR("Failed to look-up the existence of trace chunk on relay daemon");
4745 ret_code = LTTCOMM_CONSUMERD_RELAYD_FAIL;
4746 goto end_rcu_unlock;
4747 }
4748
4749 ret_code = chunk_exists_remote ?
4750 LTTCOMM_CONSUMERD_TRACE_CHUNK_EXISTS_REMOTE :
4751 LTTCOMM_CONSUMERD_UNKNOWN_TRACE_CHUNK;
4752 DBG("Trace chunk %s on relay daemon",
4753 chunk_exists_remote ? "exists" : "does not exist");
4754
4755 end_rcu_unlock:
4756 rcu_read_unlock();
4757 end:
4758 return ret_code;
4759 }
This page took 0.194365 seconds and 4 git commands to generate.