|
| 1 | +//! Import OCI layers from containers-storage via splitfdstream. |
| 2 | +//! |
| 3 | +//! This module provides functionality to import container layers directly from |
| 4 | +//! containers-storage using the splitfdstream protocol. This enables efficient |
| 5 | +//! layer transfer with file descriptor passing for external content objects. |
| 6 | +//! |
| 7 | +//! The splitfdstream format uses: |
| 8 | +//! - Inline data for tar headers and small files |
| 9 | +//! - File descriptor references for large files (passed via SCM_RIGHTS) |
| 10 | +//! |
| 11 | +//! Files are processed sequentially: tar header (inline) followed by content |
| 12 | +//! (external FD). Reflink is attempted first for efficient copying. |
| 13 | +
|
| 14 | +use std::path::Path; |
| 15 | +use std::sync::Arc; |
| 16 | + |
| 17 | +use anyhow::{Context, Result}; |
| 18 | +use rustix::fs::{copy_file_range, fstat, ftruncate}; |
| 19 | +use rustix::io::pread; |
| 20 | + |
| 21 | +use composefs::fsverity::FsVerityHashValue; |
| 22 | +use composefs::repository::Repository; |
| 23 | + |
| 24 | +use composefs_splitfdstream::{OwnedFd, SplitFDStreamChunk, SplitFDStreamClient, SplitFDStreamReader}; |
| 25 | + |
| 26 | +use crate::skopeo::TAR_LAYER_CONTENT_TYPE; |
| 27 | + |
| 28 | +/// Result of storing an FD's contents - the object ID and size. |
| 29 | +struct StoredObject<ObjectID> { |
| 30 | + object_id: ObjectID, |
| 31 | + size: u64, |
| 32 | +} |
| 33 | + |
| 34 | +/// Import a layer from a splitfdstream server into the repository. |
| 35 | +/// |
| 36 | +/// This function connects to a containers-storage splitfdstream server, |
| 37 | +/// retrieves the layer data and file descriptors, then converts the |
| 38 | +/// splitfdstream format to the composefs splitstream format. |
| 39 | +/// |
| 40 | +/// FDs are processed immediately as each batch is received, keeping max ~200 |
| 41 | +/// FDs open at a time to avoid exhausting file descriptor limits. |
| 42 | +pub fn import_from_splitfdstream<ObjectID: FsVerityHashValue>( |
| 43 | + repo: &Arc<Repository<ObjectID>>, |
| 44 | + socket_path: impl AsRef<Path>, |
| 45 | + layer_id: &str, |
| 46 | + parent_id: Option<&str>, |
| 47 | + content_identifier: &str, |
| 48 | + reference: Option<&str>, |
| 49 | +) -> Result<ObjectID> { |
| 50 | + // Connect to the splitfdstream server |
| 51 | + let mut client = SplitFDStreamClient::connect(socket_path.as_ref()) |
| 52 | + .with_context(|| format!("Connecting to splitfdstream socket {:?}", socket_path.as_ref()))?; |
| 53 | + |
| 54 | + // Get batch processor |
| 55 | + let mut batch_proc = client |
| 56 | + .get_splitfdstream(layer_id, parent_id) |
| 57 | + .with_context(|| format!("Getting splitfdstream for layer {}", layer_id))?; |
| 58 | + |
| 59 | + // Track if reflink works (detected on first FD) |
| 60 | + let mut reflink_works: Option<bool> = None; |
| 61 | + |
| 62 | + // Map of FD index -> stored object (object_id, size) |
| 63 | + let mut stored_objects: Vec<StoredObject<ObjectID>> = Vec::new(); |
| 64 | + |
| 65 | + // Receive all batches, process FDs immediately |
| 66 | + while let Some((fds, _stream_data)) = batch_proc.next_batch()? { |
| 67 | + // Process each FD immediately: copy to repo, then close |
| 68 | + for fd in fds { |
| 69 | + let stat = fstat(&fd).context("Getting file size from FD")?; |
| 70 | + let size = stat.st_size as u64; |
| 71 | + |
| 72 | + let object_id = store_fd_to_repo(repo, &fd, size, &mut reflink_works)?; |
| 73 | + stored_objects.push(StoredObject { object_id, size }); |
| 74 | + // fd is dropped here, closing the file descriptor |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + // Get complete stream data |
| 79 | + let stream_data = batch_proc.stream_data()?; |
| 80 | + |
| 81 | + // Create a splitstream writer |
| 82 | + let mut writer = repo.create_stream(TAR_LAYER_CONTENT_TYPE); |
| 83 | + |
| 84 | + // Parse stream and build splitstream |
| 85 | + let mut reader = SplitFDStreamReader::new(stream_data.to_vec()); |
| 86 | + |
| 87 | + while let Some(chunk) = reader.next_chunk()? { |
| 88 | + match chunk { |
| 89 | + SplitFDStreamChunk::Inline(data) => { |
| 90 | + writer.write_inline(&data); |
| 91 | + } |
| 92 | + SplitFDStreamChunk::External(fd_idx) => { |
| 93 | + let stored = stored_objects.get(fd_idx).ok_or_else(|| { |
| 94 | + anyhow::anyhow!( |
| 95 | + "FD index {} out of range (have {} objects)", |
| 96 | + fd_idx, |
| 97 | + stored_objects.len() |
| 98 | + ) |
| 99 | + })?; |
| 100 | + |
| 101 | + writer.add_external_size(stored.size); |
| 102 | + writer.write_reference(stored.object_id.clone())?; |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + let object_id = repo.write_stream(writer, content_identifier, reference)?; |
| 108 | + |
| 109 | + Ok(object_id) |
| 110 | +} |
| 111 | + |
| 112 | +/// Store FD contents to repository, trying reflink first. |
| 113 | +fn store_fd_to_repo<ObjectID: FsVerityHashValue>( |
| 114 | + repo: &Arc<Repository<ObjectID>>, |
| 115 | + fd: &OwnedFd, |
| 116 | + size: u64, |
| 117 | + reflink_works: &mut Option<bool>, |
| 118 | +) -> Result<ObjectID> { |
| 119 | + if reflink_works.is_none() { |
| 120 | + match try_reflink_to_repo(repo, fd, size) { |
| 121 | + Ok(id) => { |
| 122 | + *reflink_works = Some(true); |
| 123 | + return Ok(id); |
| 124 | + } |
| 125 | + Err(_) => { |
| 126 | + *reflink_works = Some(false); |
| 127 | + } |
| 128 | + } |
| 129 | + } else if *reflink_works == Some(true) { |
| 130 | + if let Ok(id) = try_reflink_to_repo(repo, fd, size) { |
| 131 | + return Ok(id); |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + let data = read_fd_contents(fd, size)?; |
| 136 | + repo.ensure_object(&data).context("Storing object") |
| 137 | +} |
| 138 | + |
| 139 | +/// Try to reflink the file descriptor contents to the repository. |
| 140 | +fn try_reflink_to_repo<ObjectID: FsVerityHashValue>( |
| 141 | + repo: &Arc<Repository<ObjectID>>, |
| 142 | + src_fd: &OwnedFd, |
| 143 | + size: u64, |
| 144 | +) -> Result<ObjectID> { |
| 145 | + let tmpfile = repo |
| 146 | + .create_object_tmpfile() |
| 147 | + .context("Creating object tmpfile")?; |
| 148 | + |
| 149 | + try_copy_file_range(src_fd, &tmpfile, size)?; |
| 150 | + |
| 151 | + repo.finalize_object_tmpfile(tmpfile.into(), size) |
| 152 | + .context("Finalizing reflinked object") |
| 153 | +} |
| 154 | + |
| 155 | +/// Try to copy file contents using copy_file_range (which may use reflink). |
| 156 | +fn try_copy_file_range(src_fd: &OwnedFd, dst_fd: &OwnedFd, size: u64) -> Result<()> { |
| 157 | + if size == 0 { |
| 158 | + return Ok(()); |
| 159 | + } |
| 160 | + |
| 161 | + ftruncate(dst_fd, size).context("Truncating destination file")?; |
| 162 | + |
| 163 | + let mut src_offset = 0u64; |
| 164 | + let mut dst_offset = 0u64; |
| 165 | + let mut remaining = size; |
| 166 | + |
| 167 | + while remaining > 0 { |
| 168 | + let copied = copy_file_range( |
| 169 | + src_fd, |
| 170 | + Some(&mut src_offset), |
| 171 | + dst_fd, |
| 172 | + Some(&mut dst_offset), |
| 173 | + remaining as usize, |
| 174 | + ) |
| 175 | + .context("copy_file_range failed")?; |
| 176 | + |
| 177 | + if copied == 0 { |
| 178 | + anyhow::bail!("copy_file_range returned 0 before completing"); |
| 179 | + } |
| 180 | + |
| 181 | + remaining -= copied as u64; |
| 182 | + } |
| 183 | + |
| 184 | + Ok(()) |
| 185 | +} |
| 186 | + |
| 187 | +/// Read the entire contents of a file descriptor using pread. |
| 188 | +fn read_fd_contents(fd: &OwnedFd, expected_size: u64) -> Result<Vec<u8>> { |
| 189 | + let size = expected_size as usize; |
| 190 | + let mut data = vec![0u8; size]; |
| 191 | + let mut offset = 0u64; |
| 192 | + let mut total_read = 0usize; |
| 193 | + |
| 194 | + while total_read < size { |
| 195 | + let n = pread(fd, &mut data[total_read..], offset) |
| 196 | + .with_context(|| format!("Reading from fd at offset {}", offset))?; |
| 197 | + if n == 0 { |
| 198 | + data.truncate(total_read); |
| 199 | + break; |
| 200 | + } |
| 201 | + total_read += n; |
| 202 | + offset += n as u64; |
| 203 | + } |
| 204 | + |
| 205 | + Ok(data) |
| 206 | +} |
| 207 | + |
| 208 | +#[cfg(test)] |
| 209 | +mod tests { |
| 210 | + // Integration tests would require a running splitfdstream server |
| 211 | +} |
0 commit comments