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