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
|
use std::collections::HashSet;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tar::{Archive, EntryType};
use walkdir::WalkDir;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArtifactManifest {
pub packages: Vec<PackageRecord>,
pub files: Vec<FileRecord>,
pub initrd: Option<InitrdRecord>,
pub services: Vec<ServiceRecord>,
pub archive_members: Vec<ArchiveMemberRecord>,
}
impl ArtifactManifest {
pub fn new(
mut packages: Vec<PackageRecord>,
mut files: Vec<FileRecord>,
initrd: Option<InitrdRecord>,
mut services: Vec<ServiceRecord>,
mut archive_members: Vec<ArchiveMemberRecord>,
) -> Result<Self> {
packages.sort_by(|left, right| left.name.cmp(&right.name));
files.sort_by(|left, right| left.path.cmp(&right.path));
services.sort_by(|left, right| left.name.cmp(&right.name));
archive_members.sort_by(|left, right| left.path.cmp(&right.path));
ensure_unique("package", packages.iter().map(|record| record.name.as_str()))?;
ensure_unique("file", files.iter().map(|record| record.path.as_str()))?;
ensure_unique("service", services.iter().map(|record| record.name.as_str()))?;
ensure_unique("archive member", archive_members.iter().map(|record| record.path.as_str()))?;
Ok(Self { packages, files, initrd, services, archive_members })
}
pub fn load(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref();
let text = fs::read_to_string(path).with_context(|| format!("read artifact manifest {}", path.display()))?;
let manifest: Self = toml::from_str(&text).with_context(|| format!("parse artifact manifest {}", path.display()))?;
Self::new(manifest.packages, manifest.files, manifest.initrd, manifest.services, manifest.archive_members)
}
pub fn write_beside(&self, artifact: impl AsRef<Path>) -> Result<PathBuf> {
let artifact = artifact.as_ref();
let directory = artifact.parent().unwrap_or_else(|| Path::new("."));
let path = directory.join("artifact.manifest.toml");
let text = toml::to_string_pretty(self).context("serialize artifact manifest")?;
fs::write(&path, text).with_context(|| format!("write artifact manifest {}", path.display()))?;
Ok(path)
}
/// Collect native filesystem and archive facts from a completed build.
/// Package records come from the typed package-installation boundary because
/// the RPM database is not a portable filesystem format.
pub fn collect(
rootfs: impl AsRef<Path>,
packages: Vec<PackageRecord>,
initrd: Option<InitrdRecord>,
archive: impl AsRef<Path>,
) -> Result<Self> {
let rootfs = rootfs.as_ref();
if !rootfs.is_dir() {
bail!("rootfs is not a directory: {}", rootfs.display());
}
Self::new(
packages,
collect_files(rootfs)?,
initrd,
collect_services(rootfs)?,
collect_archive_members(archive.as_ref())?,
)
}
}
fn collect_files(rootfs: &Path) -> Result<Vec<FileRecord>> {
let mut files = Vec::new();
for entry in WalkDir::new(rootfs).follow_links(false).min_depth(1) {
let entry = entry.with_context(|| format!("walk rootfs {}", rootfs.display()))?;
let relative = entry.path().strip_prefix(rootfs).expect("walk entry is below rootfs");
if relative.components().next().is_some_and(|part| part.as_os_str() == ".host" || part.as_os_str() == ".fakedata") {
continue;
}
let path = portable_path(relative)?;
let file_type = entry.file_type();
if file_type.is_file() {
files.push(FileRecord::file(path, sha256_file(entry.path())?));
} else if file_type.is_symlink() {
let target = fs::read_link(entry.path())
.with_context(|| format!("read rootfs symlink {}", entry.path().display()))?;
files.push(FileRecord::symlink(path, link_target(&target)?));
} else if !file_type.is_dir() {
bail!("unsupported rootfs entry type: {}", entry.path().display());
}
}
Ok(files)
}
fn collect_services(rootfs: &Path) -> Result<Vec<ServiceRecord>> {
let wants = rootfs.join("etc/systemd/system/multi-user.target.wants");
if !wants.exists() {
return Ok(Vec::new());
}
let mut services = Vec::new();
for entry in fs::read_dir(&wants).with_context(|| format!("read service state directory {}", wants.display()))? {
let entry = entry?;
let name = entry.file_name().into_string().map_err(|_| anyhow::anyhow!("non-UTF-8 service name in {}", wants.display()))?;
if entry.file_type()?.is_symlink() && name.ends_with(".service") {
services.push(ServiceRecord::new(name, true));
}
}
Ok(services)
}
fn collect_archive_members(archive_path: &Path) -> Result<Vec<ArchiveMemberRecord>> {
let file = fs::File::open(archive_path).with_context(|| format!("open archive {}", archive_path.display()))?;
let mut archive = Archive::new(file);
let mut members = Vec::new();
for entry in archive.entries().with_context(|| format!("read archive {}", archive_path.display()))? {
let entry = entry.with_context(|| format!("read archive member from {}", archive_path.display()))?;
let kind = match entry.header().entry_type() {
EntryType::Regular => "file",
EntryType::Directory => "directory",
EntryType::Symlink => "symlink",
other => bail!("unsupported archive member type {other:?} in {}", archive_path.display()),
};
members.push(ArchiveMemberRecord::new(portable_path(&entry.path()?)?, kind));
}
Ok(members)
}
fn sha256_file(path: &Path) -> Result<String> {
let mut file = fs::File::open(path).with_context(|| format!("open rootfs file {}", path.display()))?;
let mut hasher = Sha256::new();
let mut buffer = [0; 8192];
loop {
let read = file.read(&mut buffer).with_context(|| format!("read rootfs file {}", path.display()))?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
}
Ok(format!("{:x}", hasher.finalize()))
}
fn portable_path(path: &Path) -> Result<String> {
if path.is_absolute() {
bail!("absolute path is not valid in an artifact manifest: {}", path.display());
}
let value = path.to_str().ok_or_else(|| anyhow::anyhow!("non-UTF-8 path is not valid in an artifact manifest: {}", path.display()))?;
if value.is_empty() || value == "." {
bail!("empty path is not valid in an artifact manifest");
}
Ok(value.to_owned())
}
fn link_target(path: &Path) -> Result<String> {
let value = path.to_str().ok_or_else(|| anyhow::anyhow!("non-UTF-8 symlink target is not valid in an artifact manifest: {}", path.display()))?;
if value.is_empty() {
bail!("empty symlink target is not valid in an artifact manifest");
}
Ok(value.to_owned())
}
fn ensure_unique<'a>(kind: &str, keys: impl IntoIterator<Item = &'a str>) -> Result<()> {
let mut seen = HashSet::new();
for key in keys {
if key.is_empty() || !seen.insert(key) {
bail!("duplicate {kind} record: {key}");
}
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PackageRecord {
pub name: String,
pub version: String,
}
impl PackageRecord {
pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
Self { name: name.into(), version: version.into() }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileRecord {
pub path: String,
pub kind: String,
pub digest: Option<String>,
pub target: Option<String>,
}
impl FileRecord {
pub fn file(path: impl Into<String>, digest: impl Into<String>) -> Self {
Self { path: path.into(), kind: "file".into(), digest: Some(digest.into()), target: None }
}
pub fn symlink(path: impl Into<String>, target: impl Into<String>) -> Self {
Self { path: path.into(), kind: "symlink".into(), digest: None, target: Some(target.into()) }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InitrdRecord {
pub path: String,
pub sha256: String,
}
impl InitrdRecord {
pub fn new(path: impl Into<String>, sha256: impl Into<String>) -> Self {
Self { path: path.into(), sha256: sha256.into() }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServiceRecord {
pub name: String,
pub enabled: bool,
}
impl ServiceRecord {
pub fn new(name: impl Into<String>, enabled: bool) -> Self {
Self { name: name.into(), enabled }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArchiveMemberRecord {
pub path: String,
pub kind: String,
}
impl ArchiveMemberRecord {
pub fn new(path: impl Into<String>, kind: impl Into<String>) -> Self {
Self { path: path.into(), kind: kind.into() }
}
}
|