1use crate::config::RegistryConfig;
2use crate::error::Result;
3use crate::storage::{create_storage, ManifestEntry, Storage};
4use axum::{
5 body::Bytes,
6 extract::{Path, Query, State},
7 http::{HeaderMap, StatusCode},
8 response::{IntoResponse, Json},
9 routing::{get, head, patch, post, put},
10 Router,
11};
12use serde::{Deserialize, Serialize};
13use sha2::{Digest, Sha256};
14use std::net::SocketAddr;
15use std::sync::Arc;
16use tokio::net::TcpListener;
17use tower_http::trace::TraceLayer;
18use tracing::{debug, info, warn};
19
20fn strip_leading_slash(s: &str) -> &str {
21 s.strip_prefix('/').unwrap_or(s)
22}
23
24type SharedStorage = Arc<dyn Storage>;
25
26#[derive(Clone)]
27struct AppState {
28 storage: SharedStorage,
29}
30
31#[derive(Serialize)]
32struct ApiVersion {
33 version: String,
34}
35
36#[derive(Deserialize)]
37struct UploadParams {
38 digest: Option<String>,
39}
40
41pub struct RegistryServer {
42 addr: SocketAddr,
43 _handle: tokio::task::JoinHandle<()>,
44}
45
46impl RegistryServer {
47 pub async fn new(config: RegistryConfig) -> Result<Self> {
48 let storage = create_storage(&config.storage).await?;
49
50 let state = AppState { storage };
51
52 let app = Router::new()
53 .route("/v2/", get(api_version))
54 .route("/v2/{name}/blobs/{digest}", head(check_blob))
55 .route("/v2/{name}/blobs/{digest}", get(get_blob))
56 .route("/v2/{name}/blobs/uploads/", post(start_upload))
57 .route("/v2/{name}/blobs/uploads/{uuid}", patch(upload_chunk))
58 .route("/v2/{name}/blobs/uploads/{uuid}", put(finish_upload))
59 .route("/v2/{name}/manifests/{reference}", put(put_manifest))
60 .route("/v2/{name}/manifests/{reference}", get(get_manifest))
61 .route("/v2/{name}/manifests/{reference}", head(check_manifest))
62 .layer(
63 tower::ServiceBuilder::new()
64 .layer(axum::extract::DefaultBodyLimit::max(512 * 1024 * 1024))
65 .layer(TraceLayer::new_for_http()),
66 )
67 .with_state(state);
68
69 let bind_addr = if let Some(port) = config.port {
70 format!("{}:{}", config.host, port)
71 } else {
72 format!("{}:0", config.host)
73 };
74
75 let listener = TcpListener::bind(&bind_addr).await?;
76 let addr = listener.local_addr()?;
77
78 info!("Registry listening on {}", addr);
79
80 let handle = tokio::spawn(async move {
81 axum::serve(listener, app).await.ok();
82 });
83
84 Ok(Self {
85 addr,
86 _handle: handle,
87 })
88 }
89
90 pub fn addr(&self) -> SocketAddr {
91 self.addr
92 }
93
94 pub fn url(&self) -> String {
95 format!("http://{}", self.addr)
96 }
97
98 pub fn port(&self) -> u16 {
99 self.addr.port()
100 }
101}
102
103async fn api_version() -> Json<ApiVersion> {
104 Json(ApiVersion {
105 version: "registry/2.0".to_string(),
106 })
107}
108
109async fn check_blob(
110 State(state): State<AppState>,
111 Path((name, digest)): Path<(String, String)>,
112) -> impl IntoResponse {
113 let name = strip_leading_slash(&name);
114 info!("Checking blob: {}/{}", name, digest);
115
116 match state.storage.get_blob(&digest).await {
117 Ok(Some(blob)) => (StatusCode::OK, [("Content-Length", blob.len().to_string())]),
118 _ => (StatusCode::NOT_FOUND, [("Content-Length", "0".to_string())]),
119 }
120}
121
122async fn get_blob(
123 State(state): State<AppState>,
124 Path((name, digest)): Path<(String, String)>,
125) -> impl IntoResponse {
126 let name = strip_leading_slash(&name);
127 info!("Getting blob: {}/{}", name, digest);
128
129 match state.storage.get_blob(&digest).await {
130 Ok(Some(blob)) => (StatusCode::OK, blob),
131 _ => (StatusCode::NOT_FOUND, vec![]),
132 }
133}
134
135async fn start_upload(
136 Path(name): Path<String>,
137 State(state): State<AppState>,
138) -> impl IntoResponse {
139 let name = strip_leading_slash(&name);
140 let uuid = uuid::Uuid::new_v4().to_string();
141 info!("Starting upload: {} ({})", name, uuid);
142
143 if let Err(e) = state.storage.create_upload(uuid.clone()).await {
144 warn!("Failed to create upload: {}", e);
145 return (
146 StatusCode::INTERNAL_SERVER_ERROR,
147 [("Location", String::new())],
148 );
149 }
150
151 (
152 StatusCode::ACCEPTED,
153 [("Location", format!("/v2/{}/blobs/uploads/{}", name, uuid))],
154 )
155}
156
157async fn upload_chunk(
158 State(state): State<AppState>,
159 Path((name, uuid)): Path<(String, String)>,
160 body: Bytes,
161) -> impl IntoResponse {
162 let name = strip_leading_slash(&name);
163 debug!("Uploading chunk: {}/{} ({} bytes)", name, uuid, body.len());
164
165 match state.storage.append_upload(&uuid, &body).await {
166 Ok(_) => {
167 let end = body.len().saturating_sub(1);
168 (
169 StatusCode::ACCEPTED,
170 [
171 ("Location", format!("/v2/{}/blobs/uploads/{}", name, uuid)),
172 ("Range", format!("0-{}", end)),
173 ("Docker-Upload-UUID", uuid),
174 ],
175 )
176 }
177 Err(_) => {
178 warn!("Upload not found: {}", uuid);
179 (
180 StatusCode::NOT_FOUND,
181 [
182 ("Location", String::new()),
183 ("Range", String::new()),
184 ("Docker-Upload-UUID", String::new()),
185 ],
186 )
187 }
188 }
189}
190
191async fn finish_upload(
192 State(state): State<AppState>,
193 Path((name, uuid)): Path<(String, String)>,
194 Query(params): Query<UploadParams>,
195 headers: HeaderMap,
196 body: Bytes,
197) -> impl IntoResponse {
198 let name = strip_leading_slash(&name);
199 debug!("Finishing upload: {}/{}", name, uuid);
200
201 let upload_data = match state.storage.finish_upload(&uuid).await {
202 Ok(Some(mut data)) => {
203 data.extend_from_slice(&body);
204 data
205 }
206 _ => {
207 warn!("Upload not found: {}", uuid);
208 return (
209 StatusCode::NOT_FOUND,
210 [
211 ("Location", String::new()),
212 ("Docker-Content-Digest", String::new()),
213 ],
214 );
215 }
216 };
217
218 let digest_str = params
219 .digest
220 .or_else(|| {
221 headers
222 .get("digest")
223 .or_else(|| headers.get("Docker-Content-Digest"))
224 .and_then(|v| v.to_str().ok())
225 .map(|s| s.to_string())
226 })
227 .unwrap_or_else(|| {
228 let mut hasher = Sha256::new();
229 hasher.update(&upload_data);
230 format!("sha256:{}", hex::encode(hasher.finalize()))
231 });
232
233 if let Err(e) = state
234 .storage
235 .store_blob(digest_str.clone(), upload_data)
236 .await
237 {
238 warn!("Failed to store blob: {}", e);
239 return (
240 StatusCode::INTERNAL_SERVER_ERROR,
241 [
242 ("Location", String::new()),
243 ("Docker-Content-Digest", String::new()),
244 ],
245 );
246 }
247
248 info!("Stored blob: {}", digest_str);
249
250 (
251 StatusCode::CREATED,
252 [
253 ("Location", format!("/v2/{}/blobs/{}", name, digest_str)),
254 ("Docker-Content-Digest", digest_str),
255 ],
256 )
257}
258
259async fn put_manifest(
260 State(state): State<AppState>,
261 Path((name, reference)): Path<(String, String)>,
262 headers: HeaderMap,
263 body: Bytes,
264) -> impl IntoResponse {
265 let name = strip_leading_slash(&name);
266 info!("Putting manifest: {}/{}", name, reference);
267
268 let content_type = headers
269 .get("content-type")
270 .and_then(|v| v.to_str().ok())
271 .unwrap_or("application/vnd.docker.distribution.manifest.v2+json")
272 .to_string();
273
274 let mut hasher = Sha256::new();
275 hasher.update(&body);
276 let digest = format!("sha256:{}", hex::encode(hasher.finalize()));
277
278 let entry = ManifestEntry {
279 data: body.to_vec(),
280 content_type: content_type.clone(),
281 };
282
283 let key = format!("{}:{}", name, reference);
284 let digest_key = format!("{}:{}", name, digest);
285
286 if let Err(e) = state.storage.store_manifest(key, entry.clone()).await {
287 warn!("Failed to store manifest: {}", e);
288 return (
289 StatusCode::INTERNAL_SERVER_ERROR,
290 [
291 ("Location", String::new()),
292 ("Content-Type", String::new()),
293 ("Docker-Content-Digest", String::new()),
294 ],
295 );
296 }
297
298 if let Err(e) = state.storage.store_manifest(digest_key, entry).await {
299 warn!("Failed to store manifest by digest: {}", e);
300 }
301
302 info!(
303 "Stored manifest with digest: {} (type: {})",
304 digest, content_type
305 );
306
307 (
308 StatusCode::CREATED,
309 [
310 ("Location", format!("/v2/{}/manifests/{}", name, reference)),
311 ("Content-Type", content_type),
312 ("Docker-Content-Digest", digest),
313 ],
314 )
315}
316
317async fn get_manifest(
318 State(state): State<AppState>,
319 Path((name, reference)): Path<(String, String)>,
320) -> impl IntoResponse {
321 let name = strip_leading_slash(&name);
322 info!("Getting manifest: {}/{}", name, reference);
323
324 let key = format!("{}:{}", name, reference);
325
326 match state.storage.get_manifest(&key).await {
327 Ok(Some(entry)) => (
328 StatusCode::OK,
329 [("Content-Type", entry.content_type)],
330 entry.data,
331 ),
332 _ => (
333 StatusCode::NOT_FOUND,
334 [("Content-Type", "text/plain".to_string())],
335 vec![],
336 ),
337 }
338}
339
340async fn check_manifest(
341 State(state): State<AppState>,
342 Path((name, reference)): Path<(String, String)>,
343) -> impl IntoResponse {
344 let name = strip_leading_slash(&name);
345 info!("Checking manifest: {}/{}", name, reference);
346
347 let key = format!("{}:{}", name, reference);
348
349 match state.storage.get_manifest(&key).await {
350 Ok(Some(entry)) => {
351 let mut hasher = Sha256::new();
352 hasher.update(&entry.data);
353 let digest = format!("sha256:{}", hex::encode(hasher.finalize()));
354
355 (
356 StatusCode::OK,
357 [
358 ("Content-Type", entry.content_type),
359 ("Docker-Content-Digest", digest),
360 ],
361 )
362 }
363 _ => (
364 StatusCode::NOT_FOUND,
365 [
366 ("Content-Type", "text/plain".to_string()),
367 ("Docker-Content-Digest", String::new()),
368 ],
369 ),
370 }
371}