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>,
25 impl<'s> Option<&'s str> {
27 fn value(self) -> &'s str {
28 self.ok_or_else(|| anyhow!("value needed"))?
32 pub struct Secret(pub String);
33 impl Parseable for Secret {
35 fn parse(s: Option<&str>) -> Self {
37 if s.is_empty() { throw!(anyhow!("secret value cannot be empty")) }
41 fn default() -> Self { Secret(default()) }
43 impl Debug for Secret {
45 fn fmt(&self, f: &mut fmt::Formatter) { write!(f, "Secret(***)")? }
48 #[derive(hippotat_macros::ResolveConfig)]
49 pub struct InstanceConfig {
50 // Exceptional settings
51 #[special(special_server, SKL::ServerName)] pub server: ServerName,
53 #[special(special_ipif, SKL::Ordinary)] pub ipif: String,
56 #[limited] pub max_batch_down: u32,
57 #[limited] pub max_queue_time: Duration,
58 #[limited] pub http_timeout: Duration,
59 #[limited] pub target_requests_outstanding: u32,
62 pub addrs: Vec<IpAddr>,
63 pub vnetwork: Vec<IpNet>,
64 pub vaddr: Vec<IpAddr>,
68 pub ifname_server: String,
69 pub ifname_client: String,
71 // Ordinary settings, used by server only:
72 #[server] pub max_clock_skew: Duration,
74 // Ordinary settings, used by client only:
75 #[client] pub http_timeout_grace: Duration,
76 #[client] pub max_requests_outstanding: u32,
77 #[client] pub max_batch_up: u32,
78 #[client] pub http_retry: Duration,
79 #[client] pub url: Uri,
80 #[client] pub vroutes: Vec<IpNet>,
83 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
84 pub enum SectionName {
87 Server(ServerName), // includes SERVER, which is slightly special
88 ServerLimit(ServerName),
93 pub use SectionName as SN;
95 #[derive(Debug,Clone)]
96 struct RawVal { val: Option<String>, loc: Arc<PathBuf> }
97 type SectionMap = HashMap<String, RawVal>;
103 static OUTSIDE_SECTION: &str = "[";
104 static SPECIAL_SERVER_SECTION: &str = "SERVER";
106 #[derive(Default,Debug)]
108 sections: HashMap<SectionName, SectionMap>,
111 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
113 impl<'f,A> OkAnyway<'f,A> {
114 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
115 let e = r.as_ref().err()?;
122 impl FromStr for SectionName {
125 fn from_str(s: &str) -> Self {
127 "COMMON" => return SN::Common,
128 "DEFAULT" => return SN::Default,
129 "LIMIT" => return SN::GlobalLimit,
132 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
133 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
134 let (server, client) = s.split_ascii_whitespace().collect_tuple()
135 .ok_or_else(|| anyhow!(
136 "bad section name {:?} \
137 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
140 let server = server.parse().context("server name in link section name")?;
141 if client == "LIMIT" { return SN::ServerLimit(server) }
142 let client = client.parse().context("client name in link section name")?;
143 SN::Link(LinkName { server, client })
148 #[throws(AE)] // AE does not include path
149 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
151 let f = fs::File::open(path);
152 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
153 let mut f = f.context("open")?;
155 let mut s = String::new();
156 let y = f.read_to_string(&mut s);
157 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
160 let mut ini = Ini::new_cs();
161 ini.set_default_section(OUTSIDE_SECTION);
162 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
163 let map = mem::take(ini.get_mut_map());
164 if map.get(OUTSIDE_SECTION).is_some() {
165 throw!(anyhow!("INI file contains settings outside a section"));
168 let loc = Arc::new(path.to_owned());
170 for (sn, vars) in map {
171 dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
173 let sn = sn.parse().dcontext(&sn)?;
174 self.sections.entry(sn)
180 RawVal { val, loc: loc.clone() })
187 #[throws(AE)] // AE includes path
188 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
190 let dir = fs::read_dir(path);
191 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
192 let dir = dir.context("open directory").dcontext(path)?;
194 let ent = ent.context("read directory").dcontext(path)?;
195 let leaf = ent.file_name();
196 let leaf = leaf.to_str();
197 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
198 if leaf.len() == 0 { continue }
199 if ! leaf.chars().all(
200 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
203 // OK we want this one
204 let ent = ent.path();
205 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
210 #[throws(AE)] // AE includes everything
211 fn read_toplevel(&mut self, toplevel: &Path) {
212 enum Anyway { None, Dir }
213 match self.read_file(toplevel, &|k| match k {
214 EK::NotFound => Some(Anyway::None),
215 EK::IsADirectory => Some(Anyway::Dir),
218 .dcontext(toplevel).context("top-level config directory (or file)")?
220 None | Some(Anyway::None) => { },
222 Some(Anyway::Dir) => {
224 let anyway_none = |k| match k {
225 EK::NotFound => Some(AnywayNone),
229 let mk = |leaf: &str| {
230 [ toplevel, &PathBuf::from(leaf) ]
231 .iter().collect::<PathBuf>()
234 for &(try_main, desc) in &[
235 ("main.cfg", "main config file"),
236 ("master.cfg", "obsolete-named main config file"),
238 let main = mk(try_main);
240 match self.read_file(&main, &anyway_none)
241 .dcontext(main).context(desc)?
244 Some(AnywayNone) => { },
248 for &(try_dir, desc) in &[
249 ("config.d", "per-link config directory"),
250 ("secrets.d", "per-link secrets directory"),
252 let dir = mk(try_dir);
253 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
255 Some(AnywayNone) => { },
262 #[throws(AE)] // AE includes extra, but does that this is extra
263 fn read_extra(&mut self, extra: &Path) {
266 match self.read_file(extra, &|k| match k {
267 EK::IsADirectory => Some(AnywayDir),
274 self.read_dir_d(extra, &|_| None::<Void>)?;
281 enum LinkEnd { Server, Client }
283 struct ResolveContext<'c> {
287 all_sections: Vec<SectionName>,
288 special_server_section: SectionName,
291 trait Parseable: Sized {
292 fn parse(s: Option<&str>) -> Result<Self, AE>;
293 fn default() -> Result<Self, AE> {
294 Err(anyhow!("setting must be specified"))
297 fn default_for_key(key: &str) -> Self {
298 Self::default().with_context(|| key.to_string())?
302 impl Parseable for Duration {
304 fn parse(s: Option<&str>) -> Duration {
305 // todo: would be nice to parse with humantime maybe
306 Duration::from_secs( s.value()?.parse()? )
309 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
310 impl Parseable for $t {
312 fn parse(s: Option<&str>) -> $t { s.value()?.parse()? }
313 $( #[throws(AE)] fn default() -> Self { $def } )?
316 parseable_from_str!{u16, default() }
317 parseable_from_str!{u32, default() }
318 parseable_from_str!{String, default() }
319 parseable_from_str!{IpNet, default() }
320 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
321 parseable_from_str!{Uri, default() }
323 impl<T:Parseable> Parseable for Vec<T> {
325 fn parse(s: Option<&str>) -> Vec<T> {
327 .split_ascii_whitespace()
328 .map(|s| Parseable::parse(Some(s)))
329 .collect::<Result<Vec<_>,_>>()?
334 #[derive(Debug,Copy,Clone)]
335 enum SectionKindList {
342 use SectionKindList as SKL;
345 fn special_server_section() -> Self { SN::Server(ServerName(
346 SPECIAL_SERVER_SECTION.into()
350 impl SectionKindList {
351 fn contains(self, s: &SectionName) -> bool {
353 SKL::Ordinary => matches!(s, SN::Link(_)
358 SKL::Limits => matches!(s, SN::ServerLimit(_)
361 SKL::ClientAgnostic => matches!(s, SN::Common
364 SKL::Limited => SKL::Ordinary.contains(s)
365 | SKL::Limits .contains(s),
367 SKL::ServerName => matches!(s, SN::Common)
368 | matches!(s, SN::Server(ServerName(name))
369 if name == SPECIAL_SERVER_SECTION),
374 impl<'c> ResolveContext<'c> {
375 fn lookup_raw<'n, S>(&self, key: &'static str, sections: S)
376 -> Option<&'c RawVal>
377 where S: Iterator<Item=&'n SectionName>
379 for section in sections {
380 if let Some(raw) = self.agg.sections
382 .and_then(|vars: &SectionMap| vars.get(key))
390 fn first_of_raw(&self, key: &'static str, sections: SectionKindList)
391 -> Option<&'c RawVal> {
394 self.all_sections.iter()
395 .filter(|s| sections.contains(s))
400 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
404 match self.first_of_raw(key, sections) {
407 Parseable::parse(raw.val.as_deref())
409 // .with_context(|| format!(r#"in section "{}""#, §ion))
416 pub fn ordinary<T>(&self, key: &'static str) -> T
419 match self.first_of(key, SKL::Ordinary)? {
421 None => Parseable::default_for_key(key)?,
426 pub fn limited<T>(&self, key: &'static str) -> T
427 where T: Parseable + Ord
429 let val = self.ordinary(key)?;
430 if let Some(limit) = self.first_of(key, SKL::Limits)? {
438 pub fn client<T>(&self, key: &'static str) -> T
441 LinkEnd::Client => self.ordinary(key)?,
442 LinkEnd::Server => Parseable::default_for_key(key)?,
446 pub fn server<T>(&self, key: &'static str) -> T
449 LinkEnd::Server => self.ordinary(key)?,
450 LinkEnd::Client => Parseable::default_for_key(key)?,
455 pub fn special_ipif(&self, key: &'static str) -> String {
457 LinkEnd::Client => self.ordinary(key)?,
459 self.first_of(key, SKL::ClientAgnostic)?
466 pub fn special_server(&self, key: &'static str) -> ServerName {
467 let raw = match self.lookup_raw(
469 [ &SectionName::Common, &self.special_server_section ].iter().cloned()
471 Some(raw) => raw.val.as_deref().value()?,
472 None => SPECIAL_SERVER_SECTION,
474 ServerName(raw.into())
479 impl<'c> ResolveContext<'c> {
481 fn resolve_instance(&self) -> InstanceConfig {
483 max_batch_down: self.limited::<u32>("max_batch_down")?,
491 let opts = config::Opts::from_args();
494 let mut agg = Aggregate::default();
496 agg.read_toplevel(&opts.config)?;
497 for extra in &opts.extra_config {
498 agg.read_extra(extra).context("extra config")?;
501 eprintln!("GOT {:#?}", agg);
504 })().context("read configuration")?;
506 let link = LinkName {
507 server: "fooxxx".parse().unwrap(),
508 client: "127.0.0.1".parse().unwrap(),
511 let rctx = ResolveContext {
514 end: LinkEnd::Server,
516 SN::Link(link.clone()),
517 SN::Client(link.client.clone()),
518 SN::Server(link.server.clone()),
520 SN::ServerLimit(link.server.clone()),
523 special_server_section: SN::special_server_section(),