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