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