Skip to main content

rustic_rs/
config.rs

1//! Rustic Config
2//!
3//! See instructions in `commands.rs` to specify the path to your
4//! application's configuration file and/or command-line options
5//! for specifying it.
6
7pub(crate) mod hooks;
8pub(crate) mod logging;
9pub(crate) mod progress_options;
10
11use std::{
12    collections::BTreeMap,
13    fmt::{self, Display, Formatter},
14    path::PathBuf,
15};
16
17use abscissa_core::{FrameworkError, FrameworkErrorKind, config::Config, path::AbsPathBuf};
18use anyhow::{Result, anyhow};
19use clap::{Parser, ValueHint};
20use conflate::Merge;
21use directories::ProjectDirs;
22use itertools::Itertools;
23use jiff::{Timestamp, Zoned, tz::TimeZone};
24use log::Level;
25use reqwest::Url;
26use rustic_core::SnapshotGroupCriterion;
27use serde::{Deserialize, Serialize};
28use serde_with::{DisplayFromStr, serde_as};
29#[cfg(not(all(feature = "mount", feature = "webdav")))]
30use toml::Value;
31
32#[cfg(feature = "mount")]
33use crate::commands::mount::MountCmd;
34#[cfg(feature = "webdav")]
35use crate::commands::webdav::WebDavCmd;
36
37use crate::{
38    commands::{backup::BackupCmd, copy::CopyCmd, forget::ForgetOptions},
39    config::{hooks::Hooks, logging::LoggingOptions, progress_options::ProgressOptions},
40    filtering::SnapshotFilter,
41    repository::AllRepositoryOptions,
42};
43
44/// Rustic Configuration
45///
46/// Further documentation can be found [here](https://github.com/rustic-rs/rustic/blob/main/config/README.md).
47///
48/// # Example
49// TODO: add example
50#[derive(Clone, Default, Debug, Parser, Deserialize, Serialize, Merge)]
51#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
52pub struct RusticConfig {
53    /// Global options
54    #[clap(flatten, next_help_heading = "Global options")]
55    pub global: GlobalOptions,
56
57    /// Repository options
58    #[clap(flatten, next_help_heading = "Repository options")]
59    pub repository: AllRepositoryOptions,
60
61    /// Snapshot filter options
62    #[clap(flatten, next_help_heading = "Snapshot filter options")]
63    pub snapshot_filter: SnapshotFilter,
64
65    /// Backup options
66    #[clap(skip)]
67    pub backup: BackupCmd,
68
69    /// Copy options
70    #[clap(skip)]
71    pub copy: CopyCmd,
72
73    /// Forget options
74    #[clap(skip)]
75    pub forget: ForgetOptions,
76
77    /// mount options
78    #[cfg(feature = "mount")]
79    #[clap(skip)]
80    pub mount: MountCmd,
81    #[cfg(not(feature = "mount"))]
82    #[clap(skip)]
83    #[merge(skip)]
84    pub mount: Option<Value>,
85
86    /// webdav options
87    #[cfg(feature = "webdav")]
88    #[clap(skip)]
89    pub webdav: WebDavCmd,
90    #[cfg(not(feature = "webdav"))]
91    #[clap(skip)]
92    #[merge(skip)]
93    pub webdav: Option<Value>,
94}
95
96impl Display for RusticConfig {
97    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
98        let config = toml::to_string_pretty(self)
99            .unwrap_or_else(|_| "<Error serializing config>".to_string());
100
101        write!(f, "{config}",)
102    }
103}
104
105impl RusticConfig {
106    /// Merge a profile into the current config by reading the corresponding config file.
107    /// Also recursively merge all profiles given within this config file.
108    ///
109    /// # Arguments
110    ///
111    /// * `profile` - name of the profile to merge
112    /// * `merge_logs` - Vector to collect logs during merging
113    /// * `level_missing` - The log level to use if this profile is missing. Recursive calls will produce a Warning.
114    pub fn merge_profile(
115        &mut self,
116        profile: &str,
117        merge_logs: &mut Vec<(Level, String)>,
118        level_missing: Level,
119    ) -> Result<(), FrameworkError> {
120        let profile_filename = if profile.ends_with(".toml") {
121            profile.to_string()
122        } else {
123            profile.to_string() + ".toml"
124        };
125        let paths = get_config_paths(&profile_filename);
126
127        if let Some(path) = paths.iter().find(|path| path.exists()) {
128            merge_logs.push((Level::Info, format!("using config {}", path.display())));
129            let config_content = std::fs::read_to_string(AbsPathBuf::canonicalize(path)?)?;
130            let config_content = if self.global.profile_substitute_env {
131                subst::substitute(&config_content, &subst::Env).map_err(|e| {
132                    abscissa_core::error::context::Context::new(
133                        FrameworkErrorKind::ParseError,
134                        Some(Box::new(e)),
135                    )
136                })?
137            } else {
138                config_content
139            };
140            let mut config = Self::load_toml(config_content)?;
141            // sanity check
142            if config.global.profile_substitute_env && config.global.use_profiles.is_empty() {
143                merge_logs.push((Level::Warn, "Option `profile-substitute-env` is given without any profiles to load! Note that this option does NOT apply to the file where it is specified!".to_string()));
144            }
145            // if "use_profile" is defined in config file, merge the referenced profiles first
146            for profile in &config.global.use_profiles.clone() {
147                config.merge_profile(profile, merge_logs, Level::Warn)?;
148            }
149            self.merge(config);
150        } else {
151            let paths_string = paths.iter().map(|path| path.display()).join(", ");
152            merge_logs.push((
153                level_missing,
154                format!("using no config file, none of these exist: {paths_string}",),
155            ));
156        };
157        Ok(())
158    }
159}
160
161/// Global options
162///
163/// These options are available for all commands.
164#[serde_as]
165#[derive(Default, Debug, Parser, Clone, Deserialize, Serialize, Merge)]
166#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
167pub struct GlobalOptions {
168    /// Substitute environment variables in profiles
169    #[clap(long, global = true, env = "RUSTIC_PROFILE_SUBSTITUTE_ENV")]
170    #[merge(strategy=conflate::bool::overwrite_false)]
171    pub profile_substitute_env: bool,
172
173    /// Config profile to use. This parses the file `<PROFILE>.toml` in the config directory.
174    /// [default: "rustic"]
175    #[clap(
176        short = 'P',
177        long = "use-profile",
178        global = true,
179        value_name = "PROFILE",
180        env = "RUSTIC_USE_PROFILE"
181    )]
182    #[merge(strategy=conflate::vec::append)]
183    pub use_profiles: Vec<String>,
184
185    /// Group snapshots by any combination of host,label,paths,tags, e.g. to find the latest snapshot [default: "host,label,paths"]
186    #[clap(
187        long,
188        short = 'g',
189        global = true,
190        value_name = "CRITERION",
191        env = "RUSTIC_GROUP_BY"
192    )]
193    #[serde_as(as = "Option<DisplayFromStr>")]
194    #[merge(strategy=conflate::option::overwrite_none)]
195    pub group_by: Option<SnapshotGroupCriterion>,
196
197    /// Only show what would be done without modifying anything. Does not affect read-only commands.
198    #[clap(long, short = 'n', global = true, env = "RUSTIC_DRY_RUN")]
199    #[merge(strategy=conflate::bool::overwrite_false)]
200    pub dry_run: bool,
201
202    /// Additional to dry run, but still issue warm-up command if configured
203    #[clap(long, global = true, env = "RUSTIC_DRY_RUN_WARMUP")]
204    #[merge(strategy=conflate::bool::overwrite_false)]
205    pub dry_run_warmup: bool,
206
207    /// Check if index matches pack files and read pack headers if necessary
208    #[clap(long, global = true, env = "RUSTIC_CHECK_INDEX")]
209    #[merge(strategy=conflate::bool::overwrite_false)]
210    pub check_index: bool,
211
212    /// Settings to customize logging
213    #[clap(flatten)]
214    #[serde(flatten)]
215    pub logging_options: LoggingOptions,
216
217    /// Settings to customize progress bars
218    #[clap(flatten)]
219    #[serde(flatten)]
220    pub progress_options: ProgressOptions,
221
222    /// Hooks
223    #[clap(skip)]
224    pub hooks: Hooks,
225
226    /// List of environment variables to set (only in config file)
227    #[clap(skip)]
228    #[merge(strategy = conflate::btreemap::append_or_ignore)]
229    pub env: BTreeMap<String, String>,
230
231    /// Push metrics to a Prometheus Pushgateway
232    #[serde_as(as = "Option<DisplayFromStr>")]
233    #[clap(long, global = true, env = "RUSTIC_PROMETHEUS", value_name = "PUSHGATEWAY_URL", value_hint = ValueHint::Url)]
234    #[merge(strategy=conflate::option::overwrite_none)]
235    pub prometheus: Option<Url>,
236
237    /// Authenticate to Prometheus Pushgateway using this user
238    #[clap(long, value_name = "USER", env = "RUSTIC_PROMETHEUS_USER")]
239    #[merge(strategy=conflate::option::overwrite_none)]
240    pub prometheus_user: Option<String>,
241
242    /// Authenticate to Prometheus Pushgateway using this password
243    #[clap(long, value_name = "PASSWORD", env = "RUSTIC_PROMETHEUS_PASS")]
244    #[merge(strategy=conflate::option::overwrite_none)]
245    pub prometheus_pass: Option<String>,
246
247    /// Additional labels to set to generated metrics
248    #[clap(skip)]
249    #[merge(strategy=conflate::btreemap::append_or_ignore)]
250    pub metrics_labels: BTreeMap<String, String>,
251
252    /// OpenTelemetry metrics endpoint (HTTP Protobuf)
253    #[serde_as(as = "Option<DisplayFromStr>")]
254    #[clap(long, global = true, env = "RUSTIC_OTEL", value_name = "ENDPOINT_URL", value_hint = ValueHint::Url)]
255    #[merge(strategy=conflate::option::overwrite_none)]
256    pub opentelemetry: Option<Url>,
257
258    /// Show time offsets instead of converting to system time zone
259    #[clap(long, global = true, env = "RUSTIC_SHOW_TIME_OFFSET")]
260    #[merge(strategy=conflate::bool::overwrite_false)]
261    pub show_time_offset: bool,
262}
263
264pub fn parse_labels(s: &str) -> Result<BTreeMap<String, String>> {
265    s.split(',')
266        .filter_map(|s| {
267            let s = s.trim();
268            (!s.is_empty()).then_some(s)
269        })
270        .map(|s| -> Result<_> {
271            let pos = s.find('=').ok_or_else(|| {
272                anyhow!("invalid prometheus label definition: no `=` found in `{s}`")
273            })?;
274            Ok((s[..pos].to_owned(), s[pos + 1..].to_owned()))
275        })
276        .try_collect()
277}
278
279impl GlobalOptions {
280    pub fn is_metrics_configured(&self) -> bool {
281        self.prometheus.is_some() || self.opentelemetry.is_some()
282    }
283
284    pub fn format_timestamp(&self, timestamp: Timestamp) -> String {
285        self.format_time(&timestamp.to_zoned(TimeZone::UTC))
286            .to_string()
287    }
288
289    pub fn format_time(&self, time: &Zoned) -> impl Display {
290        if self.show_time_offset {
291            time.strftime("%Y-%m-%d %H:%M:%S%z")
292        } else {
293            let tz = TimeZone::system();
294            if time.offset() == tz.to_offset(time.timestamp()) {
295                time.strftime("%Y-%m-%d %H:%M:%S")
296            } else {
297                time.with_time_zone(tz).strftime("%Y-%m-%d %H:%M:%S*")
298            }
299        }
300    }
301}
302
303/// Get the paths to the config file
304///
305/// # Arguments
306///
307/// * `filename` - name of the config file
308///
309/// # Returns
310///
311/// A vector of [`PathBuf`]s to the config files
312fn get_config_paths(filename: &str) -> Vec<PathBuf> {
313    [
314        ProjectDirs::from("", "", "rustic")
315            .map(|project_dirs| project_dirs.config_dir().to_path_buf()),
316        get_global_config_path(),
317        Some(PathBuf::from(".")),
318    ]
319    .into_iter()
320    .filter_map(|path| {
321        path.map(|mut p| {
322            p.push(filename);
323            p
324        })
325    })
326    .collect()
327}
328
329/// Get the path to the global config directory on Windows.
330///
331/// # Returns
332///
333/// The path to the global config directory on Windows.
334/// If the environment variable `PROGRAMDATA` is not set, `None` is returned.
335#[cfg(target_os = "windows")]
336fn get_global_config_path() -> Option<PathBuf> {
337    std::env::var_os("PROGRAMDATA").map(|program_data| {
338        let mut path = PathBuf::from(program_data);
339        path.push(r"rustic\config");
340        path
341    })
342}
343
344/// Get the path to the global config directory on ios and wasm targets.
345///
346/// # Returns
347///
348/// `None` is returned.
349#[cfg(any(target_os = "ios", target_arch = "wasm32"))]
350fn get_global_config_path() -> Option<PathBuf> {
351    None
352}
353
354/// Get the path to the global config directory on non-Windows,
355/// non-iOS, non-wasm targets.
356///
357/// # Returns
358///
359/// "/etc/rustic" is returned.
360#[cfg(not(any(target_os = "windows", target_os = "ios", target_arch = "wasm32")))]
361fn get_global_config_path() -> Option<PathBuf> {
362    Some(PathBuf::from("/etc/rustic"))
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368    use insta::{assert_debug_snapshot, assert_snapshot};
369
370    #[test]
371    fn test_default_config_passes() {
372        let config = RusticConfig::default();
373
374        assert_debug_snapshot!(config);
375    }
376
377    #[test]
378    fn test_default_config_display_passes() {
379        let config = RusticConfig::default();
380
381        assert_snapshot!(config);
382    }
383
384    #[test]
385    fn test_global_env_roundtrip_passes() {
386        let mut config = RusticConfig::default();
387
388        for i in 0..10 {
389            let _ = config
390                .global
391                .env
392                .insert(format!("KEY{i}"), format!("VALUE{i}"));
393        }
394
395        let serialized = toml::to_string(&config).unwrap();
396
397        // Check Serialization
398        assert_snapshot!(serialized);
399
400        let deserialized: RusticConfig = toml::from_str(&serialized).unwrap();
401        // Check Deserialization and Display
402        assert_snapshot!(deserialized);
403
404        // Check Debug
405        assert_debug_snapshot!(deserialized);
406    }
407}