iceoryx2-cal 0.9.0

iceoryx2: [internal] high-level traits and implementations that represents OS primitives in an exchangeable fashion
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
// 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

//! File based implementation of [`StaticStorage`].
//!
//! # Example
//!
//! ```
//! # extern crate iceoryx2_bb_loggers;
//!
//! use iceoryx2_bb_system_types::file_name::FileName;
//! use iceoryx2_bb_system_types::path::Path;
//! use iceoryx2_bb_container::semantic_string::SemanticString;
//! use iceoryx2_cal::static_storage::file::*;
//!
//! let mut content = "some storage content".to_string();
//! let custom_config = Configuration::default()
//!                         .suffix(&FileName::new(b".conifg").unwrap())
//!                         .path_hint(&Path::new(b"/tmp").unwrap());
//!
//! let storage_name = FileName::new(b"myStaticStorage").unwrap();
//! let owner = Builder::new(&storage_name)
//!                 .config(&custom_config)
//!                 .create(content.as_bytes()).unwrap();
//!
//! // usually a different process
//! let initialization_timeout = core::time::Duration::from_millis(100);
//! let reader = Builder::new(&storage_name)
//!                 // if the config here differs the wrong static storage may be opened
//!                 .config(&custom_config)
//!                 .open(initialization_timeout).unwrap();
//!
//! let content_length = reader.len();
//! let mut content = String::from_utf8(vec![b' '; content_length as usize]).unwrap();
//! reader.read(unsafe { content.as_mut_vec() }.as_mut_slice()).unwrap();
//!
//! println!("Storage {} content: {}", reader.name(), content);
//! ```

use iceoryx2_bb_concurrency::atomic::Ordering;

use alloc::format;
use alloc::vec;
use alloc::vec::Vec;
use core::ptr::NonNull;
use iceoryx2_bb_elementary_traits::non_null::NonNullCompat;

pub use crate::named_concept::*;
pub use crate::static_storage::*;

use iceoryx2_bb_concurrency::atomic::AtomicBool;
use iceoryx2_bb_posix::adaptive_wait::AdaptiveWaitBuilder;
use iceoryx2_bb_posix::{
    directory::*, file::*, file_descriptor::FileDescriptorManagement, file_type::FileType,
};
use iceoryx2_log::{fail, trace, warn};

#[cfg(not(feature = "dev_permissions"))]
const FINAL_PERMISSIONS: Permission = Permission::OWNER_READ;

#[cfg(not(feature = "dev_permissions"))]
const DIR_PERMISSIONS: Permission = Permission::OWNER_ALL
    .const_bitor(Permission::GROUP_READ)
    .const_bitor(Permission::GROUP_EXEC);

#[cfg(feature = "dev_permissions")]
const FINAL_PERMISSIONS: Permission = Permission::OWNER_READ
    .const_bitor(Permission::GROUP_READ)
    .const_bitor(Permission::OTHERS_READ);
#[cfg(feature = "dev_permissions")]
const DIR_PERMISSIONS: Permission = Permission::ALL;

/// The custom configuration of the [`Storage`].
#[derive(Clone, Debug)]
pub struct Configuration {
    path: Path,
    suffix: FileName,
    prefix: FileName,
}

impl Default for Configuration {
    fn default() -> Self {
        Configuration {
            path: Storage::default_path_hint(),
            suffix: Storage::default_suffix(),
            prefix: Storage::default_prefix(),
        }
    }
}

impl crate::named_concept::NamedConceptConfiguration for Configuration {
    fn prefix(mut self, value: &FileName) -> Self {
        self.prefix = *value;
        self
    }

    fn get_prefix(&self) -> &FileName {
        &self.prefix
    }

    fn suffix(mut self, value: &FileName) -> Self {
        self.suffix = *value;
        self
    }

    fn path_hint(mut self, value: &Path) -> Self {
        self.path = *value;
        self
    }

    fn get_suffix(&self) -> &FileName {
        &self.suffix
    }

    fn get_path_hint(&self) -> &Path {
        &self.path
    }
}

impl crate::static_storage::StaticStorageConfiguration for Configuration {}

#[derive(Debug)]
pub struct Locked {
    static_storage: Storage,
}

impl Abandonable for Locked {
    unsafe fn abandon_in_place(mut this: NonNull<Self>) {
        let this = unsafe { this.as_mut() };
        unsafe { Storage::abandon_in_place(NonNull::iox2_from_mut(&mut this.static_storage)) };
    }
}

impl NamedConcept for Locked {
    fn name(&self) -> &FileName {
        self.static_storage.name()
    }
}

impl StaticStorageLocked<Storage> for Locked {
    fn unlock(mut self, contents: &[u8]) -> Result<Storage, StaticStorageUnlockError> {
        let msg = "Failed to unlock storage";
        let bytes_written = fail!(from self, when self.static_storage.file.write(contents),
            map FileWriteError::InsufficientPermissions => StaticStorageUnlockError::InsufficientPermissions;
                FileWriteError::NoSpaceLeft => StaticStorageUnlockError::NoSpaceLeft,
            unmatched StaticStorageUnlockError::InternalError,
            "{} due to a failure while writing the contents.", msg);

        if bytes_written != contents.len() as u64 {
            fail!(from self, with StaticStorageUnlockError::NoSpaceLeft,
                "{} since the contents length is {} bytes but only {} bytes could be written to the file.",
                msg, contents.len(), bytes_written);
        }

        fail!(from self, when self.static_storage.file.set_permission(FINAL_PERMISSIONS),
                map FileSetPermissionError::InsufficientPermissions => StaticStorageUnlockError::InsufficientPermissions,
                unmatched StaticStorageUnlockError::InternalError,
                "{} due to a failure while updating the permissions to {}.", msg, FINAL_PERMISSIONS);

        self.static_storage.len = contents.len() as u64;

        Ok(self.static_storage)
    }
}

/// Implements [`StaticStorage`] for a file.
#[derive(Debug)]
pub struct Storage {
    name: FileName,
    config: Configuration,
    has_ownership: AtomicBool,
    file: File,
    len: u64,
}

impl Abandonable for Storage {
    unsafe fn abandon_in_place(mut this: NonNull<Self>) {
        let this = unsafe { this.as_mut() };
        unsafe { File::abandon_in_place(NonNull::iox2_from_mut(&mut this.file)) };
    }
}

impl Drop for Storage {
    fn drop(&mut self) {
        if self.has_ownership.load(Ordering::Relaxed) {
            match unsafe { Self::remove_cfg(&self.name, &self.config) } {
                Ok(true) => (),
                Ok(false) => {
                    warn!(from self, "The static storage was already removed. This could be caused by a corrupted system.");
                }
                Err(v) => {
                    warn!(from self, "Unable to remove owned static storage due to {:?}. This may cause a leak and subsequent failures.", v);
                }
            }
        }
    }
}

impl crate::named_concept::NamedConcept for Storage {
    fn name(&self) -> &FileName {
        &self.name
    }
}

impl crate::named_concept::NamedConceptMgmt for Storage {
    type Configuration = Configuration;

    unsafe fn remove_cfg(
        storage_name: &FileName,
        config: &Self::Configuration,
    ) -> Result<bool, NamedConceptRemoveError> {
        let msg = format!("Unable to release static storage \"{storage_name}\"");
        let origin = "static_storage::file::Storage::remove_cfg()";

        let file_path = config.path_for(storage_name);

        let mut file = match FileBuilder::new(&file_path).open_existing(AccessMode::Read) {
            Ok(f) => f,
            Err(FileOpenError::FileDoesNotExist) => return Ok(false),
            Err(v) => {
                fail!(from origin, with NamedConceptRemoveError::InternalError,
                    "{} since the file could not be opened for permission adjustment ({:?}).", msg, v);
            }
        };

        let set_permission_result = file.set_permission(Permission::ALL);

        match File::remove(&file_path) {
            Ok(v) => Ok(v),
            Err(e) => {
                if let Err(e) = set_permission_result {
                    warn!(from origin,
                          "Unable to adjust the files permission as preparation to remove the file ({e:?}).");
                }
                match e {
                    FileRemoveError::InsufficientPermissions
                    | FileRemoveError::PartOfReadOnlyFileSystem => {
                        fail!(from origin, with NamedConceptRemoveError::InsufficientPermissions,
                                "{} due to insufficient permissions.", msg);
                    }
                    _ => {
                        fail!(from origin, with NamedConceptRemoveError::InternalError,
                                "{} due to unknown failure ({:?}).", msg, e);
                    }
                }
            }
        }
    }

    fn list_cfg(config: &Configuration) -> Result<Vec<FileName>, NamedConceptListError> {
        let msg = "Unable to list all storages";
        let origin = "static_storage::File::list_cfg()";
        let directory = match Directory::new(&config.path) {
            Ok(directory) => directory,
            Err(DirectoryOpenError::InsufficientPermissions) => {
                fail!(from origin, with NamedConceptListError::InsufficientPermissions,
                    "{} due to insufficient permissions to read the storage directory.", msg);
            }
            Err(DirectoryOpenError::DoesNotExist) => {
                return Ok(vec![]);
            }
            Err(v) => {
                fail!(from origin, with NamedConceptListError::InternalError,
                    "{} due to failure ({:?}) while reading the storage directory (\"{}\").", msg, v, config.path);
            }
        };

        let entries = fail!(from origin,
                            when directory.contents(),
                            map DirectoryReadError::InsufficientPermissions => NamedConceptListError::InsufficientPermissions,
                            unmatched NamedConceptListError::InternalError,
                            "{} due to a failure while reading the storage directory (\"{}\") contents.", msg, config.path);

        Ok(entries
            .iter()
            .filter(|entry| {
                let metadata = entry.metadata();
                metadata.file_type() == FileType::File && metadata.permission() == FINAL_PERMISSIONS
            })
            .filter_map(|entry| config.extract_name_from_file(entry.name()))
            .collect())
    }

    fn does_exist_cfg(
        storage_name: &FileName,
        config: &Configuration,
    ) -> Result<bool, NamedConceptDoesExistError> {
        let msg = format!("Unable to check if storage \"{storage_name}\" exists");
        let origin = "static_storage::file::Storage::does_exist_cfg()";

        let adjusted_path = config.path_for(storage_name);

        let does_exist = || {
            File::does_exist(&adjusted_path).or_else(|v| {
                fail!(from origin, with NamedConceptDoesExistError::UnderlyingResourcesCorrupted,
                    "{} due to an internal failure ({:?}), is the static storage in a corrupted state?", msg, v);
        })
        };

        if !does_exist()? {
            return Ok(false);
        }

        let file = FileBuilder::new(&adjusted_path).open_existing(AccessMode::Read);
        if file.is_err() {
            if !does_exist()? {
                return Ok(false);
            }

            fail!(from origin, with NamedConceptDoesExistError::UnderlyingResourcesCorrupted,
                "{} since the file could not be opened for reading ({:?}), is static storage in a corrupted state?", msg, file.err().unwrap() );
        }

        let file = file.unwrap();
        let metadata = file.metadata();
        if metadata.is_err() {
            if !does_exist()? {
                return Ok(false);
            }

            fail!(from origin, with NamedConceptDoesExistError::UnderlyingResourcesCorrupted,
                "{} due to an internal failure ({:?}) while acquiring underlying file informations, is static storage in a corrupted state?",
                msg, metadata.err().unwrap());
        }
        let metadata = metadata.unwrap();

        if metadata.file_type() == FileType::File && metadata.permission() == FINAL_PERMISSIONS {
            return Ok(true);
        }

        fail!(from origin, with NamedConceptDoesExistError::UnderlyingResourcesBeingSetUp,
                "{} since the underlying resources are currently being created or the creation process hangs.", msg);
    }

    fn remove_path_hint(value: &Path) -> Result<(), NamedConceptPathHintRemoveError> {
        crate::named_concept::remove_path_hint(value)
    }
}

impl crate::static_storage::StaticStorage for Storage {
    type Builder = Builder;
    type Locked = Locked;

    fn release_ownership(&self) {
        self.has_ownership.store(false, Ordering::Relaxed);
    }

    fn acquire_ownership(&self) {
        self.has_ownership.store(true, Ordering::Relaxed);
    }

    fn len(&self) -> u64 {
        self.len
    }

    fn is_empty(&self) -> bool {
        self.len == 0
    }

    fn read(&self, content: &mut [u8]) -> Result<(), StaticStorageReadError> {
        let msg = "Unable to read from static storage";
        let len = self.len();

        if len > content.len() as u64 {
            fail!(from self, with StaticStorageReadError::BufferTooSmall,
                "{} since a buffer with a size of a least {} bytes is required to read the file but a buffer of size {} bytes was provided.",
                msg, len, content.len());
        }

        let bytes_read = fail!(from self, when self.file.read(content),
                                with StaticStorageReadError::ReadError,
                                "{} due to a failure while reading the underlying file.", msg);

        if bytes_read != len {
            fail!(from self, with StaticStorageReadError::StaticStorageWasModified,
                        "{} since the expected read size is {} bytes but {} bytes were read instead. Was the static storage file modified?",
                        msg, len, bytes_read);
        }

        Ok(())
    }
}

/// Creates [`Storage`] or [`Locked`], a static storage that is not yet set. When
/// [`Builder::has_ownership()`] is set the constructs owns the static storage and removes it
/// when it goes out of scope.
#[derive(Debug)]
pub struct Builder {
    storage_name: FileName,
    has_ownership: bool,
    config: Configuration,
}

impl crate::named_concept::NamedConceptBuilder<Storage> for Builder {
    fn new(storage_name: &FileName) -> Self {
        Self {
            storage_name: *storage_name,
            has_ownership: true,
            config: <Configuration as Default>::default(),
        }
    }

    fn config(mut self, config: &Configuration) -> Self {
        self.config = config.clone();
        self
    }
}

impl crate::static_storage::StaticStorageBuilder<Storage> for Builder {
    fn has_ownership(mut self, value: bool) -> Self {
        self.has_ownership = value;
        self
    }

    fn create_locked(self) -> Result<Locked, StaticStorageCreateError> {
        let msg = format!("Unable to create target directory \"{}\"", self.config.path);
        if !fail!(from self, when Directory::does_exist(&self.config.path),
            with StaticStorageCreateError::Creation,
               "{} since the system is unable to determine if the directory even exists.", msg)
        {
            match Directory::create(&self.config.path, DIR_PERMISSIONS) {
                Ok(_) | Err(DirectoryCreateError::DirectoryAlreadyExists) => (),
                Err(e) => {
                    fail!(from self, with StaticStorageCreateError::Creation,
                        "{} due to a failure while creating the service root directory ({:?}).", msg, e);
                }
            }
            trace!(from self, "Created service root directory \"{}\" since it did not exist before.", self.config.path);
        }

        let file = fail!(from self, when
            FileBuilder::new(&self.config.path_for(&self.storage_name))
            .creation_mode(CreationMode::CreateExclusive)
            .permission(Permission::OWNER_ALL)
            .create(),
            map FileCreationError::FileAlreadyExists => StaticStorageCreateError::AlreadyExists;
                FileCreationError::InsufficientPermissions => StaticStorageCreateError::InsufficientPermissions,
            unmatched StaticStorageCreateError::Creation,
            "{} due to a failure while creating the underlying file.", msg);

        Ok(Locked {
            static_storage: Storage {
                name: self.storage_name,
                config: self.config,
                has_ownership: AtomicBool::new(self.has_ownership),
                file,
                len: 0,
            },
        })
    }

    fn open(self, timeout: Duration) -> Result<Storage, StaticStorageOpenError> {
        let msg = "Unable to open static storage";
        let origin = "static_storage::File::Builder::open()";

        let file = fail!(from origin,
            when FileBuilder::new(&self.config.path_for(&self.storage_name)).open_existing(AccessMode::Read),
            with StaticStorageOpenError::DoesNotExist,
            "{} due to a failure while opening the file.", msg);

        let mut wait_for_read_access = fail!(from self,
            when AdaptiveWaitBuilder::new().create(),
            with StaticStorageOpenError::InternalError,
            "{} since the AdaptiveWait could not be initialized.", msg);

        let mut elapsed_time = Duration::ZERO;

        loop {
            let metadata = fail!(from origin,
            when file.metadata(), with StaticStorageOpenError::Read,
            "{} due to a failure while reading the files metadata.", msg);

            if metadata.permission() != FINAL_PERMISSIONS {
                if elapsed_time > timeout {
                    fail!(from origin,
                        with StaticStorageOpenError::InitializationNotYetFinalized,
                        "{} since the static storage is still being created (in locked  state), try later.",
                        msg);
                }

                elapsed_time = fail!(from self,
                    when wait_for_read_access.wait(),
                    with StaticStorageOpenError::InternalError,
                    "{} since the adaptive wait call failed.", msg);
            } else {
                return Ok(Storage {
                    name: self.storage_name,
                    config: self.config,
                    has_ownership: AtomicBool::new(self.has_ownership),
                    file,
                    len: metadata.size(),
                });
            }
        }
    }
}