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