chiark / gitweb /
config, wip parsing
[hippotat.git] / src / config.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: AGPL-3.0-or-later
3 // There is NO WARRANTY.
4
5 use crate::prelude::*;
6
7 use configparser::ini::Ini;
8
9 #[derive(StructOpt,Debug)]
10 pub struct Opts {
11   /// Top-level config file or directory
12   ///
13   /// Look for `main.cfg`, `config.d` and `secrets.d` here.
14   ///
15   /// Or if this is a file, just read that file.
16   #[structopt(long, default_value="/etc/hippotat")]
17   pub config: PathBuf,
18   
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>,
22 }
23
24 pub struct CidrString(pub String);
25
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,
32
33   // Capped settings:
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,
38
39   // Ordinary settings:
40   pub addrs:                        Vec<IpAddr>,
41 //xxx  pub vnetwork:                     Vec<CidrString>,
42   pub vaddr:                        Vec<IpAddr>,
43   pub vrelay:                       IpAddr,
44   pub port:                         u16,
45   pub mtu:                          u32,
46   pub ifname_server:                String,
47   pub ifname_client:                String,
48
49   // Ordinary settings, used by server only:
50   #[server]  pub max_clock_skew:               Duration,
51
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 //xxx  #[client]  pub vroutes:                      Vec<CidrString>,
59 }
60
61 #[derive(Debug,Clone,Hash,Eq,PartialEq)]
62 pub enum SectionName {
63   Link(LinkName),
64   Client(ClientName),
65   Server(ServerName), // includes SERVER, which is slightly special
66   ServerLimit(ServerName),
67   GlobalLimit,
68   Common,
69   Default,
70 }
71 pub use SectionName as SN;
72
73 #[derive(Debug,Clone)]
74 struct RawVal { val: Option<String>, loc: Arc<PathBuf> }
75 type SectionMap = HashMap<String, RawVal>;
76
77 pub struct Config {
78   opts: Opts,
79 }
80
81 static OUTSIDE_SECTION: &str = "[";
82 static SPECIAL_SERVER_SECTION: &str = "SERVER";
83
84 #[derive(Default,Debug)]
85 struct Aggregate {
86   sections: HashMap<SectionName, SectionMap>,
87 }
88
89 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
90 #[ext]
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()?;
94     let k = e.kind();
95     let a = self(k)?;
96     Some(a)
97   }
98 }
99
100 impl FromStr for SectionName {
101   type Err = AE;
102   #[throws(AE)]
103   fn from_str(s: &str) -> Self {
104     match s {
105       "COMMON" => return SN::Common,
106       "DEFAULT" => return SN::Default,
107       "LIMIT" => return SN::GlobalLimit,
108       _ => { }
109     };
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>",
116         s
117       ))?;
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 })
122   }
123 }
124
125 impl Aggregate {
126   #[throws(AE)] // AE does not include path
127   fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
128   {
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")?;
132
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) }
136     y.context("read")?;
137
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"));
144     }
145
146     let loc = Arc::new(path.to_owned());
147
148     for (sn, vars) in map {
149       dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
150
151       let sn = sn.parse().dcontext(&sn)?;
152         self.sections.entry(sn)
153         .or_default()
154         .extend(
155           vars.into_iter()
156             .map(|(k,val)| {
157               (k.replace('-',"_"),
158                RawVal { val, loc: loc.clone() })
159             })
160         );
161     }
162     None
163   }
164
165   #[throws(AE)] // AE includes path
166   fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
167   {
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)?;
171     for ent in dir {
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()
179       ) { continue }
180
181       // OK we want this one
182       let ent = ent.path();
183       self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
184     }
185     None
186   }
187
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),
194       _ => None,
195     })
196       .dcontext(toplevel).context("top-level config directory (or file)")?
197     {
198       None | Some(Anyway::None) => { },
199
200       Some(Anyway::Dir) => {
201         struct AnywayNone;
202         let anyway_none = |k| match k {
203           EK::NotFound => Some(AnywayNone),
204           _ => None,
205         };
206
207         let mk = |leaf: &str| {
208           [ toplevel, &PathBuf::from(leaf) ]
209             .iter().collect::<PathBuf>()
210         };
211
212         for &(try_main, desc) in &[
213           ("main.cfg", "main config file"),
214           ("master.cfg", "obsolete-named main config file"),
215         ] {
216           let main = mk(try_main);
217
218           match self.read_file(&main, &anyway_none)
219             .dcontext(main).context(desc)?
220           {
221             None => break,
222             Some(AnywayNone) => { },
223           }
224         }
225
226         for &(try_dir, desc) in &[
227           ("config.d", "per-link config directory"),
228           ("secrets.d", "per-link secrets directory"),
229         ] {
230           let dir = mk(try_dir);
231           match self.read_dir_d(&dir, &anyway_none).context(desc)? {
232             None => { },
233             Some(AnywayNone) => { },
234           }
235         }
236       }
237     }
238   }
239
240   #[throws(AE)] // AE includes extra, but does that this is extra
241   fn read_extra(&mut self, extra: &Path) {
242     struct AnywayDir;
243
244     match self.read_file(extra, &|k| match k {
245       EK::IsADirectory => Some(AnywayDir),
246       _ => None,
247     })
248       .dcontext(extra)?
249     {
250       None => return,
251       Some(AnywayDir) => {
252         self.read_dir_d(extra, &|_| None::<Void>)?;
253       }
254     }
255
256   }
257 }
258
259 enum LinkEnd { Server, Client }
260
261 struct ResolveContext<'c> {
262   agg: &'c Aggregate,
263   link: &'c LinkName,
264   end: LinkEnd,
265   all_sections: Vec<SectionName>,
266   special_server_section: SectionName,
267 }
268
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"))
273   }
274   #[throws(AE)]
275   fn default_for_key(key: &str) -> Self {
276     Self::default().with_context(|| key.to_string())?
277   }
278 }
279
280 impl Parseable for Duration {
281   #[throws(AE)]
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"))
286   }
287 }
288 macro_rules! parseable_from_str { ($t:ty $(, $def:expr)? ) => {
289   impl Parseable for $t {
290     #[throws(AE)]
291     fn parse(s: Option<&str>) -> $t {
292       let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
293       s.parse()?
294     }
295     $(
296       #[throws(AE)] fn default() -> Self { $def }
297     )?
298   }
299 } }
300 parseable_from_str!{u16, default() }
301 parseable_from_str!{u32, default() }
302 parseable_from_str!{String, default() }
303 parseable_from_str!{IpAddr, Ipv4Addr::UNSPECIFIED.into() }
304 parseable_from_str!{Uri, default() }
305
306 impl<T:Parseable> Parseable for Vec<T> {
307   #[throws(AE)]
308   fn parse(s: Option<&str>) -> Vec<T> {
309     let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
310     s.split_ascii_whitespace()
311       .map(|s| Parseable::parse(Some(s)))
312       .collect::<Result<Vec<_>,_>>()?
313   }
314 }
315
316
317 #[derive(Debug,Copy,Clone)]
318 enum SectionKindList {
319   Ordinary,
320   Limited,
321   Limits,
322   ClientAgnostic,
323   ServerName,
324 }
325 use SectionKindList as SKL;
326
327 impl SectionName {
328   fn special_server_section() -> Self { SN::Server(ServerName(
329     SPECIAL_SERVER_SECTION.into()
330   )) }
331 }
332
333 impl SectionKindList {
334   fn contains(self, s: &SectionName) -> bool {
335     match self {
336       SKL::Ordinary       => matches!(s, SN::Link(_)
337                                        | SN::Client(_)
338                                        | SN::Server(_)
339                                        | SN::Common),
340
341       SKL::Limits         => matches!(s, SN::ServerLimit(_)
342                                        | SN::GlobalLimit),
343
344       SKL::ClientAgnostic => matches!(s, SN::Common
345                                        | SN::Server(_)),
346
347       SKL::Limited        => SKL::Ordinary.contains(s)
348                            | SKL::Limits  .contains(s),
349
350       SKL::ServerName     => matches!(s, SN::Common)
351                            | matches!(s, SN::Server(ServerName(name))
352                                          if name == SPECIAL_SERVER_SECTION),
353     }
354   }
355 }
356
357 impl<'c> ResolveContext<'c> {
358   fn lookup_raw<'n, S>(&self, key: &'static str, sections: S)
359                        -> Option<&'c RawVal>
360   where S: Iterator<Item=&'n SectionName>
361   {
362     for section in sections {
363       if let Some(raw) = self.agg.sections
364         .get(section)
365         .and_then(|vars: &SectionMap| vars.get(key))
366       {
367         return Some(raw)
368       }
369     }
370     None
371   }
372
373   fn first_of_raw(&self, key: &'static str, sections: SectionKindList)
374                   -> Option<&'c RawVal> {
375     self.lookup_raw(
376       key,
377       self.all_sections.iter()
378         .filter(|s| sections.contains(s))
379     )
380   }
381
382   #[throws(AE)]
383   fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
384                  -> Option<T>
385   where T: Parseable
386   {
387     match self.first_of_raw(key, sections) {
388       None => None,
389       Some(raw) => Some({
390         Parseable::parse(raw.val.as_deref())
391           .context(key)
392 //          .with_context(|| format!(r#"in section "{}""#, &section))
393           .dcontext(&raw.loc)?
394       }),
395     }
396   }
397
398   #[throws(AE)]
399   pub fn ordinary<T>(&self, key: &'static str) -> T
400   where T: Parseable
401   {
402     match self.first_of(key, SKL::Ordinary)? {
403       Some(y) => y,
404       None => Parseable::default_for_key(key)?,
405     }
406   }
407
408   #[throws(AE)]
409   pub fn limited<T>(&self, key: &'static str) -> T
410   where T: Parseable + Ord
411   {
412     let val = self.ordinary(key)?;
413     if let Some(limit) = self.first_of(key, SKL::Limits)? {
414       min(val, limit)
415     } else {
416       val
417     }
418   }
419
420   #[throws(AE)]
421   pub fn client<T>(&self, key: &'static str) -> T
422   where T: Parseable {
423     match self.end {
424       LinkEnd::Client => self.ordinary(key)?,
425       LinkEnd::Server => Parseable::default_for_key(key)?,
426     }
427   }
428   #[throws(AE)]
429   pub fn server<T>(&self, key: &'static str) -> T
430   where T: Parseable {
431     match self.end {
432       LinkEnd::Server => self.ordinary(key)?,
433       LinkEnd::Client => Parseable::default_for_key(key)?,
434     }
435   }
436
437   #[throws(AE)]
438   pub fn special_ipif(&self, key: &'static str) -> String {
439     match self.end {
440       LinkEnd::Client => self.ordinary(key)?,
441       LinkEnd::Server => {
442         self.first_of(key, SKL::ClientAgnostic)?
443           .unwrap_or_default()
444       },
445     }
446   }
447
448   #[throws(AE)]
449   pub fn special_server(&self, key: &'static str) -> ServerName {
450     let raw = match self.lookup_raw(
451       "server",
452       [ &SectionName::Common, &self.special_server_section ].iter().cloned()
453     ) {
454       Some(RawVal { val: Some(ref got),.. }) => got,
455       Some(RawVal { val: None,.. }) => throw!(anyhow!("value needed")),
456       None => SPECIAL_SERVER_SECTION,
457     };
458     ServerName(raw.into())
459   }
460 }
461
462 /*
463 impl<'c> ResolveContext<'c> {
464   #[throws(AE)]
465   fn resolve_instance(&self) -> InstanceConfig {
466     InstanceConfig {
467       max_batch_down: self.limited::<u32>("max_batch_down")?,
468     }
469   }
470 }
471 */
472
473 #[throws(AE)]
474 pub fn read() {
475   let opts = config::Opts::from_args();
476
477   let agg = (||{
478     let mut agg = Aggregate::default();
479
480     agg.read_toplevel(&opts.config)?;
481     for extra in &opts.extra_config {
482       agg.read_extra(extra).context("extra config")?;
483     }
484
485     eprintln!("GOT {:#?}", agg);
486
487     Ok::<_,AE>(agg)
488   })().context("read configuration")?;
489
490   let link = LinkName {
491     server: "fooxxx".parse().unwrap(),
492     client: "127.0.0.1".parse().unwrap(),
493   };
494
495   let rctx = ResolveContext {
496     agg: &agg,
497     link: &link,
498     end: LinkEnd::Server,
499     all_sections: vec![
500       SN::Link(link.clone()),
501       SN::Client(link.client.clone()),
502       SN::Server(link.server.clone()),
503       SN::Common,
504       SN::ServerLimit(link.server.clone()),
505       SN::GlobalLimit,
506     ],
507     special_server_section: SN::special_server_section(),
508   };
509 }