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