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