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