summaryrefslogtreecommitdiffstats
path: root/src/config.rs
blob: 859dd48900395d0af85c4f63e79448a3fd8861e3 (plain)
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
//! Module for parsing/accessing the configuration

extern crate log;
extern crate toml;

use std::path::PathBuf;
use std::convert::TryFrom;
use regex::Regex;
use error::*;
use getset::Getters;

//------------------------------------//
//  structs for deserialization       //
//------------------------------------//

/// Holds data for one Log-File.
/// Used for deserialization only
#[derive(Clone, Debug, Deserialize)]
struct LogItemDeser {
    file : String,

    #[serde(with="serde_regex")]
    regex : Regex,
    alias : String,
}

/// Used for deserialization only
#[derive(Debug, Deserialize)]
struct ConfigDeser {
    item : Vec<LogItemDeser>,
}

impl ConfigDeser {

    /// Tries to open, read and parse a toml-file
    pub fn load(path: PathBuf) -> Result<ConfigDeser> {
        debug!("configuration file name: '{}'", path.display());

        let s = std::fs::read_to_string(&path)
            .chain_err(|| "configuration file could not be read")?;

        toml::from_str(&s)
            .map(|obj| {
                info!("successfully parsed configuration file");
                debug!("Config = {:?}", obj);
                obj
            })
            .map_err(|_| ErrorKind::ConfigParseError(path).into())
    }
}

//------------------------------------//
//  struct to access data later on    //
//------------------------------------//

/// The deserialized Item would nearly always require some operation on its
/// contents to use it, so we do those operations beforehand and only access
/// the useful data from main().
#[derive(Getters)]
pub struct LogItem {
    #[getset(get = "pub")]
    file : String,

    #[getset(get = "pub")]
    regex : Regex,

    #[getset(get = "pub")]
    alias : String,

    #[getset(get = "pub")]
    capture_names : Vec<String>,

    #[getset(get = "pub")]
    aliases : Vec<String>,
}

impl TryFrom<LogItemDeser> for LogItem {
    type Error = crate::error::Error;

    /// Transforms a LogItemDeser into a more immediately usable LogItem
    fn try_from(lid : LogItemDeser) -> std::result::Result<LogItem, Self::Error> {
        // first capture is the whole match and nameless
        // second capture is always the timestamp
        let cnames : Vec<String> = lid.regex
            .capture_names()
            .skip(2)
            .filter_map(|n| n)
            .map(|n| String::from(n))
            .collect();
        debug!("capture names: {:?}", cnames);

        // The metric seen by grafana will be `alias.capturegroup_name`
        // One Regex may contain multiple named capture groups, so a vector
        // with all names is prepared here.
        let als = cnames.iter()
            .map(|name| {
                let mut temp = String::from(lid.alias.as_str());
                temp.push('.');
                temp.push_str(name.as_str());
                temp
            })
            .collect();
        debug!("aliases: {:?}", als);

        Ok(
            LogItem {
                file : lid.file,
                regex : lid.regex,
                alias: lid.alias,
                capture_names : cnames,
                aliases : als
            }
        )
    }
}

/// Contains more immediately usable data
#[derive(Getters)]
pub struct Config {
    #[getset(get = "pub")]
    items : Vec<LogItem>,

    #[getset(get = "pub")]
    all_aliases : Vec<String>,
}

impl Config {
    pub fn load(path: PathBuf) -> Result<Self> {
        ConfigDeser::load(path).and_then(Self::try_from)
    }
}

impl TryFrom<ConfigDeser> for Config {
    type Error = crate::error::Error;

    /// Lets serde do the deserialization, and transforms the given data
    /// for later access
    fn try_from(conf_deser: ConfigDeser) -> std::result::Result<Self, Self::Error> {
        let items: Vec<LogItem> = conf_deser.item
            .into_iter()
            .map(LogItem::try_from)
            .collect::<Result<_>>()?;

        // combines all aliases into one Vec for the /search endpoint
        let all_aliases = items.iter()
            .map(|li| li.aliases())
            .flatten()
            .cloned()
            .collect();

        Ok(Config { items, all_aliases })
    }
}