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