| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | | use crate::db::{now_ms, Pool}; |
| 10 | | use jet::images::{is_hash, Manifest}; |
| 11 | | use std::io::Write; |
| 12 | | use std::path::{Path, PathBuf}; |
| 13 | |
|
| 14 | |
|
| 15 | | #[derive(Clone, Debug)] |
| 16 | | pub struct Store { |
| 17 | | root: PathBuf, |
| 18 | | } |
| 19 | |
|
| 20 | | impl Store { |
| 21 | 24× | pub fn new(data: &Path) -> Store { |
| 22 | 24× | Store { root: data.join("images") } |
| 23 | 24× | } |
| 24 | |
|
| 25 | 60036× | fn chunk_path(&self, hash: &str) -> PathBuf { |
| 26 | 60036× | self.root.join("chunks").join(&hash[..2]).join(hash) |
| 27 | 60036× | } |
| 28 | |
|
| 29 | 11× | fn manifest_path(&self, hash: &str) -> PathBuf { |
| 30 | 11× | self.root.join("manifests").join(format!("{hash}.json")) |
| 31 | 11× | } |
| 32 | |
|
| 33 | 60006× | pub fn has_chunk(&self, hash: &str) -> bool { |
| 34 | 60006× | is_hash(hash) && self.chunk_path(hash).exists() |
| 35 | 60006× | } |
| 36 | |
|
| 37 | | |
| 38 | 8× | pub fn put_chunk(&self, hash: &str, bytes: &[u8]) -> std::io::Result<()> { |
| 39 | 8× | let path = self.chunk_path(hash); |
| 40 | 8× | if path.exists() { |
| 41 | 0× | return Ok(()); |
| 42 | 8× | } |
| 43 | 8× | std::fs::create_dir_all(path.parent().expect("a chunk's directory"))?; |
| 44 | 8× | let tmp = path.with_extension(format!("tmp{}", std::process::id())); |
| 45 | 8× | let mut f = std::fs::File::create(&tmp)?; |
| 46 | 8× | f.write_all(&zstd::encode_all(bytes, 3)?)?; |
| 47 | 8× | f.sync_all()?; |
| 48 | 8× | std::fs::rename(&tmp, &path) |
| 49 | 8× | } |
| 50 | |
|
| 51 | 22× | pub fn chunk(&self, hash: &str) -> std::io::Result<Vec<u8>> { |
| 52 | 22× | if !is_hash(hash) { |
| 53 | 0× | return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "not a chunk name")); |
| 54 | 22× | } |
| 55 | 22× | zstd::decode_all(std::fs::File::open(self.chunk_path(hash))?) |
| 56 | 22× | } |
| 57 | |
|
| 58 | 6× | pub fn manifest(&self, hash: &str) -> Option<Manifest> { |
| 59 | 6× | if !is_hash(hash) { |
| 60 | 0× | return None; |
| 61 | 6× | } |
| 62 | 6× | serde_json::from_slice(&std::fs::read(self.manifest_path(hash)).ok()?).ok() |
| 63 | 6× | } |
| 64 | |
|
| 65 | | |
| 66 | | |
| 67 | 5× | pub fn verify_and_keep(&self, m: &Manifest) -> Result<(), String> { |
| 68 | 5× | m.check().map_err(|e| e.to_string())?; |
| 69 | 5× | let mut whole = blake3::Hasher::new(); |
| 70 | 55× | for c in &m.chunks { |
| 71 | 55× | if c.is_zeros() { |
| 72 | 43× | whole.update(&vec![0u8; c.len()]); |
| 73 | 43× | continue; |
| 74 | 12× | } |
| 75 | 12× | let bytes = self.chunk(c.hash()).map_err(|_| format!("chunk {} was not sent; send it first", &c.hash()[..12]))?; |
| 76 | 11× | if bytes.len() != c.len() { |
| 77 | 0× | return Err(format!("chunk {} is {} bytes, not {}", &c.hash()[..12], bytes.len(), c.len())); |
| 78 | 11× | } |
| 79 | 11× | whole.update(&bytes); |
| 80 | | } |
| 81 | 4× | let got = whole.finalize().to_hex().to_string(); |
| 82 | 4× | if got != m.hash { |
| 83 | 1× | return Err(format!("the chunks make an image named {}, not {}", &got[..12], &m.hash[..12])); |
| 84 | 3× | } |
| 85 | 3× | self.keep_manifest(m) |
| 86 | 5× | } |
| 87 | |
|
| 88 | | |
| 89 | 5× | fn keep_manifest(&self, m: &Manifest) -> Result<(), String> { |
| 90 | 5× | let path = self.manifest_path(&m.hash); |
| 91 | 5× | std::fs::create_dir_all(path.parent().expect("the manifests directory")).map_err(|e| e.to_string())?; |
| 92 | 5× | let tmp = path.with_extension("json.tmp"); |
| 93 | 5× | std::fs::write(&tmp, serde_json::to_vec(m).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?; |
| 94 | 5× | std::fs::rename(&tmp, &path).map_err(|e| e.to_string()) |
| 95 | 5× | } |
| 96 | |
|
| 97 | | |
| 98 | | |
| 99 | | |
| 100 | | |
| 101 | 5× | pub fn read_arch(&self, m: &Manifest) -> Option<&'static str> { |
| 102 | 5× | let mut starts = Vec::with_capacity(m.chunks.len()); |
| 103 | 5× | let mut end = 0u64; |
| 104 | 78× | for c in &m.chunks { |
| 105 | 78× | starts.push(end); |
| 106 | 78× | end += c.len() as u64; |
| 107 | 78× | } |
| 108 | 5× | let mut cache: std::collections::HashMap<usize, Vec<u8>> = std::collections::HashMap::new(); |
| 109 | 5× | let short = || std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "past the image's end"); |
| 110 | 31× | jet::rootfs::arch(&mut |at: u64, buf: &mut [u8]| { |
| 111 | 31× | let mut done = 0usize; |
| 112 | 62× | while done < buf.len() { |
| 113 | 31× | let pos = at + done as u64; |
| 114 | 177× | let i = starts.partition_point(|&s| s <= pos).checked_sub(1).ok_or_else(short)?; |
| 115 | 31× | let c = &m.chunks[i]; |
| 116 | 31× | let within = (pos - starts[i]) as usize; |
| 117 | 31× | if within >= c.len() { |
| 118 | 0× | return Err(short()); |
| 119 | 31× | } |
| 120 | 31× | let n = (c.len() - within).min(buf.len() - done); |
| 121 | 31× | if c.is_zeros() { |
| 122 | 0× | buf[done..done + n].fill(0); |
| 123 | 0× | } else { |
| 124 | 31× | if !cache.contains_key(&i) { |
| 125 | 7× | if cache.len() >= 32 { |
| 126 | 0× | cache.clear(); |
| 127 | 7× | } |
| 128 | 7× | cache.insert(i, self.chunk(c.hash())?); |
| 129 | 24× | } |
| 130 | 31× | let bytes = &cache[&i]; |
| 131 | 31× | if bytes.len() != c.len() { |
| 132 | 0× | return Err(short()); |
| 133 | 31× | } |
| 134 | 31× | buf[done..done + n].copy_from_slice(&bytes[within..within + n]); |
| 135 | | } |
| 136 | 31× | done += n; |
| 137 | | } |
| 138 | 31× | Ok(()) |
| 139 | 31× | }) |
| 140 | 5× | } |
| 141 | |
|
| 142 | | |
| 143 | | |
| 144 | | |
| 145 | 5× | pub fn keep_reading_arch(&self, m: &Manifest) -> Result<Manifest, String> { |
| 146 | 5× | self.verify_and_keep(m)?; |
| 147 | 3× | match self.read_arch(m) { |
| 148 | 1× | Some(a) if m.arch.as_deref() != Some(a) => { |
| 149 | 1× | let mut kept = m.clone(); |
| 150 | 1× | kept.arch = Some(a.to_string()); |
| 151 | 1× | self.keep_manifest(&kept)?; |
| 152 | 1× | Ok(kept) |
| 153 | | } |
| 154 | 2× | _ => Ok(m.clone()), |
| 155 | | } |
| 156 | 5× | } |
| 157 | |
|
| 158 | | |
| 159 | 1× | fn set_arch(&self, hash: &str, arch: &str) -> Result<(), String> { |
| 160 | 1× | let mut m = self.manifest(hash).ok_or("no such image")?; |
| 161 | 1× | m.arch = Some(arch.to_string()); |
| 162 | 1× | self.keep_manifest(&m) |
| 163 | 1× | } |
| 164 | | } |
| 165 | |
|
| 166 | |
|
| 167 | 3× | pub async fn record(pool: &Pool, m: &Manifest, uploader: &str) -> sqlx::Result<()> { |
| 168 | 3× | sqlx::query( |
| 169 | 3× | "INSERT INTO jet_images (hash, size, arch, chunks, uploader, created_ms) VALUES ($1, $2, $3, $4, $5, $6) \ |
| 170 | 3× | ON CONFLICT (hash) DO UPDATE SET arch = excluded.arch WHERE excluded.arch != ''", |
| 171 | 3× | ) |
| 172 | 3× | .bind(&m.hash) |
| 173 | 3× | .bind(m.size as i64) |
| 174 | 3× | .bind(m.arch.clone().unwrap_or_default()) |
| 175 | 3× | .bind(m.chunks.len() as i64) |
| 176 | 3× | .bind(uploader) |
| 177 | 3× | .bind(now_ms()) |
| 178 | 3× | .execute(pool) |
| 179 | 3× | .await?; |
| 180 | 3× | if let Some(a) = m.arch.as_ref().filter(|a| !a.is_empty()) { |
| 181 | 2× | crate::db::flow::record_image_archs(pool, &[(m.hash.clone(), a.clone())].into_iter().collect()).await?; |
| 182 | 1× | } |
| 183 | 3× | Ok(()) |
| 184 | 3× | } |
| 185 | |
|
| 186 | |
|
| 187 | |
|
| 188 | |
|
| 189 | |
|
| 190 | |
|
| 191 | 188× | pub async fn learn_archs(app: &crate::Shared) -> sqlx::Result<usize> { |
| 192 | 188× | let mut read = 0; |
| 193 | 188× | for k in kept(&app.db).await?.into_iter().filter(|k| k.arch.is_empty()) { |
| 194 | 2× | let store = app.images(); |
| 195 | 2× | let hash = k.hash.clone(); |
| 196 | 2× | let arch = tokio::task::spawn_blocking(move || { |
| 197 | 2× | let a = store.read_arch(&store.manifest(&hash)?)?; |
| 198 | 1× | store.set_arch(&hash, a).ok()?; |
| 199 | 1× | Some(a) |
| 200 | 2× | }) |
| 201 | 2× | .await |
| 202 | 2× | .ok() |
| 203 | 2× | .flatten(); |
| 204 | 2× | if let Some(a) = arch { |
| 205 | 1× | sqlx::query("UPDATE jet_images SET arch = $1 WHERE hash = $2").bind(a).bind(&k.hash).execute(&app.db).await?; |
| 206 | 1× | crate::db::flow::record_image_archs(&app.db, &[(k.hash.clone(), a.to_string())].into_iter().collect()).await?; |
| 207 | 1× | read += 1; |
| 208 | 1× | } |
| 209 | | } |
| 210 | 188× | crate::db::flow::learn_archs_from_runs(&app.db).await?; |
| 211 | 188× | Ok(read) |
| 212 | 188× | } |
| 213 | |
|
| 214 | |
|
| 215 | 374× | pub async fn held(pool: &Pool) -> sqlx::Result<std::collections::HashSet<String>> { |
| 216 | 374× | Ok(sqlx::query_scalar::<_, String>("SELECT hash FROM jet_images").fetch_all(pool).await?.into_iter().collect()) |
| 217 | 374× | } |
| 218 | |
|
| 219 | |
|
| 220 | | #[derive(sqlx::FromRow)] |
| 221 | | pub struct Kept { |
| 222 | | pub hash: String, |
| 223 | | pub size: i64, |
| 224 | | pub arch: String, |
| 225 | | pub chunks: i64, |
| 226 | | pub uploader: String, |
| 227 | | pub created_ms: i64, |
| 228 | | } |
| 229 | |
|
| 230 | 191× | pub async fn kept(pool: &Pool) -> sqlx::Result<Vec<Kept>> { |
| 231 | 191× | sqlx::query_as("SELECT hash, size, arch, chunks, uploader, created_ms FROM jet_images").fetch_all(pool).await |
| 232 | 191× | } |
| 233 | |
|
| 234 | |
|
| 235 | |
|
| 236 | | #[derive(sqlx::FromRow)] |
| 237 | | pub struct Use { |
| 238 | | pub image: String, |
| 239 | | pub owner: String, |
| 240 | | pub name: String, |
| 241 | | pub jobs: i64, |
| 242 | | pub last_ms: i64, |
| 243 | | } |
| 244 | |
|
| 245 | |
|
| 246 | 2× | pub async fn uses(pool: &Pool, since_ms: i64) -> sqlx::Result<Vec<Use>> { |
| 247 | 2× | let rootfs = crate::db::json_text("j.sandbox", "rootfs"); |
| 248 | 2× | sqlx::query_as(&format!( |
| 249 | 2× | "SELECT lower({rootfs}) AS image, p.owner, p.name, COUNT(*) AS jobs, |
| 250 | 2× | MAX(COALESCE(j.started_ms, r.created_ms)) AS last_ms |
| 251 | 2× | FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories p ON p.id = r.repo_id |
| 252 | 2× | WHERE r.created_ms >= $1 AND COALESCE({rootfs}, '') != '' |
| 253 | 2× | GROUP BY lower({rootfs}), p.id, p.owner, p.name ORDER BY last_ms DESC" |
| 254 | 2× | )) |
| 255 | 2× | .bind(since_ms) |
| 256 | 2× | .fetch_all(pool) |
| 257 | 2× | .await |
| 258 | 2× | } |
| 259 | |
|
| 260 | |
|
| 261 | |
|
| 262 | 1× | pub async fn uses_of(pool: &Pool, repo_id: i64, since_ms: i64) -> sqlx::Result<Vec<Use>> { |
| 263 | 1× | let rootfs = crate::db::json_text("j.sandbox", "rootfs"); |
| 264 | 1× | sqlx::query_as(&format!( |
| 265 | 1× | "SELECT lower({rootfs}) AS image, p.owner, p.name, COUNT(*) AS jobs, |
| 266 | 1× | MAX(COALESCE(j.started_ms, r.created_ms)) AS last_ms |
| 267 | 1× | FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories p ON p.id = r.repo_id |
| 268 | 1× | WHERE r.created_ms >= $1 AND p.id = $2 AND COALESCE({rootfs}, '') != '' |
| 269 | 1× | GROUP BY lower({rootfs}), p.id, p.owner, p.name ORDER BY last_ms DESC" |
| 270 | 1× | )) |
| 271 | 1× | .bind(since_ms) |
| 272 | 1× | .bind(repo_id) |
| 273 | 1× | .fetch_all(pool) |
| 274 | 1× | .await |
| 275 | 1× | } |
| 276 | |
|
| 277 | |
|
| 278 | 2× | pub async fn reported_archs(pool: &Pool) -> sqlx::Result<std::collections::HashMap<String, String>> { |
| 279 | 2× | Ok(sqlx::query_as::<_, (String, String)>("SELECT hash, arch FROM flow_images").fetch_all(pool).await?.into_iter().collect()) |
| 280 | 2× | } |