1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Copyright (c) Facebook, Inc. and its affiliates.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fs;
use std::path::Path;
use std::path::PathBuf;

use anyhow::bail;
use anyhow::Result;
use once_cell::sync::OnceCell;
use serde::Deserialize;
use serde::Serialize;

#[cfg(test)]
mod test;

pub const BELOW_DEFAULT_CONF: &str = "/etc/below/below.conf";
const BELOW_DEFAULT_LOG: &str = "/var/log/below";
const BELOW_DEFAULT_STORE: &str = "/var/log/below/store";

/// Global below config
pub static BELOW_CONFIG: OnceCell<BelowConfig> = OnceCell::new();

#[derive(Serialize, Deserialize, Debug)]
// If value is missing during deserialization, use the Default::default()
#[serde(default)]
pub struct BelowConfig {
    pub log_dir: PathBuf,
    pub store_dir: PathBuf,
    pub cgroup_root: PathBuf,
    pub cgroup_filter_out: String,
    pub enable_gpu_stats: bool,
    pub use_rgpu_for_gpu_stats: bool,
    pub enable_btrfs_stats: bool,
    pub btrfs_samples: u64,
    pub btrfs_min_pct: f64,
}

impl Default for BelowConfig {
    fn default() -> Self {
        BelowConfig {
            log_dir: BELOW_DEFAULT_LOG.into(),
            store_dir: BELOW_DEFAULT_STORE.into(),
            cgroup_root: cgroupfs::DEFAULT_CG_ROOT.into(),
            cgroup_filter_out: String::new(),
            enable_gpu_stats: false,
            use_rgpu_for_gpu_stats: true,
            enable_btrfs_stats: false,
            btrfs_samples: btrfs::DEFAULT_SAMPLES,
            btrfs_min_pct: btrfs::DEFAULT_MIN_PCT,
        }
    }
}

impl BelowConfig {
    pub fn load(path: &Path) -> Result<Self> {
        match path.exists() {
            true if !path.is_file() => bail!("{} exists and is not a file", path.to_string_lossy()),
            true => BelowConfig::load_exists(path),
            false if path.to_string_lossy() == BELOW_DEFAULT_CONF => Ok(Default::default()),
            false => bail!("No such file or directory: {}", path.to_string_lossy()),
        }
    }

    fn load_exists(path: &Path) -> Result<Self> {
        let string_config = match fs::read_to_string(path) {
            Ok(sc) => sc,
            Err(e) => {
                bail!(
                    "Failed to read from config file {}: {}",
                    path.to_string_lossy(),
                    e
                );
            }
        };

        match toml::from_str(string_config.as_str()) {
            Ok(bc) => Ok(bc),
            Err(e) => {
                bail!(
                    "Failed to parse config file {}: {}\n{}",
                    path.to_string_lossy(),
                    e,
                    string_config
                );
            }
        }
    }
}