main.rs 12.6 KB
Newer Older
1
2
3
extern crate ansi_term;
#[macro_use] extern crate lazy_static;
extern crate threadpool;
4
extern crate rand;
5

Stefan Schindler's avatar
Stefan Schindler committed
6
7
8
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
9
use std::fs::{File};
Stefan Schindler's avatar
Stefan Schindler committed
10
use std::fmt::Display;
11
12
13
14
use std::sync::{Arc, Mutex};

use ansi_term::Style;
use ansi_term::Colour::*;
Stefan Schindler's avatar
Stefan Schindler committed
15

Stefan Schindler's avatar
Stefan Schindler committed
16
17
use rand::Rng;

18
19
20
21
22
lazy_static! {
    static ref BOLD: Style = Style::new().bold();
    static ref UNDERLINE: Style = Style::new().underline();
    static ref HEADING: Style = Yellow.bold();
}
Stefan Schindler's avatar
Stefan Schindler committed
23

24
const WRITE_BUFFER_SIZE: usize = 4096;
Stefan Schindler's avatar
Stefan Schindler committed
25
26
27

fn main() {
    let model = get_file_contents("/sys/devices/virtual/dmi/id/product_version");
28
    println!("\n\n    {} running on {}\n", BOLD.paint("whipe buddy"), BOLD.paint(model));
Stefan Schindler's avatar
Stefan Schindler committed
29
30
    
    let disks = parse_disks();
31
    let pool = threadpool::ThreadPool::new(2);
Stefan Schindler's avatar
Stefan Schindler committed
32
    
33
    show_disk_status(&disks);
Stefan Schindler's avatar
Stefan Schindler committed
34
    loop {
35
        println!("\nPress {} to exit, {} for a list of available commands", BOLD.paint("q"), BOLD.paint("h"));
Stefan Schindler's avatar
Stefan Schindler committed
36
        
37
        let input = read_one_line_from_stdin();
Stefan Schindler's avatar
Stefan Schindler committed
38
39
        match input.trim() {
            "q" => return,
40
            "h" => print_help(),
41
            "l" => show_disk_status(&disks),
42
            "w" => select_disk_to_whipe(&disks),
43
            ""  => show_disk_status(&disks),
44
            com =>  println!("unknown command: {}", com),
Stefan Schindler's avatar
Stefan Schindler committed
45
        }
46
47
        
        update_jobs(&disks, &pool);
Stefan Schindler's avatar
Stefan Schindler committed
48
49
50
    }
}

51
52
53
54
55
56

fn show_disk_status(disks: &Vec<Arc<DiskInformation>>) {
    println!("{}", HEADING.paint("Status of found disks:") );

    let longest = disks.iter().fold(0, |b, e| std::cmp::max(b, e.name.len())) +1;

Stefan Schindler's avatar
Stefan Schindler committed
57
    for disk in disks {
58
59
60
61
62
63
64
65
        println!("{:6}) {}:{:width$} {} -- {:?}",
            disk.id,
            BOLD.paint(&*disk.name),
            " ",
            disk.size,
            *disk.state.lock().unwrap(),
            width = longest - disk.name.len()
        );
Stefan Schindler's avatar
Stefan Schindler committed
66
67
68
    }
}

69
fn parse_disks() -> Vec<Arc<DiskInformation>> {
Stefan Schindler's avatar
Stefan Schindler committed
70
71
72
73
74
75
76
    let partitions = get_file_contents("/proc/partitions");
    //println!("partitions: {:?}", partitions);
    
    let lines = partitions.split("\n").skip(2);
    //println!("lines: {:?}", lines);
    
    let mut disks = Vec::new();
77
    let mut i = 0;
Stefan Schindler's avatar
Stefan Schindler committed
78
79
80
81
82
83
84
85
    for line in lines {
        let line = line.trim();
        //println!("line: {:?}", line);
        
        let mut parts = line.split_whitespace();
        let (_major, minor, no_blocks, name) = (parts.next(), parts.next(), parts.next(), parts.next());
        
        if let Some(name) = name {
Stefan Schindler's avatar
Stefan Schindler committed
86
            if minor == Some("0") && (name.starts_with("sd") || name.starts_with("nvme") || name.starts_with("xvd") || name.starts_with("mmcblk")) {
Stefan Schindler's avatar
Stefan Schindler committed
87
88
                /// Contains the major and minor numbers of  each  partition  as  well  as  the  number  of 1024-byte blocks and the partition name.
                let no_blocks: u64 = no_blocks.unwrap_or("0").parse().unwrap_or(0);
89
90
91
                i += 1;
                disks.push(Arc::new(DiskInformation {
                    id: i,
Stefan Schindler's avatar
Stefan Schindler committed
92
93
                    name: name.into(),
                    size: KiloByte(no_blocks),
94
95
                    state: Mutex::new(Detected),
                }));
Stefan Schindler's avatar
Stefan Schindler committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
            }
        }
    }
    
    disks
}

fn get_file_contents(path: &str) -> String {
    let f = match File::open(path) {
        Ok(f) => f,
        Err(_) => return format!("<unable to open {:?}", path),
    };
    let reader = BufReader::new(f);
    let mut buffer = String::new();

    let mut i = 0;
    for line in reader.lines() {
        i += 1;
114
        buffer += &* line.unwrap_or( format!("<read error on line {} - {}>\n", i, path) );
Stefan Schindler's avatar
Stefan Schindler committed
115
116
117
118
119
120
        buffer += "\n";
    }
    
    buffer
}

121
122
123
124
125
126
fn read_one_line_from_stdin() -> String {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap_or(0);
    input
}

Stefan Schindler's avatar
Stefan Schindler committed
127
128
#[derive(Debug)]
struct DiskInformation {
129
    id: u64,
Stefan Schindler's avatar
Stefan Schindler committed
130
131
    size: ByteUnit,
    name: String,
132
    state: Mutex<DiskState>,
Stefan Schindler's avatar
Stefan Schindler committed
133
134
}

135
#[derive(Debug,Eq,Ord)]
Stefan Schindler's avatar
Stefan Schindler committed
136
enum ByteUnit {
137
    Byte(u64),
Stefan Schindler's avatar
Stefan Schindler committed
138
139
140
141
    KiloByte(u64),
}
use ByteUnit::*;

142
143
144
145
146
147
148
149
150
impl ByteUnit {
    pub fn to_byte(&self) -> ByteUnit {
        match self {
            &Byte(v) => Byte(v),
            &KiloByte(v) => Byte(1024 * v),
        }
    }
}

151
152
153
154
155
156
157
158
159
160
161
162
163
164
impl std::cmp::PartialEq<Self> for ByteUnit {
    fn eq(&self, rhs: &Self) -> bool {
        match self {
            &Byte(l) => match rhs {
                &Byte(r) => l == r,
                &KiloByte(r) => l == 1024 * r,
            },
            &KiloByte(l) => match rhs {
                &Byte(r) => 1024 * l == r,
                &KiloByte(r) => l == r,
            }
        }
    }
}
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
impl std::cmp::PartialOrd<Self> for ByteUnit {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(match self {
            &Byte(l) => match other {
                &Byte(r) => l.cmp(&r),
                ref something_else => {
                    if let Byte(r) = something_else.to_byte() {
                        l.cmp(&r)
                    } else {
                        panic!("fn partial_cmp<ByteUnit>: this must never happen!");
                    }
                },
            },
            ref something_else => something_else.to_byte().cmp(other),
        })
    }
}
Stefan Schindler's avatar
Stefan Schindler committed
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
impl std::ops::Add for ByteUnit {
    type Output = ByteUnit;

    fn add(self, other: Self) -> Self {
        match self {
            Byte(l) => match other {
                Byte(r) => Byte(l + r),
                something_else => self + something_else.to_byte(),
            },
            something_else => something_else.to_byte() + other,
        }
    }
}
impl std::ops::AddAssign for ByteUnit {
    fn add_assign(&mut self, other: Self) {
        match self {
            &mut Byte(ref mut me) => match other {
                Byte(r) => { *me += r; },
                KiloByte(r) => { *me += r * 1024; },
            },
            &mut KiloByte(ref mut me) => match other {
                Byte(r) => *me += r / 1024, // FIXME: Rundungsfehler
                KiloByte(r) => *me += r,
            },
        }
    }
}
209
210
211
212
213
214
215
216


#[derive(Debug,PartialEq,Eq)]
enum DiskState {
    Detected,
    QueueForWhipe,
    Whiping{ progress: ByteUnit, per_second: ByteUnit },
    Whiped,
Stefan Schindler's avatar
Stefan Schindler committed
217
    WhipeFailed,
218
219
220
}
use DiskState::*;

Stefan Schindler's avatar
Stefan Schindler committed
221
impl Display for ByteUnit {
Stefan Schindler's avatar
Stefan Schindler committed
222
223
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
224
225
226
227
228
229
230
            &Byte(size) => {
                if size < 1000 {
                    return write!(f, "{:>6.2} B ", size);
                }
                
                return KiloByte(size / 1024).fmt(f);
            }
Stefan Schindler's avatar
Stefan Schindler committed
231
            &KiloByte(size) => {   
232
233
                if size < 1000 {
                    return write!(f, "{:>6.2} KB", size);
Stefan Schindler's avatar
Stefan Schindler committed
234
235
236
237
                }
                
                let size = size as f64;                
                let size: f64 = size / 1024.0;
238
239
                if size < 1000.0 {
                    return write!(f, "{:>6.2} MB", size);
Stefan Schindler's avatar
Stefan Schindler committed
240
241
242
                }
                
                let size: f64 = size / 1024.0;
243
244
                if size < 1000.0 {
                    return write!(f, "{:>6.2} GB", size);
Stefan Schindler's avatar
Stefan Schindler committed
245
246
247
                }
                
                let size: f64 = size / 1024.0;
248
                write!(f, "{:>6.2} TB", size)
Stefan Schindler's avatar
Stefan Schindler committed
249
250
251
252
            }
        }
    }
}
253
254
255
256
257
258
259
260


fn print_help() {
    println!("\n{}", HEADING.paint("Available Commands:"));
    
    let options = [
        ("q", "quit"),
        ("h", "print this help"),
261
        ("l", "list found disks and status"),
262
263
264
265
        ("w", "start whiping a disk"),
    ];
    
    for option in options.iter() {
266
        println!("       {}        {}", BOLD.paint(option.0), option.1);
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
    }
}

fn select_disk_to_whipe(disks: &Vec<Arc<DiskInformation>>) {
    println!("{}", HEADING.paint("Enter the id of the disk you would like to be whiped:"));
    
    match read_one_line_from_stdin().trim().parse() {
        Ok(id) => {
            if let Some(disk) = disks.iter().find(|ref e| e.id == id) {
                while {
                    println!("\nWhiping is {}!\nDestroy any data on {} ({})\nEnter {} to continue or {} to abort?", UNDERLINE.paint("non-reversable"), BOLD.paint(&*disk.name), disk.size, BOLD.paint("y"), BOLD.paint("a"));
                    
                    match read_one_line_from_stdin().trim() {
                        "y" | "Y" | "j" | "J" => { false },
                        "a" => { return }
                        _ => { println!("{}", Red.paint("invalid response")); true }
                    }
                    
                } {}
                
                *disk.state.lock().unwrap() = QueueForWhipe;
                
                return;
            }
        },
        Err(e) => println!("parse_error: {:?}", e),
    }
    
    println!("{}", Red.paint("invalid selection"));
}

fn update_jobs(disks: &Vec<Arc<DiskInformation>>, pool: &threadpool::ThreadPool) {
    for disk in disks {
        if *disk.state.lock().unwrap() == QueueForWhipe {
            println!("Queued {} for whipe", BOLD.paint(&*disk.name));
            let disk = disk.clone();
            pool.execute(move || {
Stefan Schindler's avatar
Stefan Schindler committed
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
                match whipe_disk(&disk) {
                    Ok(_) => {
                        *disk.state.lock().unwrap() = Whiped;
                        println!("{}{}", Green.paint("Whiped "), BOLD.paint(&*disk.name));
                    },
                    Err(e) => {
                        *disk.state.lock().unwrap() = WhipeFailed;
                        println!("{}{}{}",
                            Red.paint("Whipe of "),
                            BOLD.paint(&*disk.name),
                            Red.paint(format!(" failed: {:?}", e))
                        );
                        return
                    }
                }
319

320
321
322
323
324
            })
        }
    }
}

Stefan Schindler's avatar
Stefan Schindler committed
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
fn whipe_disk(disk: &Arc<DiskInformation>) -> std::io::Result<()> {
    let mut rng = rand::thread_rng();

    *disk.state.lock().unwrap() = Whiping{ progress: Byte(0), per_second: Byte(0) };

    let mut buf = [0; WRITE_BUFFER_SIZE];
    let mut position = Byte(0);
    let mut disk_file = std::fs::OpenOptions::new()
                        .write(true)
                        .open(&*format!("/dev/{}", disk.name))?;

    while position < disk.size {
        rng.fill_bytes(&mut buf);
        disk_file.write_all(&buf)?;

        position += Byte(WRITE_BUFFER_SIZE as u64)
    }

    Ok( () )
}

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

#[cfg(test)]
mod test {
    use ::ByteUnit::*;
    
    #[test]
    fn unit_eq() {
        let one_k_bytes = Byte(1024);
        let one_kilobyte = KiloByte(1);
        
        assert_eq!(one_k_bytes, one_kilobyte);
        assert_eq!(one_kilobyte, one_k_bytes);
    }
    
    #[test]
    fn format_byte() {
        assert_eq!("    42 B ", format!("{}", Byte(42)));
    }
    #[test]
    fn format_kilobyte() {
        assert_eq!("    42 KB", format!("{}", KiloByte(42)));
    }
    #[test]
    fn format_megabyte() {
        assert_eq!(" 42.00 MB", format!("{}", KiloByte(42 * 1024)));
    }
    #[test]
    fn format_gigabyte() {
        assert_eq!(" 42.00 GB", format!("{}", KiloByte(42 * 1024 * 1024)));
    }
    #[test]
    fn format_terrabyte() {
        assert_eq!(" 42.00 TB", format!("{}", KiloByte(42 * 1024 * 1024 * 1024)));
    }
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


    #[test]
    fn ord_eqals() {
        let one_k_bytes = Byte(1024);
        let one_kilobyte = KiloByte(1);

        assert!(one_k_bytes <= one_kilobyte);
        assert!(one_kilobyte <= one_k_bytes);

        assert!(one_k_bytes >= one_kilobyte);
        assert!(one_kilobyte >= one_k_bytes);
    }
    #[test]
    fn ord_less() {
        let two_k_bytes = Byte(2048);
        let one_kilobyte = KiloByte(1);

        assert!(two_k_bytes > one_kilobyte);
        assert!(one_kilobyte < two_k_bytes);
    }
    #[test]
    fn ord_more() {
        let one_k_bytes = Byte(1024);
        let two_kilobytes = KiloByte(2);

        assert!(two_kilobytes > one_k_bytes);
        assert!(one_k_bytes < two_kilobytes);
    }
Stefan Schindler's avatar
Stefan Schindler committed
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
443
444
445
446
447
448
449
450
451


    #[test]
    fn add_bytes() {
        assert_eq!(Byte(4), Byte(2) + Byte(2));
    }
    #[test]
    fn add_kilobytes() {
        assert_eq!(KiloByte(4), KiloByte(2) + KiloByte(2));
    }
    #[test]
    fn add_bytes_mixed_up() {
        assert_eq!(Byte(2 + 2048), Byte(2) + KiloByte(2));
    }
    #[test]
    fn add_bytes_mixed_down() {
        assert_eq!(Byte(2 + 2048), KiloByte(2) + Byte(2));
    }

    #[test]
    fn add_assign_bytes() {
        let mut four = Byte(2);
        four += Byte(2);
        assert_eq!(Byte(4), four);
    }
    #[test]
    fn add_assign_kilobytes() {
        let mut four = KiloByte(2);
        four += KiloByte(2);
        assert_eq!(KiloByte(4), four);
    }
    #[test]
    fn add_assign_mixed_up() {
        let mut four = Byte(2);
        four += KiloByte(2);
        assert_eq!(Byte(2 + 2048), four);
    }
    #[test]
    fn add_assign_mixed_down() {
        let mut four = KiloByte(2);
        four += Byte(2);
        assert_eq!(Byte(2 + 2048), four);
    }
452
}