-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathimage.rs
More file actions
285 lines (242 loc) · 9.25 KB
/
Copy pathimage.rs
File metadata and controls
285 lines (242 loc) · 9.25 KB
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
use std::{collections::BTreeMap, io::IsTerminal};
use secrecy::{ExposeSecret, SecretString};
use serde::Serialize;
use snafu::{ResultExt, Snafu};
use crate::{
cli::{Format, ImageCheckArguments, ImageListArguments, ImageSizeArguments, Pretty},
config::Config,
core::bakefile::{self, Targets, TargetsOptions},
models::{Manifest, TagList},
utils::{
format_image_index_manifest_tag, format_image_manifest_tag,
format_registry_token_env_var_name,
},
};
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("failed to serialize list as JSON"))]
SerializeList { source: serde_json::Error },
#[snafu(display("failed to build list of targets"))]
BuildTargets { source: bakefile::TargetsError },
#[snafu(display("failed to build request client"))]
BuildClient { source: reqwest::Error },
#[snafu(display("failed to send request ({url})"))]
SendRequest { source: reqwest::Error, url: String },
#[snafu(display("failed to deserialize response"))]
DeserializeResponse { source: reqwest::Error },
#[snafu(display("missing images found: \n {missing_images}", missing_images = missing_images.join("\n")))]
MissingVersion { missing_images: Vec<String> },
}
/// This is the `boil show images` command handler function.
pub fn list_images(arguments: ImageListArguments) -> Result<(), Error> {
let targets = if arguments.image.is_empty() {
Targets::all(TargetsOptions {
only_entry: true,
non_recursive: false,
})
.context(BuildTargetsSnafu)?
} else {
Targets::set(
&arguments.image,
TargetsOptions {
only_entry: true,
non_recursive: false,
},
)
.context(BuildTargetsSnafu)?
};
let list: BTreeMap<String, Vec<String>> = targets
.into_iter()
.map(|(image_name, (image_config, _))| {
let versions: Vec<_> = image_config
.versions
.into_iter()
.map(|(image_version, _)| image_version)
.collect();
(image_name, versions)
})
.collect();
serialize_to_stdout(list, arguments.pretty)
}
pub async fn check_images(arguments: ImageCheckArguments, config: Config) -> Result<(), Error> {
let targets = if arguments.image.is_empty() {
Targets::all(TargetsOptions {
only_entry: true,
non_recursive: true,
})
.context(BuildTargetsSnafu)?
} else {
Targets::set(
&arguments.image,
TargetsOptions {
only_entry: true,
non_recursive: true,
},
)
.context(BuildTargetsSnafu)?
};
let mut registry_tokens = BTreeMap::new();
let client = reqwest::ClientBuilder::new()
.build()
.context(BuildClientSnafu)?;
let mut missing_images = Vec::new();
for (image_name, (image_config, _)) in targets {
for (registry, registry_options) in image_config.metadata.registries {
// Add tokens to a map so that we don't need construct the key and retrieve the value
// over and over again.
let registry_token = registry_tokens.entry(registry.clone()).or_insert_with(|| {
let name = format_registry_token_env_var_name(®istry);
std::env::var(name).ok().map(SecretString::from)
});
println!(
"Checking {registry}/{registry_namespace}/{image_name}",
registry_namespace = registry_options.namespace,
);
let url = format!(
"https://{registry}/v2/{registry_namespace}/{image_name}/tags/list",
registry_namespace = registry_options.namespace,
);
let request = client.get(&url);
let request = match ®istry_token {
Some(registry_token) => request.bearer_auth(registry_token.expose_secret()),
None => request,
};
let tag_list: TagList = request
.send()
.await
.context(SendRequestSnafu { url })?
.json()
.await
.context(DeserializeResponseSnafu)?;
for (image_version, _) in image_config.versions.iter() {
let index_manifest_tag = format_image_index_manifest_tag(
image_version,
&config.metadata.vendor_tag_prefix,
&arguments.image_version,
);
let image_identifier = format!("{image_name}:{index_manifest_tag}");
println!("- {image_identifier}");
if !tag_list.tags.contains(&index_manifest_tag) {
missing_images.push(image_identifier);
}
}
}
}
if !missing_images.is_empty() {
return MissingVersionSnafu { missing_images }.fail();
}
Ok(())
}
pub async fn calculate_size(arguments: ImageSizeArguments, config: Config) -> Result<(), Error> {
let targets = if arguments.image.is_empty() {
Targets::all(TargetsOptions {
only_entry: true,
non_recursive: true,
})
.context(BuildTargetsSnafu)?
} else {
Targets::set(
&arguments.image,
TargetsOptions {
only_entry: true,
non_recursive: true,
},
)
.context(BuildTargetsSnafu)?
};
let mut registry_tokens = BTreeMap::new();
let client = reqwest::ClientBuilder::new()
.build()
.context(BuildClientSnafu)?;
#[derive(Serialize)]
struct SizeResult {
images: BTreeMap<String, u64>,
total: u64,
}
let mut result = SizeResult {
images: BTreeMap::new(),
total: 0,
};
for (image_name, (image_config, _)) in targets {
for (registry, registry_options) in image_config.metadata.registries {
// Add tokens to a map so that we don't need construct the key and retrieve the value
// over and over again.
let registry_token = registry_tokens.entry(registry.clone()).or_insert_with(|| {
let name = format_registry_token_env_var_name(®istry);
std::env::var(name).ok().map(SecretString::from)
});
for (image_version, _) in image_config.versions.iter() {
let image_index_manifest_tag = format_image_index_manifest_tag(
image_version,
&config.metadata.vendor_tag_prefix,
&arguments.vendor_version,
);
let manifest_tag = format_image_manifest_tag(
&image_index_manifest_tag,
arguments.target_platform.architecture(),
// Never strip the architecture, because we need to reference the exact manifest
// to be able to calculate the sizes
false,
);
let url = format!(
"https://{registry}/v2/{registry_namespace}/{image_name}/manifests/{manifest_tag}",
registry_namespace = registry_options.namespace,
);
let request = client.get(&url);
let request = match ®istry_token {
Some(registry_token) => request.bearer_auth(registry_token.expose_secret()),
None => request,
};
let manifest: Manifest = request
.send()
.await
.context(SendRequestSnafu { url })?
.json()
.await
.context(DeserializeResponseSnafu)?;
let layer_size = manifest.layers.iter().fold(0u64, |acc, e| acc + e.size);
let size = result.images.entry(image_name.clone()).or_default();
*size += layer_size;
result.total += layer_size;
}
}
}
match arguments.format {
Format::Plain => {
if let Some(max_width) = result
.images
.iter()
.map(|i| i.0.len())
.max_by(|lhs, rhs| lhs.cmp(rhs))
{
// let sorted = result.images;
for (image, size) in result.images {
println!(
"{image:max_width$} {size}",
size = humansize::format_size(size, humansize::BINARY)
);
}
println!(
"{total_text:max_width$} {total}",
total_text = "Total",
total = humansize::format_size(result.total, humansize::BINARY)
)
}
Ok(())
}
Format::Json => serialize_to_stdout(&result, arguments.pretty),
}
}
fn serialize_to_stdout<T>(value: T, pretty: Pretty) -> Result<(), Error>
where
T: Serialize,
{
let stdout = std::io::stdout();
match pretty {
Pretty::Always | Pretty::Auto if stdout.is_terminal() => {
serde_json::to_writer_pretty(stdout, &value)
}
_ => serde_json::to_writer(stdout, &value),
}
.context(SerializeListSnafu)
}