1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: AGPL-3.0-or-later
3 // There is NO WARRANTY.
7 use configparser::ini::Ini;
9 #[derive(StructOpt,Debug)]
11 /// Top-level config file or directory
13 /// Look for `main.cfg`, `config.d` and `secrets.d` here.
15 /// Or if this is a file, just read that file.
16 #[structopt(long, default_value="/etc/hippotat")]
19 /// Additional config files or dirs, which can override the others
20 #[structopt(long, multiple=true, number_of_values=1)]
21 pub extra_config: Vec<PathBuf>,
24 pub struct Secret(pub String);
25 impl Parseable for Secret {
27 fn parse(s: Option<&str>) -> Self {
28 let s = s.ok_or_else(|| anyhow!("value needed"))?;
29 if s.is_empty() { throw!(anyhow!("secret value cannot be empty")) }
33 fn default() -> Self { Secret(default()) }
35 impl Debug for Secret {
37 fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "Secret(***)")? }
40 #[derive(hippotat_macros::ResolveConfig)]
41 pub struct InstanceConfig {
42 // Exceptional settings
43 #[special(special_server, SKL::ServerName)] pub server: ServerName,
45 #[special(special_ipif, SKL::Ordinary)] pub ipif: String,
48 #[limited] pub max_batch_down: u32,
49 #[limited] pub max_queue_time: Duration,
50 #[limited] pub http_timeout: Duration,
51 #[limited] pub target_requests_outstanding: u32,
54 pub addrs: Vec<IpAddr>,
55 pub vnetwork: Vec<IpNet>,
56 pub vaddr: Vec<IpAddr>,
60 pub ifname_server: String,
61 pub ifname_client: String,
63 // Ordinary settings, used by server only:
64 #[server] pub max_clock_skew: Duration,
66 // Ordinary settings, used by client only:
67 #[client] pub http_timeout_grace: Duration,
68 #[client] pub max_requests_outstanding: u32,
69 #[client] pub max_batch_up: u32,
70 #[client] pub http_retry: Duration,
71 #[client] pub url: Uri,
72 #[client] pub vroutes: Vec<IpNet>,
75 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
76 pub enum SectionName {
79 Server(ServerName), // includes SERVER, which is slightly special
80 ServerLimit(ServerName),
85 pub use SectionName as SN;
87 #[derive(Debug,Clone)]
88 struct RawVal { val: Option<String>, loc: Arc<PathBuf> }
89 type SectionMap = HashMap<String, RawVal>;
95 static OUTSIDE_SECTION: &str = "[";
96 static SPECIAL_SERVER_SECTION: &str = "SERVER";
98 #[derive(Default,Debug)]
100 sections: HashMap<SectionName, SectionMap>,
103 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
105 impl<'f,A> OkAnyway<'f,A> {
106 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
107 let e = r.as_ref().err()?;
114 impl FromStr for SectionName {
117 fn from_str(s: &str) -> Self {
119 "COMMON" => return SN::Common,
120 "DEFAULT" => return SN::Default,
121 "LIMIT" => return SN::GlobalLimit,
124 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
125 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
126 let (server, client) = s.split_ascii_whitespace().collect_tuple()
127 .ok_or_else(|| anyhow!(
128 "bad section name {:?} \
129 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
132 let server = server.parse().context("server name in link section name")?;
133 if client == "LIMIT" { return SN::ServerLimit(server) }
134 let client = client.parse().context("client name in link section name")?;
135 SN::Link(LinkName { server, client })
140 #[throws(AE)] // AE does not include path
141 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
143 let f = fs::File::open(path);
144 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
145 let mut f = f.context("open")?;
147 let mut s = String::new();
148 let y = f.read_to_string(&mut s);
149 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
152 let mut ini = Ini::new_cs();
153 ini.set_default_section(OUTSIDE_SECTION);
154 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
155 let map = mem::take(ini.get_mut_map());
156 if map.get(OUTSIDE_SECTION).is_some() {
157 throw!(anyhow!("INI file contains settings outside a section"));
160 let loc = Arc::new(path.to_owned());
162 for (sn, vars) in map {
163 dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
165 let sn = sn.parse().dcontext(&sn)?;
166 self.sections.entry(sn)
172 RawVal { val, loc: loc.clone() })
179 #[throws(AE)] // AE includes path
180 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
182 let dir = fs::read_dir(path);
183 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
184 let dir = dir.context("open directory").dcontext(path)?;
186 let ent = ent.context("read directory").dcontext(path)?;
187 let leaf = ent.file_name();
188 let leaf = leaf.to_str();
189 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
190 if leaf.len() == 0 { continue }
191 if ! leaf.chars().all(
192 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
195 // OK we want this one
196 let ent = ent.path();
197 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
202 #[throws(AE)] // AE includes everything
203 fn read_toplevel(&mut self, toplevel: &Path) {
204 enum Anyway { None, Dir }
205 match self.read_file(toplevel, &|k| match k {
206 EK::NotFound => Some(Anyway::None),
207 EK::IsADirectory => Some(Anyway::Dir),
210 .dcontext(toplevel).context("top-level config directory (or file)")?
212 None | Some(Anyway::None) => { },
214 Some(Anyway::Dir) => {
216 let anyway_none = |k| match k {
217 EK::NotFound => Some(AnywayNone),
221 let mk = |leaf: &str| {
222 [ toplevel, &PathBuf::from(leaf) ]
223 .iter().collect::<PathBuf>()
226 for &(try_main, desc) in &[
227 ("main.cfg", "main config file"),
228 ("master.cfg", "obsolete-named main config file"),
230 let main = mk(try_main);
232 match self.read_file(&main, &anyway_none)
233 .dcontext(main).context(desc)?
236 Some(AnywayNone) => { },
240 for &(try_dir, desc) in &[
241 ("config.d", "per-link config directory"),
242 ("secrets.d", "per-link secrets directory"),
244 let dir = mk(try_dir);
245 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
247 Some(AnywayNone) => { },
254 #[throws(AE)] // AE includes extra, but does that this is extra
255 fn read_extra(&mut self, extra: &Path) {
258 match self.read_file(extra, &|k| match k {
259 EK::IsADirectory => Some(AnywayDir),
266 self.read_dir_d(extra, &|_| None::<Void>)?;
273 enum LinkEnd { Server, Client }
275 struct ResolveContext<'c> {
279 all_sections: Vec<SectionName>,
280 special_server_section: SectionName,
283 trait Parseable: Sized {
284 fn parse(s: Option<&str>) -> Result<Self, AE>;
285 fn default() -> Result<Self, AE> {
286 Err(anyhow!("setting must be specified"))
289 fn default_for_key(key: &str) -> Self {
290 Self::default().with_context(|| key.to_string())?
294 impl Parseable for Duration {
296 fn parse(s: Option<&str>) -> Duration {
297 let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
298 if let Ok(u64) = s.parse() { return Duration::from_secs(u64) }
299 throw!(anyhow!("xxx parse with humantime"))
302 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
303 impl Parseable for $t {
305 fn parse(s: Option<&str>) -> $t {
306 let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
310 #[throws(AE)] fn default() -> Self { $def }
314 parseable_from_str!{u16, default() }
315 parseable_from_str!{u32, default() }
316 parseable_from_str!{String, default() }
317 parseable_from_str!{IpNet, default() }
318 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
319 parseable_from_str!{Uri, default() }
321 impl<T:Parseable> Parseable for Vec<T> {
323 fn parse(s: Option<&str>) -> Vec<T> {
324 let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
325 s.split_ascii_whitespace()
326 .map(|s| Parseable::parse(Some(s)))
327 .collect::<Result<Vec<_>,_>>()?
332 #[derive(Debug,Copy,Clone)]
333 enum SectionKindList {
340 use SectionKindList as SKL;
343 fn special_server_section() -> Self { SN::Server(ServerName(
344 SPECIAL_SERVER_SECTION.into()
348 impl SectionKindList {
349 fn contains(self, s: &SectionName) -> bool {
351 SKL::Ordinary => matches!(s, SN::Link(_)
356 SKL::Limits => matches!(s, SN::ServerLimit(_)
359 SKL::ClientAgnostic => matches!(s, SN::Common
362 SKL::Limited => SKL::Ordinary.contains(s)
363 | SKL::Limits .contains(s),
365 SKL::ServerName => matches!(s, SN::Common)
366 | matches!(s, SN::Server(ServerName(name))
367 if name == SPECIAL_SERVER_SECTION),
372 impl<'c> ResolveContext<'c> {
373 fn lookup_raw<'n, S>(&self, key: &'static str, sections: S)
374 -> Option<&'c RawVal>
375 where S: Iterator<Item=&'n SectionName>
377 for section in sections {
378 if let Some(raw) = self.agg.sections
380 .and_then(|vars: &SectionMap| vars.get(key))
388 fn first_of_raw(&self, key: &'static str, sections: SectionKindList)
389 -> Option<&'c RawVal> {
392 self.all_sections.iter()
393 .filter(|s| sections.contains(s))
398 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
402 match self.first_of_raw(key, sections) {
405 Parseable::parse(raw.val.as_deref())
407 // .with_context(|| format!(r#"in section "{}""#, §ion))
414 pub fn ordinary<T>(&self, key: &'static str) -> T
417 match self.first_of(key, SKL::Ordinary)? {
419 None => Parseable::default_for_key(key)?,
424 pub fn limited<T>(&self, key: &'static str) -> T
425 where T: Parseable + Ord
427 let val = self.ordinary(key)?;
428 if let Some(limit) = self.first_of(key, SKL::Limits)? {
436 pub fn client<T>(&self, key: &'static str) -> T
439 LinkEnd::Client => self.ordinary(key)?,
440 LinkEnd::Server => Parseable::default_for_key(key)?,
444 pub fn server<T>(&self, key: &'static str) -> T
447 LinkEnd::Server => self.ordinary(key)?,
448 LinkEnd::Client => Parseable::default_for_key(key)?,
453 pub fn special_ipif(&self, key: &'static str) -> String {
455 LinkEnd::Client => self.ordinary(key)?,
457 self.first_of(key, SKL::ClientAgnostic)?
464 pub fn special_server(&self, key: &'static str) -> ServerName {
465 let raw = match self.lookup_raw(
467 [ &SectionName::Common, &self.special_server_section ].iter().cloned()
469 Some(RawVal { val: Some(ref got),.. }) => got,
470 Some(RawVal { val: None,.. }) => throw!(anyhow!("value needed")),
471 None => SPECIAL_SERVER_SECTION,
473 ServerName(raw.into())
478 impl<'c> ResolveContext<'c> {
480 fn resolve_instance(&self) -> InstanceConfig {
482 max_batch_down: self.limited::<u32>("max_batch_down")?,
490 let opts = config::Opts::from_args();
493 let mut agg = Aggregate::default();
495 agg.read_toplevel(&opts.config)?;
496 for extra in &opts.extra_config {
497 agg.read_extra(extra).context("extra config")?;
500 eprintln!("GOT {:#?}", agg);
503 })().context("read configuration")?;
505 let link = LinkName {
506 server: "fooxxx".parse().unwrap(),
507 client: "127.0.0.1".parse().unwrap(),
510 let rctx = ResolveContext {
513 end: LinkEnd::Server,
515 SN::Link(link.clone()),
516 SN::Client(link.client.clone()),
517 SN::Server(link.server.clone()),
519 SN::ServerLimit(link.server.clone()),
522 special_server_section: SN::special_server_section(),