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
// Copyright (c) 2019 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

#![allow(clippy::large_enum_variant)]

pub mod devices;
pub mod udev;
pub mod uevent;

#[cfg(test)]
#[macro_use]
extern crate pretty_assertions;

use std::{
    cmp::Ordering,
    collections::BTreeSet,
    hash::{Hash, Hasher},
    path::{Path, PathBuf},
};

#[derive(Debug, Clone, Eq, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct DevicePath(pub PathBuf);

impl<S: Into<PathBuf>> From<S> for DevicePath {
    fn from(s: S) -> DevicePath {
        DevicePath(s.into())
    }
}

impl<'a> From<&'a DevicePath> for &'a Path {
    fn from(s: &'a DevicePath) -> &'a Path {
        Path::new(&s.0)
    }
}

fn find_sort_slot(DevicePath(p): &DevicePath) -> usize {
    let o = &[
        Box::new(|p: &PathBuf| p.starts_with("/dev/mapper/")) as Box<dyn Fn(&PathBuf) -> bool>,
        Box::new(|p| p.starts_with("/dev/disk/by-id/")),
        Box::new(|p| p.starts_with("/dev/disk/by-path/")),
        Box::new(|p| p.starts_with("/dev/")),
        Box::new(|_| true),
    ]
    .iter()
    .position(|f| f(&p))
    .unwrap();

    *o
}

pub fn get_vdev_paths(vdev: &libzfs_types::VDev) -> BTreeSet<DevicePath> {
    match vdev {
        libzfs_types::VDev::Disk { dev_id, path, .. } => {
            let p = dev_id
                .as_ref()
                .map(|x| format!("/dev/disk/by-id/{}", x))
                .map(std::convert::Into::into)
                .or_else(|| {
                    log::warn!(
                        "VDev::Disk.dev_id not found, using VDev::Disk.path {:?}",
                        path
                    );

                    Some(path.clone())
                })
                .map(DevicePath);

            let mut b = BTreeSet::new();

            if let Some(x) = p {
                b.insert(x);
            }

            b
        }
        libzfs_types::VDev::File { .. } => BTreeSet::new(),
        libzfs_types::VDev::Mirror { children, .. }
        | libzfs_types::VDev::RaidZ { children, .. }
        | libzfs_types::VDev::Replacing { children, .. } => {
            children.iter().flat_map(get_vdev_paths).collect()
        }
        libzfs_types::VDev::Root {
            children,
            spares,
            cache,
            ..
        } => vec![children, spares, cache]
            .into_iter()
            .flatten()
            .flat_map(get_vdev_paths)
            .collect(),
    }
}

impl Ord for DevicePath {
    fn cmp(&self, other: &DevicePath) -> Ordering {
        let a_slot = find_sort_slot(self);
        let b_slot = find_sort_slot(other);

        if a_slot > b_slot {
            Ordering::Greater
        } else if a_slot < b_slot {
            Ordering::Less
        } else {
            self.0.partial_cmp(&other.0).unwrap()
        }
    }
}

impl PartialOrd for DevicePath {
    fn partial_cmp(&self, other: &DevicePath) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for DevicePath {
    fn eq(&self, other: &DevicePath) -> bool {
        self.0 == other.0
    }
}

impl Hash for DevicePath {
    fn hash<H: Hasher>(&self, h: &mut H) {
        self.0.as_path().hash(h)
    }
}

pub mod message {
    #[derive(Debug, serde::Serialize, serde::Deserialize)]
    pub enum Message {
        Data(String),
        Heartbeat,
    }
}

pub mod state {
    use crate::{mount, uevent};
    use im::{HashMap, HashSet};
    use std::path::PathBuf;

    pub type UEvents = HashMap<PathBuf, uevent::UEvent>;

    pub type ZedEvents = HashMap<u64, libzfs_types::Pool>;

    #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
    pub struct State {
        pub uevents: UEvents,
        pub zed_events: ZedEvents,
        pub local_mounts: HashSet<mount::Mount>,
    }

    impl State {
        pub fn new() -> Self {
            State {
                uevents: HashMap::new(),
                zed_events: HashMap::new(),
                local_mounts: HashSet::new(),
            }
        }
    }
}

pub mod mount {
    use crate::DevicePath;
    use std::path::PathBuf;

    #[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
    #[serde(transparent)]
    pub struct MountPoint(pub PathBuf);

    #[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
    #[serde(transparent)]
    pub struct FsType(pub String);

    #[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
    pub struct MountOpts(pub String);

    #[derive(Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, Clone)]
    pub struct Mount {
        pub source: DevicePath,
        pub target: MountPoint,
        pub fs_type: FsType,
        pub opts: MountOpts,
    }

    impl Mount {
        pub fn new(
            target: MountPoint,
            source: DevicePath,
            fs_type: FsType,
            opts: MountOpts,
        ) -> Self {
            Mount {
                target,
                source,
                fs_type,
                opts,
            }
        }
    }

    #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
    pub enum MountCommand {
        AddMount(MountPoint, DevicePath, FsType, MountOpts),
        RemoveMount(MountPoint, DevicePath, FsType, MountOpts),
        ReplaceMount(MountPoint, DevicePath, FsType, MountOpts, MountOpts),
        MoveMount(MountPoint, DevicePath, FsType, MountOpts, MountPoint),
    }
}

pub mod zed {

    #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
    pub enum PoolCommand {
        AddPools(Vec<libzfs_types::Pool>),
        AddPool(libzfs_types::Pool),
        UpdatePool(libzfs_types::Pool),
        RemovePool(zpool::Guid),
        AddDataset(zpool::Guid, libzfs_types::Dataset),
        RemoveDataset(zpool::Guid, zfs::Name),
        SetZpoolProp(zpool::Guid, prop::Key, prop::Value),
        SetZfsProp(zpool::Guid, zfs::Name, prop::Key, prop::Value),
    }

    pub mod zpool {
        #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
        pub struct Name(pub String);

        #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
        pub struct Guid(pub String);

        impl From<u64> for Guid {
            fn from(x: u64) -> Self {
                Guid(format!("{:#018X}", x))
            }
        }

        impl From<Guid> for Result<u64, std::num::ParseIntError> {
            fn from(Guid(x): Guid) -> Self {
                let without_prefix = x.trim_start_matches("0x");
                u64::from_str_radix(without_prefix, 16)
            }
        }

        #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
        pub struct State(pub String);

        impl From<State> for String {
            fn from(State(x): State) -> Self {
                x
            }
        }
    }

    pub mod zfs {
        #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
        pub struct Name(pub String);
    }

    pub mod prop {
        #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
        pub struct Key(pub String);

        #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
        pub struct Value(pub String);
    }

    #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
    pub enum ZedCommand {
        Init,
        CreateZpool(zpool::Name, zpool::Guid, zpool::State),
        ImportZpool(zpool::Name, zpool::Guid, zpool::State),
        ExportZpool(zpool::Guid, zpool::State),
        DestroyZpool(zpool::Guid),
        CreateZfs(zpool::Guid, zfs::Name),
        DestroyZfs(zpool::Guid, zfs::Name),
        SetZpoolProp(zpool::Guid, prop::Key, prop::Value),
        SetZfsProp(zpool::Guid, zfs::Name, prop::Key, prop::Value),
        AddVdev(zpool::Name, zpool::Guid),
    }
}

#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum Command {
    Stream,
    GetMounts,
    PoolCommand(zed::PoolCommand),
    UdevCommand(udev::UdevCommand),
    MountCommand(mount::MountCommand),
}

#[cfg(test)]
mod tests {
    use super::{
        mount, {Command, DevicePath},
    };
    use im::{ordset, OrdSet};
    use insta::assert_debug_snapshot;

    #[test]
    fn test_device_path_ordering() {
        let xs: OrdSet<DevicePath> = ordset![
            "/dev/disk/by-id/dm-uuid-part1-mpath-3600140550e41a841db244a992c31e7df".into(),
            "/dev/mapper/mpathd1".into(),
            "/dev/disk/by-uuid/b4550256-cf48-4013-8363-bfee5f52da12".into(),
            "/dev/disk/by-partuuid/d643e32f-b6b9-4863-af8f-8950376e28da".into(),
            "/dev/dm-20".into(),
            "/dev/disk/by-id/dm-name-mpathd1".into()
        ];

        assert_debug_snapshot!(xs);
    }

    #[test]
    fn test_mount_deserialize() {
        let s = "{\"MountCommand\":{\"AddMount\":[\"swap\",\"/dev/mapper/VolGroup00-LogVol01\",\"swap\",\"defaults\"]}}";

        let result = serde_json::from_str::<Command>(s).unwrap();

        assert_eq!(
            result,
            Command::MountCommand(mount::MountCommand::AddMount(
                mount::MountPoint("swap".into()),
                "/dev/mapper/VolGroup00-LogVol01".into(),
                mount::FsType("swap".to_string()),
                mount::MountOpts("defaults".to_string())
            ))
        )
    }
}