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