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