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 CidrString(pub String);
26 #[derive(hippotat_macros::ResolveConfig)]
27 pub struct InstanceConfig {
28 // Exceptional settings
29 #[special(special_server, SKL::ServerName)] pub server: ServerName,
30 pub secret: String, //xxx newytpe
31 #[special(special_ipif, SKL::Ordinary)] pub ipif: String,
34 #[limited] pub max_batch_down: u32,
35 #[limited] pub max_queue_time: Duration,
36 #[limited] pub http_timeout: Duration,
37 #[limited] pub target_requests_outstanding: u32,
40 pub addrs: Vec<IpAddr>,
41 pub vnetwork: Vec<IpNet>,
42 pub vaddr: Vec<IpAddr>,
46 pub ifname_server: String,
47 pub ifname_client: String,
49 // Ordinary settings, used by server only:
50 #[server] pub max_clock_skew: Duration,
52 // Ordinary settings, used by client only:
53 #[client] pub http_timeout_grace: Duration,
54 #[client] pub max_requests_outstanding: u32,
55 #[client] pub max_batch_up: u32,
56 #[client] pub http_retry: Duration,
57 #[client] pub url: Uri,
58 #[client] pub vroutes: Vec<IpNet>,
61 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
62 pub enum SectionName {
65 Server(ServerName), // includes SERVER, which is slightly special
66 ServerLimit(ServerName),
71 pub use SectionName as SN;
73 #[derive(Debug,Clone)]
74 struct RawVal { val: Option<String>, loc: Arc<PathBuf> }
75 type SectionMap = HashMap<String, RawVal>;
81 static OUTSIDE_SECTION: &str = "[";
82 static SPECIAL_SERVER_SECTION: &str = "SERVER";
84 #[derive(Default,Debug)]
86 sections: HashMap<SectionName, SectionMap>,
89 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
91 impl<'f,A> OkAnyway<'f,A> {
92 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
93 let e = r.as_ref().err()?;
100 impl FromStr for SectionName {
103 fn from_str(s: &str) -> Self {
105 "COMMON" => return SN::Common,
106 "DEFAULT" => return SN::Default,
107 "LIMIT" => return SN::GlobalLimit,
110 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
111 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
112 let (server, client) = s.split_ascii_whitespace().collect_tuple()
113 .ok_or_else(|| anyhow!(
114 "bad section name {:?} \
115 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
118 let server = server.parse().context("server name in link section name")?;
119 if client == "LIMIT" { return SN::ServerLimit(server) }
120 let client = client.parse().context("client name in link section name")?;
121 SN::Link(LinkName { server, client })
126 #[throws(AE)] // AE does not include path
127 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
129 let f = fs::File::open(path);
130 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
131 let mut f = f.context("open")?;
133 let mut s = String::new();
134 let y = f.read_to_string(&mut s);
135 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
138 let mut ini = Ini::new_cs();
139 ini.set_default_section(OUTSIDE_SECTION);
140 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
141 let map = mem::take(ini.get_mut_map());
142 if map.get(OUTSIDE_SECTION).is_some() {
143 throw!(anyhow!("INI file contains settings outside a section"));
146 let loc = Arc::new(path.to_owned());
148 for (sn, vars) in map {
149 dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
151 let sn = sn.parse().dcontext(&sn)?;
152 self.sections.entry(sn)
158 RawVal { val, loc: loc.clone() })
165 #[throws(AE)] // AE includes path
166 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
168 let dir = fs::read_dir(path);
169 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
170 let dir = dir.context("open directory").dcontext(path)?;
172 let ent = ent.context("read directory").dcontext(path)?;
173 let leaf = ent.file_name();
174 let leaf = leaf.to_str();
175 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
176 if leaf.len() == 0 { continue }
177 if ! leaf.chars().all(
178 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
181 // OK we want this one
182 let ent = ent.path();
183 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
188 #[throws(AE)] // AE includes everything
189 fn read_toplevel(&mut self, toplevel: &Path) {
190 enum Anyway { None, Dir }
191 match self.read_file(toplevel, &|k| match k {
192 EK::NotFound => Some(Anyway::None),
193 EK::IsADirectory => Some(Anyway::Dir),
196 .dcontext(toplevel).context("top-level config directory (or file)")?
198 None | Some(Anyway::None) => { },
200 Some(Anyway::Dir) => {
202 let anyway_none = |k| match k {
203 EK::NotFound => Some(AnywayNone),
207 let mk = |leaf: &str| {
208 [ toplevel, &PathBuf::from(leaf) ]
209 .iter().collect::<PathBuf>()
212 for &(try_main, desc) in &[
213 ("main.cfg", "main config file"),
214 ("master.cfg", "obsolete-named main config file"),
216 let main = mk(try_main);
218 match self.read_file(&main, &anyway_none)
219 .dcontext(main).context(desc)?
222 Some(AnywayNone) => { },
226 for &(try_dir, desc) in &[
227 ("config.d", "per-link config directory"),
228 ("secrets.d", "per-link secrets directory"),
230 let dir = mk(try_dir);
231 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
233 Some(AnywayNone) => { },
240 #[throws(AE)] // AE includes extra, but does that this is extra
241 fn read_extra(&mut self, extra: &Path) {
244 match self.read_file(extra, &|k| match k {
245 EK::IsADirectory => Some(AnywayDir),
252 self.read_dir_d(extra, &|_| None::<Void>)?;
259 enum LinkEnd { Server, Client }
261 struct ResolveContext<'c> {
265 all_sections: Vec<SectionName>,
266 special_server_section: SectionName,
269 trait Parseable: Sized {
270 fn parse(s: Option<&str>) -> Result<Self, AE>;
271 fn default() -> Result<Self, AE> {
272 Err(anyhow!("setting must be specified"))
275 fn default_for_key(key: &str) -> Self {
276 Self::default().with_context(|| key.to_string())?
280 impl Parseable for Duration {
282 fn parse(s: Option<&str>) -> Duration {
283 let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
284 if let Ok(u64) = s.parse() { return Duration::from_secs(u64) }
285 throw!(anyhow!("xxx parse with humantime"))
288 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
289 impl Parseable for $t {
291 fn parse(s: Option<&str>) -> $t {
292 let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
296 #[throws(AE)] fn default() -> Self { $def }
300 parseable_from_str!{u16, default() }
301 parseable_from_str!{u32, default() }
302 parseable_from_str!{String, default() }
303 parseable_from_str!{IpNet, default() }
304 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
305 parseable_from_str!{Uri, default() }
307 impl<T:Parseable> Parseable for Vec<T> {
309 fn parse(s: Option<&str>) -> Vec<T> {
310 let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
311 s.split_ascii_whitespace()
312 .map(|s| Parseable::parse(Some(s)))
313 .collect::<Result<Vec<_>,_>>()?
318 #[derive(Debug,Copy,Clone)]
319 enum SectionKindList {
326 use SectionKindList as SKL;
329 fn special_server_section() -> Self { SN::Server(ServerName(
330 SPECIAL_SERVER_SECTION.into()
334 impl SectionKindList {
335 fn contains(self, s: &SectionName) -> bool {
337 SKL::Ordinary => matches!(s, SN::Link(_)
342 SKL::Limits => matches!(s, SN::ServerLimit(_)
345 SKL::ClientAgnostic => matches!(s, SN::Common
348 SKL::Limited => SKL::Ordinary.contains(s)
349 | SKL::Limits .contains(s),
351 SKL::ServerName => matches!(s, SN::Common)
352 | matches!(s, SN::Server(ServerName(name))
353 if name == SPECIAL_SERVER_SECTION),
358 impl<'c> ResolveContext<'c> {
359 fn lookup_raw<'n, S>(&self, key: &'static str, sections: S)
360 -> Option<&'c RawVal>
361 where S: Iterator<Item=&'n SectionName>
363 for section in sections {
364 if let Some(raw) = self.agg.sections
366 .and_then(|vars: &SectionMap| vars.get(key))
374 fn first_of_raw(&self, key: &'static str, sections: SectionKindList)
375 -> Option<&'c RawVal> {
378 self.all_sections.iter()
379 .filter(|s| sections.contains(s))
384 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
388 match self.first_of_raw(key, sections) {
391 Parseable::parse(raw.val.as_deref())
393 // .with_context(|| format!(r#"in section "{}""#, §ion))
400 pub fn ordinary<T>(&self, key: &'static str) -> T
403 match self.first_of(key, SKL::Ordinary)? {
405 None => Parseable::default_for_key(key)?,
410 pub fn limited<T>(&self, key: &'static str) -> T
411 where T: Parseable + Ord
413 let val = self.ordinary(key)?;
414 if let Some(limit) = self.first_of(key, SKL::Limits)? {
422 pub fn client<T>(&self, key: &'static str) -> T
425 LinkEnd::Client => self.ordinary(key)?,
426 LinkEnd::Server => Parseable::default_for_key(key)?,
430 pub fn server<T>(&self, key: &'static str) -> T
433 LinkEnd::Server => self.ordinary(key)?,
434 LinkEnd::Client => Parseable::default_for_key(key)?,
439 pub fn special_ipif(&self, key: &'static str) -> String {
441 LinkEnd::Client => self.ordinary(key)?,
443 self.first_of(key, SKL::ClientAgnostic)?
450 pub fn special_server(&self, key: &'static str) -> ServerName {
451 let raw = match self.lookup_raw(
453 [ &SectionName::Common, &self.special_server_section ].iter().cloned()
455 Some(RawVal { val: Some(ref got),.. }) => got,
456 Some(RawVal { val: None,.. }) => throw!(anyhow!("value needed")),
457 None => SPECIAL_SERVER_SECTION,
459 ServerName(raw.into())
464 impl<'c> ResolveContext<'c> {
466 fn resolve_instance(&self) -> InstanceConfig {
468 max_batch_down: self.limited::<u32>("max_batch_down")?,
476 let opts = config::Opts::from_args();
479 let mut agg = Aggregate::default();
481 agg.read_toplevel(&opts.config)?;
482 for extra in &opts.extra_config {
483 agg.read_extra(extra).context("extra config")?;
486 eprintln!("GOT {:#?}", agg);
489 })().context("read configuration")?;
491 let link = LinkName {
492 server: "fooxxx".parse().unwrap(),
493 client: "127.0.0.1".parse().unwrap(),
496 let rctx = ResolveContext {
499 end: LinkEnd::Server,
501 SN::Link(link.clone()),
502 SN::Client(link.client.clone()),
503 SN::Server(link.server.clone()),
505 SN::ServerLimit(link.server.clone()),
508 special_server_section: SN::special_server_section(),