main.rs 11.5 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

16
17
18
19
20
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
21

22
const WRITE_BUFFER_SIZE: usize = 4096;
Stefan Schindler's avatar
Stefan Schindler committed
23
24
25

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

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

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

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

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

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

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


#[derive(Debug,PartialEq,Eq)]
enum DiskState {
    Detected,
    QueueForWhipe,
    Whiping{ progress: ByteUnit, per_second: ByteUnit },
    Whiped,
}
use DiskState::*;

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


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 || {
293
294
                let mut rng = rand::thread_rng();

295
296
                *disk.state.lock().unwrap() = Whiping{ progress: Byte(0), per_second: Byte(0) };
                
297
298
299
300
301
302
303
                let mut buf = [0; WRITE_BUFFER_SIZE];
                let mut position = Byte(0);
                /*
                while position < disk.size {
                    buf = rng.get();
                    position += WRITE_BUFFER_SIZE as u64;
                }*/
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
            })
        }
    }
}


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


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


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