summaryrefslogtreecommitdiffstats
path: root/systeroid-core/src/sysctl/controller.rs
blob: 118d80129262318562fbe682e3909efe8a521d0b (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
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
use crate::cache::{Cache, CacheData};
use crate::config::Config;
use crate::error::{Error, Result};
use crate::parsers::{parse_kernel_docs, KERNEL_DOCS_PATH};
use crate::sysctl::parameter::Parameter;
use crate::sysctl::section::Section;
use crate::sysctl::{
    DEFAULT_PRELOAD, DEPRECATED_PARAMS, DISABLE_CACHE_ENV, PARAMETERS_CACHE_LABEL, PROC_PATH,
};
use parseit::globwalk;
use parseit::reader;
use rayon::prelude::*;
use std::convert::TryFrom;
use std::env;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::ops::Not;
use std::path::{Path, PathBuf};
use std::result::Result as StdResult;
use sysctl::{CtlFlags, CtlIter, Sysctl as SysctlImpl};

/// Sysctl wrapper for managing the kernel parameters.
#[derive(Clone, Debug)]
pub struct Sysctl {
    /// Available kernel parameters.
    pub parameters: Vec<Parameter>,
    /// Configuration.
    pub config: Config,
}

impl Sysctl {
    /// Constructs a new instance by fetching the available kernel parameters.
    pub fn init(config: Config) -> Result<Self> {
        let parameters = CtlIter::root()
            .filter_map(StdResult::ok)
            .filter(|ctl| {
                ctl.flags()
                    .map(|flags| !flags.contains(CtlFlags::SKIP))
                    .unwrap_or(false)
            })
            .filter_map(|ctl| match Parameter::try_from(&ctl) {
                Ok(parameter) => {
                    if !config.display_deprecated {
                        parameter
                            .get_absolute_name()
                            .map(|pname| DEPRECATED_PARAMS.contains(&pname))
                            .unwrap_or(false)
                            .not()
                            .then_some(Ok(parameter))
                    } else {
                        Some(Ok(parameter))
                    }
                }
                Err(e) => match ctl.name() {
                    Ok(name) => {
                        log::trace!(target: "sysctl", "{} ({})", e, name);
                        None
                    }
                    Err(e) => Some(Err(Error::from(e))),
                },
            })
            .collect::<Result<Vec<_>>>()?;

        Ok(Self { parameters, config })
    }

    /// Returns the first found parameter in the available parameters.
    #[cfg(test)]
    fn get_parameter(&self, query: &str) -> Option<&Parameter> {
        self.get_parameters(query).first().copied()
    }

    /// Returns the parameters that matches the given query.
    pub fn get_parameters(&self, query: &str) -> Vec<&Parameter> {
        log::trace!(target: "sysctl", "Querying parameters: {:?}", query);
        let query = query.replace('/', ".");
        let parameters = self
            .parameters
            .iter()
            .filter(|param| {
                param.name == query
                    || param.get_absolute_name() == Some(&query)
                    || param.is_in_section(&query)
            })
            .collect::<Vec<&Parameter>>();
        if parameters.is_empty() && !self.config.cli.ignore_errors {
            log::error!(
                target: "sysctl",
                "{}: cannot stat {}{}: No such file or directory",
                env!("CARGO_PKG_NAME").split('-').collect::<Vec<_>>()[0],
                PROC_PATH,
                query.replace('.', "/")
            )
        }
        parameters
    }

    /// Updates the descriptions of the kernel parameters using the given cached data.
    pub fn update_docs_from_cache(&mut self, cache: &Cache) -> Result<()> {
        log::trace!(target: "cache", "{:?}", cache);
        let mut kernel_docs_path = self
            .config
            .kernel_docs
            .as_ref()
            .map(|p| vec![p.to_path_buf()])
            .unwrap_or_default();

        for path in KERNEL_DOCS_PATH {
            if let Some(mut path) = globwalk::glob(path).ok().and_then(|glob| {
                glob.filter_map(StdResult::ok)
                    .filter(|entry| entry.file_type().is_dir())
                    .map(|entry| entry.into_path())
                    .next()
            }) {
                path.pop();
                kernel_docs_path.push(path);
            }
        }
        if let Some(path) = kernel_docs_path.iter().find(|path| path.exists()) {
            if cache.exists(PARAMETERS_CACHE_LABEL) {
                log::trace!(target: "cache", "Cache hit for {:?}", path);
                let cache_data = cache.read(PARAMETERS_CACHE_LABEL)?;
                if cache_data.timestamp == CacheData::<()>::get_timestamp(path)? {
                    self.update_params(cache_data.data);
                    return Ok(());
                }
            }
            self.update_docs(path)?;
            if env::var(DISABLE_CACHE_ENV).is_err() {
                log::trace!(target: "cache", "Writing cache to {:?}", cache);
                cache.write(
                    CacheData::new(&self.parameters, path)?,
                    PARAMETERS_CACHE_LABEL,
                )?;
            }
        } else {
            log::error!(target: "sysctl", "warning: `Linux kernel documentation cannot be found. Please specify a path via '-D' argument`");
        }
        Ok(())
    }

    /// Updates the parameters internally using the given list.
    ///
    /// Keeps the original values.
    fn update_params(&mut self, parameters: Vec<Parameter>) {
        self.parameters.par_iter_mut().for_each(|parameter| {
            if let Some(param) = parameters
                .par_iter()
                .find_any(|param| param.name == parameter.name)
            {
                parameter.description = param.description.clone();
                parameter.docs_path = param.docs_path.clone();
                parameter.docs_title = param.docs_title.clone();
            }
        });
    }

    /// Updates the descriptions of the kernel parameters.
    fn update_docs(&mut self, kernel_docs: &Path) -> Result<()> {
        log::trace!(target: "sysctl", "Parsing the kernel documentation from {:?}", kernel_docs);
        let documents = parse_kernel_docs(kernel_docs)?;
        self.parameters
            .par_iter_mut()
            .filter(|p| p.description.is_none())
            .for_each(|param| {
                for document in documents
                    .iter()
                    .filter(|document| Section::from(document.path.as_path()) == param.section)
                {
                    if let Some(paragraph) =
                        document.paragraphs.par_iter().find_first(|paragraph| {
                            match param.get_absolute_name() {
                                Some(absolute_name) => {
                                    absolute_name == paragraph.title
                                        || absolute_name.len() > 2
                                            && paragraph.title.contains(absolute_name)
                                }
                                None => false,
                            }
                        })
                    {
                        param.description = Some(paragraph.contents.to_owned());
                        param.docs_title = paragraph.title.to_owned();
                        param.docs_path = document.path.clone();
                        continue;
                    }
                }
            });
        Ok(())
    }

    /// Saves the parameter values to the given file.
    pub fn save_to_file(
        &self,
        param_name: String,
        new_value: String,
        save_path: &Option<PathBuf>,
    ) -> Result<PathBuf> {
        let save_path = save_path
            .clone()
            .unwrap_or_else(|| PathBuf::from(DEFAULT_PRELOAD));
        log::trace!(
            target: "param",
            "Writing the new value ({:?}) of {:?} to {:?}",
            new_value,
            param_name,
            save_path
        );
        let data = format!("{param_name} = {new_value}");
        if save_path.exists() {
            let contents = reader::read_to_string(&save_path)?;
            let mut lines = contents.split('\n').collect::<Vec<&str>>();
            if let Some(line) = lines.iter_mut().find(|v| v.starts_with(&param_name)) {
                *line = &