summaryrefslogtreecommitdiffhomepage
path: root/tools/unitctl/unit-client-rs/src/unitd_configure_options.rs
blob: 88ab1101e49475e3944d42c22c7ab7de0ea8beef (plain) (blame)
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use custom_error::custom_error;
use std::borrow::Cow;
use std::error::Error as stdError;
use std::io::{BufRead, BufReader, Lines};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

custom_error! {UnitdStderrParseError
    VersionNotFound = "Version string output not found",
    BuildSettingsNotFound = "Build settings not found"
}

#[derive(Debug, Clone)]
pub struct UnitdConfigureOptions {
    pub version: Cow<'static, str>,
    pub all_flags: Cow<'static, str>,
}

impl UnitdConfigureOptions {
    pub fn new(unitd_path: &Path) -> Result<UnitdConfigureOptions, Box<dyn stdError>> {
        fn parse_configure_settings_from_unitd_stderr_output<B: BufRead>(
            lines: &mut Lines<B>,
        ) -> Result<UnitdConfigureOptions, Box<dyn stdError>> {
            const VERSION_PREFIX: &str = "unit version: ";
            const CONFIGURED_AS_PREFIX: &str = "configured as ";
            const CONFIGURE_PREFIX: &str = "configured as ./configure ";

            fn aggregate_parsable_lines(
                mut accum: (Option<String>, Option<String>),
                line: String,
            ) -> (Option<String>, Option<String>) {
                if line.starts_with(VERSION_PREFIX) {
                    accum.0 = line.strip_prefix(VERSION_PREFIX).map(|l| l.to_string());
                } else if line.starts_with(CONFIGURED_AS_PREFIX) {
                    accum.1 = line.strip_prefix(CONFIGURE_PREFIX).map(|l| l.to_string());
                }

                accum
            }

            let options_lines = lines
                .filter_map(|line| line.ok())
                .fold((None, None), aggregate_parsable_lines);

            if options_lines.0.is_none() {
                return Err(Box::new(UnitdStderrParseError::VersionNotFound) as Box<dyn stdError>);
            } else if options_lines.1.is_none() {
                return Err(Box::new(UnitdStderrParseError::BuildSettingsNotFound) as Box<dyn stdError>);
            }

            Ok(UnitdConfigureOptions {
                version: options_lines.0.unwrap().into(),
                all_flags: options_lines.1.unwrap().into(),
            })
        }

        let program = unitd_path.as_os_str();
        let child = Command::new(program)
            .arg("--version")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;
        let output = child.wait_with_output()?;
        let err = BufReader::new(&*output.stderr);
        parse_configure_settings_from_unitd_stderr_output(&mut err.lines())
    }

    pub fn has_flag(&self, flag_name: &str) -> bool {
        self.all_flags
            .split_ascii_whitespace()
            .any(|flag| flag.starts_with(format!("--{}", flag_name).as_str()))
    }

    pub fn get_flag_value(&self, flag_name: &str) -> Option<String> {
        self.all_flags
            .split_ascii_whitespace()
            .find(|flag| flag.starts_with(format!("--{}", flag_name).as_str()))
            .and_then(|flag| {
                let parts: Vec<&str> = flag.split('=').collect();
                if parts.len() >= 2 {
                    Some(parts[1].to_owned())
                } else {
                    None
                }
            })
    }

    pub fn debug_enabled(&self) -> bool {
        self.has_flag("debug")
    }

    pub fn openssl_enabled(&self) -> bool {
        self.has_flag("openssl")
    }

    pub fn prefix_path(&self) -> Option<Box<Path>> {
        self.get_flag_value("prefix")
            .map(PathBuf::from)
            .map(PathBuf::into_boxed_path)
    }

    fn join_to_prefix_path<S>(&self, sub_path: S) -> Option<Box<Path>>
    where
        S: Into<String>,
    {
        self.prefix_path()
            .map(|path| path.join(sub_path.into()).into_boxed_path())
    }

    pub fn default_control_api_socket_address(&self) -> Option<String> {
        // If the socket address is specific configured in the configure options, we use
        // that. Otherwise, we use the default path as assumed to be unix:$prefix/control.unit.sock.
        match self.get_flag_value("control") {
            Some(socket_address) => Some(socket_address),
            None => {
                // Give up if the unitd is compiled with unix sockets disabled
                if self.has_flag("no-unix-sockets") {
                    return None;
                }
                let socket_path = self.join_to_prefix_path("control.unit.sock");
                socket_path.map(|path| format!("unix:{}", path.to_string_lossy()))
            }
        }
    }

    pub fn default_pid_path(&self) -> Option<Box<Path>> {
        match self.get_flag_value("pid") {
            Some(pid_path) => self.join_to_prefix_path(pid_path),
            None => self.join_to_prefix_path("unit.pid"),
        }
    }

    pub fn default_log_path(&self) -> Option<Box<Path>> {
        match self.get_flag_value("log") {
            Some(pid_path) => self.join_to_prefix_path(pid_path),
            None => self.join_to_prefix_path("unit.log"),
        }
    }

    pub fn default_modules_directory(&self) -> Option<Box<Path>> {
        match self.get_flag_value("modules") {
            Some(modules_dir_name) => self.join_to_prefix_path(modules_dir_name),
            None => self.join_to_prefix_path("modules"),
        }
    }

    pub fn default_state_directory(&self) -> Option<Box<Path>> {
        match self.get_flag_value("state") {
            Some(state_dir_name) => self.join_to_prefix_path(state_dir_name),
            None => self.join_to_prefix_path("state"),
        }
    }

    pub fn default_tmp_directory(&self) -> Option<Box<Path>> {
        match self.get_flag_value("tmp") {
            Some(tmp_dir_name) => self.join_to_prefix_path(tmp_dir_name),
            None => self.join_to_prefix_path("tmp"),
        }
    }
    pub fn default_user(&self) -> Option<String> {
        self.get_flag_value("user").map(String::from)
    }
    pub fn default_group(&self) -> Option<String> {
        self.get_flag_value("group").map(String::from)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::unitd_instance;
    use crate::unitd_instance::UNITD_PATH_ENV_KEY;

    #[test]
    fn can_detect_key() {
        let options = UnitdConfigureOptions {
            version: Default::default(),
            all_flags: Cow::from("--debug --openssl --prefix=/opt/unit"),
        };
        assert!(options.has_flag("debug"));
        assert!(options.has_flag("openssl"));
        assert!(options.has_flag("prefix"));
        assert!(!options.has_flag("fobar"));
    }

    #[test]
    fn can_get_flag_value_by_key() {
        let expected = "/opt/unit";
        let options = UnitdConfigureOptions {
            version: Default::default(),
            all_flags: Cow::from("--debug --openssl --prefix=/opt/unit"),
        };

        let actual = options.get_flag_value("prefix");
        assert_eq!(expected, actual.unwrap())
    }

    #[test]
    fn can_get_prefix_path() {
        let expected: Box<Path> = Path::new("/opt/unit").into();
        let options = UnitdConfigureOptions {
            version: Default::default(),
            all_flags: Cow::from("--debug --openssl --prefix=/opt/unit"),
        };

        let actual = options.prefix_path();
        assert_eq!(expected, actual.unwrap())
    }

    #[test]
    fn can_parse_complicated_configure_options() {
        let expected: Box<Path> = Path::new("/usr").into();
        let options = UnitdConfigureOptions {
            version: Default::default(),
            all_flags: Cow::from("--prefix=/usr --state=/var/lib/unit --control=unix:/var/run/control.unit.sock --pid=/var/run/unit.pid --log=/var/log/unit.log --tmp=/var/tmp --user=unit --group=unit --tests --openssl --modules=/usr/lib/unit/modules --libdir=/usr/lib/x86_64-linux-gnu --cc-opt='-g -O2 -fdebug-prefix-map=/data/builder/debuild/unit-1.28.0/pkg/deb/debuild/unit-1.28.0=. -specs=/usr/share/dpkg/no-pie-compile.specs -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fPIC' --ld-opt='-Wl,-Bsymbolic-functions -specs=/usr/share/dpkg/no-pie-link.specs -Wl,-z,relro -Wl,-z,now -Wl,--as-needed -pie'
"),
        };

        let actual = options.prefix_path();
        assert_eq!(expected, actual.unwrap())
    }

    #[test]
    fn can_run_unitd() {
        let specific_path = std::env::var(UNITD_PATH_ENV_KEY).map_err(|error| Box::new(error) as Box<dyn stdError>);
        let unitd_path = unitd_instance::find_executable_path(specific_path);
        let config_options = UnitdConfigureOptions::new(&unitd_path.unwrap());
        match config_options {
            Ok(options) => {
                println!("{:?}", options)
            }
            Err(error) => panic!("{}", error),
        };
    }
}