1use std::io::Write;
8use std::path::{Path, PathBuf};
9
10use crate::watchdog::{Termination, run_supervised};
11use anyhow::{Context, Result, bail};
12use sha2::{Digest, Sha256};
13
14use crate::artifact::{Identity, Kind, Meta};
15
16pub struct Store {
18 access_key: String,
19 secret_key: String,
20 bucket: String,
21 endpoint: String,
22}
23
24impl Store {
25 pub fn from_env() -> Result<Self> {
31 let get = |key: &str| -> Result<String> {
32 let value = std::env::var(key).unwrap_or_default();
33 if value.is_empty() {
34 bail!("{key} is required to publish artifacts");
35 }
36 Ok(value)
37 };
38 Ok(Self {
39 access_key: get("ARTIFACTS_ACCESS_KEY_ID")?,
40 secret_key: get("ARTIFACTS_SECRET_ACCESS_KEY")?,
41 bucket: get("ARTIFACTS_BUCKET")?,
42 endpoint: get("ARTIFACTS_ENDPOINT")?,
43 })
44 }
45
46 fn s3(&self, args: &[&str]) -> Result<()> {
47 self.run_s3("s3cmd", args)
48 }
49
50 fn run_s3(&self, program: &str, args: &[&str]) -> Result<()> {
53 let mut config = tempfile::NamedTempFile::new().context("cannot make the s3cmd config")?;
54 writeln!(
55 config,
56 "[default]\naccess_key = {}\nsecret_key = {}\nhost_base = {}\nhost_bucket = %(bucket)s.{}",
57 self.access_key, self.secret_key, self.endpoint, self.endpoint
58 )
59 .context("cannot write the s3cmd config")?;
60 let mut full = vec![format!("--config={}", config.path().display())];
61 full.extend(args.iter().map(ToString::to_string));
62 run_supervised(program, &full, &[], &Termination::watch()?).context("s3cmd failed")
63 }
64
65 pub fn publish(&self, kind: Kind, tarball: &Path, identity: &Identity) -> Result<Meta> {
70 let meta = Meta {
71 kind,
72 sha256: sha256_of(tarball)?,
73 bytes: std::fs::metadata(tarball)
74 .with_context(|| format!("cannot stat {}", tarball.display()))?
75 .len(),
76 identity: identity.clone(),
77 };
78
79 let prefix = identity.prefix(&self.bucket);
80 let object = format!("{prefix}/{}", meta.object_key());
81 println!(">> publishing {} -> {object}", tarball.display());
82 self.s3(&["put", &tarball.to_string_lossy(), &object])?;
83
84 let meta_path = tarball.with_extension("meta");
85 std::fs::write(&meta_path, meta.to_text())
86 .with_context(|| format!("cannot write {}", meta_path.display()))?;
87 self.s3(&[
88 "put",
89 &meta_path.to_string_lossy(),
90 &format!("{prefix}/{}", Meta::meta_key(kind)),
91 ])?;
92 if kind == Kind::Coverage {
93 self.s3(&[
94 "put",
95 &meta_path.to_string_lossy(),
96 &format!("s3://{}/{}", self.bucket, Meta::latest_key(kind)),
97 ])?;
98 }
99
100 Ok(meta)
101 }
102}
103
104pub fn sha256_of(path: &Path) -> Result<String> {
110 use std::io::Read;
111
112 let mut file =
113 std::fs::File::open(path).with_context(|| format!("cannot open {}", path.display()))?;
114 let mut hasher = Sha256::new();
115 let mut buffer = vec![0u8; 64 * 1024];
116 loop {
117 let read = file
118 .read(&mut buffer)
119 .with_context(|| format!("cannot read {}", path.display()))?;
120 if read == 0 {
121 break;
122 }
123 hasher.update(&buffer[..read]);
124 }
125 Ok(hasher
126 .finalize()
127 .iter()
128 .fold(String::with_capacity(64), |mut hex, byte| {
129 use std::fmt::Write;
130 let _ = write!(hex, "{byte:02x}");
131 hex
132 }))
133}
134
135impl Store {
136 fn s3_get(&self, remote: &str, local: &Path) -> Result<()> {
137 self.s3(&["--force", "get", remote, &local.to_string_lossy()])
138 }
139
140 pub fn fetch_meta(&self, kind: Kind, identity: &Identity, into: &Path) -> Result<Meta> {
142 let remote = format!("{}/{}", identity.prefix(&self.bucket), Meta::meta_key(kind));
143 let local = into.join(Meta::meta_key(kind));
144 self.s3_get(&remote, &local)
145 .with_context(|| format!("no {kind} meta at {remote} — did that job publish?"))?;
146 let text = std::fs::read_to_string(&local)
147 .with_context(|| format!("cannot read {}", local.display()))?;
148 Meta::from_text(&text).with_context(|| format!("malformed {kind} meta"))
149 }
150
151 pub fn verify_object(&self, meta: &Meta, identity: &Identity, into: &Path) -> Result<PathBuf> {
156 let remote = format!("{}/{}", identity.prefix(&self.bucket), meta.object_key());
157 let local = into.join(meta.object_key());
158 self.s3_get(&remote, &local)?;
159
160 let bytes = std::fs::metadata(&local)
161 .with_context(|| format!("cannot stat {}", local.display()))?
162 .len();
163 if bytes != meta.bytes {
164 bail!(
165 "{} is {bytes} bytes, its meta says {}",
166 meta.object_key(),
167 meta.bytes
168 );
169 }
170 let sha256 = sha256_of(&local)?;
171 if sha256 != meta.sha256 {
172 bail!(
173 "{} hashes to {sha256}, its meta says {}",
174 meta.object_key(),
175 meta.sha256
176 );
177 }
178 Ok(local)
179 }
180
181 pub fn write_manifest(&self, metas: &[Meta], identity: &Identity, from: &Path) -> Result<()> {
185 let entries: Vec<serde_json::Value> = metas
186 .iter()
187 .map(|meta| {
188 serde_json::json!({
189 "kind": meta.kind.as_str(),
190 "object": meta.object_key(),
191 "sha256": meta.sha256,
192 "bytes": meta.bytes,
193 "run_attempt": meta.identity.run_attempt,
194 })
195 })
196 .collect();
197 let manifest = serde_json::json!({
198 "commit": identity.commit,
199 "run_id": identity.run_id,
200 "builder": identity.builder,
201 "artifacts": entries,
202 });
203
204 let local = from.join(crate::artifact::MANIFEST_NAME);
205 std::fs::write(&local, serde_json::to_vec_pretty(&manifest)?)
206 .with_context(|| format!("cannot write {}", local.display()))?;
207 self.s3(&[
208 "put",
209 &local.to_string_lossy(),
210 &format!(
211 "{}/{}",
212 identity.prefix(&self.bucket),
213 crate::artifact::MANIFEST_NAME
214 ),
215 ])
216 }
217}
218
219#[cfg(test)]
220mod tests;