chiark / gitweb /
config, wip macro
[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_name, SKL::ServerName)] pub server: String,
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   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   #[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
83 #[derive(Default,Debug)]
84 struct Aggregate {
85   sections: HashMap<SectionName, SectionMap>,
86 }
87
88 type OkAnyway<'f,A> = &'f dyn Fn(ErrorKind) -> Option<A>;
89 #[ext]
90 impl<'f,A> OkAnyway<'f,A> {
91   fn ok<T>(self, r: &Result<T, io::Error>) -> Option<A> {
92     let e = r.as_ref().err()?;
93     let k = e.kind();
94     let a = self(k)?;
95     Some(a)
96   }
97 }
98
99 impl FromStr for SectionName {
100   type Err = AE;
101   #[throws(AE)]
102   fn from_str(s: &str) -> Self {
103     match s {
104       "COMMON" => return SN::Common,
105       "DEFAULT" => return SN::Default,
106       "LIMIT" => return SN::GlobalLimit,
107       _ => { }
108     };
109     if let Ok(n@ ServerName(_)) = s.parse() { return SN::Server(n) }
110     if let Ok(n@ ClientName(_)) = s.parse() { return SN::Client(n) }
111     let (server, client) = s.split_ascii_whitespace().collect_tuple()
112       .ok_or_else(|| anyhow!(
113         "bad section name {:?} \
114          (must be COMMON, DEFAULT, <server>, <client>, or <server> <client>",
115         s
116       ))?;
117     let server = server.parse().context("server name in link section name")?;
118     if client == "LIMIT" { return SN::ServerLimit(server) }
119     let client = client.parse().context("client name in link section name")?;
120     SN::Link(LinkName { server, client })
121   }
122 }
123
124 impl Aggregate {
125   #[throws(AE)] // AE does not include path
126   fn read_file<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
127   {
128     let f = fs::File::open(path);
129     if let Some(anyway) = anyway.ok(&f) { return Some(anyway) }
130     let mut f = f.context("open")?;
131
132     let mut s = String::new();
133     let y = f.read_to_string(&mut s);
134     if let Some(anyway) = anyway.ok(&y) { return Some(anyway) }
135     y.context("read")?;
136
137     let mut ini = Ini::new_cs();
138     ini.set_default_section(OUTSIDE_SECTION);
139     ini.read(s).map_err(|e| anyhow!("{}", e)).context("parse as INI")?;
140     let map = mem::take(ini.get_mut_map());
141     if map.get(OUTSIDE_SECTION).is_some() {
142       throw!(anyhow!("INI file contains settings outside a section"));
143     }
144
145     let loc = Arc::new(path.to_owned());
146
147     for (sn, vars) in map {
148       dbg!( InstanceConfig::FIELDS );// check xxx vars are in fields
149
150       let sn = sn.parse().dcontext(&sn)?;
151         self.sections.entry(sn)
152         .or_default()
153         .extend(
154           vars.into_iter()
155             .map(|(k,val)| {
156               (k.replace('-',"_"),
157                RawVal { val, loc: loc.clone() })
158             })
159         );
160     }
161     None
162   }
163
164   #[throws(AE)] // AE includes path
165   fn read_dir_d<A>(&mut self, path: &Path, anyway: OkAnyway<A>) -> Option<A>
166   {
167     let dir = fs::read_dir(path);
168     if let Some(anyway) = anyway.ok(&dir) { return Some(anyway) }
169     let dir = dir.context("open directory").dcontext(path)?;
170     for ent in dir {
171       let ent = ent.context("read directory").dcontext(path)?;
172       let leaf = ent.file_name();
173       let leaf = leaf.to_str();
174       let leaf = if let Some(leaf) = leaf { leaf } else { continue }; //utf8?
175       if leaf.len() == 0 { continue }
176       if ! leaf.chars().all(
177         |c| c=='-' || c=='_' || c.is_ascii_alphanumeric()
178       ) { continue }
179
180       // OK we want this one
181       let ent = ent.path();
182       self.read_file(&ent, &|_| None::<Void>).dcontext(&ent)?;
183     }
184     None
185   }
186
187   #[throws(AE)] // AE includes everything
188   fn read_toplevel(&mut self, toplevel: &Path) {
189     enum Anyway { None, Dir }
190     match self.read_file(toplevel, &|k| match k {
191       EK::NotFound => Some(Anyway::None),
192       EK::IsADirectory => Some(Anyway::Dir),
193       _ => None,
194     })
195       .dcontext(toplevel).context("top-level config directory (or file)")?
196     {
197       None | Some(Anyway::None) => { },
198
199       Some(Anyway::Dir) => {
200         struct AnywayNone;
201         let anyway_none = |k| match k {
202           EK::NotFound => Some(AnywayNone),
203           _ => None,
204         };
205
206         let mk = |leaf: &str| {
207           [ toplevel, &PathBuf::from(leaf) ]
208             .iter().collect::<PathBuf>()
209         };
210
211         for &(try_main, desc) in &[
212           ("main.cfg", "main config file"),
213           ("master.cfg", "obsolete-named main config file"),
214         ] {
215           let main = mk(try_main);
216
217           match self.read_file(&main, &anyway_none)
218             .dcontext(main).context(desc)?
219           {
220             None => break,
221             Some(AnywayNone) => { },
222           }
223         }
224
225         for &(try_dir, desc) in &[
226           ("config.d", "per-link config directory"),
227           ("secrets.d", "per-link secrets directory"),
228         ] {
229           let dir = mk(try_dir);
230           match self.read_dir_d(&dir, &anyway_none).context(desc)? {
231             None => { },
232             Some(AnywayNone) => { },
233           }
234         }
235       }
236     }
237   }
238
239   #[throws(AE)] // AE includes extra, but does that this is extra
240   fn read_extra(&mut self, extra: &Path) {
241     struct AnywayDir;
242
243     match self.read_file(extra, &|k| match k {
244       EK::IsADirectory => Some(AnywayDir),
245       _ => None,
246     })
247       .dcontext(extra)?
248     {
249       None => return,
250       Some(AnywayDir) => {
251         self.read_dir_d(extra, &|_| None::<Void>)?;
252       }
253     }
254
255   }
256 }
257
258 enum LinkEnd { Server, Client }
259
260 struct ResolveContext<'c> {
261   agg: &'c Aggregate,
262   link: &'c LinkName,
263   end: LinkEnd,
264   all_sections: Vec<SectionName>,
265 }
266
267 trait Parseable: Sized {
268   fn parse(s: &Option<String>) -> Result<Self, AE>;
269 }
270
271 impl Parseable for Duration {
272   #[throws(AE)]
273   fn parse(s: &Option<String>) -> Duration {
274     let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
275     if let Ok(u64) = s.parse() { return Duration::from_secs(u64) }
276     throw!(anyhow!("xxx parse with humantime"))
277   }
278 }
279 macro_rules! parseable_from_str { ($t:ty) => {
280   impl Parseable for $t {
281     #[throws(AE)]
282     fn parse(s: &Option<String>) -> $t {
283       let s = s.as_ref().ok_or_else(|| anyhow!("value needed"))?;
284       s.parse()?
285     }
286   }
287 } }
288 parseable_from_str!{u32}
289
290 #[derive(Debug,Copy,Clone)]
291 enum SectionKindList {
292   Ordinary,
293   Limited,
294   Limits,
295   ClientAgnostic,
296   ServerName,
297 }
298 use SectionKindList as SKL;
299
300 impl SectionKindList {
301   fn contains(self, s: &SectionName) -> bool {
302     match self {
303       SKL::Ordinary       => matches!(s, SN::Link(_)
304                                        | SN::Client(_)
305                                        | SN::Server(_)
306                                        | SN::Common),
307
308       SKL::Limits         => matches!(s, SN::ServerLimit(_)
309                                        | SN::GlobalLimit),
310
311       SKL::ClientAgnostic => matches!(s, SN::Common
312                                        | SN::Server(_)),
313
314       SKL::Limited        => SKL::Ordinary.contains(s)
315                            | SKL::Limits  .contains(s),
316
317       SKL::ServerName     => matches!(s, SN::Common)
318                            | matches!(s, SN::Server(ServerName(name))
319                                          if name == "SERVER"),
320     }
321   }
322 }
323
324 impl<'c> ResolveContext<'c> {
325   fn first_of_raw(&self, key: &'static str, sections: SectionKindList)
326                   -> Option<&'c RawVal> {
327     for section in self.all_sections.iter()
328       .filter(|s| sections.contains(s))
329     {
330       if let Some(raw) = self.agg.sections
331         .get(section)
332         .and_then(|vars: &SectionMap| vars.get(key))
333       {
334         return Some(raw)
335       }
336     }
337     None
338   }
339
340   #[throws(AE)]
341   fn first_of<T>(&self, key: &'static str, sections: SectionKindList)
342                  -> Option<T>
343   where T: Parseable
344   {
345     match self.first_of_raw(key, sections) {
346       None => None,
347       Some(raw) => Some({
348         Parseable::parse(&raw.val)
349           .context(key)
350 //          .with_context(|| format!(r#"in section "{}""#, &section))
351           .dcontext(&raw.loc)?
352       }),
353     }
354   }
355
356   #[throws(AE)]
357   pub fn ordinary<T>(&self, key: &'static str) -> T
358   where T: Parseable + Default
359   {
360     self.first_of(key, SKL::Ordinary)?
361       .unwrap_or_default()
362   }
363
364   #[throws(AE)]
365   pub fn limited<T>(&self, key: &'static str) -> T
366   where T: Parseable + Default + Ord
367   {
368     let val = self.ordinary(key)?;
369     if let Some(limit) = self.first_of(key, SKL::Limits)? {
370       min(val, limit)
371     } else {
372       val
373     }
374   }
375
376   #[throws(AE)]
377   pub fn client<T>(&self, key: &'static str) -> T
378   where T: Parseable + Default {
379     match self.end {
380       LinkEnd::Client => self.ordinary(key)?,
381       LinkEnd::Server => default(),
382     }
383   }
384   #[throws(AE)]
385   pub fn server<T>(&self, key: &'static str) -> T
386   where T: Parseable + Default {
387     match self.end {
388       LinkEnd::Server => self.ordinary(key)?,
389       LinkEnd::Client => default(),
390     }
391   }
392
393   #[throws(AE)]
394   pub fn special_ipif<T>(&self, key: &'static str) -> T
395   where T: Parseable + Default
396   {
397     match self.end {
398       LinkEnd::Client => self.ordinary(key)?,
399       LinkEnd::Server => {
400         self.first_of(key, SKL::ClientAgnostic)?
401           .unwrap_or_default()
402       },
403     }
404   }
405 }
406
407 /*
408 impl<'c> ResolveContext<'c> {
409   #[throws(AE)]
410   fn resolve_instance(&self) -> InstanceConfig {
411     InstanceConfig {
412       max_batch_down: self.limited::<u32>("max_batch_down")?,
413     }
414   }
415 }
416 */
417
418 #[throws(AE)]
419 pub fn read() {
420   let opts = config::Opts::from_args();
421
422   let agg = (||{
423     let mut agg = Aggregate::default();
424
425     agg.read_toplevel(&opts.config)?;
426     for extra in &opts.extra_config {
427       agg.read_extra(extra).context("extra config")?;
428     }
429
430     eprintln!("GOT {:#?}", agg);
431
432     Ok::<_,AE>(agg)
433   })().context("read configuration")?;
434
435   let link = LinkName {
436     server: "fooxxx".parse().unwrap(),
437     client: "127.0.0.1".parse().unwrap(),
438   };
439
440   let rctx = ResolveContext {
441     agg: &agg,
442     link: &link,
443     end: LinkEnd::Server,
444     all_sections: vec![
445       SN::Link(link.clone()),
446       SN::Client(link.client.clone()),
447       SN::Server(link.server.clone()),
448       SN::Common,
449       SN::ServerLimit(link.server.clone()),
450       SN::GlobalLimit,
451     ],
452   };
453 }