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