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