system_update_committer/
config.rs

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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use anyhow::anyhow;
use serde::Deserialize;
use std::fs::File;
use std::io::Read;
use thiserror::Error;
use tracing::{error, info};
use typed_builder::TypedBuilder;

/// Static service configuration options.
#[derive(Debug, PartialEq, Eq, TypedBuilder)]
pub struct Config {
    #[builder(default)]
    blobfs: Mode,

    #[builder(default)]
    netstack: Mode,

    #[builder(default = true)]
    enable: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum Mode {
    #[default]
    Ignore,
    RebootOnFailure,
}

impl Config {
    pub fn blobfs(&self) -> &Mode {
        &self.blobfs
    }

    pub fn netstack(&self) -> &Mode {
        &self.netstack
    }

    pub fn enable(&self) -> bool {
        self.enable
    }

    pub fn load_from_config_data_or_default() -> Config {
        let f = match File::open("/config/data/config.json") {
            Ok(f) => f,
            Err(e) => {
                info!("no config found, using defaults: {:#}", anyhow!(e));
                return Config::builder().build();
            }
        };

        Self::load(f).unwrap_or_else(|e| {
            error!("unable to load config, using defaults: {:#}", anyhow!(e));
            Config::builder().build()
        })
    }

    fn enable_default() -> bool {
        true
    }

    fn load(r: impl Read) -> Result<Config, ConfigLoadError> {
        #[derive(Debug, Deserialize)]
        #[serde(deny_unknown_fields)]
        pub struct ParseConfig {
            #[serde(default = "Mode::default")]
            blobfs: Mode,
            #[serde(default = "Mode::default")]
            netstack: Mode,
            #[serde(default = "Config::enable_default")]
            enable: bool,
        }

        let parse_config = serde_json::from_reader::<_, ParseConfig>(r)?;

        Ok(Config {
            blobfs: parse_config.blobfs,
            netstack: parse_config.netstack,
            enable: parse_config.enable,
        })
    }
}

#[derive(Debug, Error)]
enum ConfigLoadError {
    #[error("parse error")]
    Parse(#[from] serde_json::Error),
}

#[cfg(test)]
pub(crate) mod tests {

    use super::*;
    use assert_matches::assert_matches;
    use serde_json::json;

    fn verify_load(input: serde_json::Value, expected: Config) {
        assert_eq!(
            Config::load(input.to_string().as_bytes()).expect("json value to be valid"),
            expected
        );
    }

    #[test]
    fn test_load_valid_configs() {
        for (name, val) in [("ignore", Mode::Ignore), ("reboot_on_failure", Mode::RebootOnFailure)]
        {
            // Verify that setting enable explicitly works...
            verify_load(
                json!({
                    "blobfs": name,
                    "netstack": name,
                    "enable": false,
                }),
                Config::builder().blobfs(val).netstack(val).enable(false).build(),
            );
            // ... and that leaving it unset defaults to true.
            verify_load(
                json!({
                    "blobfs": name,
                    "netstack": name,
                }),
                Config::builder().blobfs(val).netstack(val).enable(true).build(),
            );
        }
    }

    #[test]
    fn test_load_errors_on_unknown_field() {
        assert_matches!(
            Config::load(
                json!({
                    "blofs": "ignore",
                    "unknown_field": 3
                })
                .to_string()
                .as_bytes()
            ),
            Err(ConfigLoadError::Parse(_))
        );
    }

    #[test]
    fn test_no_config_data_is_default() {
        assert_eq!(Config::load_from_config_data_or_default(), Config::builder().build());
    }

    #[test]
    fn test_load_empty_is_default() {
        assert_matches!(
            Config::load("{}".as_bytes()),
            Ok(ref config) if config == &Config::builder().build());
    }

    #[test]
    fn test_load_rejects_invalid_json() {
        assert_matches!(
            Config::load("not json".as_bytes()),
            Err(ConfigLoadError::Parse(ref err)) if err.is_syntax());
    }

    #[test]
    fn test_load_rejects_invalid_mode() {
        let input = json!({
            "blobfs": "invalid-config-option",
        })
        .to_string();

        assert_matches!(
            Config::load(input.as_bytes()),
            Err(ConfigLoadError::Parse(ref err)) if err.is_data());
    }
}