main.rs 12.3 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
34
35
    
    list_disks(&disks);
    
    loop {
36
        println!("\nPress {} to exit, {} for a list of available commands", BOLD.paint("q"), BOLD.paint("h"));
Stefan Schindler's avatar
Stefan Schindler committed
37
        
38
        let input = read_one_line_from_stdin();
Stefan Schindler's avatar
Stefan Schindler committed
39
40
41
        match input.trim() {
            "q" => return,
            "l" => list_disks(&disks),
42
43
44
45
            "h" => print_help(),
            "w" => select_disk_to_whipe(&disks),
            ""  => {},
            com =>  println!("unknown command: {}", com),
Stefan Schindler's avatar
Stefan Schindler committed
46
        }
47
48
        
        update_jobs(&disks, &pool);
Stefan Schindler's avatar
Stefan Schindler committed
49
50
51
    }
}

52
53
fn list_disks(disks: &Vec<Arc<DiskInformation>>) {
    println!("{}", HEADING.paint("Found following disks:") );
Stefan Schindler's avatar
Stefan Schindler committed
54
55
    
    for disk in disks {
56
        println!("  {}) {}: {}", disk.id, BOLD.paint(&*disk.name), disk.size);
Stefan Schindler's avatar
Stefan Schindler committed
57
58
59
    }
}

60
fn parse_disks() -> Vec<Arc<DiskInformation>> {
Stefan Schindler's avatar
Stefan Schindler committed
61
62
63
64
65
66
67
    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();
68
    let mut i = 0;
Stefan Schindler's avatar
Stefan Schindler committed
69
70
71
72
73
74
75
76
    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
77
            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
78
79
                /// 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);
80
81
82
                i += 1;
                disks.push(Arc::new(DiskInformation {
                    id: i,
Stefan Schindler's avatar
Stefan Schindler committed
83
84
                    name: name.into(),
                    size: KiloByte(no_blocks),
85
86
                    state: Mutex::new(Detected),
                }));
Stefan Schindler's avatar
Stefan Schindler committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
            }
        }
    }
    
    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;
105
        buffer += &* line.unwrap_or( format!("<read error on line {} - {}>\n", i, path) );
Stefan Schindler's avatar
Stefan Schindler committed
106
107
108
109
110
111
        buffer += "\n";
    }
    
    buffer
}

112
113
114
115
116
117
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
118
119
#[derive(Debug)]
struct DiskInformation {
120
    id: u64,
Stefan Schindler's avatar
Stefan Schindler committed
121
122
    size: ByteUnit,
    name: String,
123
    state: Mutex<DiskState>,
Stefan Schindler's avatar
Stefan Schindler committed
124
125
}

126
#[derive(Debug,Eq,Ord)]
Stefan Schindler's avatar
Stefan Schindler committed
127
enum ByteUnit {
128
    Byte(u64),
Stefan Schindler's avatar
Stefan Schindler committed
129
130
131
132
    KiloByte(u64),
}
use ByteUnit::*;

133
134
135
136
137
138
139
140
141
impl ByteUnit {
    pub fn to_byte(&self) -> ByteUnit {
        match self {
            &Byte(v) => Byte(v),
            &KiloByte(v) => Byte(1024 * v),
        }
    }
}

142
143
144
145
146
147
148
149
150
151
152
153
154
155
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,
            }
        }
    }
}
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
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
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
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,
            },
        }
    }
}
200
201
202
203
204
205
206
207


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

Stefan Schindler's avatar
Stefan Schindler committed
212
impl Display for ByteUnit {
Stefan Schindler's avatar
Stefan Schindler committed
213
214
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
215
216
217
218
219
220
221
            &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
222
            &KiloByte(size) => {   
223
224
                if size < 1000 {
                    return write!(f, "{:>6.2} KB", size);
Stefan Schindler's avatar
Stefan Schindler committed
225
226
227
228
                }
                
                let size = size as f64;                
                let size: f64 = size / 1024.0;
229
230
                if size < 1000.0 {
                    return write!(f, "{:>6.2} MB", size);
Stefan Schindler's avatar
Stefan Schindler committed
231
232
233
                }
                
                let size: f64 = size / 1024.0;
234
235
                if size < 1000.0 {
                    return write!(f, "{:>6.2} GB", size);
Stefan Schindler's avatar
Stefan Schindler committed
236
237
238
                }
                
                let size: f64 = size / 1024.0;
239
                write!(f, "{:>6.2} TB", size)
Stefan Schindler's avatar
Stefan Schindler committed
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


fn print_help() {
    println!("\n{}", HEADING.paint("Available Commands:"));
    
    let options = [
        ("q", "quit"),
        ("h", "print this help"),
        ("l", "list found disks"),
        ("w", "start whiping a disk"),
        ("s", "show status updates"),
    ];
    
    for option in options.iter() {
        println!("  {}        {}", BOLD.paint(option.0), option.1);
    }
}

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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
                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
                    }
                }
311

312
313
314
315
316
            })
        }
    }
}

Stefan Schindler's avatar
Stefan Schindler committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
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( () )
}

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

#[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)));
    }
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


    #[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
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
443


    #[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);
    }
444
}