0539eeb7be17143a98d7741d5448552d7fe2e862
[lttng-tools.git] / src / common / consumer / consumer.c
1 /*
2 * Copyright (C) 2011 - Julien Desfossez <julien.desfossez@polymtl.ca>
3 * Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
4 * 2012 - David Goulet <dgoulet@efficios.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License, version 2 only,
8 * as published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13 * more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #define _LGPL_SOURCE
21 #include <assert.h>
22 #include <poll.h>
23 #include <pthread.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/mman.h>
27 #include <sys/socket.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30 #include <inttypes.h>
31 #include <signal.h>
32
33 #include <bin/lttng-consumerd/health-consumerd.h>
34 #include <common/common.h>
35 #include <common/utils.h>
36 #include <common/compat/poll.h>
37 #include <common/compat/endian.h>
38 #include <common/index/index.h>
39 #include <common/kernel-ctl/kernel-ctl.h>
40 #include <common/sessiond-comm/relayd.h>
41 #include <common/sessiond-comm/sessiond-comm.h>
42 #include <common/kernel-consumer/kernel-consumer.h>
43 #include <common/relayd/relayd.h>
44 #include <common/ust-consumer/ust-consumer.h>
45 #include <common/consumer/consumer-timer.h>
46 #include <common/consumer/consumer.h>
47 #include <common/consumer/consumer-stream.h>
48 #include <common/consumer/consumer-testpoint.h>
49 #include <common/align.h>
50 #include <common/consumer/consumer-metadata-cache.h>
51
52 struct lttng_consumer_global_data consumer_data = {
53 .stream_count = 0,
54 .need_update = 1,
55 .type = LTTNG_CONSUMER_UNKNOWN,
56 };
57
58 enum consumer_channel_action {
59 CONSUMER_CHANNEL_ADD,
60 CONSUMER_CHANNEL_DEL,
61 CONSUMER_CHANNEL_QUIT,
62 };
63
64 struct consumer_channel_msg {
65 enum consumer_channel_action action;
66 struct lttng_consumer_channel *chan; /* add */
67 uint64_t key; /* del */
68 };
69
70 /*
71 * Flag to inform the polling thread to quit when all fd hung up. Updated by
72 * the consumer_thread_receive_fds when it notices that all fds has hung up.
73 * Also updated by the signal handler (consumer_should_exit()). Read by the
74 * polling threads.
75 */
76 volatile int consumer_quit;
77
78 /*
79 * Global hash table containing respectively metadata and data streams. The
80 * stream element in this ht should only be updated by the metadata poll thread
81 * for the metadata and the data poll thread for the data.
82 */
83 static struct lttng_ht *metadata_ht;
84 static struct lttng_ht *data_ht;
85
86 /*
87 * Notify a thread lttng pipe to poll back again. This usually means that some
88 * global state has changed so we just send back the thread in a poll wait
89 * call.
90 */
91 static void notify_thread_lttng_pipe(struct lttng_pipe *pipe)
92 {
93 struct lttng_consumer_stream *null_stream = NULL;
94
95 assert(pipe);
96
97 (void) lttng_pipe_write(pipe, &null_stream, sizeof(null_stream));
98 }
99
100 static void notify_health_quit_pipe(int *pipe)
101 {
102 ssize_t ret;
103
104 ret = lttng_write(pipe[1], "4", 1);
105 if (ret < 1) {
106 PERROR("write consumer health quit");
107 }
108 }
109
110 static void notify_channel_pipe(struct lttng_consumer_local_data *ctx,
111 struct lttng_consumer_channel *chan,
112 uint64_t key,
113 enum consumer_channel_action action)
114 {
115 struct consumer_channel_msg msg;
116 ssize_t ret;
117
118 memset(&msg, 0, sizeof(msg));
119
120 msg.action = action;
121 msg.chan = chan;
122 msg.key = key;
123 ret = lttng_write(ctx->consumer_channel_pipe[1], &msg, sizeof(msg));
124 if (ret < sizeof(msg)) {
125 PERROR("notify_channel_pipe write error");
126 }
127 }
128
129 void notify_thread_del_channel(struct lttng_consumer_local_data *ctx,
130 uint64_t key)
131 {
132 notify_channel_pipe(ctx, NULL, key, CONSUMER_CHANNEL_DEL);
133 }
134
135 static int read_channel_pipe(struct lttng_consumer_local_data *ctx,
136 struct lttng_consumer_channel **chan,
137 uint64_t *key,
138 enum consumer_channel_action *action)
139 {
140 struct consumer_channel_msg msg;
141 ssize_t ret;
142
143 ret = lttng_read(ctx->consumer_channel_pipe[0], &msg, sizeof(msg));
144 if (ret < sizeof(msg)) {
145 ret = -1;
146 goto error;
147 }
148 *action = msg.action;
149 *chan = msg.chan;
150 *key = msg.key;
151 error:
152 return (int) ret;
153 }
154
155 /*
156 * Cleanup the stream list of a channel. Those streams are not yet globally
157 * visible
158 */
159 static void clean_channel_stream_list(struct lttng_consumer_channel *channel)
160 {
161 struct lttng_consumer_stream *stream, *stmp;
162
163 assert(channel);
164
165 /* Delete streams that might have been left in the stream list. */
166 cds_list_for_each_entry_safe(stream, stmp, &channel->streams.head,
167 send_node) {
168 cds_list_del(&stream->send_node);
169 /*
170 * Once a stream is added to this list, the buffers were created so we
171 * have a guarantee that this call will succeed. Setting the monitor
172 * mode to 0 so we don't lock nor try to delete the stream from the
173 * global hash table.
174 */
175 stream->monitor = 0;
176 consumer_stream_destroy(stream, NULL);
177 }
178 }
179
180 /*
181 * Find a stream. The consumer_data.lock must be locked during this
182 * call.
183 */
184 static struct lttng_consumer_stream *find_stream(uint64_t key,
185 struct lttng_ht *ht)
186 {
187 struct lttng_ht_iter iter;
188 struct lttng_ht_node_u64 *node;
189 struct lttng_consumer_stream *stream = NULL;
190
191 assert(ht);
192
193 /* -1ULL keys are lookup failures */
194 if (key == (uint64_t) -1ULL) {
195 return NULL;
196 }
197
198 rcu_read_lock();
199
200 lttng_ht_lookup(ht, &key, &iter);
201 node = lttng_ht_iter_get_node_u64(&iter);
202 if (node != NULL) {
203 stream = caa_container_of(node, struct lttng_consumer_stream, node);
204 }
205
206 rcu_read_unlock();
207
208 return stream;
209 }
210
211 static void steal_stream_key(uint64_t key, struct lttng_ht *ht)
212 {
213 struct lttng_consumer_stream *stream;
214
215 rcu_read_lock();
216 stream = find_stream(key, ht);
217 if (stream) {
218 stream->key = (uint64_t) -1ULL;
219 /*
220 * We don't want the lookup to match, but we still need
221 * to iterate on this stream when iterating over the hash table. Just
222 * change the node key.
223 */
224 stream->node.key = (uint64_t) -1ULL;
225 }
226 rcu_read_unlock();
227 }
228
229 /*
230 * Return a channel object for the given key.
231 *
232 * RCU read side lock MUST be acquired before calling this function and
233 * protects the channel ptr.
234 */
235 struct lttng_consumer_channel *consumer_find_channel(uint64_t key)
236 {
237 struct lttng_ht_iter iter;
238 struct lttng_ht_node_u64 *node;
239 struct lttng_consumer_channel *channel = NULL;
240
241 /* -1ULL keys are lookup failures */
242 if (key == (uint64_t) -1ULL) {
243 return NULL;
244 }
245
246 lttng_ht_lookup(consumer_data.channel_ht, &key, &iter);
247 node = lttng_ht_iter_get_node_u64(&iter);
248 if (node != NULL) {
249 channel = caa_container_of(node, struct lttng_consumer_channel, node);
250 }
251
252 return channel;
253 }
254
255 /*
256 * There is a possibility that the consumer does not have enough time between
257 * the close of the channel on the session daemon and the cleanup in here thus
258 * once we have a channel add with an existing key, we know for sure that this
259 * channel will eventually get cleaned up by all streams being closed.
260 *
261 * This function just nullifies the already existing channel key.
262 */
263 static void steal_channel_key(uint64_t key)
264 {
265 struct lttng_consumer_channel *channel;
266
267 rcu_read_lock();
268 channel = consumer_find_channel(key);
269 if (channel) {
270 channel->key = (uint64_t) -1ULL;
271 /*
272 * We don't want the lookup to match, but we still need to iterate on
273 * this channel when iterating over the hash table. Just change the
274 * node key.
275 */
276 channel->node.key = (uint64_t) -1ULL;
277 }
278 rcu_read_unlock();
279 }
280
281 static void free_channel_rcu(struct rcu_head *head)
282 {
283 struct lttng_ht_node_u64 *node =
284 caa_container_of(head, struct lttng_ht_node_u64, head);
285 struct lttng_consumer_channel *channel =
286 caa_container_of(node, struct lttng_consumer_channel, node);
287
288 switch (consumer_data.type) {
289 case LTTNG_CONSUMER_KERNEL:
290 break;
291 case LTTNG_CONSUMER32_UST:
292 case LTTNG_CONSUMER64_UST:
293 lttng_ustconsumer_free_channel(channel);
294 break;
295 default:
296 ERR("Unknown consumer_data type");
297 abort();
298 }
299 free(channel);
300 }
301
302 /*
303 * RCU protected relayd socket pair free.
304 */
305 static void free_relayd_rcu(struct rcu_head *head)
306 {
307 struct lttng_ht_node_u64 *node =
308 caa_container_of(head, struct lttng_ht_node_u64, head);
309 struct consumer_relayd_sock_pair *relayd =
310 caa_container_of(node, struct consumer_relayd_sock_pair, node);
311
312 /*
313 * Close all sockets. This is done in the call RCU since we don't want the
314 * socket fds to be reassigned thus potentially creating bad state of the
315 * relayd object.
316 *
317 * We do not have to lock the control socket mutex here since at this stage
318 * there is no one referencing to this relayd object.
319 */
320 (void) relayd_close(&relayd->control_sock);
321 (void) relayd_close(&relayd->data_sock);
322
323 pthread_mutex_destroy(&relayd->ctrl_sock_mutex);
324 free(relayd);
325 }
326
327 /*
328 * Destroy and free relayd socket pair object.
329 */
330 void consumer_destroy_relayd(struct consumer_relayd_sock_pair *relayd)
331 {
332 int ret;
333 struct lttng_ht_iter iter;
334
335 if (relayd == NULL) {
336 return;
337 }
338
339 DBG("Consumer destroy and close relayd socket pair");
340
341 iter.iter.node = &relayd->node.node;
342 ret = lttng_ht_del(consumer_data.relayd_ht, &iter);
343 if (ret != 0) {
344 /* We assume the relayd is being or is destroyed */
345 return;
346 }
347
348 /* RCU free() call */
349 call_rcu(&relayd->node.head, free_relayd_rcu);
350 }
351
352 /*
353 * Remove a channel from the global list protected by a mutex. This function is
354 * also responsible for freeing its data structures.
355 */
356 void consumer_del_channel(struct lttng_consumer_channel *channel)
357 {
358 int ret;
359 struct lttng_ht_iter iter;
360
361 DBG("Consumer delete channel key %" PRIu64, channel->key);
362
363 pthread_mutex_lock(&consumer_data.lock);
364 pthread_mutex_lock(&channel->lock);
365
366 /* Destroy streams that might have been left in the stream list. */
367 clean_channel_stream_list(channel);
368
369 if (channel->live_timer_enabled == 1) {
370 consumer_timer_live_stop(channel);
371 }
372
373 switch (consumer_data.type) {
374 case LTTNG_CONSUMER_KERNEL:
375 break;
376 case LTTNG_CONSUMER32_UST:
377 case LTTNG_CONSUMER64_UST:
378 lttng_ustconsumer_del_channel(channel);
379 break;
380 default:
381 ERR("Unknown consumer_data type");
382 assert(0);
383 goto end;
384 }
385
386 rcu_read_lock();
387 iter.iter.node = &channel->node.node;
388 ret = lttng_ht_del(consumer_data.channel_ht, &iter);
389 assert(!ret);
390 rcu_read_unlock();
391
392 call_rcu(&channel->node.head, free_channel_rcu);
393 end:
394 pthread_mutex_unlock(&channel->lock);
395 pthread_mutex_unlock(&consumer_data.lock);
396 }
397
398 /*
399 * Iterate over the relayd hash table and destroy each element. Finally,
400 * destroy the whole hash table.
401 */
402 static void cleanup_relayd_ht(void)
403 {
404 struct lttng_ht_iter iter;
405 struct consumer_relayd_sock_pair *relayd;
406
407 rcu_read_lock();
408
409 cds_lfht_for_each_entry(consumer_data.relayd_ht->ht, &iter.iter, relayd,
410 node.node) {
411 consumer_destroy_relayd(relayd);
412 }
413
414 rcu_read_unlock();
415
416 lttng_ht_destroy(consumer_data.relayd_ht);
417 }
418
419 /*
420 * Update the end point status of all streams having the given network sequence
421 * index (relayd index).
422 *
423 * It's atomically set without having the stream mutex locked which is fine
424 * because we handle the write/read race with a pipe wakeup for each thread.
425 */
426 static void update_endpoint_status_by_netidx(uint64_t net_seq_idx,
427 enum consumer_endpoint_status status)
428 {
429 struct lttng_ht_iter iter;
430 struct lttng_consumer_stream *stream;
431
432 DBG("Consumer set delete flag on stream by idx %" PRIu64, net_seq_idx);
433
434 rcu_read_lock();
435
436 /* Let's begin with metadata */
437 cds_lfht_for_each_entry(metadata_ht->ht, &iter.iter, stream, node.node) {
438 if (stream->net_seq_idx == net_seq_idx) {
439 uatomic_set(&stream->endpoint_status, status);
440 DBG("Delete flag set to metadata stream %d", stream->wait_fd);
441 }
442 }
443
444 /* Follow up by the data streams */
445 cds_lfht_for_each_entry(data_ht->ht, &iter.iter, stream, node.node) {
446 if (stream->net_seq_idx == net_seq_idx) {
447 uatomic_set(&stream->endpoint_status, status);
448 DBG("Delete flag set to data stream %d", stream->wait_fd);
449 }
450 }
451 rcu_read_unlock();
452 }
453
454 /*
455 * Cleanup a relayd object by flagging every associated streams for deletion,
456 * destroying the object meaning removing it from the relayd hash table,
457 * closing the sockets and freeing the memory in a RCU call.
458 *
459 * If a local data context is available, notify the threads that the streams'
460 * state have changed.
461 */
462 void lttng_consumer_cleanup_relayd(struct consumer_relayd_sock_pair *relayd)
463 {
464 uint64_t netidx;
465
466 assert(relayd);
467
468 DBG("Cleaning up relayd object ID %"PRIu64, relayd->net_seq_idx);
469
470 /* Save the net sequence index before destroying the object */
471 netidx = relayd->net_seq_idx;
472
473 /*
474 * Delete the relayd from the relayd hash table, close the sockets and free
475 * the object in a RCU call.
476 */
477 consumer_destroy_relayd(relayd);
478
479 /* Set inactive endpoint to all streams */
480 update_endpoint_status_by_netidx(netidx, CONSUMER_ENDPOINT_INACTIVE);
481
482 /*
483 * With a local data context, notify the threads that the streams' state
484 * have changed. The write() action on the pipe acts as an "implicit"
485 * memory barrier ordering the updates of the end point status from the
486 * read of this status which happens AFTER receiving this notify.
487 */
488 notify_thread_lttng_pipe(relayd->ctx->consumer_data_pipe);
489 notify_thread_lttng_pipe(relayd->ctx->consumer_metadata_pipe);
490 }
491
492 /*
493 * Flag a relayd socket pair for destruction. Destroy it if the refcount
494 * reaches zero.
495 *
496 * RCU read side lock MUST be aquired before calling this function.
497 */
498 void consumer_flag_relayd_for_destroy(struct consumer_relayd_sock_pair *relayd)
499 {
500 assert(relayd);
501
502 /* Set destroy flag for this object */
503 uatomic_set(&relayd->destroy_flag, 1);
504
505 /* Destroy the relayd if refcount is 0 */
506 if (uatomic_read(&relayd->refcount) == 0) {
507 consumer_destroy_relayd(relayd);
508 }
509 }
510
511 /*
512 * Completly destroy stream from every visiable data structure and the given
513 * hash table if one.
514 *
515 * One this call returns, the stream object is not longer usable nor visible.
516 */
517 void consumer_del_stream(struct lttng_consumer_stream *stream,
518 struct lttng_ht *ht)
519 {
520 consumer_stream_destroy(stream, ht);
521 }
522
523 /*
524 * XXX naming of del vs destroy is all mixed up.
525 */
526 void consumer_del_stream_for_data(struct lttng_consumer_stream *stream)
527 {
528 consumer_stream_destroy(stream, data_ht);
529 }
530
531 void consumer_del_stream_for_metadata(struct lttng_consumer_stream *stream)
532 {
533 consumer_stream_destroy(stream, metadata_ht);
534 }
535
536 struct lttng_consumer_stream *consumer_allocate_stream(uint64_t channel_key,
537 uint64_t stream_key,
538 enum lttng_consumer_stream_state state,
539 const char *channel_name,
540 uid_t uid,
541 gid_t gid,
542 uint64_t relayd_id,
543 uint64_t session_id,
544 int cpu,
545 int *alloc_ret,
546 enum consumer_channel_type type,
547 unsigned int monitor)
548 {
549 int ret;
550 struct lttng_consumer_stream *stream;
551
552 stream = zmalloc(sizeof(*stream));
553 if (stream == NULL) {
554 PERROR("malloc struct lttng_consumer_stream");
555 ret = -ENOMEM;
556 goto end;
557 }
558
559 rcu_read_lock();
560
561 stream->key = stream_key;
562 stream->out_fd = -1;
563 stream->out_fd_offset = 0;
564 stream->output_written = 0;
565 stream->state = state;
566 stream->uid = uid;
567 stream->gid = gid;
568 stream->net_seq_idx = relayd_id;
569 stream->session_id = session_id;
570 stream->monitor = monitor;
571 stream->endpoint_status = CONSUMER_ENDPOINT_ACTIVE;
572 stream->index_file = NULL;
573 stream->last_sequence_number = -1ULL;
574 pthread_mutex_init(&stream->lock, NULL);
575 pthread_mutex_init(&stream->metadata_timer_lock, NULL);
576
577 /* If channel is the metadata, flag this stream as metadata. */
578 if (type == CONSUMER_CHANNEL_TYPE_METADATA) {
579 stream->metadata_flag = 1;
580 /* Metadata is flat out. */
581 strncpy(stream->name, DEFAULT_METADATA_NAME, sizeof(stream->name));
582 /* Live rendez-vous point. */
583 pthread_cond_init(&stream->metadata_rdv, NULL);
584 pthread_mutex_init(&stream->metadata_rdv_lock, NULL);
585 } else {
586 /* Format stream name to <channel_name>_<cpu_number> */
587 ret = snprintf(stream->name, sizeof(stream->name), "%s_%d",
588 channel_name, cpu);
589 if (ret < 0) {
590 PERROR("snprintf stream name");
591 goto error;
592 }
593 }
594
595 /* Key is always the wait_fd for streams. */
596 lttng_ht_node_init_u64(&stream->node, stream->key);
597
598 /* Init node per channel id key */
599 lttng_ht_node_init_u64(&stream->node_channel_id, channel_key);
600
601 /* Init session id node with the stream session id */
602 lttng_ht_node_init_u64(&stream->node_session_id, stream->session_id);
603
604 DBG3("Allocated stream %s (key %" PRIu64 ", chan_key %" PRIu64
605 " relayd_id %" PRIu64 ", session_id %" PRIu64,
606 stream->name, stream->key, channel_key,
607 stream->net_seq_idx, stream->session_id);
608
609 rcu_read_unlock();
610 return stream;
611
612 error:
613 rcu_read_unlock();
614 free(stream);
615 end:
616 if (alloc_ret) {
617 *alloc_ret = ret;
618 }
619 return NULL;
620 }
621
622 /*
623 * Add a stream to the global list protected by a mutex.
624 */
625 int consumer_add_data_stream(struct lttng_consumer_stream *stream)
626 {
627 struct lttng_ht *ht = data_ht;
628 int ret = 0;
629
630 assert(stream);
631 assert(ht);
632
633 DBG3("Adding consumer stream %" PRIu64, stream->key);
634
635 pthread_mutex_lock(&consumer_data.lock);
636 pthread_mutex_lock(&stream->chan->lock);
637 pthread_mutex_lock(&stream->chan->timer_lock);
638 pthread_mutex_lock(&stream->lock);
639 rcu_read_lock();
640
641 /* Steal stream identifier to avoid having streams with the same key */
642 steal_stream_key(stream->key, ht);
643
644 lttng_ht_add_unique_u64(ht, &stream->node);
645
646 lttng_ht_add_u64(consumer_data.stream_per_chan_id_ht,
647 &stream->node_channel_id);
648
649 /*
650 * Add stream to the stream_list_ht of the consumer data. No need to steal
651 * the key since the HT does not use it and we allow to add redundant keys
652 * into this table.
653 */
654 lttng_ht_add_u64(consumer_data.stream_list_ht, &stream->node_session_id);
655
656 /*
657 * When nb_init_stream_left reaches 0, we don't need to trigger any action
658 * in terms of destroying the associated channel, because the action that
659 * causes the count to become 0 also causes a stream to be added. The
660 * channel deletion will thus be triggered by the following removal of this
661 * stream.
662 */
663 if (uatomic_read(&stream->chan->nb_init_stream_left) > 0) {
664 /* Increment refcount before decrementing nb_init_stream_left */
665 cmm_smp_wmb();
666 uatomic_dec(&stream->chan->nb_init_stream_left);
667 }
668
669 /* Update consumer data once the node is inserted. */
670 consumer_data.stream_count++;
671 consumer_data.need_update = 1;
672
673 rcu_read_unlock();
674 pthread_mutex_unlock(&stream->lock);
675 pthread_mutex_unlock(&stream->chan->timer_lock);
676 pthread_mutex_unlock(&stream->chan->lock);
677 pthread_mutex_unlock(&consumer_data.lock);
678
679 return ret;
680 }
681
682 void consumer_del_data_stream(struct lttng_consumer_stream *stream)
683 {
684 consumer_del_stream(stream, data_ht);
685 }
686
687 /*
688 * Add relayd socket to global consumer data hashtable. RCU read side lock MUST
689 * be acquired before calling this.
690 */
691 static int add_relayd(struct consumer_relayd_sock_pair *relayd)
692 {
693 int ret = 0;
694 struct lttng_ht_node_u64 *node;
695 struct lttng_ht_iter iter;
696
697 assert(relayd);
698
699 lttng_ht_lookup(consumer_data.relayd_ht,
700 &relayd->net_seq_idx, &iter);
701 node = lttng_ht_iter_get_node_u64(&iter);
702 if (node != NULL) {
703 goto end;
704 }
705 lttng_ht_add_unique_u64(consumer_data.relayd_ht, &relayd->node);
706
707 end:
708 return ret;
709 }
710
711 /*
712 * Allocate and return a consumer relayd socket.
713 */
714 static struct consumer_relayd_sock_pair *consumer_allocate_relayd_sock_pair(
715 uint64_t net_seq_idx)
716 {
717 struct consumer_relayd_sock_pair *obj = NULL;
718
719 /* net sequence index of -1 is a failure */
720 if (net_seq_idx == (uint64_t) -1ULL) {
721 goto error;
722 }
723
724 obj = zmalloc(sizeof(struct consumer_relayd_sock_pair));
725 if (obj == NULL) {
726 PERROR("zmalloc relayd sock");
727 goto error;
728 }
729
730 obj->net_seq_idx = net_seq_idx;
731 obj->refcount = 0;
732 obj->destroy_flag = 0;
733 obj->control_sock.sock.fd = -1;
734 obj->data_sock.sock.fd = -1;
735 lttng_ht_node_init_u64(&obj->node, obj->net_seq_idx);
736 pthread_mutex_init(&obj->ctrl_sock_mutex, NULL);
737
738 error:
739 return obj;
740 }
741
742 /*
743 * Find a relayd socket pair in the global consumer data.
744 *
745 * Return the object if found else NULL.
746 * RCU read-side lock must be held across this call and while using the
747 * returned object.
748 */
749 struct consumer_relayd_sock_pair *consumer_find_relayd(uint64_t key)
750 {
751 struct lttng_ht_iter iter;
752 struct lttng_ht_node_u64 *node;
753 struct consumer_relayd_sock_pair *relayd = NULL;
754
755 /* Negative keys are lookup failures */
756 if (key == (uint64_t) -1ULL) {
757 goto error;
758 }
759
760 lttng_ht_lookup(consumer_data.relayd_ht, &key,
761 &iter);
762 node = lttng_ht_iter_get_node_u64(&iter);
763 if (node != NULL) {
764 relayd = caa_container_of(node, struct consumer_relayd_sock_pair, node);
765 }
766
767 error:
768 return relayd;
769 }
770
771 /*
772 * Find a relayd and send the stream
773 *
774 * Returns 0 on success, < 0 on error
775 */
776 int consumer_send_relayd_stream(struct lttng_consumer_stream *stream,
777 char *path)
778 {
779 int ret = 0;
780 struct consumer_relayd_sock_pair *relayd;
781
782 assert(stream);
783 assert(stream->net_seq_idx != -1ULL);
784 assert(path);
785
786 /* The stream is not metadata. Get relayd reference if exists. */
787 rcu_read_lock();
788 relayd = consumer_find_relayd(stream->net_seq_idx);
789 if (relayd != NULL) {
790 /* Add stream on the relayd */
791 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
792 ret = relayd_add_stream(&relayd->control_sock, stream->name,
793 path, &stream->relayd_stream_id,
794 stream->chan->tracefile_size, stream->chan->tracefile_count);
795 if (ret < 0) {
796 ERR("Relayd add stream failed. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
797 lttng_consumer_cleanup_relayd(relayd);
798 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
799 goto end;
800 }
801 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
802
803 uatomic_inc(&relayd->refcount);
804 stream->sent_to_relayd = 1;
805 } else {
806 ERR("Stream %" PRIu64 " relayd ID %" PRIu64 " unknown. Can't send it.",
807 stream->key, stream->net_seq_idx);
808 ret = -1;
809 goto end;
810 }
811
812 DBG("Stream %s with key %" PRIu64 " sent to relayd id %" PRIu64,
813 stream->name, stream->key, stream->net_seq_idx);
814
815 end:
816 rcu_read_unlock();
817 return ret;
818 }
819
820 /*
821 * Find a relayd and send the streams sent message
822 *
823 * Returns 0 on success, < 0 on error
824 */
825 int consumer_send_relayd_streams_sent(uint64_t net_seq_idx)
826 {
827 int ret = 0;
828 struct consumer_relayd_sock_pair *relayd;
829
830 assert(net_seq_idx != -1ULL);
831
832 /* The stream is not metadata. Get relayd reference if exists. */
833 rcu_read_lock();
834 relayd = consumer_find_relayd(net_seq_idx);
835 if (relayd != NULL) {
836 /* Add stream on the relayd */
837 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
838 ret = relayd_streams_sent(&relayd->control_sock);
839 if (ret < 0) {
840 ERR("Relayd streams sent failed. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
841 lttng_consumer_cleanup_relayd(relayd);
842 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
843 goto end;
844 }
845 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
846 } else {
847 ERR("Relayd ID %" PRIu64 " unknown. Can't send streams_sent.",
848 net_seq_idx);
849 ret = -1;
850 goto end;
851 }
852
853 ret = 0;
854 DBG("All streams sent relayd id %" PRIu64, net_seq_idx);
855
856 end:
857 rcu_read_unlock();
858 return ret;
859 }
860
861 /*
862 * Find a relayd and close the stream
863 */
864 void close_relayd_stream(struct lttng_consumer_stream *stream)
865 {
866 struct consumer_relayd_sock_pair *relayd;
867
868 /* The stream is not metadata. Get relayd reference if exists. */
869 rcu_read_lock();
870 relayd = consumer_find_relayd(stream->net_seq_idx);
871 if (relayd) {
872 consumer_stream_relayd_close(stream, relayd);
873 }
874 rcu_read_unlock();
875 }
876
877 /*
878 * Handle stream for relayd transmission if the stream applies for network
879 * streaming where the net sequence index is set.
880 *
881 * Return destination file descriptor or negative value on error.
882 */
883 static int write_relayd_stream_header(struct lttng_consumer_stream *stream,
884 size_t data_size, unsigned long padding,
885 struct consumer_relayd_sock_pair *relayd)
886 {
887 int outfd = -1, ret;
888 struct lttcomm_relayd_data_hdr data_hdr;
889
890 /* Safety net */
891 assert(stream);
892 assert(relayd);
893
894 /* Reset data header */
895 memset(&data_hdr, 0, sizeof(data_hdr));
896
897 if (stream->metadata_flag) {
898 /* Caller MUST acquire the relayd control socket lock */
899 ret = relayd_send_metadata(&relayd->control_sock, data_size);
900 if (ret < 0) {
901 goto error;
902 }
903
904 /* Metadata are always sent on the control socket. */
905 outfd = relayd->control_sock.sock.fd;
906 } else {
907 /* Set header with stream information */
908 data_hdr.stream_id = htobe64(stream->relayd_stream_id);
909 data_hdr.data_size = htobe32(data_size);
910 data_hdr.padding_size = htobe32(padding);
911 /*
912 * Note that net_seq_num below is assigned with the *current* value of
913 * next_net_seq_num and only after that the next_net_seq_num will be
914 * increment. This is why when issuing a command on the relayd using
915 * this next value, 1 should always be substracted in order to compare
916 * the last seen sequence number on the relayd side to the last sent.
917 */
918 data_hdr.net_seq_num = htobe64(stream->next_net_seq_num);
919 /* Other fields are zeroed previously */
920
921 ret = relayd_send_data_hdr(&relayd->data_sock, &data_hdr,
922 sizeof(data_hdr));
923 if (ret < 0) {
924 goto error;
925 }
926
927 ++stream->next_net_seq_num;
928
929 /* Set to go on data socket */
930 outfd = relayd->data_sock.sock.fd;
931 }
932
933 error:
934 return outfd;
935 }
936
937 /*
938 * Allocate and return a new lttng_consumer_channel object using the given key
939 * to initialize the hash table node.
940 *
941 * On error, return NULL.
942 */
943 struct lttng_consumer_channel *consumer_allocate_channel(uint64_t key,
944 uint64_t session_id,
945 const char *pathname,
946 const char *name,
947 uid_t uid,
948 gid_t gid,
949 uint64_t relayd_id,
950 enum lttng_event_output output,
951 uint64_t tracefile_size,
952 uint64_t tracefile_count,
953 uint64_t session_id_per_pid,
954 unsigned int monitor,
955 unsigned int live_timer_interval,
956 const char *root_shm_path,
957 const char *shm_path)
958 {
959 struct lttng_consumer_channel *channel;
960
961 channel = zmalloc(sizeof(*channel));
962 if (channel == NULL) {
963 PERROR("malloc struct lttng_consumer_channel");
964 goto end;
965 }
966
967 channel->key = key;
968 channel->refcount = 0;
969 channel->session_id = session_id;
970 channel->session_id_per_pid = session_id_per_pid;
971 channel->uid = uid;
972 channel->gid = gid;
973 channel->relayd_id = relayd_id;
974 channel->tracefile_size = tracefile_size;
975 channel->tracefile_count = tracefile_count;
976 channel->monitor = monitor;
977 channel->live_timer_interval = live_timer_interval;
978 pthread_mutex_init(&channel->lock, NULL);
979 pthread_mutex_init(&channel->timer_lock, NULL);
980
981 switch (output) {
982 case LTTNG_EVENT_SPLICE:
983 channel->output = CONSUMER_CHANNEL_SPLICE;
984 break;
985 case LTTNG_EVENT_MMAP:
986 channel->output = CONSUMER_CHANNEL_MMAP;
987 break;
988 default:
989 assert(0);
990 free(channel);
991 channel = NULL;
992 goto end;
993 }
994
995 /*
996 * In monitor mode, the streams associated with the channel will be put in
997 * a special list ONLY owned by this channel. So, the refcount is set to 1
998 * here meaning that the channel itself has streams that are referenced.
999 *
1000 * On a channel deletion, once the channel is no longer visible, the
1001 * refcount is decremented and checked for a zero value to delete it. With
1002 * streams in no monitor mode, it will now be safe to destroy the channel.
1003 */
1004 if (!channel->monitor) {
1005 channel->refcount = 1;
1006 }
1007
1008 strncpy(channel->pathname, pathname, sizeof(channel->pathname));
1009 channel->pathname[sizeof(channel->pathname) - 1] = '\0';
1010
1011 strncpy(channel->name, name, sizeof(channel->name));
1012 channel->name[sizeof(channel->name) - 1] = '\0';
1013
1014 if (root_shm_path) {
1015 strncpy(channel->root_shm_path, root_shm_path, sizeof(channel->root_shm_path));
1016 channel->root_shm_path[sizeof(channel->root_shm_path) - 1] = '\0';
1017 }
1018 if (shm_path) {
1019 strncpy(channel->shm_path, shm_path, sizeof(channel->shm_path));
1020 channel->shm_path[sizeof(channel->shm_path) - 1] = '\0';
1021 }
1022
1023 lttng_ht_node_init_u64(&channel->node, channel->key);
1024
1025 channel->wait_fd = -1;
1026
1027 CDS_INIT_LIST_HEAD(&channel->streams.head);
1028
1029 DBG("Allocated channel (key %" PRIu64 ")", channel->key);
1030
1031 end:
1032 return channel;
1033 }
1034
1035 /*
1036 * Add a channel to the global list protected by a mutex.
1037 *
1038 * Always return 0 indicating success.
1039 */
1040 int consumer_add_channel(struct lttng_consumer_channel *channel,
1041 struct lttng_consumer_local_data *ctx)
1042 {
1043 pthread_mutex_lock(&consumer_data.lock);
1044 pthread_mutex_lock(&channel->lock);
1045 pthread_mutex_lock(&channel->timer_lock);
1046
1047 /*
1048 * This gives us a guarantee that the channel we are about to add to the
1049 * channel hash table will be unique. See this function comment on the why
1050 * we need to steel the channel key at this stage.
1051 */
1052 steal_channel_key(channel->key);
1053
1054 rcu_read_lock();
1055 lttng_ht_add_unique_u64(consumer_data.channel_ht, &channel->node);
1056 rcu_read_unlock();
1057
1058 pthread_mutex_unlock(&channel->timer_lock);
1059 pthread_mutex_unlock(&channel->lock);
1060 pthread_mutex_unlock(&consumer_data.lock);
1061
1062 if (channel->wait_fd != -1 && channel->type == CONSUMER_CHANNEL_TYPE_DATA) {
1063 notify_channel_pipe(ctx, channel, -1, CONSUMER_CHANNEL_ADD);
1064 }
1065
1066 return 0;
1067 }
1068
1069 /*
1070 * Allocate the pollfd structure and the local view of the out fds to avoid
1071 * doing a lookup in the linked list and concurrency issues when writing is
1072 * needed. Called with consumer_data.lock held.
1073 *
1074 * Returns the number of fds in the structures.
1075 */
1076 static int update_poll_array(struct lttng_consumer_local_data *ctx,
1077 struct pollfd **pollfd, struct lttng_consumer_stream **local_stream,
1078 struct lttng_ht *ht, int *nb_inactive_fd)
1079 {
1080 int i = 0;
1081 struct lttng_ht_iter iter;
1082 struct lttng_consumer_stream *stream;
1083
1084 assert(ctx);
1085 assert(ht);
1086 assert(pollfd);
1087 assert(local_stream);
1088
1089 DBG("Updating poll fd array");
1090 *nb_inactive_fd = 0;
1091 rcu_read_lock();
1092 cds_lfht_for_each_entry(ht->ht, &iter.iter, stream, node.node) {
1093 /*
1094 * Only active streams with an active end point can be added to the
1095 * poll set and local stream storage of the thread.
1096 *
1097 * There is a potential race here for endpoint_status to be updated
1098 * just after the check. However, this is OK since the stream(s) will
1099 * be deleted once the thread is notified that the end point state has
1100 * changed where this function will be called back again.
1101 *
1102 * We track the number of inactive FDs because they still need to be
1103 * closed by the polling thread after a wakeup on the data_pipe or
1104 * metadata_pipe.
1105 */
1106 if (stream->state != LTTNG_CONSUMER_ACTIVE_STREAM ||
1107 stream->endpoint_status == CONSUMER_ENDPOINT_INACTIVE) {
1108 (*nb_inactive_fd)++;
1109 continue;
1110 }
1111 /*
1112 * This clobbers way too much the debug output. Uncomment that if you
1113 * need it for debugging purposes.
1114 *
1115 * DBG("Active FD %d", stream->wait_fd);
1116 */
1117 (*pollfd)[i].fd = stream->wait_fd;
1118 (*pollfd)[i].events = POLLIN | POLLPRI;
1119 local_stream[i] = stream;
1120 i++;
1121 }
1122 rcu_read_unlock();
1123
1124 /*
1125 * Insert the consumer_data_pipe at the end of the array and don't
1126 * increment i so nb_fd is the number of real FD.
1127 */
1128 (*pollfd)[i].fd = lttng_pipe_get_readfd(ctx->consumer_data_pipe);
1129 (*pollfd)[i].events = POLLIN | POLLPRI;
1130
1131 (*pollfd)[i + 1].fd = lttng_pipe_get_readfd(ctx->consumer_wakeup_pipe);
1132 (*pollfd)[i + 1].events = POLLIN | POLLPRI;
1133 return i;
1134 }
1135
1136 /*
1137 * Poll on the should_quit pipe and the command socket return -1 on
1138 * error, 1 if should exit, 0 if data is available on the command socket
1139 */
1140 int lttng_consumer_poll_socket(struct pollfd *consumer_sockpoll)
1141 {
1142 int num_rdy;
1143
1144 restart:
1145 num_rdy = poll(consumer_sockpoll, 2, -1);
1146 if (num_rdy == -1) {
1147 /*
1148 * Restart interrupted system call.
1149 */
1150 if (errno == EINTR) {
1151 goto restart;
1152 }
1153 PERROR("Poll error");
1154 return -1;
1155 }
1156 if (consumer_sockpoll[0].revents & (POLLIN | POLLPRI)) {
1157 DBG("consumer_should_quit wake up");
1158 return 1;
1159 }
1160 return 0;
1161 }
1162
1163 /*
1164 * Set the error socket.
1165 */
1166 void lttng_consumer_set_error_sock(struct lttng_consumer_local_data *ctx,
1167 int sock)
1168 {
1169 ctx->consumer_error_socket = sock;
1170 }
1171
1172 /*
1173 * Set the command socket path.
1174 */
1175 void lttng_consumer_set_command_sock_path(
1176 struct lttng_consumer_local_data *ctx, char *sock)
1177 {
1178 ctx->consumer_command_sock_path = sock;
1179 }
1180
1181 /*
1182 * Send return code to the session daemon.
1183 * If the socket is not defined, we return 0, it is not a fatal error
1184 */
1185 int lttng_consumer_send_error(struct lttng_consumer_local_data *ctx, int cmd)
1186 {
1187 if (ctx->consumer_error_socket > 0) {
1188 return lttcomm_send_unix_sock(ctx->consumer_error_socket, &cmd,
1189 sizeof(enum lttcomm_sessiond_command));
1190 }
1191
1192 return 0;
1193 }
1194
1195 /*
1196 * Close all the tracefiles and stream fds and MUST be called when all
1197 * instances are destroyed i.e. when all threads were joined and are ended.
1198 */
1199 void lttng_consumer_cleanup(void)
1200 {
1201 struct lttng_ht_iter iter;
1202 struct lttng_consumer_channel *channel;
1203
1204 rcu_read_lock();
1205
1206 cds_lfht_for_each_entry(consumer_data.channel_ht->ht, &iter.iter, channel,
1207 node.node) {
1208 consumer_del_channel(channel);
1209 }
1210
1211 rcu_read_unlock();
1212
1213 lttng_ht_destroy(consumer_data.channel_ht);
1214
1215 cleanup_relayd_ht();
1216
1217 lttng_ht_destroy(consumer_data.stream_per_chan_id_ht);
1218
1219 /*
1220 * This HT contains streams that are freed by either the metadata thread or
1221 * the data thread so we do *nothing* on the hash table and simply destroy
1222 * it.
1223 */
1224 lttng_ht_destroy(consumer_data.stream_list_ht);
1225 }
1226
1227 /*
1228 * Called from signal handler.
1229 */
1230 void lttng_consumer_should_exit(struct lttng_consumer_local_data *ctx)
1231 {
1232 ssize_t ret;
1233
1234 consumer_quit = 1;
1235 ret = lttng_write(ctx->consumer_should_quit[1], "4", 1);
1236 if (ret < 1) {
1237 PERROR("write consumer quit");
1238 }
1239
1240 DBG("Consumer flag that it should quit");
1241 }
1242
1243
1244 /*
1245 * Flush pending writes to trace output disk file.
1246 */
1247 static
1248 void lttng_consumer_sync_trace_file(struct lttng_consumer_stream *stream,
1249 off_t orig_offset)
1250 {
1251 int ret;
1252 int outfd = stream->out_fd;
1253
1254 /*
1255 * This does a blocking write-and-wait on any page that belongs to the
1256 * subbuffer prior to the one we just wrote.
1257 * Don't care about error values, as these are just hints and ways to
1258 * limit the amount of page cache used.
1259 */
1260 if (orig_offset < stream->max_sb_size) {
1261 return;
1262 }
1263 lttng_sync_file_range(outfd, orig_offset - stream->max_sb_size,
1264 stream->max_sb_size,
1265 SYNC_FILE_RANGE_WAIT_BEFORE
1266 | SYNC_FILE_RANGE_WRITE
1267 | SYNC_FILE_RANGE_WAIT_AFTER);
1268 /*
1269 * Give hints to the kernel about how we access the file:
1270 * POSIX_FADV_DONTNEED : we won't re-access data in a near future after
1271 * we write it.
1272 *
1273 * We need to call fadvise again after the file grows because the
1274 * kernel does not seem to apply fadvise to non-existing parts of the
1275 * file.
1276 *
1277 * Call fadvise _after_ having waited for the page writeback to
1278 * complete because the dirty page writeback semantic is not well
1279 * defined. So it can be expected to lead to lower throughput in
1280 * streaming.
1281 */
1282 ret = posix_fadvise(outfd, orig_offset - stream->max_sb_size,
1283 stream->max_sb_size, POSIX_FADV_DONTNEED);
1284 if (ret && ret != -ENOSYS) {
1285 errno = ret;
1286 PERROR("posix_fadvise on fd %i", outfd);
1287 }
1288 }
1289
1290 /*
1291 * Initialise the necessary environnement :
1292 * - create a new context
1293 * - create the poll_pipe
1294 * - create the should_quit pipe (for signal handler)
1295 * - create the thread pipe (for splice)
1296 *
1297 * Takes a function pointer as argument, this function is called when data is
1298 * available on a buffer. This function is responsible to do the
1299 * kernctl_get_next_subbuf, read the data with mmap or splice depending on the
1300 * buffer configuration and then kernctl_put_next_subbuf at the end.
1301 *
1302 * Returns a pointer to the new context or NULL on error.
1303 */
1304 struct lttng_consumer_local_data *lttng_consumer_create(
1305 enum lttng_consumer_type type,
1306 ssize_t (*buffer_ready)(struct lttng_consumer_stream *stream,
1307 struct lttng_consumer_local_data *ctx),
1308 int (*recv_channel)(struct lttng_consumer_channel *channel),
1309 int (*recv_stream)(struct lttng_consumer_stream *stream),
1310 int (*update_stream)(uint64_t stream_key, uint32_t state))
1311 {
1312 int ret;
1313 struct lttng_consumer_local_data *ctx;
1314
1315 assert(consumer_data.type == LTTNG_CONSUMER_UNKNOWN ||
1316 consumer_data.type == type);
1317 consumer_data.type = type;
1318
1319 ctx = zmalloc(sizeof(struct lttng_consumer_local_data));
1320 if (ctx == NULL) {
1321 PERROR("allocating context");
1322 goto error;
1323 }
1324
1325 ctx->consumer_error_socket = -1;
1326 ctx->consumer_metadata_socket = -1;
1327 pthread_mutex_init(&ctx->metadata_socket_lock, NULL);
1328 /* assign the callbacks */
1329 ctx->on_buffer_ready = buffer_ready;
1330 ctx->on_recv_channel = recv_channel;
1331 ctx->on_recv_stream = recv_stream;
1332 ctx->on_update_stream = update_stream;
1333
1334 ctx->consumer_data_pipe = lttng_pipe_open(0);
1335 if (!ctx->consumer_data_pipe) {
1336 goto error_poll_pipe;
1337 }
1338
1339 ctx->consumer_wakeup_pipe = lttng_pipe_open(0);
1340 if (!ctx->consumer_wakeup_pipe) {
1341 goto error_wakeup_pipe;
1342 }
1343
1344 ret = pipe(ctx->consumer_should_quit);
1345 if (ret < 0) {
1346 PERROR("Error creating recv pipe");
1347 goto error_quit_pipe;
1348 }
1349
1350 ret = pipe(ctx->consumer_channel_pipe);
1351 if (ret < 0) {
1352 PERROR("Error creating channel pipe");
1353 goto error_channel_pipe;
1354 }
1355
1356 ctx->consumer_metadata_pipe = lttng_pipe_open(0);
1357 if (!ctx->consumer_metadata_pipe) {
1358 goto error_metadata_pipe;
1359 }
1360
1361 return ctx;
1362
1363 error_metadata_pipe:
1364 utils_close_pipe(ctx->consumer_channel_pipe);
1365 error_channel_pipe:
1366 utils_close_pipe(ctx->consumer_should_quit);
1367 error_quit_pipe:
1368 lttng_pipe_destroy(ctx->consumer_wakeup_pipe);
1369 error_wakeup_pipe:
1370 lttng_pipe_destroy(ctx->consumer_data_pipe);
1371 error_poll_pipe:
1372 free(ctx);
1373 error:
1374 return NULL;
1375 }
1376
1377 /*
1378 * Iterate over all streams of the hashtable and free them properly.
1379 */
1380 static void destroy_data_stream_ht(struct lttng_ht *ht)
1381 {
1382 struct lttng_ht_iter iter;
1383 struct lttng_consumer_stream *stream;
1384
1385 if (ht == NULL) {
1386 return;
1387 }
1388
1389 rcu_read_lock();
1390 cds_lfht_for_each_entry(ht->ht, &iter.iter, stream, node.node) {
1391 /*
1392 * Ignore return value since we are currently cleaning up so any error
1393 * can't be handled.
1394 */
1395 (void) consumer_del_stream(stream, ht);
1396 }
1397 rcu_read_unlock();
1398
1399 lttng_ht_destroy(ht);
1400 }
1401
1402 /*
1403 * Iterate over all streams of the metadata hashtable and free them
1404 * properly.
1405 */
1406 static void destroy_metadata_stream_ht(struct lttng_ht *ht)
1407 {
1408 struct lttng_ht_iter iter;
1409 struct lttng_consumer_stream *stream;
1410
1411 if (ht == NULL) {
1412 return;
1413 }
1414
1415 rcu_read_lock();
1416 cds_lfht_for_each_entry(ht->ht, &iter.iter, stream, node.node) {
1417 /*
1418 * Ignore return value since we are currently cleaning up so any error
1419 * can't be handled.
1420 */
1421 (void) consumer_del_metadata_stream(stream, ht);
1422 }
1423 rcu_read_unlock();
1424
1425 lttng_ht_destroy(ht);
1426 }
1427
1428 /*
1429 * Close all fds associated with the instance and free the context.
1430 */
1431 void lttng_consumer_destroy(struct lttng_consumer_local_data *ctx)
1432 {
1433 int ret;
1434
1435 DBG("Consumer destroying it. Closing everything.");
1436
1437 if (!ctx) {
1438 return;
1439 }
1440
1441 destroy_data_stream_ht(data_ht);
1442 destroy_metadata_stream_ht(metadata_ht);
1443
1444 ret = close(ctx->consumer_error_socket);
1445 if (ret) {
1446 PERROR("close");
1447 }
1448 ret = close(ctx->consumer_metadata_socket);
1449 if (ret) {
1450 PERROR("close");
1451 }
1452 utils_close_pipe(ctx->consumer_channel_pipe);
1453 lttng_pipe_destroy(ctx->consumer_data_pipe);
1454 lttng_pipe_destroy(ctx->consumer_metadata_pipe);
1455 lttng_pipe_destroy(ctx->consumer_wakeup_pipe);
1456 utils_close_pipe(ctx->consumer_should_quit);
1457
1458 unlink(ctx->consumer_command_sock_path);
1459 free(ctx);
1460 }
1461
1462 /*
1463 * Write the metadata stream id on the specified file descriptor.
1464 */
1465 static int write_relayd_metadata_id(int fd,
1466 struct lttng_consumer_stream *stream,
1467 struct consumer_relayd_sock_pair *relayd, unsigned long padding)
1468 {
1469 ssize_t ret;
1470 struct lttcomm_relayd_metadata_payload hdr;
1471
1472 hdr.stream_id = htobe64(stream->relayd_stream_id);
1473 hdr.padding_size = htobe32(padding);
1474 ret = lttng_write(fd, (void *) &hdr, sizeof(hdr));
1475 if (ret < sizeof(hdr)) {
1476 /*
1477 * This error means that the fd's end is closed so ignore the PERROR
1478 * not to clubber the error output since this can happen in a normal
1479 * code path.
1480 */
1481 if (errno != EPIPE) {
1482 PERROR("write metadata stream id");
1483 }
1484 DBG3("Consumer failed to write relayd metadata id (errno: %d)", errno);
1485 /*
1486 * Set ret to a negative value because if ret != sizeof(hdr), we don't
1487 * handle writting the missing part so report that as an error and
1488 * don't lie to the caller.
1489 */
1490 ret = -1;
1491 goto end;
1492 }
1493 DBG("Metadata stream id %" PRIu64 " with padding %lu written before data",
1494 stream->relayd_stream_id, padding);
1495
1496 end:
1497 return (int) ret;
1498 }
1499
1500 /*
1501 * Mmap the ring buffer, read it and write the data to the tracefile. This is a
1502 * core function for writing trace buffers to either the local filesystem or
1503 * the network.
1504 *
1505 * It must be called with the stream lock held.
1506 *
1507 * Careful review MUST be put if any changes occur!
1508 *
1509 * Returns the number of bytes written
1510 */
1511 ssize_t lttng_consumer_on_read_subbuffer_mmap(
1512 struct lttng_consumer_local_data *ctx,
1513 struct lttng_consumer_stream *stream, unsigned long len,
1514 unsigned long padding,
1515 struct ctf_packet_index *index)
1516 {
1517 unsigned long mmap_offset;
1518 void *mmap_base;
1519 ssize_t ret = 0;
1520 off_t orig_offset = stream->out_fd_offset;
1521 /* Default is on the disk */
1522 int outfd = stream->out_fd;
1523 struct consumer_relayd_sock_pair *relayd = NULL;
1524 unsigned int relayd_hang_up = 0;
1525
1526 /* RCU lock for the relayd pointer */
1527 rcu_read_lock();
1528
1529 /* Flag that the current stream if set for network streaming. */
1530 if (stream->net_seq_idx != (uint64_t) -1ULL) {
1531 relayd = consumer_find_relayd(stream->net_seq_idx);
1532 if (relayd == NULL) {
1533 ret = -EPIPE;
1534 goto end;
1535 }
1536 }
1537
1538 /* get the offset inside the fd to mmap */
1539 switch (consumer_data.type) {
1540 case LTTNG_CONSUMER_KERNEL:
1541 mmap_base = stream->mmap_base;
1542 ret = kernctl_get_mmap_read_offset(stream->wait_fd, &mmap_offset);
1543 if (ret < 0) {
1544 PERROR("tracer ctl get_mmap_read_offset");
1545 goto end;
1546 }
1547 break;
1548 case LTTNG_CONSUMER32_UST:
1549 case LTTNG_CONSUMER64_UST:
1550 mmap_base = lttng_ustctl_get_mmap_base(stream);
1551 if (!mmap_base) {
1552 ERR("read mmap get mmap base for stream %s", stream->name);
1553 ret = -EPERM;
1554 goto end;
1555 }
1556 ret = lttng_ustctl_get_mmap_read_offset(stream, &mmap_offset);
1557 if (ret != 0) {
1558 PERROR("tracer ctl get_mmap_read_offset");
1559 ret = -EINVAL;
1560 goto end;
1561 }
1562 break;
1563 default:
1564 ERR("Unknown consumer_data type");
1565 assert(0);
1566 }
1567
1568 /* Handle stream on the relayd if the output is on the network */
1569 if (relayd) {
1570 unsigned long netlen = len;
1571
1572 /*
1573 * Lock the control socket for the complete duration of the function
1574 * since from this point on we will use the socket.
1575 */
1576 if (stream->metadata_flag) {
1577 /* Metadata requires the control socket. */
1578 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
1579 if (stream->reset_metadata_flag) {
1580 ret = relayd_reset_metadata(&relayd->control_sock,
1581 stream->relayd_stream_id,
1582 stream->metadata_version);
1583 if (ret < 0) {
1584 relayd_hang_up = 1;
1585 goto write_error;
1586 }
1587 stream->reset_metadata_flag = 0;
1588 }
1589 netlen += sizeof(struct lttcomm_relayd_metadata_payload);
1590 }
1591
1592 ret = write_relayd_stream_header(stream, netlen, padding, relayd);
1593 if (ret < 0) {
1594 relayd_hang_up = 1;
1595 goto write_error;
1596 }
1597 /* Use the returned socket. */
1598 outfd = ret;
1599
1600 /* Write metadata stream id before payload */
1601 if (stream->metadata_flag) {
1602 ret = write_relayd_metadata_id(outfd, stream, relayd, padding);
1603 if (ret < 0) {
1604 relayd_hang_up = 1;
1605 goto write_error;
1606 }
1607 }
1608 } else {
1609 /* No streaming, we have to set the len with the full padding */
1610 len += padding;
1611
1612 if (stream->metadata_flag && stream->reset_metadata_flag) {
1613 ret = utils_truncate_stream_file(stream->out_fd, 0);
1614 if (ret < 0) {
1615 ERR("Reset metadata file");
1616 goto end;
1617 }
1618 stream->reset_metadata_flag = 0;
1619 }
1620
1621 /*
1622 * Check if we need to change the tracefile before writing the packet.
1623 */
1624 if (stream->chan->tracefile_size > 0 &&
1625 (stream->tracefile_size_current + len) >
1626 stream->chan->tracefile_size) {
1627 ret = utils_rotate_stream_file(stream->chan->pathname,
1628 stream->name, stream->chan->tracefile_size,
1629 stream->chan->tracefile_count, stream->uid, stream->gid,
1630 stream->out_fd, &(stream->tracefile_count_current),
1631 &stream->out_fd);
1632 if (ret < 0) {
1633 ERR("Rotating output file");
1634 goto end;
1635 }
1636 outfd = stream->out_fd;
1637
1638 if (stream->index_file) {
1639 lttng_index_file_put(stream->index_file);
1640 stream->index_file = lttng_index_file_create(stream->chan->pathname,
1641 stream->name, stream->uid, stream->gid,
1642 stream->chan->tracefile_size,
1643 stream->tracefile_count_current,
1644 CTF_INDEX_MAJOR, CTF_INDEX_MINOR);
1645 if (!stream->index_file) {
1646 goto end;
1647 }
1648 }
1649
1650 /* Reset current size because we just perform a rotation. */
1651 stream->tracefile_size_current = 0;
1652 stream->out_fd_offset = 0;
1653 orig_offset = 0;
1654 }
1655 stream->tracefile_size_current += len;
1656 if (index) {
1657 index->offset = htobe64(stream->out_fd_offset);
1658 }
1659 }
1660
1661 /*
1662 * This call guarantee that len or less is returned. It's impossible to
1663 * receive a ret value that is bigger than len.
1664 */
1665 ret = lttng_write(outfd, mmap_base + mmap_offset, len);
1666 DBG("Consumer mmap write() ret %zd (len %lu)", ret, len);
1667 if (ret < 0 || ((size_t) ret != len)) {
1668 /*
1669 * Report error to caller if nothing was written else at least send the
1670 * amount written.
1671 */
1672 if (ret < 0) {
1673 ret = -errno;
1674 }
1675 relayd_hang_up = 1;
1676
1677 /* Socket operation failed. We consider the relayd dead */
1678 if (errno == EPIPE || errno == EINVAL || errno == EBADF) {
1679 /*
1680 * This is possible if the fd is closed on the other side
1681 * (outfd) or any write problem. It can be verbose a bit for a
1682 * normal execution if for instance the relayd is stopped
1683 * abruptly. This can happen so set this to a DBG statement.
1684 */
1685 DBG("Consumer mmap write detected relayd hang up");
1686 } else {
1687 /* Unhandled error, print it and stop function right now. */
1688 PERROR("Error in write mmap (ret %zd != len %lu)", ret, len);
1689 }
1690 goto write_error;
1691 }
1692 stream->output_written += ret;
1693
1694 /* This call is useless on a socket so better save a syscall. */
1695 if (!relayd) {
1696 /* This won't block, but will start writeout asynchronously */
1697 lttng_sync_file_range(outfd, stream->out_fd_offset, len,
1698 SYNC_FILE_RANGE_WRITE);
1699 stream->out_fd_offset += len;
1700 lttng_consumer_sync_trace_file(stream, orig_offset);
1701 }
1702
1703 write_error:
1704 /*
1705 * This is a special case that the relayd has closed its socket. Let's
1706 * cleanup the relayd object and all associated streams.
1707 */
1708 if (relayd && relayd_hang_up) {
1709 ERR("Relayd hangup. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
1710 lttng_consumer_cleanup_relayd(relayd);
1711 }
1712
1713 end:
1714 /* Unlock only if ctrl socket used */
1715 if (relayd && stream->metadata_flag) {
1716 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
1717 }
1718
1719 rcu_read_unlock();
1720 return ret;
1721 }
1722
1723 /*
1724 * Splice the data from the ring buffer to the tracefile.
1725 *
1726 * It must be called with the stream lock held.
1727 *
1728 * Returns the number of bytes spliced.
1729 */
1730 ssize_t lttng_consumer_on_read_subbuffer_splice(
1731 struct lttng_consumer_local_data *ctx,
1732 struct lttng_consumer_stream *stream, unsigned long len,
1733 unsigned long padding,
1734 struct ctf_packet_index *index)
1735 {
1736 ssize_t ret = 0, written = 0, ret_splice = 0;
1737 loff_t offset = 0;
1738 off_t orig_offset = stream->out_fd_offset;
1739 int fd = stream->wait_fd;
1740 /* Default is on the disk */
1741 int outfd = stream->out_fd;
1742 struct consumer_relayd_sock_pair *relayd = NULL;
1743 int *splice_pipe;
1744 unsigned int relayd_hang_up = 0;
1745
1746 switch (consumer_data.type) {
1747 case LTTNG_CONSUMER_KERNEL:
1748 break;
1749 case LTTNG_CONSUMER32_UST:
1750 case LTTNG_CONSUMER64_UST:
1751 /* Not supported for user space tracing */
1752 return -ENOSYS;
1753 default:
1754 ERR("Unknown consumer_data type");
1755 assert(0);
1756 }
1757
1758 /* RCU lock for the relayd pointer */
1759 rcu_read_lock();
1760
1761 /* Flag that the current stream if set for network streaming. */
1762 if (stream->net_seq_idx != (uint64_t) -1ULL) {
1763 relayd = consumer_find_relayd(stream->net_seq_idx);
1764 if (relayd == NULL) {
1765 written = -ret;
1766 goto end;
1767 }
1768 }
1769 splice_pipe = stream->splice_pipe;
1770
1771 /* Write metadata stream id before payload */
1772 if (relayd) {
1773 unsigned long total_len = len;
1774
1775 if (stream->metadata_flag) {
1776 /*
1777 * Lock the control socket for the complete duration of the function
1778 * since from this point on we will use the socket.
1779 */
1780 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
1781
1782 if (stream->reset_metadata_flag) {
1783 ret = relayd_reset_metadata(&relayd->control_sock,
1784 stream->relayd_stream_id,
1785 stream->metadata_version);
1786 if (ret < 0) {
1787 relayd_hang_up = 1;
1788 goto write_error;
1789 }
1790 stream->reset_metadata_flag = 0;
1791 }
1792 ret = write_relayd_metadata_id(splice_pipe[1], stream, relayd,
1793 padding);
1794 if (ret < 0) {
1795 written = ret;
1796 relayd_hang_up = 1;
1797 goto write_error;
1798 }
1799
1800 total_len += sizeof(struct lttcomm_relayd_metadata_payload);
1801 }
1802
1803 ret = write_relayd_stream_header(stream, total_len, padding, relayd);
1804 if (ret < 0) {
1805 written = ret;
1806 relayd_hang_up = 1;
1807 goto write_error;
1808 }
1809 /* Use the returned socket. */
1810 outfd = ret;
1811 } else {
1812 /* No streaming, we have to set the len with the full padding */
1813 len += padding;
1814
1815 if (stream->metadata_flag && stream->reset_metadata_flag) {
1816 ret = utils_truncate_stream_file(stream->out_fd, 0);
1817 if (ret < 0) {
1818 ERR("Reset metadata file");
1819 goto end;
1820 }
1821 stream->reset_metadata_flag = 0;
1822 }
1823 /*
1824 * Check if we need to change the tracefile before writing the packet.
1825 */
1826 if (stream->chan->tracefile_size > 0 &&
1827 (stream->tracefile_size_current + len) >
1828 stream->chan->tracefile_size) {
1829 ret = utils_rotate_stream_file(stream->chan->pathname,
1830 stream->name, stream->chan->tracefile_size,
1831 stream->chan->tracefile_count, stream->uid, stream->gid,
1832 stream->out_fd, &(stream->tracefile_count_current),
1833 &stream->out_fd);
1834 if (ret < 0) {
1835 written = ret;
1836 ERR("Rotating output file");
1837 goto end;
1838 }
1839 outfd = stream->out_fd;
1840
1841 if (stream->index_file) {
1842 lttng_index_file_put(stream->index_file);
1843 stream->index_file = lttng_index_file_create(stream->chan->pathname,
1844 stream->name, stream->uid, stream->gid,
1845 stream->chan->tracefile_size,
1846 stream->tracefile_count_current,
1847 CTF_INDEX_MAJOR, CTF_INDEX_MINOR);
1848 if (!stream->index_file) {
1849 goto end;
1850 }
1851 }
1852
1853 /* Reset current size because we just perform a rotation. */
1854 stream->tracefile_size_current = 0;
1855 stream->out_fd_offset = 0;
1856 orig_offset = 0;
1857 }
1858 stream->tracefile_size_current += len;
1859 index->offset = htobe64(stream->out_fd_offset);
1860 }
1861
1862 while (len > 0) {
1863 DBG("splice chan to pipe offset %lu of len %lu (fd : %d, pipe: %d)",
1864 (unsigned long)offset, len, fd, splice_pipe[1]);
1865 ret_splice = splice(fd, &offset, splice_pipe[1], NULL, len,
1866 SPLICE_F_MOVE | SPLICE_F_MORE);
1867 DBG("splice chan to pipe, ret %zd", ret_splice);
1868 if (ret_splice < 0) {
1869 ret = errno;
1870 written = -ret;
1871 PERROR("Error in relay splice");
1872 goto splice_error;
1873 }
1874
1875 /* Handle stream on the relayd if the output is on the network */
1876 if (relayd && stream->metadata_flag) {
1877 size_t metadata_payload_size =
1878 sizeof(struct lttcomm_relayd_metadata_payload);
1879
1880 /* Update counter to fit the spliced data */
1881 ret_splice += metadata_payload_size;
1882 len += metadata_payload_size;
1883 /*
1884 * We do this so the return value can match the len passed as
1885 * argument to this function.
1886 */
1887 written -= metadata_payload_size;
1888 }
1889
1890 /* Splice data out */
1891 ret_splice = splice(splice_pipe[0], NULL, outfd, NULL,
1892 ret_splice, SPLICE_F_MOVE | SPLICE_F_MORE);
1893 DBG("Consumer splice pipe to file (out_fd: %d), ret %zd",
1894 outfd, ret_splice);
1895 if (ret_splice < 0) {
1896 ret = errno;
1897 written = -ret;
1898 relayd_hang_up = 1;
1899 goto write_error;
1900 } else if (ret_splice > len) {
1901 /*
1902 * We don't expect this code path to be executed but you never know
1903 * so this is an extra protection agains a buggy splice().
1904 */
1905 ret = errno;
1906 written += ret_splice;
1907 PERROR("Wrote more data than requested %zd (len: %lu)", ret_splice,
1908 len);
1909 goto splice_error;
1910 } else {
1911 /* All good, update current len and continue. */
1912 len -= ret_splice;
1913 }
1914
1915 /* This call is useless on a socket so better save a syscall. */
1916 if (!relayd) {
1917 /* This won't block, but will start writeout asynchronously */
1918 lttng_sync_file_range(outfd, stream->out_fd_offset, ret_splice,
1919 SYNC_FILE_RANGE_WRITE);
1920 stream->out_fd_offset += ret_splice;
1921 }
1922 stream->output_written += ret_splice;
1923 written += ret_splice;
1924 }
1925 if (!relayd) {
1926 lttng_consumer_sync_trace_file(stream, orig_offset);
1927 }
1928 goto end;
1929
1930 write_error:
1931 /*
1932 * This is a special case that the relayd has closed its socket. Let's
1933 * cleanup the relayd object and all associated streams.
1934 */
1935 if (relayd && relayd_hang_up) {
1936 ERR("Relayd hangup. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
1937 lttng_consumer_cleanup_relayd(relayd);
1938 /* Skip splice error so the consumer does not fail */
1939 goto end;
1940 }
1941
1942 splice_error:
1943 /* send the appropriate error description to sessiond */
1944 switch (ret) {
1945 case EINVAL:
1946 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_EINVAL);
1947 break;
1948 case ENOMEM:
1949 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_ENOMEM);
1950 break;
1951 case ESPIPE:
1952 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_SPLICE_ESPIPE);
1953 break;
1954 }
1955
1956 end:
1957 if (relayd && stream->metadata_flag) {
1958 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
1959 }
1960
1961 rcu_read_unlock();
1962 return written;
1963 }
1964
1965 /*
1966 * Take a snapshot for a specific fd
1967 *
1968 * Returns 0 on success, < 0 on error
1969 */
1970 int lttng_consumer_take_snapshot(struct lttng_consumer_stream *stream)
1971 {
1972 switch (consumer_data.type) {
1973 case LTTNG_CONSUMER_KERNEL:
1974 return lttng_kconsumer_take_snapshot(stream);
1975 case LTTNG_CONSUMER32_UST:
1976 case LTTNG_CONSUMER64_UST:
1977 return lttng_ustconsumer_take_snapshot(stream);
1978 default:
1979 ERR("Unknown consumer_data type");
1980 assert(0);
1981 return -ENOSYS;
1982 }
1983 }
1984
1985 /*
1986 * Get the produced position
1987 *
1988 * Returns 0 on success, < 0 on error
1989 */
1990 int lttng_consumer_get_produced_snapshot(struct lttng_consumer_stream *stream,
1991 unsigned long *pos)
1992 {
1993 switch (consumer_data.type) {
1994 case LTTNG_CONSUMER_KERNEL:
1995 return lttng_kconsumer_get_produced_snapshot(stream, pos);
1996 case LTTNG_CONSUMER32_UST:
1997 case LTTNG_CONSUMER64_UST:
1998 return lttng_ustconsumer_get_produced_snapshot(stream, pos);
1999 default:
2000 ERR("Unknown consumer_data type");
2001 assert(0);
2002 return -ENOSYS;
2003 }
2004 }
2005
2006 int lttng_consumer_recv_cmd(struct lttng_consumer_local_data *ctx,
2007 int sock, struct pollfd *consumer_sockpoll)
2008 {
2009 switch (consumer_data.type) {
2010 case LTTNG_CONSUMER_KERNEL:
2011 return lttng_kconsumer_recv_cmd(ctx, sock, consumer_sockpoll);
2012 case LTTNG_CONSUMER32_UST:
2013 case LTTNG_CONSUMER64_UST:
2014 return lttng_ustconsumer_recv_cmd(ctx, sock, consumer_sockpoll);
2015 default:
2016 ERR("Unknown consumer_data type");
2017 assert(0);
2018 return -ENOSYS;
2019 }
2020 }
2021
2022 void lttng_consumer_close_all_metadata(void)
2023 {
2024 switch (consumer_data.type) {
2025 case LTTNG_CONSUMER_KERNEL:
2026 /*
2027 * The Kernel consumer has a different metadata scheme so we don't
2028 * close anything because the stream will be closed by the session
2029 * daemon.
2030 */
2031 break;
2032 case LTTNG_CONSUMER32_UST:
2033 case LTTNG_CONSUMER64_UST:
2034 /*
2035 * Close all metadata streams. The metadata hash table is passed and
2036 * this call iterates over it by closing all wakeup fd. This is safe
2037 * because at this point we are sure that the metadata producer is
2038 * either dead or blocked.
2039 */
2040 lttng_ustconsumer_close_all_metadata(metadata_ht);
2041 break;
2042 default:
2043 ERR("Unknown consumer_data type");
2044 assert(0);
2045 }
2046 }
2047
2048 /*
2049 * Clean up a metadata stream and free its memory.
2050 */
2051 void consumer_del_metadata_stream(struct lttng_consumer_stream *stream,
2052 struct lttng_ht *ht)
2053 {
2054 struct lttng_consumer_channel *free_chan = NULL;
2055
2056 assert(stream);
2057 /*
2058 * This call should NEVER receive regular stream. It must always be
2059 * metadata stream and this is crucial for data structure synchronization.
2060 */
2061 assert(stream->metadata_flag);
2062
2063 DBG3("Consumer delete metadata stream %d", stream->wait_fd);
2064
2065 pthread_mutex_lock(&consumer_data.lock);
2066 pthread_mutex_lock(&stream->chan->lock);
2067 pthread_mutex_lock(&stream->lock);
2068 if (stream->chan->metadata_cache) {
2069 /* Only applicable to userspace consumers. */
2070 pthread_mutex_lock(&stream->chan->metadata_cache->lock);
2071 }
2072
2073 /* Remove any reference to that stream. */
2074 consumer_stream_delete(stream, ht);
2075
2076 /* Close down everything including the relayd if one. */
2077 consumer_stream_close(stream);
2078 /* Destroy tracer buffers of the stream. */
2079 consumer_stream_destroy_buffers(stream);
2080
2081 /* Atomically decrement channel refcount since other threads can use it. */
2082 if (!uatomic_sub_return(&stream->chan->refcount, 1)
2083 && !uatomic_read(&stream->chan->nb_init_stream_left)) {
2084 /* Go for channel deletion! */
2085 free_chan = stream->chan;
2086 }
2087
2088 /*
2089 * Nullify the stream reference so it is not used after deletion. The
2090 * channel lock MUST be acquired before being able to check for a NULL
2091 * pointer value.
2092 */
2093 stream->chan->metadata_stream = NULL;
2094
2095 if (stream->chan->metadata_cache) {
2096 pthread_mutex_unlock(&stream->chan->metadata_cache->lock);
2097 }
2098 pthread_mutex_unlock(&stream->lock);
2099 pthread_mutex_unlock(&stream->chan->lock);
2100 pthread_mutex_unlock(&consumer_data.lock);
2101
2102 if (free_chan) {
2103 consumer_del_channel(free_chan);
2104 }
2105
2106 consumer_stream_free(stream);
2107 }
2108
2109 /*
2110 * Action done with the metadata stream when adding it to the consumer internal
2111 * data structures to handle it.
2112 */
2113 int consumer_add_metadata_stream(struct lttng_consumer_stream *stream)
2114 {
2115 struct lttng_ht *ht = metadata_ht;
2116 int ret = 0;
2117 struct lttng_ht_iter iter;
2118 struct lttng_ht_node_u64 *node;
2119
2120 assert(stream);
2121 assert(ht);
2122
2123 DBG3("Adding metadata stream %" PRIu64 " to hash table", stream->key);
2124
2125 pthread_mutex_lock(&consumer_data.lock);
2126 pthread_mutex_lock(&stream->chan->lock);
2127 pthread_mutex_lock(&stream->chan->timer_lock);
2128 pthread_mutex_lock(&stream->lock);
2129
2130 /*
2131 * From here, refcounts are updated so be _careful_ when returning an error
2132 * after this point.
2133 */
2134
2135 rcu_read_lock();
2136
2137 /*
2138 * Lookup the stream just to make sure it does not exist in our internal
2139 * state. This should NEVER happen.
2140 */
2141 lttng_ht_lookup(ht, &stream->key, &iter);
2142 node = lttng_ht_iter_get_node_u64(&iter);
2143 assert(!node);
2144
2145 /*
2146 * When nb_init_stream_left reaches 0, we don't need to trigger any action
2147 * in terms of destroying the associated channel, because the action that
2148 * causes the count to become 0 also causes a stream to be added. The
2149 * channel deletion will thus be triggered by the following removal of this
2150 * stream.
2151 */
2152 if (uatomic_read(&stream->chan->nb_init_stream_left) > 0) {
2153 /* Increment refcount before decrementing nb_init_stream_left */
2154 cmm_smp_wmb();
2155 uatomic_dec(&stream->chan->nb_init_stream_left);
2156 }
2157
2158 lttng_ht_add_unique_u64(ht, &stream->node);
2159
2160 lttng_ht_add_u64(consumer_data.stream_per_chan_id_ht,
2161 &stream->node_channel_id);
2162
2163 /*
2164 * Add stream to the stream_list_ht of the consumer data. No need to steal
2165 * the key since the HT does not use it and we allow to add redundant keys
2166 * into this table.
2167 */
2168 lttng_ht_add_u64(consumer_data.stream_list_ht, &stream->node_session_id);
2169
2170 rcu_read_unlock();
2171
2172 pthread_mutex_unlock(&stream->lock);
2173 pthread_mutex_unlock(&stream->chan->lock);
2174 pthread_mutex_unlock(&stream->chan->timer_lock);
2175 pthread_mutex_unlock(&consumer_data.lock);
2176 return ret;
2177 }
2178
2179 /*
2180 * Delete data stream that are flagged for deletion (endpoint_status).
2181 */
2182 static void validate_endpoint_status_data_stream(void)
2183 {
2184 struct lttng_ht_iter iter;
2185 struct lttng_consumer_stream *stream;
2186
2187 DBG("Consumer delete flagged data stream");
2188
2189 rcu_read_lock();
2190 cds_lfht_for_each_entry(data_ht->ht, &iter.iter, stream, node.node) {
2191 /* Validate delete flag of the stream */
2192 if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
2193 continue;
2194 }
2195 /* Delete it right now */
2196 consumer_del_stream(stream, data_ht);
2197 }
2198 rcu_read_unlock();
2199 }
2200
2201 /*
2202 * Delete metadata stream that are flagged for deletion (endpoint_status).
2203 */
2204 static void validate_endpoint_status_metadata_stream(
2205 struct lttng_poll_event *pollset)
2206 {
2207 struct lttng_ht_iter iter;
2208 struct lttng_consumer_stream *stream;
2209
2210 DBG("Consumer delete flagged metadata stream");
2211
2212 assert(pollset);
2213
2214 rcu_read_lock();
2215 cds_lfht_for_each_entry(metadata_ht->ht, &iter.iter, stream, node.node) {
2216 /* Validate delete flag of the stream */
2217 if (stream->endpoint_status == CONSUMER_ENDPOINT_ACTIVE) {
2218 continue;
2219 }
2220 /*
2221 * Remove from pollset so the metadata thread can continue without
2222 * blocking on a deleted stream.
2223 */
2224 lttng_poll_del(pollset, stream->wait_fd);
2225
2226 /* Delete it right now */
2227 consumer_del_metadata_stream(stream, metadata_ht);
2228 }
2229 rcu_read_unlock();
2230 }
2231
2232 /*
2233 * Thread polls on metadata file descriptor and write them on disk or on the
2234 * network.
2235 */
2236 void *consumer_thread_metadata_poll(void *data)
2237 {
2238 int ret, i, pollfd, err = -1;
2239 uint32_t revents, nb_fd;
2240 struct lttng_consumer_stream *stream = NULL;
2241 struct lttng_ht_iter iter;
2242 struct lttng_ht_node_u64 *node;
2243 struct lttng_poll_event events;
2244 struct lttng_consumer_local_data *ctx = data;
2245 ssize_t len;
2246
2247 rcu_register_thread();
2248
2249 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_METADATA);
2250
2251 if (testpoint(consumerd_thread_metadata)) {
2252 goto error_testpoint;
2253 }
2254
2255 health_code_update();
2256
2257 DBG("Thread metadata poll started");
2258
2259 /* Size is set to 1 for the consumer_metadata pipe */
2260 ret = lttng_poll_create(&events, 2, LTTNG_CLOEXEC);
2261 if (ret < 0) {
2262 ERR("Poll set creation failed");
2263 goto end_poll;
2264 }
2265
2266 ret = lttng_poll_add(&events,
2267 lttng_pipe_get_readfd(ctx->consumer_metadata_pipe), LPOLLIN);
2268 if (ret < 0) {
2269 goto end;
2270 }
2271
2272 /* Main loop */
2273 DBG("Metadata main loop started");
2274
2275 while (1) {
2276 restart:
2277 health_code_update();
2278 health_poll_entry();
2279 DBG("Metadata poll wait");
2280 ret = lttng_poll_wait(&events, -1);
2281 DBG("Metadata poll return from wait with %d fd(s)",
2282 LTTNG_POLL_GETNB(&events));
2283 health_poll_exit();
2284 DBG("Metadata event caught in thread");
2285 if (ret < 0) {
2286 if (errno == EINTR) {
2287 ERR("Poll EINTR caught");
2288 goto restart;
2289 }
2290 if (LTTNG_POLL_GETNB(&events) == 0) {
2291 err = 0; /* All is OK */
2292 }
2293 goto end;
2294 }
2295
2296 nb_fd = ret;
2297
2298 /* From here, the event is a metadata wait fd */
2299 for (i = 0; i < nb_fd; i++) {
2300 health_code_update();
2301
2302 revents = LTTNG_POLL_GETEV(&events, i);
2303 pollfd = LTTNG_POLL_GETFD(&events, i);
2304
2305 if (!revents) {
2306 /* No activity for this FD (poll implementation). */
2307 continue;
2308 }
2309
2310 if (pollfd == lttng_pipe_get_readfd(ctx->consumer_metadata_pipe)) {
2311 if (revents & LPOLLIN) {
2312 ssize_t pipe_len;
2313
2314 pipe_len = lttng_pipe_read(ctx->consumer_metadata_pipe,
2315 &stream, sizeof(stream));
2316 if (pipe_len < sizeof(stream)) {
2317 if (pipe_len < 0) {
2318 PERROR("read metadata stream");
2319 }
2320 /*
2321 * Remove the pipe from the poll set and continue the loop
2322 * since their might be data to consume.
2323 */
2324 lttng_poll_del(&events,
2325 lttng_pipe_get_readfd(ctx->consumer_metadata_pipe));
2326 lttng_pipe_read_close(ctx->consumer_metadata_pipe);
2327 continue;
2328 }
2329
2330 /* A NULL stream means that the state has changed. */
2331 if (stream == NULL) {
2332 /* Check for deleted streams. */
2333 validate_endpoint_status_metadata_stream(&events);
2334 goto restart;
2335 }
2336
2337 DBG("Adding metadata stream %d to poll set",
2338 stream->wait_fd);
2339
2340 /* Add metadata stream to the global poll events list */
2341 lttng_poll_add(&events, stream->wait_fd,
2342 LPOLLIN | LPOLLPRI | LPOLLHUP);
2343 } else if (revents & (LPOLLERR | LPOLLHUP)) {
2344 DBG("Metadata thread pipe hung up");
2345 /*
2346 * Remove the pipe from the poll set and continue the loop
2347 * since their might be data to consume.
2348 */
2349 lttng_poll_del(&events,
2350 lttng_pipe_get_readfd(ctx->consumer_metadata_pipe));
2351 lttng_pipe_read_close(ctx->consumer_metadata_pipe);
2352 continue;
2353 } else {
2354 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2355 goto end;
2356 }
2357
2358 /* Handle other stream */
2359 continue;
2360 }
2361
2362 rcu_read_lock();
2363 {
2364 uint64_t tmp_id = (uint64_t) pollfd;
2365
2366 lttng_ht_lookup(metadata_ht, &tmp_id, &iter);
2367 }
2368 node = lttng_ht_iter_get_node_u64(&iter);
2369 assert(node);
2370
2371 stream = caa_container_of(node, struct lttng_consumer_stream,
2372 node);
2373
2374 if (revents & (LPOLLIN | LPOLLPRI)) {
2375 /* Get the data out of the metadata file descriptor */
2376 DBG("Metadata available on fd %d", pollfd);
2377 assert(stream->wait_fd == pollfd);
2378
2379 do {
2380 health_code_update();
2381
2382 len = ctx->on_buffer_ready(stream, ctx);
2383 /*
2384 * We don't check the return value here since if we get
2385 * a negative len, it means an error occurred thus we
2386 * simply remove it from the poll set and free the
2387 * stream.
2388 */
2389 } while (len > 0);
2390
2391 /* It's ok to have an unavailable sub-buffer */
2392 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
2393 /* Clean up stream from consumer and free it. */
2394 lttng_poll_del(&events, stream->wait_fd);
2395 consumer_del_metadata_stream(stream, metadata_ht);
2396 }
2397 } else if (revents & (LPOLLERR | LPOLLHUP)) {
2398 DBG("Metadata fd %d is hup|err.", pollfd);
2399 if (!stream->hangup_flush_done
2400 && (consumer_data.type == LTTNG_CONSUMER32_UST
2401 || consumer_data.type == LTTNG_CONSUMER64_UST)) {
2402 DBG("Attempting to flush and consume the UST buffers");
2403 lttng_ustconsumer_on_stream_hangup(stream);
2404
2405 /* We just flushed the stream now read it. */
2406 do {
2407 health_code_update();
2408
2409 len = ctx->on_buffer_ready(stream, ctx);
2410 /*
2411 * We don't check the return value here since if we get
2412 * a negative len, it means an error occurred thus we
2413 * simply remove it from the poll set and free the
2414 * stream.
2415 */
2416 } while (len > 0);
2417 }
2418
2419 lttng_poll_del(&events, stream->wait_fd);
2420 /*
2421 * This call update the channel states, closes file descriptors
2422 * and securely free the stream.
2423 */
2424 consumer_del_metadata_stream(stream, metadata_ht);
2425 } else {
2426 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2427 rcu_read_unlock();
2428 goto end;
2429 }
2430 /* Release RCU lock for the stream looked up */
2431 rcu_read_unlock();
2432 }
2433 }
2434
2435 /* All is OK */
2436 err = 0;
2437 end:
2438 DBG("Metadata poll thread exiting");
2439
2440 lttng_poll_clean(&events);
2441 end_poll:
2442 error_testpoint:
2443 if (err) {
2444 health_error();
2445 ERR("Health error occurred in %s", __func__);
2446 }
2447 health_unregister(health_consumerd);
2448 rcu_unregister_thread();
2449 return NULL;
2450 }
2451
2452 /*
2453 * This thread polls the fds in the set to consume the data and write
2454 * it to tracefile if necessary.
2455 */
2456 void *consumer_thread_data_poll(void *data)
2457 {
2458 int num_rdy, num_hup, high_prio, ret, i, err = -1;
2459 struct pollfd *pollfd = NULL;
2460 /* local view of the streams */
2461 struct lttng_consumer_stream **local_stream = NULL, *new_stream = NULL;
2462 /* local view of consumer_data.fds_count */
2463 int nb_fd = 0;
2464 /* Number of FDs with CONSUMER_ENDPOINT_INACTIVE but still open. */
2465 int nb_inactive_fd = 0;
2466 struct lttng_consumer_local_data *ctx = data;
2467 ssize_t len;
2468
2469 rcu_register_thread();
2470
2471 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_DATA);
2472
2473 if (testpoint(consumerd_thread_data)) {
2474 goto error_testpoint;
2475 }
2476
2477 health_code_update();
2478
2479 local_stream = zmalloc(sizeof(struct lttng_consumer_stream *));
2480 if (local_stream == NULL) {
2481 PERROR("local_stream malloc");
2482 goto end;
2483 }
2484
2485 while (1) {
2486 health_code_update();
2487
2488 high_prio = 0;
2489 num_hup = 0;
2490
2491 /*
2492 * the fds set has been updated, we need to update our
2493 * local array as well
2494 */
2495 pthread_mutex_lock(&consumer_data.lock);
2496 if (consumer_data.need_update) {
2497 free(pollfd);
2498 pollfd = NULL;
2499
2500 free(local_stream);
2501 local_stream = NULL;
2502
2503 /*
2504 * Allocate for all fds +1 for the consumer_data_pipe and +1 for
2505 * wake up pipe.
2506 */
2507 pollfd = zmalloc((consumer_data.stream_count + 2) * sizeof(struct pollfd));
2508 if (pollfd == NULL) {
2509 PERROR("pollfd malloc");
2510 pthread_mutex_unlock(&consumer_data.lock);
2511 goto end;
2512 }
2513
2514 local_stream = zmalloc((consumer_data.stream_count + 2) *
2515 sizeof(struct lttng_consumer_stream *));
2516 if (local_stream == NULL) {
2517 PERROR("local_stream malloc");
2518 pthread_mutex_unlock(&consumer_data.lock);
2519 goto end;
2520 }
2521 ret = update_poll_array(ctx, &pollfd, local_stream,
2522 data_ht, &nb_inactive_fd);
2523 if (ret < 0) {
2524 ERR("Error in allocating pollfd or local_outfds");
2525 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
2526 pthread_mutex_unlock(&consumer_data.lock);
2527 goto end;
2528 }
2529 nb_fd = ret;
2530 consumer_data.need_update = 0;
2531 }
2532 pthread_mutex_unlock(&consumer_data.lock);
2533
2534 /* No FDs and consumer_quit, consumer_cleanup the thread */
2535 if (nb_fd == 0 && consumer_quit == 1 && nb_inactive_fd == 0) {
2536 err = 0; /* All is OK */
2537 goto end;
2538 }
2539 /* poll on the array of fds */
2540 restart:
2541 DBG("polling on %d fd", nb_fd + 2);
2542 health_poll_entry();
2543 num_rdy = poll(pollfd, nb_fd + 2, -1);
2544 health_poll_exit();
2545 DBG("poll num_rdy : %d", num_rdy);
2546 if (num_rdy == -1) {
2547 /*
2548 * Restart interrupted system call.
2549 */
2550 if (errno == EINTR) {
2551 goto restart;
2552 }
2553 PERROR("Poll error");
2554 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
2555 goto end;
2556 } else if (num_rdy == 0) {
2557 DBG("Polling thread timed out");
2558 goto end;
2559 }
2560
2561 /*
2562 * If the consumer_data_pipe triggered poll go directly to the
2563 * beginning of the loop to update the array. We want to prioritize
2564 * array update over low-priority reads.
2565 */
2566 if (pollfd[nb_fd].revents & (POLLIN | POLLPRI)) {
2567 ssize_t pipe_readlen;
2568
2569 DBG("consumer_data_pipe wake up");
2570 pipe_readlen = lttng_pipe_read(ctx->consumer_data_pipe,
2571 &new_stream, sizeof(new_stream));
2572 if (pipe_readlen < sizeof(new_stream)) {
2573 PERROR("Consumer data pipe");
2574 /* Continue so we can at least handle the current stream(s). */
2575 continue;
2576 }
2577
2578 /*
2579 * If the stream is NULL, just ignore it. It's also possible that
2580 * the sessiond poll thread changed the consumer_quit state and is
2581 * waking us up to test it.
2582 */
2583 if (new_stream == NULL) {
2584 validate_endpoint_status_data_stream();
2585 continue;
2586 }
2587
2588 /* Continue to update the local streams and handle prio ones */
2589 continue;
2590 }
2591
2592 /* Handle wakeup pipe. */
2593 if (pollfd[nb_fd + 1].revents & (POLLIN | POLLPRI)) {
2594 char dummy;
2595 ssize_t pipe_readlen;
2596
2597 pipe_readlen = lttng_pipe_read(ctx->consumer_wakeup_pipe, &dummy,
2598 sizeof(dummy));
2599 if (pipe_readlen < 0) {
2600 PERROR("Consumer data wakeup pipe");
2601 }
2602 /* We've been awakened to handle stream(s). */
2603 ctx->has_wakeup = 0;
2604 }
2605
2606 /* Take care of high priority channels first. */
2607 for (i = 0; i < nb_fd; i++) {
2608 health_code_update();
2609
2610 if (local_stream[i] == NULL) {
2611 continue;
2612 }
2613 if (pollfd[i].revents & POLLPRI) {
2614 DBG("Urgent read on fd %d", pollfd[i].fd);
2615 high_prio = 1;
2616 len = ctx->on_buffer_ready(local_stream[i], ctx);
2617 /* it's ok to have an unavailable sub-buffer */
2618 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
2619 /* Clean the stream and free it. */
2620 consumer_del_stream(local_stream[i], data_ht);
2621 local_stream[i] = NULL;
2622 } else if (len > 0) {
2623 local_stream[i]->data_read = 1;
2624 }
2625 }
2626 }
2627
2628 /*
2629 * If we read high prio channel in this loop, try again
2630 * for more high prio data.
2631 */
2632 if (high_prio) {
2633 continue;
2634 }
2635
2636 /* Take care of low priority channels. */
2637 for (i = 0; i < nb_fd; i++) {
2638 health_code_update();
2639
2640 if (local_stream[i] == NULL) {
2641 continue;
2642 }
2643 if ((pollfd[i].revents & POLLIN) ||
2644 local_stream[i]->hangup_flush_done ||
2645 local_stream[i]->has_data) {
2646 DBG("Normal read on fd %d", pollfd[i].fd);
2647 len = ctx->on_buffer_ready(local_stream[i], ctx);
2648 /* it's ok to have an unavailable sub-buffer */
2649 if (len < 0 && len != -EAGAIN && len != -ENODATA) {
2650 /* Clean the stream and free it. */
2651 consumer_del_stream(local_stream[i], data_ht);
2652 local_stream[i] = NULL;
2653 } else if (len > 0) {
2654 local_stream[i]->data_read = 1;
2655 }
2656 }
2657 }
2658
2659 /* Handle hangup and errors */
2660 for (i = 0; i < nb_fd; i++) {
2661 health_code_update();
2662
2663 if (local_stream[i] == NULL) {
2664 continue;
2665 }
2666 if (!local_stream[i]->hangup_flush_done
2667 && (pollfd[i].revents & (POLLHUP | POLLERR | POLLNVAL))
2668 && (consumer_data.type == LTTNG_CONSUMER32_UST
2669 || consumer_data.type == LTTNG_CONSUMER64_UST)) {
2670 DBG("fd %d is hup|err|nval. Attempting flush and read.",
2671 pollfd[i].fd);
2672 lttng_ustconsumer_on_stream_hangup(local_stream[i]);
2673 /* Attempt read again, for the data we just flushed. */
2674 local_stream[i]->data_read = 1;
2675 }
2676 /*
2677 * If the poll flag is HUP/ERR/NVAL and we have
2678 * read no data in this pass, we can remove the
2679 * stream from its hash table.
2680 */
2681 if ((pollfd[i].revents & POLLHUP)) {
2682 DBG("Polling fd %d tells it has hung up.", pollfd[i].fd);
2683 if (!local_stream[i]->data_read) {
2684 consumer_del_stream(local_stream[i], data_ht);
2685 local_stream[i] = NULL;
2686 num_hup++;
2687 }
2688 } else if (pollfd[i].revents & POLLERR) {
2689 ERR("Error returned in polling fd %d.", pollfd[i].fd);
2690 if (!local_stream[i]->data_read) {
2691 consumer_del_stream(local_stream[i], data_ht);
2692 local_stream[i] = NULL;
2693 num_hup++;
2694 }
2695 } else if (pollfd[i].revents & POLLNVAL) {
2696 ERR("Polling fd %d tells fd is not open.", pollfd[i].fd);
2697 if (!local_stream[i]->data_read) {
2698 consumer_del_stream(local_stream[i], data_ht);
2699 local_stream[i] = NULL;
2700 num_hup++;
2701 }
2702 }
2703 if (local_stream[i] != NULL) {
2704 local_stream[i]->data_read = 0;
2705 }
2706 }
2707 }
2708 /* All is OK */
2709 err = 0;
2710 end:
2711 DBG("polling thread exiting");
2712 free(pollfd);
2713 free(local_stream);
2714
2715 /*
2716 * Close the write side of the pipe so epoll_wait() in
2717 * consumer_thread_metadata_poll can catch it. The thread is monitoring the
2718 * read side of the pipe. If we close them both, epoll_wait strangely does
2719 * not return and could create a endless wait period if the pipe is the
2720 * only tracked fd in the poll set. The thread will take care of closing
2721 * the read side.
2722 */
2723 (void) lttng_pipe_write_close(ctx->consumer_metadata_pipe);
2724
2725 error_testpoint:
2726 if (err) {
2727 health_error();
2728 ERR("Health error occurred in %s", __func__);
2729 }
2730 health_unregister(health_consumerd);
2731
2732 rcu_unregister_thread();
2733 return NULL;
2734 }
2735
2736 /*
2737 * Close wake-up end of each stream belonging to the channel. This will
2738 * allow the poll() on the stream read-side to detect when the
2739 * write-side (application) finally closes them.
2740 */
2741 static
2742 void consumer_close_channel_streams(struct lttng_consumer_channel *channel)
2743 {
2744 struct lttng_ht *ht;
2745 struct lttng_consumer_stream *stream;
2746 struct lttng_ht_iter iter;
2747
2748 ht = consumer_data.stream_per_chan_id_ht;
2749
2750 rcu_read_lock();
2751 cds_lfht_for_each_entry_duplicate(ht->ht,
2752 ht->hash_fct(&channel->key, lttng_ht_seed),
2753 ht->match_fct, &channel->key,
2754 &iter.iter, stream, node_channel_id.node) {
2755 /*
2756 * Protect against teardown with mutex.
2757 */
2758 pthread_mutex_lock(&stream->lock);
2759 if (cds_lfht_is_node_deleted(&stream->node.node)) {
2760 goto next;
2761 }
2762 switch (consumer_data.type) {
2763 case LTTNG_CONSUMER_KERNEL:
2764 break;
2765 case LTTNG_CONSUMER32_UST:
2766 case LTTNG_CONSUMER64_UST:
2767 if (stream->metadata_flag) {
2768 /* Safe and protected by the stream lock. */
2769 lttng_ustconsumer_close_metadata(stream->chan);
2770 } else {
2771 /*
2772 * Note: a mutex is taken internally within
2773 * liblttng-ust-ctl to protect timer wakeup_fd
2774 * use from concurrent close.
2775 */
2776 lttng_ustconsumer_close_stream_wakeup(stream);
2777 }
2778 break;
2779 default:
2780 ERR("Unknown consumer_data type");
2781 assert(0);
2782 }
2783 next:
2784 pthread_mutex_unlock(&stream->lock);
2785 }
2786 rcu_read_unlock();
2787 }
2788
2789 static void destroy_channel_ht(struct lttng_ht *ht)
2790 {
2791 struct lttng_ht_iter iter;
2792 struct lttng_consumer_channel *channel;
2793 int ret;
2794
2795 if (ht == NULL) {
2796 return;
2797 }
2798
2799 rcu_read_lock();
2800 cds_lfht_for_each_entry(ht->ht, &iter.iter, channel, wait_fd_node.node) {
2801 ret = lttng_ht_del(ht, &iter);
2802 assert(ret != 0);
2803 }
2804 rcu_read_unlock();
2805
2806 lttng_ht_destroy(ht);
2807 }
2808
2809 /*
2810 * This thread polls the channel fds to detect when they are being
2811 * closed. It closes all related streams if the channel is detected as
2812 * closed. It is currently only used as a shim layer for UST because the
2813 * consumerd needs to keep the per-stream wakeup end of pipes open for
2814 * periodical flush.
2815 */
2816 void *consumer_thread_channel_poll(void *data)
2817 {
2818 int ret, i, pollfd, err = -1;
2819 uint32_t revents, nb_fd;
2820 struct lttng_consumer_channel *chan = NULL;
2821 struct lttng_ht_iter iter;
2822 struct lttng_ht_node_u64 *node;
2823 struct lttng_poll_event events;
2824 struct lttng_consumer_local_data *ctx = data;
2825 struct lttng_ht *channel_ht;
2826
2827 rcu_register_thread();
2828
2829 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_CHANNEL);
2830
2831 if (testpoint(consumerd_thread_channel)) {
2832 goto error_testpoint;
2833 }
2834
2835 health_code_update();
2836
2837 channel_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
2838 if (!channel_ht) {
2839 /* ENOMEM at this point. Better to bail out. */
2840 goto end_ht;
2841 }
2842
2843 DBG("Thread channel poll started");
2844
2845 /* Size is set to 1 for the consumer_channel pipe */
2846 ret = lttng_poll_create(&events, 2, LTTNG_CLOEXEC);
2847 if (ret < 0) {
2848 ERR("Poll set creation failed");
2849 goto end_poll;
2850 }
2851
2852 ret = lttng_poll_add(&events, ctx->consumer_channel_pipe[0], LPOLLIN);
2853 if (ret < 0) {
2854 goto end;
2855 }
2856
2857 /* Main loop */
2858 DBG("Channel main loop started");
2859
2860 while (1) {
2861 restart:
2862 health_code_update();
2863 DBG("Channel poll wait");
2864 health_poll_entry();
2865 ret = lttng_poll_wait(&events, -1);
2866 DBG("Channel poll return from wait with %d fd(s)",
2867 LTTNG_POLL_GETNB(&events));
2868 health_poll_exit();
2869 DBG("Channel event caught in thread");
2870 if (ret < 0) {
2871 if (errno == EINTR) {
2872 ERR("Poll EINTR caught");
2873 goto restart;
2874 }
2875 if (LTTNG_POLL_GETNB(&events) == 0) {
2876 err = 0; /* All is OK */
2877 }
2878 goto end;
2879 }
2880
2881 nb_fd = ret;
2882
2883 /* From here, the event is a channel wait fd */
2884 for (i = 0; i < nb_fd; i++) {
2885 health_code_update();
2886
2887 revents = LTTNG_POLL_GETEV(&events, i);
2888 pollfd = LTTNG_POLL_GETFD(&events, i);
2889
2890 if (!revents) {
2891 /* No activity for this FD (poll implementation). */
2892 continue;
2893 }
2894
2895 if (pollfd == ctx->consumer_channel_pipe[0]) {
2896 if (revents & LPOLLIN) {
2897 enum consumer_channel_action action;
2898 uint64_t key;
2899
2900 ret = read_channel_pipe(ctx, &chan, &key, &action);
2901 if (ret <= 0) {
2902 if (ret < 0) {
2903 ERR("Error reading channel pipe");
2904 }
2905 lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
2906 continue;
2907 }
2908
2909 switch (action) {
2910 case CONSUMER_CHANNEL_ADD:
2911 DBG("Adding channel %d to poll set",
2912 chan->wait_fd);
2913
2914 lttng_ht_node_init_u64(&chan->wait_fd_node,
2915 chan->wait_fd);
2916 rcu_read_lock();
2917 lttng_ht_add_unique_u64(channel_ht,
2918 &chan->wait_fd_node);
2919 rcu_read_unlock();
2920 /* Add channel to the global poll events list */
2921 lttng_poll_add(&events, chan->wait_fd,
2922 LPOLLERR | LPOLLHUP);
2923 break;
2924 case CONSUMER_CHANNEL_DEL:
2925 {
2926 /*
2927 * This command should never be called if the channel
2928 * has streams monitored by either the data or metadata
2929 * thread. The consumer only notify this thread with a
2930 * channel del. command if it receives a destroy
2931 * channel command from the session daemon that send it
2932 * if a command prior to the GET_CHANNEL failed.
2933 */
2934
2935 rcu_read_lock();
2936 chan = consumer_find_channel(key);
2937 if (!chan) {
2938 rcu_read_unlock();
2939 ERR("UST consumer get channel key %" PRIu64 " not found for del channel", key);
2940 break;
2941 }
2942 lttng_poll_del(&events, chan->wait_fd);
2943 iter.iter.node = &chan->wait_fd_node.node;
2944 ret = lttng_ht_del(channel_ht, &iter);
2945 assert(ret == 0);
2946
2947 switch (consumer_data.type) {
2948 case LTTNG_CONSUMER_KERNEL:
2949 break;
2950 case LTTNG_CONSUMER32_UST:
2951 case LTTNG_CONSUMER64_UST:
2952 health_code_update();
2953 /* Destroy streams that might have been left in the stream list. */
2954 clean_channel_stream_list(chan);
2955 break;
2956 default:
2957 ERR("Unknown consumer_data type");
2958 assert(0);
2959 }
2960
2961 /*
2962 * Release our own refcount. Force channel deletion even if
2963 * streams were not initialized.
2964 */
2965 if (!uatomic_sub_return(&chan->refcount, 1)) {
2966 consumer_del_channel(chan);
2967 }
2968 rcu_read_unlock();
2969 goto restart;
2970 }
2971 case CONSUMER_CHANNEL_QUIT:
2972 /*
2973 * Remove the pipe from the poll set and continue the loop
2974 * since their might be data to consume.
2975 */
2976 lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
2977 continue;
2978 default:
2979 ERR("Unknown action");
2980 break;
2981 }
2982 } else if (revents & (LPOLLERR | LPOLLHUP)) {
2983 DBG("Channel thread pipe hung up");
2984 /*
2985 * Remove the pipe from the poll set and continue the loop
2986 * since their might be data to consume.
2987 */
2988 lttng_poll_del(&events, ctx->consumer_channel_pipe[0]);
2989 continue;
2990 } else {
2991 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
2992 goto end;
2993 }
2994
2995 /* Handle other stream */
2996 continue;
2997 }
2998
2999 rcu_read_lock();
3000 {
3001 uint64_t tmp_id = (uint64_t) pollfd;
3002
3003 lttng_ht_lookup(channel_ht, &tmp_id, &iter);
3004 }
3005 node = lttng_ht_iter_get_node_u64(&iter);
3006 assert(node);
3007
3008 chan = caa_container_of(node, struct lttng_consumer_channel,
3009 wait_fd_node);
3010
3011 /* Check for error event */
3012 if (revents & (LPOLLERR | LPOLLHUP)) {
3013 DBG("Channel fd %d is hup|err.", pollfd);
3014
3015 lttng_poll_del(&events, chan->wait_fd);
3016 ret = lttng_ht_del(channel_ht, &iter);
3017 assert(ret == 0);
3018
3019 /*
3020 * This will close the wait fd for each stream associated to
3021 * this channel AND monitored by the data/metadata thread thus
3022 * will be clean by the right thread.
3023 */
3024 consumer_close_channel_streams(chan);
3025
3026 /* Release our own refcount */
3027 if (!uatomic_sub_return(&chan->refcount, 1)
3028 && !uatomic_read(&chan->nb_init_stream_left)) {
3029 consumer_del_channel(chan);
3030 }
3031 } else {
3032 ERR("Unexpected poll events %u for sock %d", revents, pollfd);
3033 rcu_read_unlock();
3034 goto end;
3035 }
3036
3037 /* Release RCU lock for the channel looked up */
3038 rcu_read_unlock();
3039 }
3040 }
3041
3042 /* All is OK */
3043 err = 0;
3044 end:
3045 lttng_poll_clean(&events);
3046 end_poll:
3047 destroy_channel_ht(channel_ht);
3048 end_ht:
3049 error_testpoint:
3050 DBG("Channel poll thread exiting");
3051 if (err) {
3052 health_error();
3053 ERR("Health error occurred in %s", __func__);
3054 }
3055 health_unregister(health_consumerd);
3056 rcu_unregister_thread();
3057 return NULL;
3058 }
3059
3060 static int set_metadata_socket(struct lttng_consumer_local_data *ctx,
3061 struct pollfd *sockpoll, int client_socket)
3062 {
3063 int ret;
3064
3065 assert(ctx);
3066 assert(sockpoll);
3067
3068 ret = lttng_consumer_poll_socket(sockpoll);
3069 if (ret) {
3070 goto error;
3071 }
3072 DBG("Metadata connection on client_socket");
3073
3074 /* Blocking call, waiting for transmission */
3075 ctx->consumer_metadata_socket = lttcomm_accept_unix_sock(client_socket);
3076 if (ctx->consumer_metadata_socket < 0) {
3077 WARN("On accept metadata");
3078 ret = -1;
3079 goto error;
3080 }
3081 ret = 0;
3082
3083 error:
3084 return ret;
3085 }
3086
3087 /*
3088 * This thread listens on the consumerd socket and receives the file
3089 * descriptors from the session daemon.
3090 */
3091 void *consumer_thread_sessiond_poll(void *data)
3092 {
3093 int sock = -1, client_socket, ret, err = -1;
3094 /*
3095 * structure to poll for incoming data on communication socket avoids
3096 * making blocking sockets.
3097 */
3098 struct pollfd consumer_sockpoll[2];
3099 struct lttng_consumer_local_data *ctx = data;
3100
3101 rcu_register_thread();
3102
3103 health_register(health_consumerd, HEALTH_CONSUMERD_TYPE_SESSIOND);
3104
3105 if (testpoint(consumerd_thread_sessiond)) {
3106 goto error_testpoint;
3107 }
3108
3109 health_code_update();
3110
3111 DBG("Creating command socket %s", ctx->consumer_command_sock_path);
3112 unlink(ctx->consumer_command_sock_path);
3113 client_socket = lttcomm_create_unix_sock(ctx->consumer_command_sock_path);
3114 if (client_socket < 0) {
3115 ERR("Cannot create command socket");
3116 goto end;
3117 }
3118
3119 ret = lttcomm_listen_unix_sock(client_socket);
3120 if (ret < 0) {
3121 goto end;
3122 }
3123
3124 DBG("Sending ready command to lttng-sessiond");
3125 ret = lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_COMMAND_SOCK_READY);
3126 /* return < 0 on error, but == 0 is not fatal */
3127 if (ret < 0) {
3128 ERR("Error sending ready command to lttng-sessiond");
3129 goto end;
3130 }
3131
3132 /* prepare the FDs to poll : to client socket and the should_quit pipe */
3133 consumer_sockpoll[0].fd = ctx->consumer_should_quit[0];
3134 consumer_sockpoll[0].events = POLLIN | POLLPRI;
3135 consumer_sockpoll[1].fd = client_socket;
3136 consumer_sockpoll[1].events = POLLIN | POLLPRI;
3137
3138 ret = lttng_consumer_poll_socket(consumer_sockpoll);
3139 if (ret) {
3140 if (ret > 0) {
3141 /* should exit */
3142 err = 0;
3143 }
3144 goto end;
3145 }
3146 DBG("Connection on client_socket");
3147
3148 /* Blocking call, waiting for transmission */
3149 sock = lttcomm_accept_unix_sock(client_socket);
3150 if (sock < 0) {
3151 WARN("On accept");
3152 goto end;
3153 }
3154
3155 /*
3156 * Setup metadata socket which is the second socket connection on the
3157 * command unix socket.
3158 */
3159 ret = set_metadata_socket(ctx, consumer_sockpoll, client_socket);
3160 if (ret) {
3161 if (ret > 0) {
3162 /* should exit */
3163 err = 0;
3164 }
3165 goto end;
3166 }
3167
3168 /* This socket is not useful anymore. */
3169 ret = close(client_socket);
3170 if (ret < 0) {
3171 PERROR("close client_socket");
3172 }
3173 client_socket = -1;
3174
3175 /* update the polling structure to poll on the established socket */
3176 consumer_sockpoll[1].fd = sock;
3177 consumer_sockpoll[1].events = POLLIN | POLLPRI;
3178
3179 while (1) {
3180 health_code_update();
3181
3182 health_poll_entry();
3183 ret = lttng_consumer_poll_socket(consumer_sockpoll);
3184 health_poll_exit();
3185 if (ret) {
3186 if (ret > 0) {
3187 /* should exit */
3188 err = 0;
3189 }
3190 goto end;
3191 }
3192 DBG("Incoming command on sock");
3193 ret = lttng_consumer_recv_cmd(ctx, sock, consumer_sockpoll);
3194 if (ret <= 0) {
3195 /*
3196 * This could simply be a session daemon quitting. Don't output
3197 * ERR() here.
3198 */
3199 DBG("Communication interrupted on command socket");
3200 err = 0;
3201 goto end;
3202 }
3203 if (consumer_quit) {
3204 DBG("consumer_thread_receive_fds received quit from signal");
3205 err = 0; /* All is OK */
3206 goto end;
3207 }
3208 DBG("received command on sock");
3209 }
3210 /* All is OK */
3211 err = 0;
3212
3213 end:
3214 DBG("Consumer thread sessiond poll exiting");
3215
3216 /*
3217 * Close metadata streams since the producer is the session daemon which
3218 * just died.
3219 *
3220 * NOTE: for now, this only applies to the UST tracer.
3221 */
3222 lttng_consumer_close_all_metadata();
3223
3224 /*
3225 * when all fds have hung up, the polling thread
3226 * can exit cleanly
3227 */
3228 consumer_quit = 1;
3229
3230 /*
3231 * Notify the data poll thread to poll back again and test the
3232 * consumer_quit state that we just set so to quit gracefully.
3233 */
3234 notify_thread_lttng_pipe(ctx->consumer_data_pipe);
3235
3236 notify_channel_pipe(ctx, NULL, -1, CONSUMER_CHANNEL_QUIT);
3237
3238 notify_health_quit_pipe(health_quit_pipe);
3239
3240 /* Cleaning up possibly open sockets. */
3241 if (sock >= 0) {
3242 ret = close(sock);
3243 if (ret < 0) {
3244 PERROR("close sock sessiond poll");
3245 }
3246 }
3247 if (client_socket >= 0) {
3248 ret = close(client_socket);
3249 if (ret < 0) {
3250 PERROR("close client_socket sessiond poll");
3251 }
3252 }
3253
3254 error_testpoint:
3255 if (err) {
3256 health_error();
3257 ERR("Health error occurred in %s", __func__);
3258 }
3259 health_unregister(health_consumerd);
3260
3261 rcu_unregister_thread();
3262 return NULL;
3263 }
3264
3265 ssize_t lttng_consumer_read_subbuffer(struct lttng_consumer_stream *stream,
3266 struct lttng_consumer_local_data *ctx)
3267 {
3268 ssize_t ret;
3269
3270 pthread_mutex_lock(&stream->lock);
3271 if (stream->metadata_flag) {
3272 pthread_mutex_lock(&stream->metadata_rdv_lock);
3273 }
3274
3275 switch (consumer_data.type) {
3276 case LTTNG_CONSUMER_KERNEL:
3277 ret = lttng_kconsumer_read_subbuffer(stream, ctx);
3278 break;
3279 case LTTNG_CONSUMER32_UST:
3280 case LTTNG_CONSUMER64_UST:
3281 ret = lttng_ustconsumer_read_subbuffer(stream, ctx);
3282 break;
3283 default:
3284 ERR("Unknown consumer_data type");
3285 assert(0);
3286 ret = -ENOSYS;
3287 break;
3288 }
3289
3290 if (stream->metadata_flag) {
3291 pthread_cond_broadcast(&stream->metadata_rdv);
3292 pthread_mutex_unlock(&stream->metadata_rdv_lock);
3293 }
3294 pthread_mutex_unlock(&stream->lock);
3295 return ret;
3296 }
3297
3298 int lttng_consumer_on_recv_stream(struct lttng_consumer_stream *stream)
3299 {
3300 switch (consumer_data.type) {
3301 case LTTNG_CONSUMER_KERNEL:
3302 return lttng_kconsumer_on_recv_stream(stream);
3303 case LTTNG_CONSUMER32_UST:
3304 case LTTNG_CONSUMER64_UST:
3305 return lttng_ustconsumer_on_recv_stream(stream);
3306 default:
3307 ERR("Unknown consumer_data type");
3308 assert(0);
3309 return -ENOSYS;
3310 }
3311 }
3312
3313 /*
3314 * Allocate and set consumer data hash tables.
3315 */
3316 int lttng_consumer_init(void)
3317 {
3318 consumer_data.channel_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3319 if (!consumer_data.channel_ht) {
3320 goto error;
3321 }
3322
3323 consumer_data.relayd_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3324 if (!consumer_data.relayd_ht) {
3325 goto error;
3326 }
3327
3328 consumer_data.stream_list_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3329 if (!consumer_data.stream_list_ht) {
3330 goto error;
3331 }
3332
3333 consumer_data.stream_per_chan_id_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3334 if (!consumer_data.stream_per_chan_id_ht) {
3335 goto error;
3336 }
3337
3338 data_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3339 if (!data_ht) {
3340 goto error;
3341 }
3342
3343 metadata_ht = lttng_ht_new(0, LTTNG_HT_TYPE_U64);
3344 if (!metadata_ht) {
3345 goto error;
3346 }
3347
3348 return 0;
3349
3350 error:
3351 return -1;
3352 }
3353
3354 /*
3355 * Process the ADD_RELAYD command receive by a consumer.
3356 *
3357 * This will create a relayd socket pair and add it to the relayd hash table.
3358 * The caller MUST acquire a RCU read side lock before calling it.
3359 */
3360 int consumer_add_relayd_socket(uint64_t net_seq_idx, int sock_type,
3361 struct lttng_consumer_local_data *ctx, int sock,
3362 struct pollfd *consumer_sockpoll,
3363 struct lttcomm_relayd_sock *relayd_sock, uint64_t sessiond_id,
3364 uint64_t relayd_session_id)
3365 {
3366 int fd = -1, ret = -1, relayd_created = 0;
3367 enum lttcomm_return_code ret_code = LTTCOMM_CONSUMERD_SUCCESS;
3368 struct consumer_relayd_sock_pair *relayd = NULL;
3369
3370 assert(ctx);
3371 assert(relayd_sock);
3372
3373 DBG("Consumer adding relayd socket (idx: %" PRIu64 ")", net_seq_idx);
3374
3375 /* Get relayd reference if exists. */
3376 relayd = consumer_find_relayd(net_seq_idx);
3377 if (relayd == NULL) {
3378 assert(sock_type == LTTNG_STREAM_CONTROL);
3379 /* Not found. Allocate one. */
3380 relayd = consumer_allocate_relayd_sock_pair(net_seq_idx);
3381 if (relayd == NULL) {
3382 ret = -ENOMEM;
3383 ret_code = LTTCOMM_CONSUMERD_ENOMEM;
3384 goto error;
3385 } else {
3386 relayd->sessiond_session_id = sessiond_id;
3387 relayd_created = 1;
3388 }
3389
3390 /*
3391 * This code path MUST continue to the consumer send status message to
3392 * we can notify the session daemon and continue our work without
3393 * killing everything.
3394 */
3395 } else {
3396 /*
3397 * relayd key should never be found for control socket.
3398 */
3399 assert(sock_type != LTTNG_STREAM_CONTROL);
3400 }
3401
3402 /* First send a status message before receiving the fds. */
3403 ret = consumer_send_status_msg(sock, LTTCOMM_CONSUMERD_SUCCESS);
3404 if (ret < 0) {
3405 /* Somehow, the session daemon is not responding anymore. */
3406 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_FATAL);
3407 goto error_nosignal;
3408 }
3409
3410 /* Poll on consumer socket. */
3411 ret = lttng_consumer_poll_socket(consumer_sockpoll);
3412 if (ret) {
3413 /* Needing to exit in the middle of a command: error. */
3414 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_POLL_ERROR);
3415 ret = -EINTR;
3416 goto error_nosignal;
3417 }
3418
3419 /* Get relayd socket from session daemon */
3420 ret = lttcomm_recv_fds_unix_sock(sock, &fd, 1);
3421 if (ret != sizeof(fd)) {
3422 ret = -1;
3423 fd = -1; /* Just in case it gets set with an invalid value. */
3424
3425 /*
3426 * Failing to receive FDs might indicate a major problem such as
3427 * reaching a fd limit during the receive where the kernel returns a
3428 * MSG_CTRUNC and fails to cleanup the fd in the queue. Any case, we
3429 * don't take any chances and stop everything.
3430 *
3431 * XXX: Feature request #558 will fix that and avoid this possible
3432 * issue when reaching the fd limit.
3433 */
3434 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_ERROR_RECV_FD);
3435 ret_code = LTTCOMM_CONSUMERD_ERROR_RECV_FD;
3436 goto error;
3437 }
3438
3439 /* Copy socket information and received FD */
3440 switch (sock_type) {
3441 case LTTNG_STREAM_CONTROL:
3442 /* Copy received lttcomm socket */
3443 lttcomm_copy_sock(&relayd->control_sock.sock, &relayd_sock->sock);
3444 ret = lttcomm_create_sock(&relayd->control_sock.sock);
3445 /* Handle create_sock error. */
3446 if (ret < 0) {
3447 ret_code = LTTCOMM_CONSUMERD_ENOMEM;
3448 goto error;
3449 }
3450 /*
3451 * Close the socket created internally by
3452 * lttcomm_create_sock, so we can replace it by the one
3453 * received from sessiond.
3454 */
3455 if (close(relayd->control_sock.sock.fd)) {
3456 PERROR("close");
3457 }
3458
3459 /* Assign new file descriptor */
3460 relayd->control_sock.sock.fd = fd;
3461 fd = -1; /* For error path */
3462 /* Assign version values. */
3463 relayd->control_sock.major = relayd_sock->major;
3464 relayd->control_sock.minor = relayd_sock->minor;
3465
3466 relayd->relayd_session_id = relayd_session_id;
3467
3468 break;
3469 case LTTNG_STREAM_DATA:
3470 /* Copy received lttcomm socket */
3471 lttcomm_copy_sock(&relayd->data_sock.sock, &relayd_sock->sock);
3472 ret = lttcomm_create_sock(&relayd->data_sock.sock);
3473 /* Handle create_sock error. */
3474 if (ret < 0) {
3475 ret_code = LTTCOMM_CONSUMERD_ENOMEM;
3476 goto error;
3477 }
3478 /*
3479 * Close the socket created internally by
3480 * lttcomm_create_sock, so we can replace it by the one
3481 * received from sessiond.
3482 */
3483 if (close(relayd->data_sock.sock.fd)) {
3484 PERROR("close");
3485 }
3486
3487 /* Assign new file descriptor */
3488 relayd->data_sock.sock.fd = fd;
3489 fd = -1; /* for eventual error paths */
3490 /* Assign version values. */
3491 relayd->data_sock.major = relayd_sock->major;
3492 relayd->data_sock.minor = relayd_sock->minor;
3493 break;
3494 default:
3495 ERR("Unknown relayd socket type (%d)", sock_type);
3496 ret = -1;
3497 ret_code = LTTCOMM_CONSUMERD_FATAL;
3498 goto error;
3499 }
3500
3501 DBG("Consumer %s socket created successfully with net idx %" PRIu64 " (fd: %d)",
3502 sock_type == LTTNG_STREAM_CONTROL ? "control" : "data",
3503 relayd->net_seq_idx, fd);
3504
3505 /* We successfully added the socket. Send status back. */
3506 ret = consumer_send_status_msg(sock, ret_code);
3507 if (ret < 0) {
3508 /* Somehow, the session daemon is not responding anymore. */
3509 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_FATAL);
3510 goto error_nosignal;
3511 }
3512
3513 /*
3514 * Add relayd socket pair to consumer data hashtable. If object already
3515 * exists or on error, the function gracefully returns.
3516 */
3517 relayd->ctx = ctx;
3518 add_relayd(relayd);
3519
3520 /* All good! */
3521 return 0;
3522
3523 error:
3524 if (consumer_send_status_msg(sock, ret_code) < 0) {
3525 lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_FATAL);
3526 }
3527
3528 error_nosignal:
3529 /* Close received socket if valid. */
3530 if (fd >= 0) {
3531 if (close(fd)) {
3532 PERROR("close received socket");
3533 }
3534 }
3535
3536 if (relayd_created) {
3537 free(relayd);
3538 }
3539
3540 return ret;
3541 }
3542
3543 /*
3544 * Try to lock the stream mutex.
3545 *
3546 * On success, 1 is returned else 0 indicating that the mutex is NOT lock.
3547 */
3548 static int stream_try_lock(struct lttng_consumer_stream *stream)
3549 {
3550 int ret;
3551
3552 assert(stream);
3553
3554 /*
3555 * Try to lock the stream mutex. On failure, we know that the stream is
3556 * being used else where hence there is data still being extracted.
3557 */
3558 ret = pthread_mutex_trylock(&stream->lock);
3559 if (ret) {
3560 /* For both EBUSY and EINVAL error, the mutex is NOT locked. */
3561 ret = 0;
3562 goto end;
3563 }
3564
3565 ret = 1;
3566
3567 end:
3568 return ret;
3569 }
3570
3571 /*
3572 * Search for a relayd associated to the session id and return the reference.
3573 *
3574 * A rcu read side lock MUST be acquire before calling this function and locked
3575 * until the relayd object is no longer necessary.
3576 */
3577 static struct consumer_relayd_sock_pair *find_relayd_by_session_id(uint64_t id)
3578 {
3579 struct lttng_ht_iter iter;
3580 struct consumer_relayd_sock_pair *relayd = NULL;
3581
3582 /* Iterate over all relayd since they are indexed by net_seq_idx. */
3583 cds_lfht_for_each_entry(consumer_data.relayd_ht->ht, &iter.iter, relayd,
3584 node.node) {
3585 /*
3586 * Check by sessiond id which is unique here where the relayd session
3587 * id might not be when having multiple relayd.
3588 */
3589 if (relayd->sessiond_session_id == id) {
3590 /* Found the relayd. There can be only one per id. */
3591 goto found;
3592 }
3593 }
3594
3595 return NULL;
3596
3597 found:
3598 return relayd;
3599 }
3600
3601 /*
3602 * Check if for a given session id there is still data needed to be extract
3603 * from the buffers.
3604 *
3605 * Return 1 if data is pending or else 0 meaning ready to be read.
3606 */
3607 int consumer_data_pending(uint64_t id)
3608 {
3609 int ret;
3610 struct lttng_ht_iter iter;
3611 struct lttng_ht *ht;
3612 struct lttng_consumer_stream *stream;
3613 struct consumer_relayd_sock_pair *relayd = NULL;
3614 int (*data_pending)(struct lttng_consumer_stream *);
3615
3616 DBG("Consumer data pending command on session id %" PRIu64, id);
3617
3618 rcu_read_lock();
3619 pthread_mutex_lock(&consumer_data.lock);
3620
3621 switch (consumer_data.type) {
3622 case LTTNG_CONSUMER_KERNEL:
3623 data_pending = lttng_kconsumer_data_pending;
3624 break;
3625 case LTTNG_CONSUMER32_UST:
3626 case LTTNG_CONSUMER64_UST:
3627 data_pending = lttng_ustconsumer_data_pending;
3628 break;
3629 default:
3630 ERR("Unknown consumer data type");
3631 assert(0);
3632 }
3633
3634 /* Ease our life a bit */
3635 ht = consumer_data.stream_list_ht;
3636
3637 relayd = find_relayd_by_session_id(id);
3638 if (relayd) {
3639 /* Send init command for data pending. */
3640 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
3641 ret = relayd_begin_data_pending(&relayd->control_sock,
3642 relayd->relayd_session_id);
3643 if (ret < 0) {
3644 /* Communication error thus the relayd so no data pending. */
3645 ERR("Relayd begin data pending failed. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
3646 lttng_consumer_cleanup_relayd(relayd);
3647 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3648 goto data_not_pending;
3649 }
3650 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3651 }
3652
3653 cds_lfht_for_each_entry_duplicate(ht->ht,
3654 ht->hash_fct(&id, lttng_ht_seed),
3655 ht->match_fct, &id,
3656 &iter.iter, stream, node_session_id.node) {
3657 /* If this call fails, the stream is being used hence data pending. */
3658 ret = stream_try_lock(stream);
3659 if (!ret) {
3660 goto data_pending;
3661 }
3662
3663 /*
3664 * A removed node from the hash table indicates that the stream has
3665 * been deleted thus having a guarantee that the buffers are closed
3666 * on the consumer side. However, data can still be transmitted
3667 * over the network so don't skip the relayd check.
3668 */
3669 ret = cds_lfht_is_node_deleted(&stream->node.node);
3670 if (!ret) {
3671 /* Check the stream if there is data in the buffers. */
3672 ret = data_pending(stream);
3673 if (ret == 1) {
3674 pthread_mutex_unlock(&stream->lock);
3675 goto data_pending;
3676 }
3677 }
3678
3679 /* Relayd check */
3680 if (relayd) {
3681 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
3682 if (stream->metadata_flag) {
3683 ret = relayd_quiescent_control(&relayd->control_sock,
3684 stream->relayd_stream_id);
3685 } else {
3686 ret = relayd_data_pending(&relayd->control_sock,
3687 stream->relayd_stream_id,
3688 stream->next_net_seq_num - 1);
3689 }
3690 if (ret < 0) {
3691 ERR("Relayd data pending failed. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
3692 lttng_consumer_cleanup_relayd(relayd);
3693 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3694 pthread_mutex_unlock(&stream->lock);
3695 goto data_not_pending;
3696 }
3697 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3698 if (ret == 1) {
3699 pthread_mutex_unlock(&stream->lock);
3700 goto data_pending;
3701 }
3702 }
3703 pthread_mutex_unlock(&stream->lock);
3704 }
3705
3706 if (relayd) {
3707 unsigned int is_data_inflight = 0;
3708
3709 /* Send init command for data pending. */
3710 pthread_mutex_lock(&relayd->ctrl_sock_mutex);
3711 ret = relayd_end_data_pending(&relayd->control_sock,
3712 relayd->relayd_session_id, &is_data_inflight);
3713 if (ret < 0) {
3714 ERR("Relayd end data pending failed. Cleaning up relayd %" PRIu64".", relayd->net_seq_idx);
3715 lttng_consumer_cleanup_relayd(relayd);
3716 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3717 goto data_not_pending;
3718 }
3719 pthread_mutex_unlock(&relayd->ctrl_sock_mutex);
3720 if (is_data_inflight) {
3721 goto data_pending;
3722 }
3723 }
3724
3725 /*
3726 * Finding _no_ node in the hash table and no inflight data means that the
3727 * stream(s) have been removed thus data is guaranteed to be available for
3728 * analysis from the trace files.
3729 */
3730
3731 data_not_pending:
3732 /* Data is available to be read by a viewer. */
3733 pthread_mutex_unlock(&consumer_data.lock);
3734 rcu_read_unlock();
3735 return 0;
3736
3737 data_pending:
3738 /* Data is still being extracted from buffers. */
3739 pthread_mutex_unlock(&consumer_data.lock);
3740 rcu_read_unlock();
3741 return 1;
3742 }
3743
3744 /*
3745 * Send a ret code status message to the sessiond daemon.
3746 *
3747 * Return the sendmsg() return value.
3748 */
3749 int consumer_send_status_msg(int sock, int ret_code)
3750 {
3751 struct lttcomm_consumer_status_msg msg;
3752
3753 memset(&msg, 0, sizeof(msg));
3754 msg.ret_code = ret_code;
3755
3756 return lttcomm_send_unix_sock(sock, &msg, sizeof(msg));
3757 }
3758
3759 /*
3760 * Send a channel status message to the sessiond daemon.
3761 *
3762 * Return the sendmsg() return value.
3763 */
3764 int consumer_send_status_channel(int sock,
3765 struct lttng_consumer_channel *channel)
3766 {
3767 struct lttcomm_consumer_status_channel msg;
3768
3769 assert(sock >= 0);
3770
3771 memset(&msg, 0, sizeof(msg));
3772 if (!channel) {
3773 msg.ret_code = LTTCOMM_CONSUMERD_CHANNEL_FAIL;
3774 } else {
3775 msg.ret_code = LTTCOMM_CONSUMERD_SUCCESS;
3776 msg.key = channel->key;
3777 msg.stream_count = channel->streams.count;
3778 }
3779
3780 return lttcomm_send_unix_sock(sock, &msg, sizeof(msg));
3781 }
3782
3783 unsigned long consumer_get_consume_start_pos(unsigned long consumed_pos,
3784 unsigned long produced_pos, uint64_t nb_packets_per_stream,
3785 uint64_t max_sb_size)
3786 {
3787 unsigned long start_pos;
3788
3789 if (!nb_packets_per_stream) {
3790 return consumed_pos; /* Grab everything */
3791 }
3792 start_pos = produced_pos - offset_align_floor(produced_pos, max_sb_size);
3793 start_pos -= max_sb_size * nb_packets_per_stream;
3794 if ((long) (start_pos - consumed_pos) < 0) {
3795 return consumed_pos; /* Grab everything */
3796 }
3797 return start_pos;
3798 }
This page took 0.147416 seconds and 4 git commands to generate.