4cf0c99a Andy McCall 24 days ago ↶
1
2
3
4
5
6
7
8
use crate :: home:: Home;
9
use anyhow:: { bail, Context, Result } ;
10
use jet:: images:: { self , Chunk, Manifest} ;
11
use std:: collections:: HashSet;
12
use std:: path:: { Path, PathBuf} ;
13
use std:: sync:: Mutex;
14
use std:: time:: { Duration, Instant} ;
15
16
17
const PARALLEL : usize = 8 ;
01043bff Andy McCall 23 days ago ↶
18
19
const ASK : usize = 20_000 ;
4cf0c99a Andy McCall 24 days ago ↶
20
21
22
pub struct Client {
b14aeaae Andy McCall 23 days ago ↶
23
root : String,
4cf0c99a Andy McCall 24 days ago ↶
24
base : String,
25
token : String,
26
agent : ureq:: Agent,
27
}
28
29
30
pub struct Moved {
31
pub chunks : usize ,
32
pub bytes : u64 ,
b14aeaae Andy McCall 23 days ago ↶
33
34
pub peer_bytes : u64 ,
4cf0c99a Andy McCall 24 days ago ↶
35
pub elapsed : Duration,
36
}
37
38
impl Client {
39
pub fn new ( hub : & str , token : & str , ca : Option< & Path> ) -> Result< Client> {
40
let tls = oxy_core:: protocol:: tls_client_config( ca) .map_err ( | e | anyhow:: anyhow! ( " {e}" ) ) ? ;
41
let agent = ureq:: AgentBuilder:: new( ) .tls_config ( tls) .timeout ( Duration:: from_secs( 120 ) ) .build ( ) ;
b14aeaae Andy McCall 23 days ago ↶
42
let root = hub.trim_end_matches ( ' /' ) .to_string ( ) ;
43
Ok ( Client { base: format! ( " {root} /api/v1" ) , root, token: token.into ( ) , agent } )
4cf0c99a Andy McCall 24 days ago ↶
44
}
45
46
fn auth ( & self ) -> String {
47
format! ( " Bearer {} " , self .token)
48
}
49
50
fn fail ( url : & str , e : ureq:: Error) -> anyhow:: Error {
51
match e {
52
ureq:: Error:: Status( code, r) => {
53
let text = r.into_string ( ) .unwrap_or_default ( ) ;
54
let detail = serde_json:: from_str:: < serde_json:: Value> ( & text)
55
.ok ( )
56
.and_then ( | v | v[ " detail" ] .as_str ( ) .map ( String :: from) )
57
.unwrap_or ( text) ;
58
anyhow:: anyhow! ( " {url}: HTTP {code}: {detail}" )
59
}
60
e => anyhow:: anyhow! ( " {url}: {e}" ) ,
61
}
62
}
63
64
65
pub fn manifest ( & self , hash : & str ) -> Result< Option< Manifest> > {
66
let url = format! ( " {} /flow/images/{hash} " , self .base) ;
67
match self .agent.get ( & url) .set ( " Authorization" , & self .auth ( ) ) .call ( ) {
68
Ok ( r) => Ok ( Some ( r.into_json ( ) ? ) ) ,
69
Err ( ureq:: Error:: Status( 404 , _ ) ) => Ok ( None ) ,
70
Err ( e) => Err ( Self :: fail( & url, e) ) ,
71
}
72
}
73
b14aeaae Andy McCall 23 days ago ↶
74
75
76
pub fn hub_identity ( & self ) -> Result< oxy_core:: identity:: Identity> {
77
let url = format! ( " {} /.well-known/oxyhub-key" , self .root) ;
78
let r = self .agent.get ( & url) .call ( ) .map_err ( | e | Self :: fail( & url, e) ) ? ;
79
let mut out = Vec :: new( ) ;
80
std:: io:: Read:: read_to_end( & mut r.into_reader ( ) , & mut out) ? ;
81
oxy_core:: identity:: Identity:: decode( & out) .map_err ( | e | anyhow:: anyhow! ( " {url}: not a hub identity: {e}" ) )
82
}
83
84
85
86
pub fn announce ( & self , hash : & str , state : & str ) -> Result< flow_core:: api:: Announced> {
87
let url = format! ( " {} /flow/swarm/announce" , self .base) ;
88
let body = flow_core:: api:: Announce { image: hash.into ( ) , state: state.into ( ) } ;
89
Ok ( self .agent.post ( & url) .set ( " Authorization" , & self .auth ( ) ) .send_json ( & body) .map_err ( | e | Self :: fail( & url, e) ) ? .into_json ( ) ? )
90
}
91
92
pub ( crate ) fn chunk ( & self , hash : & str ) -> Result< Vec< u8 > > {
4cf0c99a Andy McCall 24 days ago ↶
93
let url = format! ( " {} /flow/images/chunks/{hash} " , self .base) ;
94
let r = self .agent.get ( & url) .set ( " Authorization" , & self .auth ( ) ) .call ( ) .map_err ( | e | Self :: fail( & url, e) ) ? ;
95
let mut out = Vec :: new( ) ;
96
std:: io:: Read:: read_to_end( & mut r.into_reader ( ) , & mut out) ? ;
97
Ok ( out)
98
}
99
100
101
102
pub fn push ( & self , home : & Home, hash : & str ) -> Result< Moved> {
103
let start = Instant:: now( ) ;
104
let path = home.rootfs ( hash) ;
105
if ! path.is_file ( ) {
106
bail! ( " {} is not in this Flow home ({}); import it first" , & hash[ .. 12. min ( hash.len ( ) ) ] , path.display ( ) ) ;
107
}
108
let m = images:: scan_file( & path, home.image_arch ( hash) , | _, _| Ok ( ( ) ) ) ? ;
109
if m.hash ! = hash {
110
bail! ( " {} holds an image named {}, not {}: the file was changed" , path.display ( ) , & m.hash[ .. 12 ] , & hash[ .. 12 ] ) ;
111
}
112
let mut missing: HashSet< String> = HashSet:: new( ) ;
01043bff Andy McCall 23 days ago ↶
113
114
115
for ask in m.needed ( ) .chunks ( ASK ) {
4cf0c99a Andy McCall 24 days ago ↶
116
let url = format! ( " {} /flow/images/missing" , self .base) ;
117
let r: serde_json:: Value = self
118
.agent
119
.post ( & url)
120
.set ( " Authorization" , & self .auth ( ) )
121
.send_json ( serde_json:: json! ( { " chunks" : ask } ) )
122
.map_err ( | e | Self :: fail( & url, e) ) ?
123
.into_json ( ) ? ;
124
missing.extend ( r[ " missing" ] .as_array ( ) .into_iter ( ) .flatten ( ) .filter_map ( | h | h.as_str ( ) .map ( String :: from) ) ) ;
125
}
126
127
let ( count, bytes) = ( missing.len ( ) , Mutex:: new( 0 u64 ) ) ;
128
let queue: Mutex< Vec< ( String, Vec< u8 > ) > > = Mutex:: new( Vec :: new( ) ) ;
129
let failed: Mutex< Option< anyhow:: Error> > = Mutex:: new( None ) ;
130
let sent = Mutex:: new( HashSet:: new( ) ) ;
131
let send = | c : & str , b : & [u8 ]| -> Result< ( ) > {
132
let url = format! ( " {} /flow/images/chunks/{c} " , self .base) ;
133
self .agent.put ( & url) .set ( " Authorization" , & self .auth ( ) ) .send_bytes ( b) .map_err ( | e | Self :: fail( & url, e) ) ? ;
134
* bytes.lock ( ) .unwrap ( ) + = b.len ( ) as u64 ;
135
Ok ( ( ) )
136
} ;
137
images:: scan_file( & path, None , | c : & Chunk, b : & [u8 ]| {
138
if missing.contains ( c.hash ( ) ) & & sent.lock ( ) .unwrap ( ) .insert ( c.hash ( ) .to_string ( ) ) {
139
queue.lock ( ) .unwrap ( ) .push ( ( c.hash ( ) .to_string ( ) , b.to_vec ( ) ) ) ;
140
}
141
if queue.lock ( ) .unwrap ( ) .len ( ) > = PARALLEL * 4 {
142
let batch: Vec< _ > = std:: mem:: take( & mut * queue.lock ( ) .unwrap ( ) ) ;
143
send_batch ( & batch, & send, & failed) ;
144
}
145
match failed.lock ( ) .unwrap ( ) .take ( ) {
146
Some ( e) => Err ( images:: Error:: Bad( format! ( " {e:#} " ) ) ) ,
147
None => Ok ( ( ) ) ,
148
}
149
} ) ? ;
150
let rest: Vec< _ > = std:: mem:: take( & mut * queue.lock ( ) .unwrap ( ) ) ;
151
send_batch ( & rest, & send, & failed) ;
152
if let Some ( e) = failed.lock ( ) .unwrap ( ) .take ( ) {
153
return Err ( e) ;
154
}
155
let url = format! ( " {} /flow/images/{hash} " , self .base) ;
156
self .agent.put ( & url) .set ( " Authorization" , & self .auth ( ) ) .send_json ( & m) .map_err ( | e | Self :: fail( & url, e) ) ? ;
157
let bytes = * bytes.lock ( ) .unwrap ( ) ;
b14aeaae Andy McCall 23 days ago ↶
158
Ok ( Moved { chunks: count, bytes, peer_bytes: 0 , elapsed: start.elapsed ( ) } )
4cf0c99a Andy McCall 24 days ago ↶
159
}
160
161
162
163
164
pub fn fetch ( & self , home : & Home, hash : & str ) -> Result< Option< Moved> > {
165
let start = Instant:: now( ) ;
166
let Some ( m) = self .manifest ( hash) ? else { return Ok ( None ) } ;
167
if m.hash ! = hash {
168
bail! ( " the hub's manifest for {} names {}" , & hash[ .. 12 ] , & m.hash[ .. 12 ] ) ;
169
}
170
let cache = chunk_cache ( home) ;
b14aeaae Andy McCall 23 days ago ↶
171
save_manifest ( & home.root, & m) ? ;
4cf0c99a Andy McCall 24 days ago ↶
172
let wanted: Vec< String> = m.needed ( ) .into_iter ( ) .filter ( | h | ! cache_path ( & cache, h) .is_file ( ) ) .map ( String :: from) .collect ( ) ;
173
let ( bytes, failed) = ( Mutex:: new( 0 u64 ) , Mutex:: new( None : : < anyhow:: Error> ) ) ;
174
let next = Mutex:: new( wanted.iter ( ) ) ;
175
std:: thread:: scope( | s | {
176
for _ in 0 .. PARALLEL {
177
s.spawn ( | | loop {
178
let Some ( h) = next.lock ( ) .unwrap ( ) .next ( ) else { break } ;
179
if failed.lock ( ) .unwrap ( ) .is_some ( ) {
180
break ;
181
}
182
let got = self .chunk ( h) .and_then ( | b | {
183
if blake3:: hash( & b) .to_hex ( ) .as_str ( ) ! = h {
184
bail! ( " chunk {} came back with other bytes" , & h[ .. 12 ] ) ;
185
}
186
let p = cache_path ( & cache, h) ;
187
std:: fs:: create_dir_all( p.parent ( ) .expect ( " a chunk directory" ) ) ? ;
188
let tmp = p.with_extension ( " part" ) ;
189
std:: fs:: write( & tmp, & b) ? ;
190
std:: fs:: rename( & tmp, & p) ? ;
191
* bytes.lock ( ) .unwrap ( ) + = b.len ( ) as u64 ;
192
Ok ( ( ) )
193
} ) ;
194
if let Err ( e) = got {
195
* failed.lock ( ) .unwrap ( ) = Some ( e) ;
196
break ;
197
}
198
} ) ;
199
}
200
} ) ;
201
if let Some ( e) = failed.into_inner ( ) .unwrap ( ) {
202
return Err ( e) ;
203
}
b14aeaae Andy McCall 23 days ago ↶
204
write_image ( home, & m) ? ;
205
Ok ( Some ( Moved { chunks: wanted.len ( ) , bytes: bytes.into_inner ( ) .unwrap ( ) , peer_bytes: 0 , elapsed: start.elapsed ( ) } ) )
206
}
207
}
208
209
210
211
pub ( crate ) fn write_image ( home : & Home, m : & Manifest) -> Result< ( ) > {
212
let cache = chunk_cache ( home) ;
213
let out = home.rootfs ( & m.hash) ;
214
std:: fs:: create_dir_all( out.parent ( ) .expect ( " the cas directory" ) ) ? ;
215
images:: assemble( m, & out, | c | Ok ( std:: fs:: read( cache_path ( & cache, c.hash ( ) ) ) ? ) )
216
.with_context ( | | format! ( " write image {} " , & m.hash[ .. 12 ] ) ) ? ;
217
if let Some ( arch) = & m.arch {
218
let manifest = serde_json:: json! ( { " arch" : arch, " imported_ms" : std:: time:: SystemTime:: now( ) .duration_since ( std:: time:: UNIX_EPOCH ) .map ( | d | d.as_millis ( ) as u64 ) .unwrap_or ( 0 ) , " from" : " hub" } ) ;
219
std:: fs:: write( home.image_manifest ( & m.hash) , serde_json:: to_vec( & manifest) ? ) ? ;
4cf0c99a Andy McCall 24 days ago ↶
220
}
b14aeaae Andy McCall 23 days ago ↶
221
Ok ( ( ) )
222
}
223
224
225
226
pub ( crate ) fn manifest_path ( root : & Path, hash : & str ) -> PathBuf {
227
root.join ( " manifests" ) .join ( format! ( " {hash} .json" ) )
228
}
229
230
pub ( crate ) fn save_manifest ( root : & Path, m : & Manifest) -> Result< ( ) > {
231
let p = manifest_path ( root, & m.hash) ;
232
std:: fs:: create_dir_all( p.parent ( ) .expect ( " the manifests directory" ) ) ? ;
233
let tmp = p.with_extension ( " part" ) ;
234
std:: fs:: write( & tmp, serde_json:: to_vec( m) ? ) ? ;
235
std:: fs:: rename( & tmp, & p) ? ;
236
Ok ( ( ) )
4cf0c99a Andy McCall 24 days ago ↶
237
}
238
239
fn send_batch ( batch : & [( String , Vec <u8 >) ], send : & ( dyn Fn (&str , &[u8 ]) -> Result< ( ) > + Sync) , failed: & Mutex< Option< anyhow:: Error> > ) {
240
std:: thread:: scope( | s | {
241
for part in batch.chunks ( batch.len ( ) .div_ceil ( PARALLEL ) .max ( 1 ) ) {
242
s.spawn ( move | | {
243
for ( h, b) in part {
244
if let Err ( e) = send ( h, b) {
245
* failed.lock ( ) .unwrap ( ) = Some ( e) ;
246
return ;
247
}
248
}
249
} ) ;
250
}
251
} ) ;
252
}
253
254
255
pub fn chunk_cache ( home : & Home) -> PathBuf {
256
home.root.join ( " chunks" )
257
}
258
b14aeaae Andy McCall 23 days ago ↶
259
pub ( crate ) fn cache_path ( cache : & Path, hash : & str ) -> PathBuf {
4cf0c99a Andy McCall 24 days ago ↶
260
cache.join ( & hash[ .. 2 ] ) .join ( hash)
261
}
262
263
264
pub fn human ( bytes : u64 ) -> String {
265
if bytes > = 1 < < 30 {
266
format! ( " {:.1} GiB" , bytes as f64 / ( 1 u64 < < 30 ) as f64 )
267
} else {
268
format! ( " {} MiB" , bytes > > 20 )
269
}
270
}