iceoryx2 0.9.0

iceoryx2: Lock-Free Zero-Copy Interprocess Communication
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
// Copyright (c) 2023 Contributors to the Eclipse Foundation
//
// See the NOTICE file(s) distributed with this work for additional
// information regarding copyright ownership.
//
// This program and the accompanying materials are made available under the
// terms of the Apache Software License 2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0, or the MIT license
// which is available at https://opensource.org/licenses/MIT.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT

use core::alloc::Layout;
use core::ptr::NonNull;
use iceoryx2_bb_concurrency::atomic::Ordering;

use alloc::format;
use alloc::vec::Vec;

use iceoryx2_bb_concurrency::atomic::AtomicUsize;
use iceoryx2_bb_concurrency::cell::UnsafeCell;
use iceoryx2_bb_elementary::cyclic_tagger::*;
use iceoryx2_bb_elementary_traits::non_null::NonNullCompat;
use iceoryx2_bb_elementary_traits::testing::abandonable::Abandonable;
use iceoryx2_cal::named_concept::NamedConceptBuilder;
use iceoryx2_cal::shm_allocator::{AllocationError, PointerOffset, ShmAllocationError};
use iceoryx2_cal::zero_copy_connection::{
    BackpressureToReceiverAction, ChannelId, ChannelState, ZeroCopyConnection,
    ZeroCopyConnectionBuilder, ZeroCopyCreationError, ZeroCopyPortDetails, ZeroCopySendError,
    ZeroCopySender,
};
use iceoryx2_log::{error, fail, fatal_panic, warn};

use crate::node::SharedNode;
use crate::port::{
    BackpressureHandler, BackpressureInfo, DegradationAction, DegradationCause, DegradationHandler,
    DegradationInfo, LoanError, SendError,
};
use crate::prelude::BackpressureStrategy;
use crate::service::config_scheme::connection_config;
use crate::service::static_config::message_type_details::{MessageTypeDetails, TypeVariant};
use crate::service::{NoResource, SharedServiceState};
use crate::{service, service::naming_scheme::connection_name};

use super::chunk::ChunkMut;
use super::data_segment::DataSegment;
use super::segment_state::SegmentState;

#[derive(Clone, Copy)]
pub(crate) struct ReceiverDetails {
    pub(crate) port_id: u128,
    pub(crate) buffer_size: usize,
}

#[derive(Debug)]
pub(crate) struct Connection<Service: service::Service> {
    pub(crate) sender: <Service::Connection as ZeroCopyConnection>::Sender,
    pub(crate) receiver_port_id: u128,
    tag: Tag,
}

impl<Service: service::Service> Abandonable for Connection<Service> {
    unsafe fn abandon_in_place(mut this: NonNull<Self>) {
        let this = unsafe { this.as_mut() };
        unsafe {
            <Service::Connection as ZeroCopyConnection>::Sender::abandon_in_place(
                NonNull::iox2_from_mut(&mut this.sender),
            )
        };
    }
}

impl<Service: service::Service> Taggable for Connection<Service> {
    fn tag(&self) -> &Tag {
        &self.tag
    }
}

impl<Service: service::Service> Connection<Service> {
    fn new(
        this: &Sender<Service>,
        receiver_port_id: u128,
        buffer_size: usize,
        number_of_samples: usize,
        tag: Tag,
        initial_channel_state: ChannelState,
    ) -> Result<Self, ZeroCopyCreationError> {
        let msg = format!(
            "Unable to establish connection to receiver port {:?} from sender port {:?}",
            receiver_port_id, this.sender_port_id
        );
        if this.receiver_max_buffer_size < buffer_size {
            fail!(from this, with ZeroCopyCreationError::IncompatibleBufferSize,
                "{} since the receiver buffer size {} exceeds the max receiver buffer size of {}.",
                msg, buffer_size, this.receiver_max_buffer_size);
        }

        let sender = fail!(from this, when <Service::Connection as ZeroCopyConnection>::
                        Builder::new( &connection_name(this.sender_port_id, receiver_port_id))
                                .config(&connection_config::<Service>(this.shared_node.config()))
                                .buffer_size(buffer_size)
                                .receiver_max_borrowed_samples_per_channel(this.receiver_max_borrowed_samples)
                                .enable_safe_overflow(this.enable_safe_overflow)
                                .number_of_samples_per_segment(number_of_samples)
                                .max_supported_shared_memory_segments(this.max_number_of_segments)
                                .initial_channel_state(initial_channel_state)
                                .number_of_channels(this.number_of_channels)
                                .timeout(this.shared_node.config().global.creation_timeout)
                                .create_sender(),
                        "{}.", msg);

        Ok(Self {
            sender,
            receiver_port_id,
            tag,
        })
    }
}

#[derive(Debug)]
pub(crate) struct Sender<Service: service::Service> {
    pub(crate) segment_states: Vec<SegmentState>,
    pub(crate) data_segment: DataSegment<Service>,
    pub(crate) connections: Vec<UnsafeCell<Option<Connection<Service>>>>,
    pub(crate) sender_port_id: u128,
    pub(crate) shared_node: SharedNode<Service>,
    pub(crate) receiver_max_buffer_size: usize,
    pub(crate) receiver_max_borrowed_samples: usize,
    pub(crate) sender_max_borrowed_samples: usize,
    pub(crate) enable_safe_overflow: bool,
    pub(crate) number_of_samples: usize,
    pub(crate) max_number_of_segments: u8,
    pub(crate) degradation_handler: DegradationHandler<'static>,
    pub(crate) backpressure_handler: Option<BackpressureHandler<'static>>,
    pub(crate) service_state: SharedServiceState<Service, NoResource>,
    pub(crate) tagger: CyclicTagger,
    pub(crate) loan_counter: AtomicUsize,
    pub(crate) backpressure_strategy: BackpressureStrategy,
    pub(crate) message_type_details: MessageTypeDetails,
    pub(crate) number_of_channels: usize,
    pub(crate) initial_channel_state: ChannelState,
}

impl<Service: service::Service> Abandonable for Sender<Service> {
    unsafe fn abandon_in_place(mut this: NonNull<Self>) {
        let this = unsafe { this.as_mut() };
        unsafe {
            SharedNode::<Service>::abandon_in_place(NonNull::iox2_from_mut(&mut this.shared_node))
        };
        unsafe {
            SharedServiceState::abandon_in_place(NonNull::iox2_from_mut(&mut this.service_state))
        };
        unsafe {
            DataSegment::<Service>::abandon_in_place(NonNull::iox2_from_mut(&mut this.data_segment))
        };

        for connection in &mut this.connections {
            if let Some(c) = connection.get_mut() {
                unsafe { Connection::<Service>::abandon_in_place(NonNull::iox2_from_mut(c)) };
            }
        }
    }
}

impl<Service: service::Service> Sender<Service> {
    fn get(&self, index: usize) -> &Option<Connection<Service>> {
        unsafe { &(*self.connections[index].get()) }
    }

    // only used internally as convinience function
    #[allow(clippy::mut_from_ref)]
    fn get_mut(&self, index: usize) -> &mut Option<Connection<Service>> {
        #[deny(clippy::mut_from_ref)]
        unsafe {
            &mut (*self.connections[index].get())
        }
    }

    pub(crate) fn get_connection_id_of(&self, receiver_port_id: u128) -> Option<usize> {
        for i in 0..self.len() {
            if let Some(connection) = self.get(i) {
                if connection.receiver_port_id == receiver_port_id {
                    return Some(i);
                }
            }
        }

        None
    }

    fn deliver_offset_to_connection_impl(
        &self,
        offset: PointerOffset,
        sample_size: usize,
        channel_id: ChannelId,
        connection_id: usize,
    ) -> Result<usize, SendError> {
        let msg = "While delivering the sample:";

        let mut number_of_recipients = 0;
        if let Some(connection) = self.get(connection_id) {
            let delivery_call_result = if let Some(handler) = self.backpressure_handler.as_ref() {
                let backpressure_action_for_strategy = match self.backpressure_strategy {
                    BackpressureStrategy::RetryUntilDelivered => {
                        BackpressureToReceiverAction::Retry
                    }
                    BackpressureStrategy::DiscardData => {
                        BackpressureToReceiverAction::DiscardPointerOffset
                    }
                };

                <Service::Connection as ZeroCopyConnection>::Sender::blocking_send(
                    &connection.sender,
                    offset,
                    sample_size,
                    channel_id,
                    |retries, elapsed_time| {
                        handler
                            .call(&BackpressureInfo {
                                service_id: self
                                    .service_state
                                    .static_config()
                                    .unique_service_id()
                                    .value(),
                                sender_port_id: self.sender_port_id,
                                receiver_port_id: connection.receiver_port_id,
                                retries,
                                elapsed_time,
                            })
                            .into()
                    },
                    backpressure_action_for_strategy,
                )
            } else {
                match self.backpressure_strategy {
                    BackpressureStrategy::DiscardData => {
                        <Service::Connection as ZeroCopyConnection>::Sender::try_send(
                            &connection.sender,
                            offset,
                            sample_size,
                            channel_id,
                        )
                    }
                    BackpressureStrategy::RetryUntilDelivered => {
                        <Service::Connection as ZeroCopyConnection>::Sender::blocking_send(
                            &connection.sender,
                            offset,
                            sample_size,
                            channel_id,
                            |_, _| BackpressureToReceiverAction::FollowBackpressureyStrategy,
                            BackpressureToReceiverAction::Retry,
                        )
                    }
                }
            };

            match delivery_call_result {
                Err(ZeroCopySendError::UnableToDeliver) => {
                    // can only happen with blocking send and the degradation handler triggered a failure
                    fail!(from self, with SendError::UnableToDeliver,
                          "{msg} {:?} could not be delivered to receiver {:?}.",
                          offset, connection.receiver_port_id);
                }
                Err(ZeroCopySendError::ReceiveBufferFull)
                | Err(ZeroCopySendError::UsedChunkListFull) => {
                    /* causes no problem
                     *   blocking_send => can never happen
                     *   try_send => we tried and expect that the buffer is full
                     *
                     * */
                }
                Err(ZeroCopySendError::NoConnectedReceiver)
                | Err(ZeroCopySendError::ChannelIsClosed) => {
                    // causes no problem, when the receiver/subscriber disconnected it will be
                    // cleaned up in the next round and it is no failure when we skip delivering data
                    // to subscribers that have disconnected
                }
                Err(ZeroCopySendError::InternalError) => {
                    fail!(from self, with SendError::InternalError,
                        "{msg} {:?} to receiver {:?} an internal mechanism failed and the offset was delivered only to a subset of receivers.", offset, connection.receiver_port_id);
                }
                Err(ZeroCopySendError::ConnectionCorrupted) => {
                    match self.degradation_handler.call(
                        DegradationCause::ConnectionCorrupted,
                        &DegradationInfo {
                            service_id: self
                                .service_state
                                .static_config()
                                .unique_service_id()
                                .value(),
                            sender_port_id: self.sender_port_id,
                            receiver_port_id: connection.receiver_port_id,
                        },
                    ) {
                        DegradationAction::Ignore => (),
                        DegradationAction::Warn => {
                            error!(from self,
                                        "{msg} {:?} a corrupted connection was detected with receiver {:?}.",
                                        offset, connection.receiver_port_id);
                        }
                        DegradationAction::DegradeAndFail => {
                            fail!(from self, with SendError::ConnectionCorrupted,
                                        "{msg} {:?} a corrupted connection was detected with receiver {:?}.",
                                        offset, connection.receiver_port_id);
                        }
                    }
                }
                Ok(overflow) => {
                    self.borrow_sample(offset);
                    number_of_recipients += 1;

                    if let Some(old) = overflow {
                        self.release_sample(old)
                    }
                }
            }
        }
        Ok(number_of_recipients)
    }

    pub(crate) fn has_disconnect_hint(
        &self,
        channel_id: ChannelId,
        connection_id: usize,
        state: ChannelState,
    ) -> bool {
        if let Some(connection) = self.get(connection_id) {
            connection.sender.has_disconnect_hint(channel_id, state)
        } else {
            false
        }
    }

    pub(crate) fn has_channel_state(
        &self,
        channel_id: ChannelId,
        connection_id: usize,
        state: ChannelState,
    ) -> bool {
        if let Some(connection) = self.get(connection_id) {
            connection.sender.has_channel_state(channel_id, state)
        } else {
            false
        }
    }

    pub(crate) fn close_channel(
        &self,
        channel_id: ChannelId,
        connection_id: usize,
        expected_state: ChannelState,
    ) {
        if let Some(connection) = self.get(connection_id) {
            connection.sender.close_channel(channel_id, expected_state);
        }
    }

    pub(crate) fn deliver_offset_to_connection(
        &self,
        offset: PointerOffset,
        sample_size: usize,
        channel_id: ChannelId,
        connection_id: usize,
    ) -> Result<usize, SendError> {
        self.retrieve_returned_samples();
        self.deliver_offset_to_connection_impl(offset, sample_size, channel_id, connection_id)
    }

    pub(crate) fn deliver_offset(
        &self,
        offset: PointerOffset,
        sample_size: usize,
        channel_id: ChannelId,
    ) -> Result<usize, SendError> {
        self.retrieve_returned_samples();

        let mut number_of_recipients = 0;
        let mut delivery_error = None;
        for i in 0..self.len() {
            match self.deliver_offset_to_connection_impl(offset, sample_size, channel_id, i) {
                Ok(n) => number_of_recipients += n,
                Err(error) => match error {
                    SendError::ConnectionCorrupted => {
                        // `ConnectionCorrupted` has the highest priority and will overwrite
                        // an existing `UnableToDeliver` error
                        delivery_error = Some(error)
                    }
                    SendError::UnableToDeliver if delivery_error.is_none() => {
                        // only store the `UnableToDeliver` if there is no existing error
                        // to prevent overriding a higher priority `ConnectionCorrupted` error
                        delivery_error = Some(error)
                    }
                    SendError::UnableToDeliver => {
                        // there is already an error stored; nothing to do
                    }
                    e => {
                        // the `deliver_offset_to_connection_impl` cannot fail with
                        // `ConnectionBrokenSinceSenderNoLongerExists`, `ConnectionError`,
                        // or `LoanError`, since these types of errors are triggered one layer
                        // above this function; this leaves the `InternalError` which can be
                        // triggered by EINTR, which should return immediately
                        fail!(with e, "Delivery of the data was aborted due to error: {:?}", e);
                    }
                },
            }
        }
        if let Some(e) = delivery_error {
            Err(e)
        } else {
            Ok(number_of_recipients)
        }
    }

    pub(crate) fn return_loaned_sample(&self, distance_to_chunk: PointerOffset) {
        self.release_sample(distance_to_chunk);
        self.loan_counter.fetch_sub(1, Ordering::Relaxed);
    }

    fn create(
        &self,
        index: usize,
        receiver_details: ReceiverDetails,
    ) -> Result<(), ZeroCopyCreationError> {
        *self.get_mut(index) = Some(Connection::new(
            self,
            receiver_details.port_id,
            receiver_details.buffer_size,
            self.number_of_samples,
            self.tagger.create_tag(),
            self.initial_channel_state,
        )?);

        Ok(())
    }

    fn len(&self) -> usize {
        self.connections.len()
    }

    pub(crate) fn allocate(&self, layout: Layout) -> Result<ChunkMut, LoanError> {
        self.retrieve_returned_samples();
        let msg = "Unable to allocate data";

        if self.loan_counter.load(Ordering::Relaxed) >= self.sender_max_borrowed_samples {
            fail!(from self, with LoanError::ExceedsMaxLoans,
                "{} {:?} since already {} samples were loaned and it would exceed the maximum of parallel loans of {}. Release or send a loaned sample to loan another sample.",
                msg, layout, self.loan_counter.load(Ordering::Relaxed), self.sender_max_borrowed_samples);
        }

        let shm_pointer = match self.data_segment.allocate(layout) {
            Ok(chunk) => chunk,
            Err(ShmAllocationError::AllocationError(AllocationError::OutOfMemory)) => {
                fail!(from self, with LoanError::OutOfMemory,
                    "{} {:?} since the underlying shared memory is out of memory.", msg, layout);
            }
            Err(ShmAllocationError::AllocationError(AllocationError::SizeTooLarge))
            | Err(ShmAllocationError::AllocationError(AllocationError::AlignmentFailure)) => {
                fatal_panic!(from self, "{} {:?} since the system seems to be corrupted.", msg, layout);
            }
            Err(v) => {
                fail!(from self, with LoanError::InternalFailure,
                    "{} {:?} since an internal failure occurred ({:?}).", msg, layout, v);
            }
        };

        let (ref_count, sample_size) = self.borrow_sample(shm_pointer.offset);
        if ref_count != 0 {
            fatal_panic!(from self,
                "{} since the allocated sample is already in use! This should never happen!", msg);
        }

        self.loan_counter.fetch_add(1, Ordering::Relaxed);
        Ok(ChunkMut::new(
            &self.message_type_details,
            shm_pointer,
            sample_size,
        ))
    }

    pub(crate) fn borrow_sample(&self, offset: PointerOffset) -> (u64, usize) {
        let segment_id = offset.segment_id();
        let segment_state = &self.segment_states[segment_id.value() as usize];
        let mut payload_size = segment_state.payload_size();
        if segment_state.payload_size() == 0 {
            payload_size = self.data_segment.bucket_size(segment_id);
            segment_state.set_payload_size(payload_size);
        }
        (segment_state.borrow_sample(offset.offset()), payload_size)
    }

    pub(crate) fn retrieve_returned_samples(&self) {
        for i in 0..self.len() {
            if let Some(connection) = self.get(i) {
                for channel_id in 0..self.number_of_channels {
                    let id = ChannelId::new(channel_id);
                    loop {
                        match connection.sender.reclaim(id) {
                            Ok(Some(ptr_dist)) => {
                                self.release_sample(ptr_dist);
                            }
                            Ok(None) => break,
                            Err(e) => {
                                warn!(from self, "Unable to reclaim samples from connection {:?} due to {:?}. This may lead to a situation where no more samples will be delivered to this connection.", connection, e)
                            }
                        }
                    }
                }
            }
        }
    }

    pub(crate) fn release_sample(&self, offset: PointerOffset) {
        if self.segment_states[offset.segment_id().value() as usize].release_sample(offset.offset())
            == 1
        {
            unsafe {
                self.data_segment.deallocate_bucket(offset);
            }
        }
    }

    fn remove_connection(&self, i: usize) {
        if let Some(connection) = self.get(i) {
            // # SAFETY: the receiver no longer exist, therefore we can
            //           reacquire all delivered samples
            unsafe {
                connection
                    .sender
                    .acquire_used_offsets(|offset| self.release_sample(offset))
            };

            *self.get_mut(i) = None;
        }
    }

    pub(crate) fn start_update_connection_cycle(&self) {
        self.tagger.next_cycle();
    }

    pub(crate) fn update_connection<E: Fn(&Connection<Service>)>(
        &self,
        index: usize,
        receiver_details: ReceiverDetails,
        establish_new_connection_call: E,
    ) -> Result<(), ZeroCopyCreationError> {
        let create_connection = match self.get(index) {
            None => true,
            Some(connection) => {
                let is_connected = connection.receiver_port_id == receiver_details.port_id;
                if is_connected {
                    self.tagger.tag(connection);
                } else {
                    self.remove_connection(index);
                }
                !is_connected
            }
        };

        if create_connection {
            match self.create(index, receiver_details) {
                Ok(()) => match &self.get(index) {
                    Some(connection) => establish_new_connection_call(connection),
                    None => {
                        fatal_panic!(from self, "This should never happen! Unable to acquire previously created receiver connection.")
                    }
                },
                Err(e) => match self.degradation_handler.call(
                    DegradationCause::FailedToEstablishConnection,
                    &DegradationInfo {
                        service_id: self
                            .service_state
                            .static_config()
                            .unique_service_id()
                            .value(),
                        sender_port_id: self.sender_port_id,
                        receiver_port_id: receiver_details.port_id,
                    },
                ) {
                    DegradationAction::Ignore => (),
                    DegradationAction::Warn => {
                        warn!(from self,
                                            "Unable to establish connection to new receiver {:?}.",
                                            receiver_details.port_id )
                    }
                    DegradationAction::DegradeAndFail => {
                        fail!(from self, with e,
                                           "Unable to establish connection to new receiver {:?}.",
                                           receiver_details.port_id );
                    }
                },
            }
        }

        Ok(())
    }

    pub(crate) fn finish_update_connection_cycle(&self) {
        for n in 0..self.len() {
            if let Some(connection) = self.get(n) {
                if !connection.was_tagged_by(&self.tagger) {
                    self.remove_connection(n);
                }
            }
        }
    }

    pub(crate) fn payload_size(&self) -> usize {
        self.message_type_details.payload.size
    }

    pub(crate) fn sample_layout(&self, number_of_elements: usize) -> Layout {
        self.message_type_details.sample_layout(number_of_elements)
    }

    pub(crate) fn payload_type_variant(&self) -> TypeVariant {
        self.message_type_details.payload.variant
    }
}