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