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