mdevctl 1.4.0

A mediated device management utility for Linux
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! A filesystem environment for mdevctl

use crate::callouts::{callout, CalloutScriptCache, CalloutScriptInfo};
use crate::mdev::{MDev, MDevSysfsData, MDevType};
use anyhow::{anyhow, Result};
use log::{debug, warn};
use std::collections::BTreeMap;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Mutex;
use std::{env, fs};
use uuid::Uuid;

/// A trait which provides filesystem paths for certain system resources and provides functions to
/// query the state of that environment.
///
/// The main purpose that this is a trait is to enable testability of the mdevctl commands by
/// abstracting out the filesystem locations. Tests can implement [`Environment`] and provide
/// filesystem paths within a mock filesystem environment that will not affect the system.
pub trait Environment: std::fmt::Debug {
    fn root(&self) -> &Path;

    fn find_script(&self, dev: &MDev) -> Option<CalloutScriptInfo>;

    fn as_env(self: Rc<Self>) -> Rc<dyn Environment>;

    fn mdev_base(&self) -> PathBuf {
        self.root().join("sys/bus/mdev/devices")
    }

    fn config_base(&self) -> PathBuf {
        self.root().join("etc/mdevctl.d")
    }

    fn parent_base(&self) -> PathBuf {
        self.root().join("sys/class/mdev_bus")
    }

    fn config_scripts_base(&self) -> PathBuf {
        self.config_base().join("scripts.d")
    }

    fn scripts_base(&self) -> PathBuf {
        self.root().join("usr/lib/mdevctl/scripts.d")
    }

    fn callout_dir(&self) -> PathBuf {
        self.scripts_base().join("callouts")
    }

    fn old_callout_dir(&self) -> PathBuf {
        self.config_scripts_base().join("callouts")
    }

    fn callout_dirs(&self) -> Vec<PathBuf> {
        vec![self.callout_dir(), self.old_callout_dir()]
    }

    fn notification_dir(&self) -> PathBuf {
        self.scripts_base().join("notifiers")
    }

    fn old_notification_dir(&self) -> PathBuf {
        self.config_scripts_base().join("notifiers")
    }

    fn notification_dirs(&self) -> Vec<PathBuf> {
        vec![self.notification_dir(), self.old_notification_dir()]
    }

    fn self_check(&self) -> Result<()> {
        debug!("checking that the environment is sane");
        // ensure required system dirs exist. Generally distro packages or 'make install' should
        // create these dirs.
        for dir in [
            self.config_base(),
            self.callout_dir(),
            self.notification_dir(),
        ] {
            if !dir.exists() {
                return Err(anyhow!("Required directory {:?} doesn't exist. This may indicate a packaging or installation error", dir));
            }
        }
        Ok(())
    }

    /// convenience function to lookup an active device by uuid and parent
    fn get_active_device(self: Rc<Self>, uuid: Uuid, parent: Option<&String>) -> Result<MDev> {
        let devs = self.get_active_devices(Some(&uuid), parent)?;
        if devs.is_empty() {
            match parent {
                None => Err(anyhow!(
                    "Mediated device {} is not active",
                    uuid.hyphenated().to_string()
                )),
                Some(p) => Err(anyhow!(
                    "Mediated device {}/{} is not active",
                    p,
                    uuid.hyphenated().to_string()
                )),
            }
        } else if devs.len() > 1 {
            Err(anyhow!(
                "Multiple parents found for {}. System error?",
                uuid.hyphenated().to_string()
            ))
        } else {
            let (parent, children) = devs.iter().next().unwrap();
            if children.len() > 1 {
                return Err(anyhow!(
                    "Multiple definitions found for {}/{}",
                    parent,
                    uuid.hyphenated().to_string()
                ));
            }
            Ok(children.first().unwrap().clone())
        }
    }

    /// Get a map of all active devices, optionally filtered by uuid and parent
    fn get_active_devices(
        self: Rc<Self>,
        uuid: Option<&Uuid>,
        parent: Option<&String>,
    ) -> Result<BTreeMap<String, Vec<MDev>>> {
        let mut devices: BTreeMap<String, Vec<MDev>> = BTreeMap::new();
        debug!(
            "Looking up active mdevs: uuid={:?}, parent={:?}",
            uuid, parent
        );
        if let Ok(dir) = self.mdev_base().read_dir() {
            for dir_dev in dir {
                let dir_dev = dir_dev?;
                let fname = dir_dev.file_name();
                let basename = fname.to_str().unwrap();
                debug!("found defined mdev {}", basename);
                let u = Uuid::parse_str(basename);

                if u.is_err() {
                    warn!("Can't determine uuid for file '{}'", basename);
                    continue;
                }
                let u = u.unwrap();

                if uuid.is_some() && uuid != Some(&u) {
                    debug!(
                        "Ignoring device {} because it doesn't match uuid {}",
                        u,
                        uuid.unwrap()
                    );
                    continue;
                }

                let mut dev = MDev::new(self.clone().as_env(), u);
                if let Ok(sysfs_data) = MDevSysfsData::load_for_mdev(&dev) {
                    dev.set_sysfs_data(sysfs_data);
                    if dev.active {
                        if parent.is_some() && (parent != dev.parent.as_ref()) {
                            debug!(
                                "Ignoring device {} because it doesn't match parent {}",
                                dev.uuid,
                                parent.as_ref().unwrap()
                            );
                            continue;
                        }

                        // retrieve autostart from persisted mdev if possible
                        let mut per_dev = MDev::new(self.clone().as_env(), u);
                        per_dev.parent.clone_from(&dev.parent);
                        if per_dev.load_definition().is_ok() {
                            dev.autostart = per_dev.autostart;
                        }

                        // if the device is supported by a callout script that gets attributes, show
                        // those in the output
                        let mut c = callout(&mut dev)?;
                        if let Ok(attrs) = c.get_attributes() {
                            let _ = c.dev.add_attributes(&attrs);
                        }

                        let devparent = dev.parent()?;
                        if !devices.contains_key(devparent) {
                            devices.insert(devparent.clone(), Vec::new());
                        };

                        devices.get_mut(devparent).unwrap().push(dev);
                    };
                };
            }
        }
        Ok(devices)
    }

    /// Get a map of all defined devices, optionally filtered by uuid and parent
    fn get_defined_devices(
        self: Rc<Self>,
        uuid: Option<&Uuid>,
        parent: Option<&String>,
    ) -> Result<BTreeMap<String, Vec<MDev>>> {
        let mut devices: BTreeMap<String, Vec<MDev>> = BTreeMap::new();
        debug!(
            "Looking up defined mdevs: uuid={:?}, parent={:?}",
            uuid, parent
        );
        let thisenv = self.as_env();
        for parentpath in thisenv.config_base().read_dir()?.skip_while(|x| match x {
            Ok(d) => d.path() == thisenv.scripts_base(),
            _ => false,
        }) {
            let parentpath = parentpath?;
            let parentname = parentpath.file_name();
            let parentname = parentname.to_str().unwrap();
            if (parent.is_some() && parent.unwrap() != parentname)
                || !parentpath.metadata()?.is_dir()
            {
                debug!("Ignoring child devices for parent {}", parentname);
                continue;
            }

            let mut childdevices = Vec::new();

            match parentpath.path().read_dir() {
                Ok(res) => {
                    for child in res {
                        let child = child?;
                        match child.metadata() {
                            Ok(metadata) => {
                                if !metadata.is_file() {
                                    continue;
                                }
                            }
                            Err(e) => {
                                warn!("unable to access file {:?}: {}", child.path(), e);
                                continue;
                            }
                        }

                        let path = child.path();
                        let basename = path.file_name().unwrap().to_str().unwrap();
                        let u = Uuid::parse_str(basename);
                        if u.is_err() {
                            warn!("Can't determine uuid for file '{}'", basename);
                            continue;
                        }
                        let u = u.unwrap();

                        debug!("found mdev {:?}", u);
                        if uuid.is_some() && uuid != Some(&u) {
                            debug!(
                                "Ignoring device {} because it doesn't match uuid {}",
                                u,
                                uuid.unwrap()
                            );
                            continue;
                        }

                        match fs::File::open(&path) {
                            Ok(mut f) => {
                                let mut contents = String::new();
                                f.read_to_string(&mut contents)?;
                                let val = serde_json::from_str(&contents)?;
                                let mut dev = MDev::new(thisenv.clone(), u);
                                dev.load_from_json(parentname.to_string(), &val)?;
                                match MDevSysfsData::load_for_mdev(&dev) {
                                    Err(e) => warn!(
                                        "For device {} a sysfs update caused the error: {:?}",
                                        u, e
                                    ),
                                    Ok(Some(sysfs_data)) => {
                                        if dev.sysfs_data_matches(&sysfs_data) {
                                            dev.set_sysfs_data(Some(sysfs_data));
                                        }
                                    }
                                    _ => (),
                                };
                                childdevices.push(dev);
                            }
                            Err(e) => {
                                warn!("Unable to open file {:?}: {}", path, e);
                                continue;
                            }
                        };
                    }
                }
                Err(e) => warn!("Unable to read directory {:?}: {}", parentpath.path(), e),
            }
            if !childdevices.is_empty() {
                devices.insert(parentname.to_string(), childdevices);
            }
        }
        Ok(devices)
    }

    /// convenience function to lookup a defined device by uuid and parent
    fn get_defined_device(self: Rc<Self>, uuid: Uuid, parent: Option<&String>) -> Result<MDev> {
        let devs = self.get_defined_devices(Some(&uuid), parent)?;
        if devs.is_empty() {
            match parent {
                None => Err(anyhow!(
                    "Mediated device {} is not defined",
                    uuid.hyphenated().to_string()
                )),
                Some(p) => Err(anyhow!(
                    "Mediated device {}/{} is not defined",
                    p,
                    uuid.hyphenated().to_string()
                )),
            }
        } else if devs.len() > 1 {
            match parent {
                None => Err(anyhow!(
                    "Multiple definitions found for {}, specify a parent",
                    uuid.hyphenated().to_string()
                )),
                Some(p) => Err(anyhow!(
                    "Multiple definitions found for {}/{}",
                    p,
                    uuid.hyphenated().to_string()
                )),
            }
        } else {
            let (parent, children) = devs.iter().next().unwrap();
            if children.len() > 1 {
                return Err(anyhow!(
                    "Multiple definitions found for {}/{}",
                    parent,
                    uuid.hyphenated().to_string()
                ));
            }
            Ok(children.first().unwrap().clone())
        }
    }

    /// Get a map of all mediated device types that are supported on this machine
    fn get_supported_types(
        self: Rc<Self>,
        parent: Option<String>,
    ) -> Result<BTreeMap<String, Vec<MDevType>>> {
        debug!("Finding supported mdev types");
        let mut types: BTreeMap<String, Vec<MDevType>> = BTreeMap::new();

        if let Ok(dir) = self.parent_base().read_dir() {
            for parentpath in dir {
                let parentpath = parentpath?;
                let parentname = parentpath.file_name();
                let parentname = parentname.to_str().unwrap();
                debug!("Looking for supported types for device {}", parentname);
                if parent.is_some() && parent.as_ref().unwrap() != parentname {
                    debug!("Ignoring types for parent {}", parentname);
                    continue;
                }

                let mut childtypes = Vec::new();
                let mut parentpath = parentpath.path();
                parentpath.push("mdev_supported_types");
                for child in parentpath.read_dir()? {
                    let child = child?;
                    if !child.metadata()?.is_dir() {
                        continue;
                    }

                    let mut t = MDevType::new();
                    t.parent = parentname.to_string();

                    let mut path = child.path();
                    t.typename = path.file_name().unwrap().to_str().unwrap().to_string();
                    debug!("found mdev type {}", t.typename);

                    path.push("available_instances");
                    debug!("Checking available instances: {:?}", path);
                    t.available_instances = fs::read_to_string(&path)?.trim().parse()?;

                    path.pop();
                    path.push("device_api");
                    t.device_api = fs::read_to_string(&path)?.trim().to_string();

                    path.pop();
                    path.push("name");
                    if path.exists() {
                        t.name = fs::read_to_string(&path)?.trim().to_string();
                    }

                    path.pop();
                    path.push("description");
                    if path.exists() {
                        t.description = fs::read_to_string(&path)?
                            .trim()
                            .replace('\n', ", ")
                            .to_string();
                    }

                    childtypes.push(t);
                }
                types.insert(parentname.to_string(), childtypes);
            }
        }
        for v in types.values_mut() {
            v.sort_by(|a, b| a.typename.cmp(&b.typename));
        }
        Ok(types)
    }
}

/// A default implementation of the Environment trait which uses '/' as the filesystem root.
#[derive(Debug)]
pub struct DefaultEnvironment {
    rootpath: PathBuf,
    callout_scripts: Mutex<CalloutScriptCache>,
}

impl Environment for DefaultEnvironment {
    fn root(&self) -> &Path {
        self.rootpath.as_path()
    }

    fn find_script(&self, dev: &MDev) -> Option<CalloutScriptInfo> {
        return self
            .callout_scripts
            .lock()
            .unwrap()
            .find_versioned_script(dev);
    }

    fn as_env(self: Rc<Self>) -> Rc<dyn Environment> {
        self.clone()
    }
}

impl DefaultEnvironment {
    #[allow(clippy::new_ret_no_self)]
    pub fn new() -> Rc<dyn Environment> {
        let root = match env::var("MDEVCTL_ENV_ROOT") {
            Ok(d) => d,
            _ => "/".to_string(),
        };
        Rc::new(DefaultEnvironment {
            rootpath: PathBuf::from(root),
            callout_scripts: Mutex::new(CalloutScriptCache::new()),
        })
    }
}