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