Skip to main content

keramics_formats/linuxlvm/
volume_system.rs

1/* Copyright 2024-2026 Joachim Metz <joachim.metz@gmail.com>
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may
5 * obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software
8 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 * License for the specific language governing permissions and limitations
11 * under the License.
12 */
13
14use std::cmp::Ordering;
15use std::collections::HashMap;
16use std::io::SeekFrom;
17
18use keramics_core::{DataStreamReference, ErrorTrace};
19
20use crate::fake_file_resolver::FakeFileResolver;
21use crate::file_resolver::FileResolverReference;
22use crate::path_component::PathComponent;
23
24use super::data_area_descriptor::LinuxLvmDataAreaDescriptor;
25use super::extent::{LinuxLvmExtent, LinuxLvmExtentValues};
26use super::logical_volume::LinuxLvmLogicalVolume;
27use super::metadata::LinuxLvmMetadata;
28use super::metadata_area_header::LinuxLvmMetadataAreaHeader;
29use super::physical_volume::LinuxLvmPhysicalVolume;
30use super::physical_volume_label::LinuxLvmPhysicalVolumeLabel;
31use super::raw_location_descriptor::LinuxLvmRawLocationDescriptor;
32use super::volume::LinuxLvmVolume;
33use super::volume_group::LinuxLvmVolumeGroup;
34use super::volumes::LinuxLvmVolumesIterator;
35
36/// Linux Logical Volume Manager (LVM) volume system.
37pub struct LinuxLvmVolumeSystem {
38    /// File resolver.
39    file_resolver: FileResolverReference,
40
41    /// Bytes per sector.
42    bytes_per_sector: u16,
43
44    /// File names.
45    file_names: Vec<PathComponent>,
46
47    /// Volume group.
48    volume_group: Option<LinuxLvmVolumeGroup>,
49}
50
51impl LinuxLvmVolumeSystem {
52    /// Creates a new volume system.
53    pub fn new() -> Self {
54        Self {
55            file_resolver: FileResolverReference::new(Box::new(FakeFileResolver::new())),
56            bytes_per_sector: 0,
57            file_names: Vec::new(),
58            volume_group: None,
59        }
60    }
61
62    /// Retrieves the bytes per sector.
63    pub fn get_bytes_per_sector(&self) -> u16 {
64        self.bytes_per_sector
65    }
66
67    /// Retrieves the (volume group) identifier.
68    pub fn get_identifier(&self) -> Option<&str> {
69        match &self.volume_group {
70            Some(volume_group) => Some(volume_group.identifier.as_str()),
71            None => None,
72        }
73    }
74
75    /// Retrieves the (volume group) name.
76    pub fn get_name(&self) -> Option<&str> {
77        match &self.volume_group {
78            Some(volume_group) => Some(volume_group.name.as_str()),
79            None => None,
80        }
81    }
82
83    /// Retrieves the number of physical volumes.
84    pub fn get_number_of_physical_volumes(&self) -> usize {
85        match &self.volume_group {
86            Some(volume_group) => volume_group.physical_volumes.len(),
87            None => 0,
88        }
89    }
90
91    /// Retrieves a physical volume by index.
92    pub fn get_physical_volume_by_index(
93        &self,
94        volume_index: usize,
95    ) -> Option<&LinuxLvmPhysicalVolume> {
96        match &self.volume_group {
97            Some(volume_group) => volume_group.physical_volumes.get(volume_index),
98            None => None,
99        }
100    }
101
102    /// Retrieves the number of (logical) volumes.
103    pub fn get_number_of_volumes(&self) -> usize {
104        match &self.volume_group {
105            Some(volume_group) => volume_group.logical_volumes.len(),
106            None => 0,
107        }
108    }
109
110    /// Retrieves a volume by index.
111    pub fn get_volume_by_index(&self, volume_index: usize) -> Result<LinuxLvmVolume, ErrorTrace> {
112        let volume_group: &LinuxLvmVolumeGroup = match &self.volume_group {
113            Some(volume_group) => volume_group,
114            None => {
115                return Err(keramics_core::error_trace_new!("Missing volume group"));
116            }
117        };
118        let logical_volume: &LinuxLvmLogicalVolume =
119            match volume_group.logical_volumes.get(volume_index) {
120                Some(logical_volume) => logical_volume,
121                None => {
122                    return Err(keramics_core::error_trace_new!(format!(
123                        "No logical volume with index: {}",
124                        volume_index
125                    )));
126                }
127            };
128        Ok(LinuxLvmVolume::new(
129            &self.file_resolver,
130            &self.file_names,
131            volume_index,
132            logical_volume,
133        ))
134    }
135
136    /// Retrieves a volumes iterator.
137    pub fn volumes(&self) -> LinuxLvmVolumesIterator<'_> {
138        LinuxLvmVolumesIterator::new(self, self.get_number_of_volumes())
139    }
140
141    /// Opens a storage media image.
142    pub fn open(
143        &mut self,
144        file_resolver: &FileResolverReference,
145        file_names: &[PathComponent],
146    ) -> Result<(), ErrorTrace> {
147        let mut physical_volume_labels: HashMap<String, LinuxLvmPhysicalVolumeLabel> =
148            HashMap::new();
149
150        for file_name in file_names.iter() {
151            let path_components: [PathComponent; 1] = [file_name.clone()];
152
153            let data_stream: DataStreamReference =
154                match file_resolver.get_data_stream(&path_components) {
155                    Ok(Some(data_stream)) => data_stream,
156                    Ok(None) => {
157                        return Err(keramics_core::error_trace_new!(format!(
158                            "Missing data stream: {}",
159                            file_name
160                        )));
161                    }
162                    Err(mut error) => {
163                        keramics_core::error_trace_add_frame!(
164                            error,
165                            format!("Unable to open file: {}", file_name)
166                        );
167                        return Err(error);
168                    }
169                };
170            let volume_label_offset: u64 = 512;
171
172            let mut physical_volume_label: LinuxLvmPhysicalVolumeLabel =
173                LinuxLvmPhysicalVolumeLabel::new();
174
175            match physical_volume_label
176                .read_at_position(&data_stream, SeekFrom::Start(volume_label_offset))
177            {
178                Ok(_) => {}
179                Err(mut error) => {
180                    keramics_core::error_trace_add_frame!(
181                        error,
182                        format!(
183                            "Unable to read physical volume label at offset: {} (0x{:08x})",
184                            volume_label_offset, volume_label_offset
185                        )
186                    );
187                    return Err(error);
188                }
189            }
190            let data_area_descriptor: &LinuxLvmDataAreaDescriptor =
191                match physical_volume_label.metadata_area_descriptors.first() {
192                    Some(data_area_descriptor) => data_area_descriptor,
193                    None => {
194                        return Err(keramics_core::error_trace_new!(
195                            "Missing metadata area descriptors"
196                        ));
197                    }
198                };
199            let volume_group: LinuxLvmVolumeGroup =
200                match self.read_volume_group(&data_stream, data_area_descriptor) {
201                    Ok(volume_group) => volume_group,
202                    Err(mut error) => {
203                        keramics_core::error_trace_add_frame!(
204                            error,
205                            format!("Unable to read volume group from file: {}", file_name)
206                        );
207                        return Err(error);
208                    }
209                };
210            physical_volume_labels.insert(
211                physical_volume_label.identifier.to_string(),
212                physical_volume_label,
213            );
214            // TODO: make sure the file names are in order of physical volume index
215            self.file_names.push(file_name.clone());
216
217            if self.volume_group.is_none() {
218                self.volume_group = Some(volume_group);
219            }
220        }
221        self.bytes_per_sector = 512;
222
223        let mut physical_volumes: HashMap<String, (usize, String)> = HashMap::new();
224
225        if let Some(volume_group) = &mut self.volume_group {
226            let number_of_physical_volumes: usize = volume_group.physical_volumes.len();
227
228            if number_of_physical_volumes == 0 {
229                return Err(keramics_core::error_trace_new!("Missing physical volumes"));
230            }
231            // TODO: add support for multiple physical volumes.
232            if volume_group.physical_volumes.len() != 1 {
233                return Err(keramics_core::error_trace_new!(
234                    "Unsupported number of physical volumes",
235                ));
236            }
237            for physical_volume in volume_group.physical_volumes.iter() {
238                let identifier: String = physical_volume.identifier.to_string();
239                let lookup_identifier: String = identifier.replace("-", "");
240
241                if !physical_volume_labels.contains_key(&lookup_identifier) {
242                    return Err(keramics_core::error_trace_new!(format!(
243                        "Missing physical volume: {}",
244                        identifier
245                    )));
246                }
247                physical_volumes.insert(
248                    physical_volume.name.clone(),
249                    (physical_volume.index, lookup_identifier),
250                );
251            }
252            let extent_size: u64 =
253                (volume_group.extent_size as u64) * (self.bytes_per_sector as u64);
254
255            for logical_volume in volume_group.logical_volumes.iter_mut() {
256                let mut logical_volume_size: u64 = 0;
257
258                for (segment_index, segment) in logical_volume.segments.iter().enumerate() {
259                    let segment_offset: u64 = (segment.start_extent as u64) * extent_size;
260                    let segment_size: u64 = (segment.number_of_extents as u64) * extent_size;
261
262                    match segment.segment_type.as_str() {
263                        "striped" => {
264                            let number_of_stripes: usize = segment.stripes.len();
265
266                            if number_of_stripes == 0 {
267                                return Err(keramics_core::error_trace_new!(format!(
268                                    "Unsupported segment: {} - missing stripes",
269                                    segment_index
270                                )));
271                            }
272                            // TODO: add support for multiple stripes.
273                            if number_of_stripes != 1 {
274                                return Err(keramics_core::error_trace_new!(
275                                    "Unsupported segment: {} - unsupported number of stripes",
276                                ));
277                            }
278                            let stripe_offset: u64 = segment_offset;
279                            let stripe_size: u64 = segment_size;
280
281                            for (stripe_index, stripe) in segment.stripes.iter().enumerate() {
282                                let (physical_volume_index, physical_volume_identifier) =
283                                    match physical_volumes.get(&stripe.physical_volume_name) {
284                                        Some(result) => result,
285                                        None => {
286                                            return Err(keramics_core::error_trace_new!(format!(
287                                                "Invalid segment: {} - invalid stripe: {} - missing physical volume: {}",
288                                                segment_index,
289                                                stripe_index,
290                                                stripe.physical_volume_name
291                                            )));
292                                        }
293                                    };
294                                let physical_volume_label: &LinuxLvmPhysicalVolumeLabel =
295                                    match physical_volume_labels.get(physical_volume_identifier) {
296                                        Some(physical_volume_label) => physical_volume_label,
297                                        None => {
298                                            return Err(keramics_core::error_trace_new!(format!(
299                                                "Missing physical volume label: {}",
300                                                physical_volume_identifier
301                                            )));
302                                        }
303                                    };
304                                let data_area_offset: u64 =
305                                    (stripe.start_extent as u64) * extent_size;
306
307                                let data_area_descriptor_index: usize = match physical_volume_label
308                                    .data_area_descriptors
309                                    .binary_search_by(|data_area_descriptor| {
310                                        let area_end_offset: u64 = data_area_descriptor
311                                            .logical_offset
312                                            + data_area_descriptor.size;
313
314                                        if data_area_offset >= area_end_offset {
315                                            Ordering::Less
316                                        } else if data_area_offset
317                                            < data_area_descriptor.logical_offset
318                                        {
319                                            Ordering::Greater
320                                        } else {
321                                            Ordering::Equal
322                                        }
323                                    }) {
324                                    Ok(data_area_descriptor_index) => data_area_descriptor_index,
325                                    Err(_) => {
326                                        return Err(keramics_core::error_trace_new!(format!(
327                                            "Missing data area descriptor for offset: {} (0x{:08x})",
328                                            data_area_offset, data_area_offset
329                                        )));
330                                    }
331                                };
332                                let data_area_descriptor: &LinuxLvmDataAreaDescriptor =
333                                    match physical_volume_label
334                                        .data_area_descriptors
335                                        .get(data_area_descriptor_index)
336                                    {
337                                        Some(data_area_descriptor) => data_area_descriptor,
338                                        None => {
339                                            return Err(keramics_core::error_trace_new!(format!(
340                                                "Missing data area descriptor: {}",
341                                                data_area_descriptor_index
342                                            )));
343                                        }
344                                    };
345                                let data_area_physical_offset: u64 = data_area_descriptor
346                                    .physical_offset
347                                    + (data_area_offset - data_area_descriptor.logical_offset);
348
349                                let extent: LinuxLvmExtent = LinuxLvmExtent {
350                                    logical_offset: stripe_offset,
351                                    size: stripe_size,
352                                    values: LinuxLvmExtentValues::Stripe {
353                                        physical_offset: data_area_physical_offset,
354                                        physical_volume_index: *physical_volume_index,
355                                    },
356                                };
357                                logical_volume.extents.push(extent);
358                            }
359                        }
360                        _ => {
361                            return Err(keramics_core::error_trace_new!(format!(
362                                "Unsupported segment: {} - unsupported type: {}",
363                                segment_index, segment.segment_type
364                            )));
365                        }
366                    }
367                    logical_volume_size += segment_size;
368                }
369                logical_volume.size = logical_volume_size;
370            }
371        }
372        self.file_resolver = file_resolver.clone();
373
374        Ok(())
375    }
376
377    /// Reads the volume group from the metadata area,
378    fn read_volume_group(
379        &mut self,
380        data_stream: &DataStreamReference,
381        data_area_descriptor: &LinuxLvmDataAreaDescriptor,
382    ) -> Result<LinuxLvmVolumeGroup, ErrorTrace> {
383        let mut metadata_area_header: LinuxLvmMetadataAreaHeader =
384            LinuxLvmMetadataAreaHeader::new();
385
386        match metadata_area_header.read_at_position(
387            data_stream,
388            SeekFrom::Start(data_area_descriptor.physical_offset),
389        ) {
390            Ok(_) => {}
391            Err(mut error) => {
392                keramics_core::error_trace_add_frame!(
393                    error,
394                    format!(
395                        "Unable to read metadata area header at offset: {} (0x{:08x})",
396                        data_area_descriptor.physical_offset, data_area_descriptor.physical_offset
397                    )
398                );
399                return Err(error);
400            }
401        }
402        let location_descriptor: &LinuxLvmRawLocationDescriptor =
403            match metadata_area_header.location_descriptors.first() {
404                Some(location_descriptor) => location_descriptor,
405                None => {
406                    return Err(keramics_core::error_trace_new!(
407                        "Missing location descriptors"
408                    ));
409                }
410            };
411        let mut metadata: LinuxLvmMetadata = LinuxLvmMetadata::new();
412
413        match metadata.read_at_position(
414            data_stream,
415            location_descriptor.size,
416            SeekFrom::Start(data_area_descriptor.physical_offset + location_descriptor.offset),
417            location_descriptor.checksum,
418        ) {
419            Ok(_) => {}
420            Err(mut error) => {
421                keramics_core::error_trace_add_frame!(error, "Unable to read metadata");
422                return Err(error);
423            }
424        }
425        match metadata.volume_group {
426            Some(volume_group) => Ok(volume_group),
427            None => Err(keramics_core::error_trace_new!("Missing volume group")),
428        }
429    }
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435
436    use std::path::PathBuf;
437
438    use crate::os_file_resolver::OsFileResolver;
439
440    use crate::tests::get_test_data_path;
441
442    fn get_volume_system() -> Result<LinuxLvmVolumeSystem, ErrorTrace> {
443        let mut volume_system: LinuxLvmVolumeSystem = LinuxLvmVolumeSystem::new();
444
445        let path_string: String = get_test_data_path("linuxlvm");
446        let path_buf: PathBuf = PathBuf::from(path_string.as_str());
447        let file_resolver: FileResolverReference =
448            FileResolverReference::new(Box::new(OsFileResolver::new(path_buf)));
449
450        let file_names: [PathComponent; 1] = [PathComponent::from("lvm2.raw")];
451        volume_system.open(&file_resolver, &file_names)?;
452
453        Ok(volume_system)
454    }
455
456    #[test]
457    fn test_get_bytes_per_sector() -> Result<(), ErrorTrace> {
458        let volume_system: LinuxLvmVolumeSystem = get_volume_system()?;
459
460        let bytes_per_sector: u16 = volume_system.get_bytes_per_sector();
461        assert_eq!(bytes_per_sector, 512);
462
463        Ok(())
464    }
465
466    #[test]
467    fn test_get_identifier() -> Result<(), ErrorTrace> {
468        let volume_system: LinuxLvmVolumeSystem = get_volume_system()?;
469
470        let identifier: Option<&str> = volume_system.get_identifier();
471        assert_eq!(identifier, Some("22IVml-3dws-I85y-vDVy-wYV3-Umbr-pUkQSX"));
472
473        Ok(())
474    }
475
476    #[test]
477    fn test_get_name() -> Result<(), ErrorTrace> {
478        let volume_system: LinuxLvmVolumeSystem = get_volume_system()?;
479
480        let name: Option<&str> = volume_system.get_name();
481        assert_eq!(name, Some("test_volume_group"));
482
483        Ok(())
484    }
485
486    // TODO: add tests for get_number_of_physical_volumes
487    // TODO: add tests for get_number_of_volumes
488    // TODO: add tests for get_volume_by_index
489
490    #[test]
491    fn test_volumes() -> Result<(), ErrorTrace> {
492        let volume_system: LinuxLvmVolumeSystem = get_volume_system()?;
493
494        let mut volumes_iterator: LinuxLvmVolumesIterator = volume_system.volumes();
495
496        let result: Option<Result<LinuxLvmVolume, ErrorTrace>> = volumes_iterator.next();
497        assert!(result.is_some());
498        assert!(result.unwrap().is_ok());
499
500        let result: Option<Result<LinuxLvmVolume, ErrorTrace>> = volumes_iterator.skip(1).next();
501        assert!(result.is_none());
502
503        Ok(())
504    }
505
506    #[test]
507    fn test_open() -> Result<(), ErrorTrace> {
508        let mut volume_system: LinuxLvmVolumeSystem = LinuxLvmVolumeSystem::new();
509
510        let path_string: String = get_test_data_path("linuxlvm");
511        let path_buf: PathBuf = PathBuf::from(path_string.as_str());
512        let file_resolver: FileResolverReference =
513            FileResolverReference::new(Box::new(OsFileResolver::new(path_buf)));
514
515        assert!(volume_system.volume_group.is_none());
516
517        let file_names: [PathComponent; 1] = [PathComponent::from("lvm2.raw")];
518        volume_system.open(&file_resolver, &file_names)?;
519        assert!(volume_system.volume_group.is_some());
520
521        Ok(())
522    }
523}