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