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
30 #[special(special_name, SKL::ServerName)] pub server: String,
31 pub secret: String, // xxx newytpe
32 #[special(special_ipif, SKL::Ordinary)] pub ipif: String,
36 #[limited] pub max_batch_down: u32,
37 #[limited] pub max_queue_time: Duration,
38 #[limited] pub http_timeout: Duration,
39 #[limited] 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 #[server] pub max_clock_skew: Duration,
54 // Ordinary settings, used by client only:
55 #[client] pub http_timeout_grace: Duration,
56 #[client] pub max_requests_outstanding: u32,
57 #[client] pub max_batch_up: u32,
58 #[client] pub http_retry: Duration,
59 #[client] pub url: Uri,
60 #[client] pub vroutes: Vec<CidrString>,
63 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
64 pub enum SectionName {
67 Server(ServerName), // includes SERVER, which is slightly special
68 ServerLimit(ServerName),
73 pub use SectionName as SN;
75 #[derive(Debug,Clone)]
76 struct RawVal { val: Option<String>, loc: Arc<PathBuf> }
77 type SectionMap = HashMap<String, RawVal>;
83 static OUTSIDE_SECTION: &str = "[";
85 #[derive(Default,Debug)]
87 sections: HashMap<SectionName, SectionMap>,
90 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
92 impl<'f,A> OkAnyway<'f,A> {
93 fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
94 let e = r.as_ref().err()?;
101 impl FromStr for SectionName {
104 fn from_str(s: &str) -> Self {
106 "COMMON" => return SN::Common,
107 "DEFAULT" => return SN::Default,
108 "LIMIT" => return SN::GlobalLimit,
111 if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
112 if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
113 let (server, client) = s.split_ascii_whitespace().collect_tuple()
114 .ok_or_else(|| anyhow!(
115 "bad section name {:?} \
116 (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
119 let server = server.parse().context("server name in link section name")?;
120 if client == "LIMIT" { return SN::ServerLimit(server) }
121 let client = client.parse().context("client name in link section name")?;
122 SN::Link(LinkName { server, client })
127 #[throws(AE)] // AE does not include path
128 fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
130 let f = fs::File::open(path);
131 if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
132 let mut f = f.context("open")?;
134 let mut s = String::new();
135 let y = f.read_to_string(&mut s);
136 if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
139 let mut ini = Ini::new_cs();
140 ini.set_default_section(OUTSIDE_SECTION);
141 ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
142 let map = mem::take(ini.get_mut_map());
143 if map.get(OUTSIDE_SECTION).is_some() {
144 throw!(anyhow!("INI file contains settings outside a section"));
147 let loc = Arc::new(path.to_owned());
149 for (sn, vars) in map {
150 dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
152 let sn = sn.parse().dcontext(&sn)?;
153 self.sections.entry(sn)
159 RawVal { val, loc: loc.clone() })
166 #[throws(AE)] // AE includes path
167 fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
169 let dir = fs::read_dir(path);
170 if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
171 let dir = dir.context("open directory").dcontext(path)?;
173 let ent = ent.context("read directory").dcontext(path)?;
174 let leaf = ent.file_name();
175 let leaf = leaf.to_str();
176 let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
177 if leaf.len() == 0 { continue }
178 if ! leaf.chars().all(
179 |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
182 // OK we want this one
183 let ent = ent.path();
184 self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
189 #[throws(AE)] // AE includes everything
190 fn read_toplevel(&mut self, toplevel: &Path) {
191 enum Anyway { None, Dir }
192 match self.read_file(toplevel, &|k| match k {
193 EK::NotFound => Some(Anyway::None),
194 EK::IsADirectory => Some(Anyway::Dir),
197 .dcontext(toplevel).context("top-level config directory (or file)")?
199 None | Some(Anyway::None) => { },
201 Some(Anyway::Dir) => {
203 let anyway_none = |k| match k {
204 EK::NotFound => Some(AnywayNone),
208 let mk = |leaf: &str| {
209 [ toplevel, &PathBuf::from(leaf) ]
210 .iter().collect::<PathBuf>()
213 for &(try_main, desc) in &[
214 ("main.cfg", "main config file"),
215 ("master.cfg", "obsolete-named main config file"),
217 let main = mk(try_main);
219 match self.read_file(&main, &anyway_none)
220 .dcontext(main).context(desc)?
223 Some(AnywayNone) => { },
227 for &(try_dir, desc) in &[
228 ("config.d", "per-link config directory"),
229 ("secrets.d", "per-link secrets directory"),
231 let dir = mk(try_dir);
232 match self.read_dir_d(&dir, &anyway_none).context(desc)? {
234 Some(AnywayNone) => { },
241 #[throws(AE)] // AE includes extra, but does that this is extra
242 fn read_extra(&mut self, extra: &Path) {
245 match self.read_file(extra, &|k| match k {
246 EK::IsADirectory => Some(AnywayDir),
253 self.read_dir_d(extra, &|_| None::<Void>)?;
260 enum LinkEnd { Server, Client }
262 struct ResolveContext<'c> {
266 all_sections: Vec<SectionName>,
269 trait Parseable: Sized {
270 fn parse(s: &Option<String>) -> Result<Self, AE>;
273 impl Parseable for Duration {
275 fn parse(s: &Option<String>) -> Duration {
276 let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
277 if let Ok(u64) = s.parse() { return Duration::from_secs(u64) }
278 throw!(anyhow!("xxx parse with humantime"))
281 macro_rules! parseable_from_str { ($t:ty) => {
282 impl Parseable for $t {
284 fn parse(s: &Option<String>) -> $t {
285 let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
290 parseable_from_str!{u32}
291 parseable_from_str!{IpAddr}
293 impl<T:Parseable> Parseable for Vec<T> {
295 fn parse(s: &Option<String>) -> Vec<T> {
296 let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
297 s.split_ascii_whitespace()
299 .collect::<Result<Vec<_>>>()?
304 #[derive(Debug,Copy,Clone)]
305 enum SectionKindList {
312 use SectionKindList as SKL;
314 impl SectionKindList {
315 fn contains(self, s: &SectionName) -> bool {
317 SKL::Ordinary => matches!(s, SN::Link(_)
322 SKL::Limits => matches!(s, SN::ServerLimit(_)
325 SKL::ClientAgnostic => matches!(s, SN::Common
328 SKL::Limited => SKL::Ordinary.contains(s)
329 | SKL::Limits .contains(s),
331 SKL::ServerName => matches!(s, SN::Common)
332 | matches!(s, SN::Server(ServerName(name))
333 if name == "SERVER"),
338 impl<'c> ResolveContext<'c> {
339 fn first_of_raw(&self, key: &'static str, sections: SectionKindList)
340 -> Option<&'c RawVal> {
341 for section in self.all_sections.iter()
342 .filter(|s| sections.contains(s))
344 if let Some(raw) = self.agg.sections
346 .and_then(|vars: &SectionMap| vars.get(key))
355 fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
359 match self.first_of_raw(key, sections) {
362 Parseable::parse(&raw.val)
364 // .with_context(|| format!(r#"in section "{}""#, §ion))
371 pub fn ordinary<T>(&self, key: &'static str) -> T
372 where T: Parseable + Default
374 self.first_of(key, SKL::Ordinary)?
379 pub fn limited<T>(&self, key: &'static str) -> T
380 where T: Parseable + Default + Ord
382 let val = self.ordinary(key)?;
383 if let Some(limit) = self.first_of(key, SKL::Limits)? {
391 pub fn client<T>(&self, key: &'static str) -> T
392 where T: Parseable + Default {
394 LinkEnd::Client => self.ordinary(key)?,
395 LinkEnd::Server => default(),
399 pub fn server<T>(&self, key: &'static str) -> T
400 where T: Parseable + Default {
402 LinkEnd::Server => self.ordinary(key)?,
403 LinkEnd::Client => default(),
408 pub fn special_ipif<T>(&self, key: &'static str) -> T
409 where T: Parseable + Default
412 LinkEnd::Client => self.ordinary(key)?,
414 self.first_of(key, SKL::ClientAgnostic)?
422 impl<'c> ResolveContext<'c> {
424 fn resolve_instance(&self) -> InstanceConfig {
426 max_batch_down: self.limited::<u32>("max_batch_down")?,
434 let opts = config::Opts::from_args();
437 let mut agg = Aggregate::default();
439 agg.read_toplevel(&opts.config)?;
440 for extra in &opts.extra_config {
441 agg.read_extra(extra).context("extra config")?;
444 eprintln!("GOT {:#?}", agg);
447 })().context("read configuration")?;
449 let link = LinkName {
450 server: "fooxxx".parse().unwrap(),
451 client: "127.0.0.1".parse().unwrap(),
454 let rctx = ResolveContext {
457 end: LinkEnd::Server,
459 SN::Link(link.clone()),
460 SN::Client(link.client.clone()),
461 SN::Server(link.server.clone()),
463 SN::ServerLimit(link.server.clone()),