1use std::fmt;
7use std::path::PathBuf;
8
9use crate::model::Target;
10use crate::profile::ProfileProblem;
11use crate::syntax::Problem;
12
13#[derive(Debug, thiserror::Error)]
15#[non_exhaustive]
16pub enum Error {
17 #[error("no isoloom.yml in {}", .0.display())]
19 NotFound(PathBuf),
20 #[error("both isoloom.yml and isoloom.yaml exist in {}; keep one", .0.display())]
22 Ambiguous(PathBuf),
23 #[error("can't read {}: {source}", path.display())]
25 Read {
26 path: PathBuf,
28 #[source]
30 source: std::io::Error,
31 },
32 #[error("{0}")]
35 Yaml(#[from] serde_yaml_ng::Error),
36 #[error("{}", Rendered { file, problems })]
38 Invalid {
39 file: String,
41 problems: Vec<Problem>,
43 },
44 #[error("`-s {set}`: expected key=value, like -s machines.web.vm.os=ubuntu@24.04")]
46 SetShape {
47 set: String,
49 },
50 #[error("`-s {set}`: the key is a dotted path, like cloud.aws.region")]
52 SetKey {
53 set: String,
55 },
56 #[error("`{value}` isn't a valid {what}: {rule}")]
58 Name {
59 what: &'static str,
61 value: String,
63 rule: &'static str,
65 },
66 #[error("unknown OS `{text}`; write `<family>@<version>` with one of: {known}")]
68 UnknownOs {
69 text: String,
71 known: String,
73 },
74 #[error("{family} has no version `{version}`; use one of: {known} (`{family}` alone is {family}@{default})")]
76 UnknownOsVersion {
77 family: &'static str,
79 version: String,
81 known: String,
83 default: &'static str,
85 },
86 #[error("`{{{{ {path} }}}}` isn't a placeholder Isoloom knows: {why}")]
88 Placeholder {
89 path: String,
91 why: &'static str,
93 },
94 #[error("a `{{{{` without its `}}}}`")]
96 Unclosed,
97 #[error("`{{{{ {reference} }}}}`: {why}")]
99 NotHere {
100 reference: crate::syntax::placeholder::Reference,
102 why: &'static str,
104 },
105 #[error("`{0}` isn't a file mode: octal digits up to 0777, like \"0444\"")]
107 Mode(String),
108 #[error("`service` and `app` are both given: a machine is a catalogue service or a custom app")]
110 ServiceAndApp,
111 #[error("`with` sets a catalogue service's settings: it goes with `service`")]
113 WithWithoutService,
114 #[error("`config` is an appliance's: it goes with `appliance`")]
116 ConfigWithoutAppliance,
117 #[error("an appliance comes from its `image` (or `firmware`), not a `build`")]
119 ApplianceBuild,
120 #[error("`firmware` is `cisco-dynamips`'s: it goes with `appliance: cisco-dynamips`")]
122 FirmwareWithoutDynamips,
123 #[error("an app needs a recipe: `image`, `build`, `steps` or `appliance`")]
125 NoRecipe,
126 #[error("`cisco-dynamips` boots its `firmware`; Isoloom builds its image, so no `image`")]
128 DynamipsImage,
129 #[error("`cisco-dynamips` needs the `firmware` it boots (the IOS `.bin`)")]
131 DynamipsFirmware,
132 #[error("`firmware` is `cisco-dynamips`'s; this appliance runs its `image`")]
134 ApplianceFirmware,
135 #[error("an appliance runs its `image` (`vrnetlab/cisco_iol:<version>`)")]
137 ApplianceImage,
138 #[error("`test` and `http` are both given: a healthcheck is a `test` or an `http` page")]
140 TestAndHttp,
141 #[error("a healthcheck says what to try: `{{ test: <command> }}` or `{{ http: {{ port, path }} }}`")]
143 NoHealthProbe,
144 #[error("a file needs one of `source`, `content`, `input` and `secret`")]
146 NoFileSource,
147 #[error("`{}` are {} given: keep one source", .0.join("` and `"), if .0.len() == 2 { "both" } else { "all" })]
149 FileSources(Vec<&'static str>),
150 #[error("write one of `{{ input: NAME }}`")]
152 EnvReference,
153 #[error("`gpus.count`: a whole number or `all`, not {0}")]
155 GpuCount(String),
156 #[error("`gpus`: a number, `all` or a mapping, not `{0}`")]
158 GpusWord(String),
159 #[error("`{0}`: a device is `host[:guest[:permissions]]`")]
161 Device(String),
162 #[error("{}: {source}", path.display())]
164 Layer {
165 path: PathBuf,
167 #[source]
169 source: serde_yaml_ng::Error,
170 },
171 #[error("defaults ({sources}): {source}")]
173 Defaults {
174 sources: String,
176 #[source]
178 source: serde_yaml_ng::Error,
179 },
180 #[error("{0}")]
182 Images(#[source] serde_yaml_ng::Error),
183 #[error("profile `{0}`: a profile name is kebab-case (lowercase letters, digits, dashes)")]
185 ProfileName(String),
186 #[error("no profile `{name}` ({})", Known { folder, known })]
188 NoProfile {
189 name: String,
191 folder: PathBuf,
193 known: Vec<String>,
195 },
196 #[error("both {}/{name}.yml and {}/{name}.yaml exist; keep one", crate::profile::DIR, crate::profile::DIR)]
198 TwoProfiles {
199 name: String,
201 },
202 #[error("profile `{name}` ({}): {source}", path.display())]
204 ProfileYaml {
205 name: String,
207 path: PathBuf,
209 #[source]
211 source: serde_yaml_ng::Error,
212 },
213 #[error("profile `{name}` ({}): `{key}` is a mapping", path.display())]
215 ProfileMapping {
216 name: String,
218 path: PathBuf,
220 key: &'static str,
222 },
223 #[error("profile `{name}` ({}): input `{input}` takes a single value (text, a number or a boolean)", path.display())]
225 ProfileInput {
226 name: String,
228 path: PathBuf,
230 input: String,
232 },
233 #[error("{}", Lines(problems))]
235 ProfileMismatch {
236 problems: Vec<ProfileProblem>,
238 },
239 #[error("profile `{profile}` runs on `{}`, not `{asked}`: drop the target or choose another profile", target.id())]
241 ProfileTarget {
242 profile: String,
244 target: Target,
246 asked: String,
248 },
249 #[error("an instance number is 1 to {}", crate::instance::MAX)]
251 InstanceNumber(u8),
252 #[error("`{0}` is too long for an instance name (at most 55 characters with the suffix)")]
254 InstanceName(String),
255 #[error("`{0}` isn't an IPv4 block: write the network's own address, `/` and the prefix length (`10.20.0.0/24`)")]
257 Cidr(String),
258 #[error("`{0}` isn't an IPv6 block: write a unique local or global network address and `/64` (`fd00:20::/64`)")]
260 Cidr6(String),
261 #[error("machines.{machine}.ports: published port {port} leaves no room for instance {instance} (ports shift by 100 per instance)")]
263 InstancePort {
264 machine: String,
266 port: u16,
268 instance: u8,
270 },
271 #[error("networks.{network}.ipv6.cidr: {cidr} leaves no room for instance {instance}")]
273 InstanceIpv6 {
274 network: String,
276 cidr: String,
278 instance: u8,
280 },
281}
282
283pub type Result<T, E = Error> = std::result::Result<T, E>;
285
286struct Rendered<'a> {
288 file: &'a str,
289 problems: &'a [Problem],
290}
291
292impl fmt::Display for Rendered<'_> {
293 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294 for (i, p) in self.problems.iter().enumerate() {
295 if i > 0 {
296 f.write_str("\n")?;
297 }
298 f.write_str(&p.render(self.file))?;
299 }
300 Ok(())
301 }
302}
303
304struct Lines<'a, T>(&'a [T]);
306
307impl<T: fmt::Display> fmt::Display for Lines<'_, T> {
308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 for (i, item) in self.0.iter().enumerate() {
310 if i > 0 {
311 f.write_str("\n")?;
312 }
313 write!(f, "{item}")?;
314 }
315 Ok(())
316 }
317}
318
319struct Known<'a> {
321 folder: &'a PathBuf,
322 known: &'a [String],
323}
324
325impl fmt::Display for Known<'_> {
326 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327 if self.known.is_empty() {
328 write!(f, "no profiles in {}", self.folder.display())
329 } else {
330 write!(f, "profiles here: {}", self.known.join(", "))
331 }
332 }
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338 use crate::syntax::{Code, FieldPath};
339
340 #[test]
341 fn a_specs_problems_read_one_after_the_other() {
342 let problems = vec![
343 Problem::new(Code::MissingField, FieldPath::new("version"), "a spec says its format's version"),
344 Problem::new(Code::UnknownField, FieldPath::new("nme"), "`nme` isn't a field here"),
345 ];
346 let invalid = Error::Invalid {
347 file: "isoloom.yaml".into(),
348 problems,
349 };
350 assert_eq!(
351 invalid.to_string(),
352 "error[missing-field] version\n a spec says its format's version\nerror[unknown-field] nme\n `nme` isn't a field here"
353 );
354 }
355
356 #[test]
357 fn a_missing_profile_lists_the_profiles_there_are() {
358 let missing = |known: &[&str]| Error::NoProfile {
359 name: "c".into(),
360 folder: PathBuf::from("/lab/profiles"),
361 known: known.iter().map(|k| (*k).to_owned()).collect(),
362 };
363 assert_eq!(missing(&[]).to_string(), "no profile `c` (no profiles in /lab/profiles)");
364 assert_eq!(missing(&["a", "b"]).to_string(), "no profile `c` (profiles here: a, b)");
365 }
366
367 #[test]
368 fn a_profiles_problems_read_one_per_line() {
369 let problems = vec![
370 ProfileProblem::Input {
371 profile: "p".into(),
372 input: "A".into(),
373 },
374 ProfileProblem::Input {
375 profile: "p".into(),
376 input: "B".into(),
377 },
378 ];
379 assert_eq!(
380 Error::ProfileMismatch { problems }.to_string(),
381 "profile `p`: input `A` isn't one of the spec's `inputs`\nprofile `p`: input `B` isn't one of the spec's `inputs`"
382 );
383 }
384
385 #[test]
386 fn several_sources_of_one_file_are_named_together() {
387 assert_eq!(
388 Error::FileSources(vec!["source", "input"]).to_string(),
389 "`source` and `input` are both given: keep one source"
390 );
391 assert_eq!(
392 Error::FileSources(vec!["source", "content", "input"]).to_string(),
393 "`source` and `content` and `input` are all given: keep one source"
394 );
395 }
396}