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