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 {
29 // Exceptional settings
31 pub secret: String, // make a newytpe
35 pub max_batch_down: u32,
37 pub max_queue_time: Duration,
38 pub http_timeout: Duration,
39 pub target_requests_outstanding: u32,
42 pub addrs: Vec<IpAddr>,
43 pub vnetwork: Vec<CidrString>,
44 pub vaddr: Vec<IpAddr>,
48 pub ifname_server: String,
49 pub ifname_client: String,
51 // Ordinary settings, used by server only:
52 pub max_clock_skew: Duration,
54 // Ordinary settings, used by client only:
55 pub http_timeout_grace: Duration,
56 pub max_requests_outstanding: u32,
57 pub max_batch_up: u32,
58 pub http_retry: Duration,
60 pub vroutes: Vec<CidrString>,
64 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
65 pub enum SectionName {
68 Server(ServerName), // includes SERVER, which is slightly special
69 ServerLimit(ServerName),
74 pub use SectionName as SN;
76 #[derive(Debug,Clone)]
77 struct RawVal { val: Option<String>, loc: Arc<PathBuf> }
78 type SectionMap = HashMap<String, RawVal>;
84 static OUTSIDE_SECTION: &str = "[";
86 #[derive(Default,Debug)]
88 sections: HashMap<SectionName, SectionMap>,
91 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
93 impl<'f,A> OkAnyway<'f,A> {
94 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
95 let e = r.as_ref().err()?;
102 impl FromStr for SectionName {
105 fn from_str(s: &str) -> Self {
107 "COMMON" => return SN::Common,
108 "DEFAULT" => return SN::Default,
109 "LIMIT" => return SN::GlobalLimit,
112 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
113 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
114 let (server, client) = s.split_ascii_whitespace().collect_tuple()
115 .ok_or_else(|| anyhow!(
116 "bad section name {:?} \
117 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
120 let server = server.parse().context("server name in link section name")?;
121 if client == "LIMIT" { return SN::ServerLimit(server) }
122 let client = client.parse().context("client name in link section name")?;
123 SN::Link(LinkName { server, client })
128 #[throws(AE)] // AE does not include path
129 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
131 let f = fs::File::open(path);
132 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
133 let mut f = f.context("open")?;
135 let mut s = String::new();
136 let y = f.read_to_string(&mut s);
137 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
140 let mut ini = Ini::new_cs();
141 ini.set_default_section(OUTSIDE_SECTION);
142 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
143 let map = mem::take(ini.get_mut_map());
144 if map.get(OUTSIDE_SECTION).is_some() {
145 throw!(anyhow!("INI file contains settings outside a section"));
148 let loc = Arc::new(path.to_owned());
150 for (sn, vars) in map {
151 dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
153 let sn = sn.parse().dcontext(&sn)?;
154 self.sections.entry(sn)
160 RawVal { val, loc: loc.clone() })
167 #[throws(AE)] // AE includes path
168 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
170 let dir = fs::read_dir(path);
171 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
172 let dir = dir.context("open directory").dcontext(path)?;
174 let ent = ent.context("read directory").dcontext(path)?;
175 let leaf = ent.file_name();
176 let leaf = leaf.to_str();
177 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
178 if leaf.len() == 0 { continue }
179 if ! leaf.chars().all(
180 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
183 // OK we want this one
184 let ent = ent.path();
185 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
190 #[throws(AE)] // AE includes everything
191 fn read_toplevel(&mut self, toplevel: &Path) {
192 enum Anyway { None, Dir }
193 match self.read_file(toplevel, &|k| match k {
194 EK::NotFound => Some(Anyway::None),
195 EK::IsADirectory => Some(Anyway::Dir),
198 .dcontext(toplevel).context("top-level config directory (or file)")?
200 None | Some(Anyway::None) => { },
202 Some(Anyway::Dir) => {
204 let anyway_none = |k| match k {
205 EK::NotFound => Some(AnywayNone),
209 let mk = |leaf: &str| {
210 [ toplevel, &PathBuf::from(leaf) ]
211 .iter().collect::<PathBuf>()
214 for &(try_main, desc) in &[
215 ("main.cfg", "main config file"),
216 ("master.cfg", "obsolete-named main config file"),
218 let main = mk(try_main);
220 match self.read_file(&main, &anyway_none)
221 .dcontext(main).context(desc)?
224 Some(AnywayNone) => { },
228 for &(try_dir, desc) in &[
229 ("config.d", "per-link config directory"),
230 ("secrets.d", "per-link secrets directory"),
232 let dir = mk(try_dir);
233 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
235 Some(AnywayNone) => { },
242 #[throws(AE)] // AE includes extra, but does that this is extra
243 fn read_extra(&mut self, extra: &Path) {
246 match self.read_file(extra, &|k| match k {
247 EK::IsADirectory => Some(AnywayDir),
254 self.read_dir_d(extra, &|_| None::<Void>)?;
261 enum LinkEnd { Server, Client }
263 struct ResolveContext<'c> {
267 all_sections: Vec<SectionName>,
270 trait Parseable: Sized {
271 fn parse(s: &Option<String>) -> Result<Self, AE>;
274 impl Parseable for Duration {
276 fn parse(s: &Option<String>) -> Duration {
277 let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
278 if let Ok(u64) = s.parse() { return Duration::from_secs(u64) }
279 throw!(anyhow!("xxx parse with humantime"))
282 macro_rules! parseable_from_str { ($t:ty) => {
283 impl Parseable for $t {
285 fn parse(s: &Option<String>) -> $t {
286 let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
291 parseable_from_str!{u32}
293 #[derive(Debug,Copy,Clone)]
294 enum SectionKindList {
301 use SectionKindList as SKL;
303 impl SectionKindList {
304 fn contains(self, s: &SectionName) -> bool {
306 SKL::Ordinary => matches!(s, SN::Link(_)
311 SKL::Limits => matches!(s, SN::ServerLimit(_)
314 SKL::ClientAgnostic => matches!(s, SN::Common
317 SKL::Limited => SKL::Ordinary.contains(s)
318 | SKL::Limits .contains(s),
320 SKL::ServerName => matches!(s, SN::Common)
321 | matches!(s, SN::Server(ServerName(name))
322 if name == "SERVER"),
327 impl<'c> ResolveContext<'c> {
328 fn first_of_raw(&self, key: &'static str, sections: SectionKindList)
329 -> Option<&'c RawVal> {
330 for section in self.all_sections.iter()
331 .filter(|s| sections.contains(s))
333 if let Some(raw) = self.agg.sections
335 .and_then(|vars: &SectionMap| vars.get(key))
344 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
348 match self.first_of_raw(key, sections) {
351 Parseable::parse(&raw.val)
353 // .with_context(|| format!(r#"in section "{}""#, §ion))
360 pub fn ordinary<T>(&self, key: &'static str) -> T
361 where T: Parseable + Default
363 self.first_of(key, SKL::Ordinary)?
368 pub fn limited<T>(&self, key: &'static str) -> T
369 where T: Parseable + Default + Ord
371 let val = self.ordinary(key)?;
372 if let Some(limit) = self.first_of(key, SKL::Limits)? {
380 pub fn client<T>(&self, key: &'static str) -> T
381 where T: Parseable + Default {
383 LinkEnd::Client => self.ordinary(key)?,
384 LinkEnd::Server => default(),
388 pub fn server<T>(&self, key: &'static str) -> T
389 where T: Parseable + Default {
391 LinkEnd::Server => self.ordinary(key)?,
392 LinkEnd::Client => default(),
397 pub fn special_ipif<T>(&self, key: &'static str) -> T
398 where T: Parseable + Default
401 LinkEnd::Client => self.ordinary(key)?,
403 self.first_of(key, SKL::ClientAgnostic)?
410 impl<'c> ResolveContext<'c> {
412 fn resolve_instance(&self) -> InstanceConfig {
414 max_batch_down: self.limited::<u32>("max_batch_down")?.into(),
421 let opts = config::Opts::from_args();
424 let mut agg = Aggregate::default();
426 agg.read_toplevel(&opts.config)?;
427 for extra in &opts.extra_config {
428 agg.read_extra(extra).context("extra config")?;
431 eprintln!("GOT {:#?}", agg);
434 })().context("read configuration")?;
436 let link = LinkName {
437 server: "fooxxx".parse().unwrap(),
438 client: "127.0.0.1".parse().unwrap(),
441 let rctx = ResolveContext {
444 end: LinkEnd::Server,
446 SN::Link(link.clone()),
447 SN::Client(link.client.clone()),
448 SN::Server(link.server.clone()),
450 SN::ServerLimit(link.server.clone()),