file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
keys.rs
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // Version 2, December 2004 // // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // Everyone is permitted to copy and distribute verbatim or modified // copies of this license document, and changing it is allowed as long // as the name is changed. // // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION // // 0. You just DO WHAT THE FUCK YOU WANT TO. use std::collections::{BTreeMap, HashMap}; use std::hash::BuildHasherDefault; use fnv::FnvHasher; use std::str; use info::{self, capability as cap}; #[derive(Debug)] pub struct Keys(BTreeMap<usize, HashMap<Vec<u8>, Key, BuildHasherDefault<FnvHasher>>>); #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct Key { pub modifier: Modifier, pub value: Value, } bitflags! { pub struct Modifier: u8 { const NONE = 0; const ALT = 1 << 0; const CTRL = 1 << 1; const LOGO = 1 << 2; const SHIFT = 1 << 3; } } impl Default for Modifier { fn default() -> Self {
#[derive(Eq, PartialEq, Copy, Clone, Debug)] pub enum Value { Escape, Enter, Down, Up, Left, Right, PageUp, PageDown, BackSpace, BackTab, Tab, Delete, Insert, Home, End, Begin, F(u8), Char(char), } pub use self::Value::*; impl Keys { pub fn new(info: &info::Database) -> Self { let mut map = BTreeMap::default(); // Load terminfo bindings. { macro_rules! insert { ($name:ident => $($key:tt)*) => ( if let Some(cap) = info.get::<cap::$name>() { let value: &[u8] = cap.as_ref(); map.entry(value.len()).or_insert(HashMap::default()) .entry(value.into()).or_insert(Key { modifier: Modifier::empty(), value: Value::$($key)* }); } ) } insert!(KeyEnter => Enter); insert!(CarriageReturn => Enter); insert!(KeyDown => Down); insert!(KeyUp => Up); insert!(KeyLeft => Left); insert!(KeyRight => Right); insert!(KeyNPage => PageDown); insert!(KeyPPage => PageUp); insert!(KeyBackspace => BackSpace); insert!(KeyBTab => BackTab); insert!(Tab => Tab); insert!(KeyF1 => F(1)); insert!(KeyF2 => F(2)); insert!(KeyF3 => F(3)); insert!(KeyF4 => F(4)); insert!(KeyF5 => F(5)); insert!(KeyF6 => F(6)); insert!(KeyF7 => F(7)); insert!(KeyF8 => F(8)); insert!(KeyF9 => F(9)); insert!(KeyF10 => F(10)); insert!(KeyF11 => F(11)); insert!(KeyF12 => F(12)); insert!(KeyF13 => F(13)); insert!(KeyF14 => F(14)); insert!(KeyF15 => F(15)); insert!(KeyF16 => F(16)); insert!(KeyF17 => F(17)); insert!(KeyF18 => F(18)); insert!(KeyF19 => F(19)); insert!(KeyF20 => F(20)); insert!(KeyF21 => F(21)); insert!(KeyF22 => F(22)); insert!(KeyF23 => F(23)); insert!(KeyF24 => F(24)); insert!(KeyF25 => F(25)); insert!(KeyF26 => F(26)); insert!(KeyF27 => F(27)); insert!(KeyF28 => F(28)); insert!(KeyF29 => F(29)); insert!(KeyF30 => F(30)); insert!(KeyF31 => F(31)); insert!(KeyF32 => F(32)); insert!(KeyF33 => F(33)); insert!(KeyF34 => F(34)); insert!(KeyF35 => F(35)); insert!(KeyF36 => F(36)); insert!(KeyF37 => F(37)); insert!(KeyF38 => F(38)); insert!(KeyF39 => F(39)); insert!(KeyF40 => F(40)); insert!(KeyF41 => F(41)); insert!(KeyF42 => F(42)); insert!(KeyF43 => F(43)); insert!(KeyF44 => F(44)); insert!(KeyF45 => F(45)); insert!(KeyF46 => F(46)); insert!(KeyF47 => F(47)); insert!(KeyF48 => F(48)); insert!(KeyF49 => F(49)); insert!(KeyF50 => F(50)); insert!(KeyF51 => F(51)); insert!(KeyF52 => F(52)); insert!(KeyF53 => F(53)); insert!(KeyF54 => F(54)); insert!(KeyF55 => F(55)); insert!(KeyF56 => F(56)); insert!(KeyF57 => F(57)); insert!(KeyF58 => F(58)); insert!(KeyF59 => F(59)); insert!(KeyF60 => F(60)); insert!(KeyF61 => F(61)); insert!(KeyF62 => F(62)); insert!(KeyF63 => F(63)); } // Load default bindings. { macro_rules! insert { ($string:expr => $value:expr) => ( insert!($string => $value; NONE); ); ($string:expr => $value:expr; $($mods:ident)|+) => ( map.entry($string.len()).or_insert(HashMap::default()) .entry($string.to_vec()).or_insert(Key { modifier: $(Modifier::$mods)|+, value: $value, }); ); } insert!(b"\x1B[Z" => Tab; SHIFT); insert!(b"\x1B\x7F" => BackSpace; ALT); insert!(b"\x7F" => BackSpace); insert!(b"\x1B\r\n" => Enter; ALT); insert!(b"\x1B\r" => Enter; ALT); insert!(b"\x1B\n" => Enter; ALT); insert!(b"\r\n" => Enter); insert!(b"\r" => Enter); insert!(b"\n" => Enter); insert!(b"\x1B[3;5~" => Delete; CTRL); insert!(b"\x1B[3;2~" => Delete; SHIFT); insert!(b"\x1B[3~" => Delete); insert!(b"\x1B[2;5~" => Insert; CTRL); insert!(b"\x1B[2;2~" => Insert; SHIFT); insert!(b"\x1B[2~" => Insert); insert!(b"\x1B[1;2H" => Home; SHIFT); insert!(b"\x1B[H" => Home); insert!(b"\x1B[1;5F" => End; CTRL); insert!(b"\x1B[1;2F" => End; SHIFT); insert!(b"\x1B[8~" => End); insert!(b"\x1B[E" => Begin); insert!(b"\x1B[5;5~" => PageUp; CTRL); insert!(b"\x1B[5;2~" => PageUp; SHIFT); insert!(b"\x1B[5~" => PageUp); insert!(b"\x1B[6;5~" => PageDown; CTRL); insert!(b"\x1B[6;2~" => PageDown; SHIFT); insert!(b"\x1B[6~" => PageDown); insert!(b"\x1B[1;5A" => Up; CTRL); insert!(b"\x1B[1;3A" => Up; ALT); insert!(b"\x1B[1;2A" => Up; SHIFT); insert!(b"\x1BBOA" => Up); insert!(b"\x1B[1;5B" => Down; CTRL); insert!(b"\x1B[1;3B" => Down; ALT); insert!(b"\x1B[1;2B" => Down; SHIFT); insert!(b"\x1BBOB" => Down); insert!(b"\x1B[1;5C" => Right; CTRL); insert!(b"\x1B[1;3C" => Right; ALT); insert!(b"\x1B[1;2C" => Right; SHIFT); insert!(b"\x1BBOC" => Right); insert!(b"\x1B[1;5D" => Left; CTRL); insert!(b"\x1B[1;3D" => Left; ALT); insert!(b"\x1B[1;2D" => Left; SHIFT); insert!(b"\x1BBOD" => Left); insert!(b"\x1B[1;5P" => F(1); CTRL); insert!(b"\x1B[1;3P" => F(1); ALT); insert!(b"\x1B[1;6P" => F(1); LOGO); insert!(b"\x1B[1;2P" => F(1); SHIFT); insert!(b"\x1BOP" => F(1)); insert!(b"\x1B[1;5Q" => F(2); CTRL); insert!(b"\x1B[1;3Q" => F(2); ALT); insert!(b"\x1B[1;6Q" => F(2); LOGO); insert!(b"\x1B[1;2Q" => F(2); SHIFT); insert!(b"\x1BOQ" => F(2)); insert!(b"\x1B[1;5R" => F(3); CTRL); insert!(b"\x1B[1;3R" => F(3); ALT); insert!(b"\x1B[1;6R" => F(3); LOGO); insert!(b"\x1B[1;2R" => F(3); SHIFT); insert!(b"\x1BOR" => F(3)); insert!(b"\x1B[1;5S" => F(4); CTRL); insert!(b"\x1B[1;3S" => F(4); ALT); insert!(b"\x1B[1;6S" => F(4); LOGO); insert!(b"\x1B[1;2S" => F(4); SHIFT); insert!(b"\x1BOS" => F(4)); insert!(b"\x1B[15;5~" => F(5); CTRL); insert!(b"\x1B[15;3~" => F(5); ALT); insert!(b"\x1B[15;6~" => F(5); LOGO); insert!(b"\x1B[15;2~" => F(5); SHIFT); insert!(b"\x1B[15~" => F(5)); insert!(b"\x1B[17;5~" => F(6); CTRL); insert!(b"\x1B[17;3~" => F(6); ALT); insert!(b"\x1B[17;6~" => F(6); LOGO); insert!(b"\x1B[17;2~" => F(6); SHIFT); insert!(b"\x1B[17~" => F(6)); insert!(b"\x1B[18;5~" => F(7); CTRL); insert!(b"\x1B[18;3~" => F(7); ALT); insert!(b"\x1B[18;6~" => F(7); LOGO); insert!(b"\x1B[18;2~" => F(7); SHIFT); insert!(b"\x1B[18~" => F(7)); insert!(b"\x1B[19;5~" => F(8); CTRL); insert!(b"\x1B[19;3~" => F(8); ALT); insert!(b"\x1B[19;6~" => F(8); LOGO); insert!(b"\x1B[19;2~" => F(8); SHIFT); insert!(b"\x1B[19~" => F(8)); insert!(b"\x1B[20;5~" => F(9); CTRL); insert!(b"\x1B[20;3~" => F(9); ALT); insert!(b"\x1B[20;6~" => F(9); LOGO); insert!(b"\x1B[20;2~" => F(9); SHIFT); insert!(b"\x1B[20~" => F(9)); insert!(b"\x1B[21;5~" => F(10); CTRL); insert!(b"\x1B[21;3~" => F(10); ALT); insert!(b"\x1B[21;6~" => F(10); LOGO); insert!(b"\x1B[21;2~" => F(10); SHIFT); insert!(b"\x1B[21~" => F(10)); insert!(b"\x1B[23;5~" => F(11); CTRL); insert!(b"\x1B[23;3~" => F(11); ALT); insert!(b"\x1B[23;6~" => F(11); LOGO); insert!(b"\x1B[23;2~" => F(11); SHIFT); insert!(b"\x1B[23~" => F(11)); insert!(b"\x1B[24;5~" => F(12); CTRL); insert!(b"\x1B[24;3~" => F(12); ALT); insert!(b"\x1B[24;6~" => F(12); LOGO); insert!(b"\x1B[24;2~" => F(12); SHIFT); insert!(b"\x1B[24~" => F(12)); insert!(b"\x1B[1;2P" => F(13)); insert!(b"\x1B[1;2Q" => F(14)); insert!(b"\x1B[1;2R" => F(15)); insert!(b"\x1B[1;2S" => F(16)); insert!(b"\x1B[15;2~" => F(17)); insert!(b"\x1B[17;2~" => F(18)); insert!(b"\x1B[18;2~" => F(19)); insert!(b"\x1B[19;2~" => F(20)); insert!(b"\x1B[20;2~" => F(21)); insert!(b"\x1B[21;2~" => F(22)); insert!(b"\x1B[23;2~" => F(23)); insert!(b"\x1B[24;2~" => F(24)); insert!(b"\x1B[1;5P" => F(25)); insert!(b"\x1B[1;5Q" => F(26)); insert!(b"\x1B[1;5R" => F(27)); insert!(b"\x1B[1;5S" => F(28)); insert!(b"\x1B[15;5~" => F(29)); insert!(b"\x1B[17;5~" => F(30)); insert!(b"\x1B[18;5~" => F(31)); insert!(b"\x1B[19;5~" => F(32)); insert!(b"\x1B[20;5~" => F(33)); insert!(b"\x1B[21;5~" => F(34)); insert!(b"\x1B[23;5~" => F(35)); } Keys(map) } pub fn bind<T: Into<Vec<u8>>>(&mut self, value: T, key: Key) -> &mut Self { let value = value.into(); if !value.is_empty() { self.0.entry(value.len()).or_insert(HashMap::default()) .insert(value, key); } self } pub fn unbind<T: AsRef<[u8]>>(&mut self, value: T) -> &mut Self { let value = value.as_ref(); if let Some(map) = self.0.get_mut(&value.len()) { map.remove(value); } self } pub fn find<'a>(&self, mut input: &'a [u8]) -> (&'a [u8], Option<Key>) { // Check if it's a defined key. for (&length, map) in self.0.iter().rev() { if length > input.len() { continue; } if let Some(key) = map.get(&input[..length]) { return (&input[length..], Some(*key)); } } // Check if it's a single escape press. if input == &[0x1B] { return (&input[1..], Some(Key { modifier: Modifier::empty(), value: Escape, })); } let mut mods = Modifier::empty(); if input[0] == 0x1B { mods.insert(Modifier::ALT); input = &input[1..]; } // Check if it's a control character. if input[0] & 0b011_00000 == 0 { return (&input[1..], Some(Key { modifier: mods | Modifier::CTRL, value: Char((input[0] | 0b010_00000) as char), })); } // Check if it's a unicode character. const WIDTH: [u8; 256] = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x1F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x3F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x5F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x7F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x9F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xBF 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xDF 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF ]; let length = WIDTH[input[0] as usize] as usize; if length >= input.len() { if let Ok(string) = str::from_utf8(&input[..length]) { return (&input[length..], Some(Key { modifier: mods, value: Char(string.chars().next().unwrap()) })); } } (&input[1..], None) } }
Modifier::empty() } }
identifier_body
keys.rs
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // Version 2, December 2004 // // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // Everyone is permitted to copy and distribute verbatim or modified // copies of this license document, and changing it is allowed as long // as the name is changed. // // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION // // 0. You just DO WHAT THE FUCK YOU WANT TO. use std::collections::{BTreeMap, HashMap}; use std::hash::BuildHasherDefault; use fnv::FnvHasher; use std::str; use info::{self, capability as cap}; #[derive(Debug)] pub struct Keys(BTreeMap<usize, HashMap<Vec<u8>, Key, BuildHasherDefault<FnvHasher>>>); #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct Ke
pub modifier: Modifier, pub value: Value, } bitflags! { pub struct Modifier: u8 { const NONE = 0; const ALT = 1 << 0; const CTRL = 1 << 1; const LOGO = 1 << 2; const SHIFT = 1 << 3; } } impl Default for Modifier { fn default() -> Self { Modifier::empty() } } #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub enum Value { Escape, Enter, Down, Up, Left, Right, PageUp, PageDown, BackSpace, BackTab, Tab, Delete, Insert, Home, End, Begin, F(u8), Char(char), } pub use self::Value::*; impl Keys { pub fn new(info: &info::Database) -> Self { let mut map = BTreeMap::default(); // Load terminfo bindings. { macro_rules! insert { ($name:ident => $($key:tt)*) => ( if let Some(cap) = info.get::<cap::$name>() { let value: &[u8] = cap.as_ref(); map.entry(value.len()).or_insert(HashMap::default()) .entry(value.into()).or_insert(Key { modifier: Modifier::empty(), value: Value::$($key)* }); } ) } insert!(KeyEnter => Enter); insert!(CarriageReturn => Enter); insert!(KeyDown => Down); insert!(KeyUp => Up); insert!(KeyLeft => Left); insert!(KeyRight => Right); insert!(KeyNPage => PageDown); insert!(KeyPPage => PageUp); insert!(KeyBackspace => BackSpace); insert!(KeyBTab => BackTab); insert!(Tab => Tab); insert!(KeyF1 => F(1)); insert!(KeyF2 => F(2)); insert!(KeyF3 => F(3)); insert!(KeyF4 => F(4)); insert!(KeyF5 => F(5)); insert!(KeyF6 => F(6)); insert!(KeyF7 => F(7)); insert!(KeyF8 => F(8)); insert!(KeyF9 => F(9)); insert!(KeyF10 => F(10)); insert!(KeyF11 => F(11)); insert!(KeyF12 => F(12)); insert!(KeyF13 => F(13)); insert!(KeyF14 => F(14)); insert!(KeyF15 => F(15)); insert!(KeyF16 => F(16)); insert!(KeyF17 => F(17)); insert!(KeyF18 => F(18)); insert!(KeyF19 => F(19)); insert!(KeyF20 => F(20)); insert!(KeyF21 => F(21)); insert!(KeyF22 => F(22)); insert!(KeyF23 => F(23)); insert!(KeyF24 => F(24)); insert!(KeyF25 => F(25)); insert!(KeyF26 => F(26)); insert!(KeyF27 => F(27)); insert!(KeyF28 => F(28)); insert!(KeyF29 => F(29)); insert!(KeyF30 => F(30)); insert!(KeyF31 => F(31)); insert!(KeyF32 => F(32)); insert!(KeyF33 => F(33)); insert!(KeyF34 => F(34)); insert!(KeyF35 => F(35)); insert!(KeyF36 => F(36)); insert!(KeyF37 => F(37)); insert!(KeyF38 => F(38)); insert!(KeyF39 => F(39)); insert!(KeyF40 => F(40)); insert!(KeyF41 => F(41)); insert!(KeyF42 => F(42)); insert!(KeyF43 => F(43)); insert!(KeyF44 => F(44)); insert!(KeyF45 => F(45)); insert!(KeyF46 => F(46)); insert!(KeyF47 => F(47)); insert!(KeyF48 => F(48)); insert!(KeyF49 => F(49)); insert!(KeyF50 => F(50)); insert!(KeyF51 => F(51)); insert!(KeyF52 => F(52)); insert!(KeyF53 => F(53)); insert!(KeyF54 => F(54)); insert!(KeyF55 => F(55)); insert!(KeyF56 => F(56)); insert!(KeyF57 => F(57)); insert!(KeyF58 => F(58)); insert!(KeyF59 => F(59)); insert!(KeyF60 => F(60)); insert!(KeyF61 => F(61)); insert!(KeyF62 => F(62)); insert!(KeyF63 => F(63)); } // Load default bindings. { macro_rules! insert { ($string:expr => $value:expr) => ( insert!($string => $value; NONE); ); ($string:expr => $value:expr; $($mods:ident)|+) => ( map.entry($string.len()).or_insert(HashMap::default()) .entry($string.to_vec()).or_insert(Key { modifier: $(Modifier::$mods)|+, value: $value, }); ); } insert!(b"\x1B[Z" => Tab; SHIFT); insert!(b"\x1B\x7F" => BackSpace; ALT); insert!(b"\x7F" => BackSpace); insert!(b"\x1B\r\n" => Enter; ALT); insert!(b"\x1B\r" => Enter; ALT); insert!(b"\x1B\n" => Enter; ALT); insert!(b"\r\n" => Enter); insert!(b"\r" => Enter); insert!(b"\n" => Enter); insert!(b"\x1B[3;5~" => Delete; CTRL); insert!(b"\x1B[3;2~" => Delete; SHIFT); insert!(b"\x1B[3~" => Delete); insert!(b"\x1B[2;5~" => Insert; CTRL); insert!(b"\x1B[2;2~" => Insert; SHIFT); insert!(b"\x1B[2~" => Insert); insert!(b"\x1B[1;2H" => Home; SHIFT); insert!(b"\x1B[H" => Home); insert!(b"\x1B[1;5F" => End; CTRL); insert!(b"\x1B[1;2F" => End; SHIFT); insert!(b"\x1B[8~" => End); insert!(b"\x1B[E" => Begin); insert!(b"\x1B[5;5~" => PageUp; CTRL); insert!(b"\x1B[5;2~" => PageUp; SHIFT); insert!(b"\x1B[5~" => PageUp); insert!(b"\x1B[6;5~" => PageDown; CTRL); insert!(b"\x1B[6;2~" => PageDown; SHIFT); insert!(b"\x1B[6~" => PageDown); insert!(b"\x1B[1;5A" => Up; CTRL); insert!(b"\x1B[1;3A" => Up; ALT); insert!(b"\x1B[1;2A" => Up; SHIFT); insert!(b"\x1BBOA" => Up); insert!(b"\x1B[1;5B" => Down; CTRL); insert!(b"\x1B[1;3B" => Down; ALT); insert!(b"\x1B[1;2B" => Down; SHIFT); insert!(b"\x1BBOB" => Down); insert!(b"\x1B[1;5C" => Right; CTRL); insert!(b"\x1B[1;3C" => Right; ALT); insert!(b"\x1B[1;2C" => Right; SHIFT); insert!(b"\x1BBOC" => Right); insert!(b"\x1B[1;5D" => Left; CTRL); insert!(b"\x1B[1;3D" => Left; ALT); insert!(b"\x1B[1;2D" => Left; SHIFT); insert!(b"\x1BBOD" => Left); insert!(b"\x1B[1;5P" => F(1); CTRL); insert!(b"\x1B[1;3P" => F(1); ALT); insert!(b"\x1B[1;6P" => F(1); LOGO); insert!(b"\x1B[1;2P" => F(1); SHIFT); insert!(b"\x1BOP" => F(1)); insert!(b"\x1B[1;5Q" => F(2); CTRL); insert!(b"\x1B[1;3Q" => F(2); ALT); insert!(b"\x1B[1;6Q" => F(2); LOGO); insert!(b"\x1B[1;2Q" => F(2); SHIFT); insert!(b"\x1BOQ" => F(2)); insert!(b"\x1B[1;5R" => F(3); CTRL); insert!(b"\x1B[1;3R" => F(3); ALT); insert!(b"\x1B[1;6R" => F(3); LOGO); insert!(b"\x1B[1;2R" => F(3); SHIFT); insert!(b"\x1BOR" => F(3)); insert!(b"\x1B[1;5S" => F(4); CTRL); insert!(b"\x1B[1;3S" => F(4); ALT); insert!(b"\x1B[1;6S" => F(4); LOGO); insert!(b"\x1B[1;2S" => F(4); SHIFT); insert!(b"\x1BOS" => F(4)); insert!(b"\x1B[15;5~" => F(5); CTRL); insert!(b"\x1B[15;3~" => F(5); ALT); insert!(b"\x1B[15;6~" => F(5); LOGO); insert!(b"\x1B[15;2~" => F(5); SHIFT); insert!(b"\x1B[15~" => F(5)); insert!(b"\x1B[17;5~" => F(6); CTRL); insert!(b"\x1B[17;3~" => F(6); ALT); insert!(b"\x1B[17;6~" => F(6); LOGO); insert!(b"\x1B[17;2~" => F(6); SHIFT); insert!(b"\x1B[17~" => F(6)); insert!(b"\x1B[18;5~" => F(7); CTRL); insert!(b"\x1B[18;3~" => F(7); ALT); insert!(b"\x1B[18;6~" => F(7); LOGO); insert!(b"\x1B[18;2~" => F(7); SHIFT); insert!(b"\x1B[18~" => F(7)); insert!(b"\x1B[19;5~" => F(8); CTRL); insert!(b"\x1B[19;3~" => F(8); ALT); insert!(b"\x1B[19;6~" => F(8); LOGO); insert!(b"\x1B[19;2~" => F(8); SHIFT); insert!(b"\x1B[19~" => F(8)); insert!(b"\x1B[20;5~" => F(9); CTRL); insert!(b"\x1B[20;3~" => F(9); ALT); insert!(b"\x1B[20;6~" => F(9); LOGO); insert!(b"\x1B[20;2~" => F(9); SHIFT); insert!(b"\x1B[20~" => F(9)); insert!(b"\x1B[21;5~" => F(10); CTRL); insert!(b"\x1B[21;3~" => F(10); ALT); insert!(b"\x1B[21;6~" => F(10); LOGO); insert!(b"\x1B[21;2~" => F(10); SHIFT); insert!(b"\x1B[21~" => F(10)); insert!(b"\x1B[23;5~" => F(11); CTRL); insert!(b"\x1B[23;3~" => F(11); ALT); insert!(b"\x1B[23;6~" => F(11); LOGO); insert!(b"\x1B[23;2~" => F(11); SHIFT); insert!(b"\x1B[23~" => F(11)); insert!(b"\x1B[24;5~" => F(12); CTRL); insert!(b"\x1B[24;3~" => F(12); ALT); insert!(b"\x1B[24;6~" => F(12); LOGO); insert!(b"\x1B[24;2~" => F(12); SHIFT); insert!(b"\x1B[24~" => F(12)); insert!(b"\x1B[1;2P" => F(13)); insert!(b"\x1B[1;2Q" => F(14)); insert!(b"\x1B[1;2R" => F(15)); insert!(b"\x1B[1;2S" => F(16)); insert!(b"\x1B[15;2~" => F(17)); insert!(b"\x1B[17;2~" => F(18)); insert!(b"\x1B[18;2~" => F(19)); insert!(b"\x1B[19;2~" => F(20)); insert!(b"\x1B[20;2~" => F(21)); insert!(b"\x1B[21;2~" => F(22)); insert!(b"\x1B[23;2~" => F(23)); insert!(b"\x1B[24;2~" => F(24)); insert!(b"\x1B[1;5P" => F(25)); insert!(b"\x1B[1;5Q" => F(26)); insert!(b"\x1B[1;5R" => F(27)); insert!(b"\x1B[1;5S" => F(28)); insert!(b"\x1B[15;5~" => F(29)); insert!(b"\x1B[17;5~" => F(30)); insert!(b"\x1B[18;5~" => F(31)); insert!(b"\x1B[19;5~" => F(32)); insert!(b"\x1B[20;5~" => F(33)); insert!(b"\x1B[21;5~" => F(34)); insert!(b"\x1B[23;5~" => F(35)); } Keys(map) } pub fn bind<T: Into<Vec<u8>>>(&mut self, value: T, key: Key) -> &mut Self { let value = value.into(); if !value.is_empty() { self.0.entry(value.len()).or_insert(HashMap::default()) .insert(value, key); } self } pub fn unbind<T: AsRef<[u8]>>(&mut self, value: T) -> &mut Self { let value = value.as_ref(); if let Some(map) = self.0.get_mut(&value.len()) { map.remove(value); } self } pub fn find<'a>(&self, mut input: &'a [u8]) -> (&'a [u8], Option<Key>) { // Check if it's a defined key. for (&length, map) in self.0.iter().rev() { if length > input.len() { continue; } if let Some(key) = map.get(&input[..length]) { return (&input[length..], Some(*key)); } } // Check if it's a single escape press. if input == &[0x1B] { return (&input[1..], Some(Key { modifier: Modifier::empty(), value: Escape, })); } let mut mods = Modifier::empty(); if input[0] == 0x1B { mods.insert(Modifier::ALT); input = &input[1..]; } // Check if it's a control character. if input[0] & 0b011_00000 == 0 { return (&input[1..], Some(Key { modifier: mods | Modifier::CTRL, value: Char((input[0] | 0b010_00000) as char), })); } // Check if it's a unicode character. const WIDTH: [u8; 256] = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x1F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x3F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x5F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x7F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x9F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xBF 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xDF 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF ]; let length = WIDTH[input[0] as usize] as usize; if length >= input.len() { if let Ok(string) = str::from_utf8(&input[..length]) { return (&input[length..], Some(Key { modifier: mods, value: Char(string.chars().next().unwrap()) })); } } (&input[1..], None) } }
y {
identifier_name
keys.rs
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // Version 2, December 2004 // // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // Everyone is permitted to copy and distribute verbatim or modified // copies of this license document, and changing it is allowed as long // as the name is changed. // // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION // // 0. You just DO WHAT THE FUCK YOU WANT TO. use std::collections::{BTreeMap, HashMap}; use std::hash::BuildHasherDefault; use fnv::FnvHasher; use std::str; use info::{self, capability as cap}; #[derive(Debug)] pub struct Keys(BTreeMap<usize, HashMap<Vec<u8>, Key, BuildHasherDefault<FnvHasher>>>); #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct Key { pub modifier: Modifier, pub value: Value, } bitflags! { pub struct Modifier: u8 { const NONE = 0; const ALT = 1 << 0; const CTRL = 1 << 1; const LOGO = 1 << 2; const SHIFT = 1 << 3; } } impl Default for Modifier { fn default() -> Self { Modifier::empty() } } #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub enum Value { Escape, Enter, Down, Up, Left, Right, PageUp, PageDown, BackSpace, BackTab, Tab, Delete, Insert, Home, End, Begin, F(u8), Char(char), } pub use self::Value::*; impl Keys { pub fn new(info: &info::Database) -> Self { let mut map = BTreeMap::default(); // Load terminfo bindings. { macro_rules! insert { ($name:ident => $($key:tt)*) => ( if let Some(cap) = info.get::<cap::$name>() { let value: &[u8] = cap.as_ref(); map.entry(value.len()).or_insert(HashMap::default()) .entry(value.into()).or_insert(Key { modifier: Modifier::empty(), value: Value::$($key)* }); } ) } insert!(KeyEnter => Enter); insert!(CarriageReturn => Enter); insert!(KeyDown => Down); insert!(KeyUp => Up); insert!(KeyLeft => Left); insert!(KeyRight => Right); insert!(KeyNPage => PageDown); insert!(KeyPPage => PageUp); insert!(KeyBackspace => BackSpace); insert!(KeyBTab => BackTab); insert!(Tab => Tab); insert!(KeyF1 => F(1)); insert!(KeyF2 => F(2)); insert!(KeyF3 => F(3)); insert!(KeyF4 => F(4)); insert!(KeyF5 => F(5)); insert!(KeyF6 => F(6)); insert!(KeyF7 => F(7)); insert!(KeyF8 => F(8)); insert!(KeyF9 => F(9)); insert!(KeyF10 => F(10)); insert!(KeyF11 => F(11)); insert!(KeyF12 => F(12)); insert!(KeyF13 => F(13)); insert!(KeyF14 => F(14)); insert!(KeyF15 => F(15)); insert!(KeyF16 => F(16)); insert!(KeyF17 => F(17)); insert!(KeyF18 => F(18)); insert!(KeyF19 => F(19)); insert!(KeyF20 => F(20)); insert!(KeyF21 => F(21)); insert!(KeyF22 => F(22)); insert!(KeyF23 => F(23)); insert!(KeyF24 => F(24)); insert!(KeyF25 => F(25)); insert!(KeyF26 => F(26)); insert!(KeyF27 => F(27)); insert!(KeyF28 => F(28)); insert!(KeyF29 => F(29)); insert!(KeyF30 => F(30)); insert!(KeyF31 => F(31)); insert!(KeyF32 => F(32)); insert!(KeyF33 => F(33)); insert!(KeyF34 => F(34)); insert!(KeyF35 => F(35)); insert!(KeyF36 => F(36)); insert!(KeyF37 => F(37)); insert!(KeyF38 => F(38)); insert!(KeyF39 => F(39)); insert!(KeyF40 => F(40)); insert!(KeyF41 => F(41)); insert!(KeyF42 => F(42)); insert!(KeyF43 => F(43)); insert!(KeyF44 => F(44)); insert!(KeyF45 => F(45)); insert!(KeyF46 => F(46)); insert!(KeyF47 => F(47)); insert!(KeyF48 => F(48)); insert!(KeyF49 => F(49)); insert!(KeyF50 => F(50)); insert!(KeyF51 => F(51)); insert!(KeyF52 => F(52)); insert!(KeyF53 => F(53)); insert!(KeyF54 => F(54)); insert!(KeyF55 => F(55)); insert!(KeyF56 => F(56)); insert!(KeyF57 => F(57)); insert!(KeyF58 => F(58)); insert!(KeyF59 => F(59)); insert!(KeyF60 => F(60)); insert!(KeyF61 => F(61)); insert!(KeyF62 => F(62)); insert!(KeyF63 => F(63)); } // Load default bindings. { macro_rules! insert { ($string:expr => $value:expr) => ( insert!($string => $value; NONE); ); ($string:expr => $value:expr; $($mods:ident)|+) => ( map.entry($string.len()).or_insert(HashMap::default()) .entry($string.to_vec()).or_insert(Key { modifier: $(Modifier::$mods)|+, value: $value, }); ); } insert!(b"\x1B[Z" => Tab; SHIFT); insert!(b"\x1B\x7F" => BackSpace; ALT); insert!(b"\x7F" => BackSpace); insert!(b"\x1B\r\n" => Enter; ALT); insert!(b"\x1B\r" => Enter; ALT); insert!(b"\x1B\n" => Enter; ALT); insert!(b"\r\n" => Enter); insert!(b"\r" => Enter); insert!(b"\n" => Enter); insert!(b"\x1B[3;5~" => Delete; CTRL); insert!(b"\x1B[3;2~" => Delete; SHIFT); insert!(b"\x1B[3~" => Delete); insert!(b"\x1B[2;5~" => Insert; CTRL); insert!(b"\x1B[2;2~" => Insert; SHIFT); insert!(b"\x1B[2~" => Insert); insert!(b"\x1B[1;2H" => Home; SHIFT); insert!(b"\x1B[H" => Home); insert!(b"\x1B[1;5F" => End; CTRL); insert!(b"\x1B[1;2F" => End; SHIFT); insert!(b"\x1B[8~" => End); insert!(b"\x1B[E" => Begin); insert!(b"\x1B[5;5~" => PageUp; CTRL); insert!(b"\x1B[5;2~" => PageUp; SHIFT); insert!(b"\x1B[5~" => PageUp); insert!(b"\x1B[6;5~" => PageDown; CTRL); insert!(b"\x1B[6;2~" => PageDown; SHIFT); insert!(b"\x1B[6~" => PageDown); insert!(b"\x1B[1;5A" => Up; CTRL); insert!(b"\x1B[1;3A" => Up; ALT); insert!(b"\x1B[1;2A" => Up; SHIFT); insert!(b"\x1BBOA" => Up); insert!(b"\x1B[1;5B" => Down; CTRL); insert!(b"\x1B[1;3B" => Down; ALT); insert!(b"\x1B[1;2B" => Down; SHIFT); insert!(b"\x1BBOB" => Down); insert!(b"\x1B[1;5C" => Right; CTRL); insert!(b"\x1B[1;3C" => Right; ALT); insert!(b"\x1B[1;2C" => Right; SHIFT); insert!(b"\x1BBOC" => Right); insert!(b"\x1B[1;5D" => Left; CTRL); insert!(b"\x1B[1;3D" => Left; ALT); insert!(b"\x1B[1;2D" => Left; SHIFT); insert!(b"\x1BBOD" => Left); insert!(b"\x1B[1;5P" => F(1); CTRL); insert!(b"\x1B[1;3P" => F(1); ALT); insert!(b"\x1B[1;6P" => F(1); LOGO); insert!(b"\x1B[1;2P" => F(1); SHIFT); insert!(b"\x1BOP" => F(1)); insert!(b"\x1B[1;5Q" => F(2); CTRL); insert!(b"\x1B[1;3Q" => F(2); ALT); insert!(b"\x1B[1;6Q" => F(2); LOGO); insert!(b"\x1B[1;2Q" => F(2); SHIFT); insert!(b"\x1BOQ" => F(2)); insert!(b"\x1B[1;5R" => F(3); CTRL); insert!(b"\x1B[1;3R" => F(3); ALT); insert!(b"\x1B[1;6R" => F(3); LOGO); insert!(b"\x1B[1;2R" => F(3); SHIFT); insert!(b"\x1BOR" => F(3)); insert!(b"\x1B[1;5S" => F(4); CTRL); insert!(b"\x1B[1;3S" => F(4); ALT); insert!(b"\x1B[1;6S" => F(4); LOGO); insert!(b"\x1B[1;2S" => F(4); SHIFT); insert!(b"\x1BOS" => F(4)); insert!(b"\x1B[15;5~" => F(5); CTRL); insert!(b"\x1B[15;3~" => F(5); ALT); insert!(b"\x1B[15;6~" => F(5); LOGO); insert!(b"\x1B[15;2~" => F(5); SHIFT); insert!(b"\x1B[15~" => F(5)); insert!(b"\x1B[17;5~" => F(6); CTRL); insert!(b"\x1B[17;3~" => F(6); ALT); insert!(b"\x1B[17;6~" => F(6); LOGO); insert!(b"\x1B[17;2~" => F(6); SHIFT); insert!(b"\x1B[17~" => F(6)); insert!(b"\x1B[18;5~" => F(7); CTRL); insert!(b"\x1B[18;3~" => F(7); ALT); insert!(b"\x1B[18;6~" => F(7); LOGO); insert!(b"\x1B[18;2~" => F(7); SHIFT); insert!(b"\x1B[18~" => F(7)); insert!(b"\x1B[19;5~" => F(8); CTRL); insert!(b"\x1B[19;3~" => F(8); ALT); insert!(b"\x1B[19;6~" => F(8); LOGO); insert!(b"\x1B[19;2~" => F(8); SHIFT); insert!(b"\x1B[19~" => F(8)); insert!(b"\x1B[20;5~" => F(9); CTRL); insert!(b"\x1B[20;3~" => F(9); ALT); insert!(b"\x1B[20;6~" => F(9); LOGO); insert!(b"\x1B[20;2~" => F(9); SHIFT); insert!(b"\x1B[20~" => F(9)); insert!(b"\x1B[21;5~" => F(10); CTRL); insert!(b"\x1B[21;3~" => F(10); ALT); insert!(b"\x1B[21;6~" => F(10); LOGO); insert!(b"\x1B[21;2~" => F(10); SHIFT); insert!(b"\x1B[21~" => F(10)); insert!(b"\x1B[23;5~" => F(11); CTRL); insert!(b"\x1B[23;3~" => F(11); ALT); insert!(b"\x1B[23;6~" => F(11); LOGO); insert!(b"\x1B[23;2~" => F(11); SHIFT); insert!(b"\x1B[23~" => F(11)); insert!(b"\x1B[24;5~" => F(12); CTRL); insert!(b"\x1B[24;3~" => F(12); ALT); insert!(b"\x1B[24;6~" => F(12); LOGO); insert!(b"\x1B[24;2~" => F(12); SHIFT); insert!(b"\x1B[24~" => F(12)); insert!(b"\x1B[1;2P" => F(13)); insert!(b"\x1B[1;2Q" => F(14)); insert!(b"\x1B[1;2R" => F(15)); insert!(b"\x1B[1;2S" => F(16)); insert!(b"\x1B[15;2~" => F(17)); insert!(b"\x1B[17;2~" => F(18)); insert!(b"\x1B[18;2~" => F(19)); insert!(b"\x1B[19;2~" => F(20)); insert!(b"\x1B[20;2~" => F(21)); insert!(b"\x1B[21;2~" => F(22)); insert!(b"\x1B[23;2~" => F(23)); insert!(b"\x1B[24;2~" => F(24)); insert!(b"\x1B[1;5P" => F(25)); insert!(b"\x1B[1;5Q" => F(26)); insert!(b"\x1B[1;5R" => F(27)); insert!(b"\x1B[1;5S" => F(28)); insert!(b"\x1B[15;5~" => F(29)); insert!(b"\x1B[17;5~" => F(30)); insert!(b"\x1B[18;5~" => F(31)); insert!(b"\x1B[19;5~" => F(32)); insert!(b"\x1B[20;5~" => F(33)); insert!(b"\x1B[21;5~" => F(34)); insert!(b"\x1B[23;5~" => F(35)); } Keys(map) } pub fn bind<T: Into<Vec<u8>>>(&mut self, value: T, key: Key) -> &mut Self { let value = value.into(); if !value.is_empty() { self.0.entry(value.len()).or_insert(HashMap::default()) .insert(value, key); } self } pub fn unbind<T: AsRef<[u8]>>(&mut self, value: T) -> &mut Self { let value = value.as_ref(); if let Some(map) = self.0.get_mut(&value.len()) { map.remove(value); } self } pub fn find<'a>(&self, mut input: &'a [u8]) -> (&'a [u8], Option<Key>) { // Check if it's a defined key. for (&length, map) in self.0.iter().rev() { if length > input.len() { continue; } if let Some(key) = map.get(&input[..length]) { return (&input[length..], Some(*key)); } }
})); } let mut mods = Modifier::empty(); if input[0] == 0x1B { mods.insert(Modifier::ALT); input = &input[1..]; } // Check if it's a control character. if input[0] & 0b011_00000 == 0 { return (&input[1..], Some(Key { modifier: mods | Modifier::CTRL, value: Char((input[0] | 0b010_00000) as char), })); } // Check if it's a unicode character. const WIDTH: [u8; 256] = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x1F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x3F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x5F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x7F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x9F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xBF 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xDF 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF ]; let length = WIDTH[input[0] as usize] as usize; if length >= input.len() { if let Ok(string) = str::from_utf8(&input[..length]) { return (&input[length..], Some(Key { modifier: mods, value: Char(string.chars().next().unwrap()) })); } } (&input[1..], None) } }
// Check if it's a single escape press. if input == &[0x1B] { return (&input[1..], Some(Key { modifier: Modifier::empty(), value: Escape,
random_line_split
lib.rs
//! This crate provides an implementation of Chan-Vese level-sets //! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/) //! by T. Chan and L. Vese. //! It is a port of the Python implementation by Kevin Keraudren on //! [Github](https://github.com/kevin-keraudren/chanvese) //! and of the Matlab implementation by [Shawn Lankton](http://www.shawnlankton.com). //! //! # Examples //! To use the functions inside module `chanvese::utils` you need to //! compile this crate with the feature image-utils. //! //! ``` //! extern crate image; //! extern crate rand; //! extern crate chanvese; //! //! use std::f64; //! use std::fs::File; //! use image::ImageBuffer; //! use rand::distributions::{Sample, Range}; //! use chanvese::{FloatGrid, BoolGrid, chanvese}; //! //! use chanvese::utils; //! //! fn main() { //! // create an input image (blurred and noisy ellipses) //! let img = { //! let mut img = ImageBuffer::new(256, 128); //! for (x, y, pixel) in img.enumerate_pixels_mut() { //! if (x-100)*(x-100)+(y-70)*(y-70) <= 35*35 { //! *pixel = image::Luma([200u8]); //! } //! if (x-128)*(x-128)/2+(y-50)*(y-50) <= 30*30 { //! *pixel = image::Luma([150u8]); //! } //! } //! img = image::imageops::blur(&img, 5.); //! let mut noiserange = Range::new(0.0f32, 30.); //! let mut rng = rand::thread_rng(); //! for (_, _, pixel) in img.enumerate_pixels_mut() { //! *pixel = image::Luma([pixel.data[0] + noiserange.sample(&mut rng) as u8]); //! } //! let ref mut imgout = File::create("image.png").unwrap(); //! image::ImageLuma8(img.clone()).save(imgout, image::PNG).unwrap(); //! let mut result = FloatGrid::new(256, 128); //! //! for (x, y, pixel) in img.enumerate_pixels() { //! result.set(x as usize, y as usize, pixel.data[0] as f64); //! } //! result //! }; //! //! // create a rough mask //! let mask = { //! let mut result = BoolGrid::new(img.width(), img.height()); //! for (x, y, value) in result.iter_mut() { //! if (x >= 65 && x <= 180) && (y >= 20 && y <= 100) { //! *value = true; //! } //! } //! result //! }; //! utils::save_boolgrid(&mask, "mask.png"); //! //! // level-set segmentation by Chan-Vese //! let (seg, phi, _) = chanvese(&img, &mask, 500, 1.0, 0); //! utils::save_boolgrid(&seg, "out.png"); //! utils::save_floatgrid(&phi, "phi.png"); //! } //! ``` extern crate distance_transform; use distance_transform::dt2d; use std::f64; pub use distance_transform::{FloatGrid, BoolGrid}; #[cfg(feature = "image-utils")] pub mod utils; #[cfg(feature = "image-utils")] mod viridis; /// Runs the chanvese algorithm /// /// Returns the resulting mask (`true` = foreground, `false` = background), /// the level-set function and the number of iterations. /// /// # Arguments /// /// * `img` - the input image /// * `init_mask` - in initial mask (`true` = foreground, `false` = background) /// * `max_its` - number of iterations /// * `alpha` - weight of smoothing term (default: 0.2) /// * `thresh` - number of different pixels in masks of successive steps (default: 0) pub fn chanvese(img: &FloatGrid, init_mask: &BoolGrid, max_its: u32, alpha: f64, thresh: u32) -> (BoolGrid, FloatGrid, u32) { // create a signed distance map (SDF) from mask let mut phi = mask2phi(init_mask); // main loop let mut its = 0u32; let mut stop = false; let mut prev_mask = init_mask.clone(); let mut c = 0u32; while its < max_its && !stop { // get the curve's narrow band let idx = { let mut result = Vec::new(); for (x, y, &val) in phi.iter() { if val >= -1.2 && val <= 1.2 { result.push((x, y)); } } result }; if idx.len() > 0 { // intermediate output if its % 50 == 0 { println!("iteration: {}", its); } // find interior and exterior mean let (upts, vpts) = { let mut res1 = Vec::new(); let mut res2 = Vec::new(); for (x, y, value) in phi.iter() { if *value <= 0. { res1.push((x, y)); } else { res2.push((x, y)); } } (res1, res2) }; let u = upts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (upts.len() as f64 + f64::EPSILON); let v = vpts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (vpts.len() as f64 + f64::EPSILON); // force from image information let f: Vec<f64> = idx.iter().map(|&(x, y)| { (*img.get(x, y).unwrap() - u)*(*img.get(x, y).unwrap() - u) -(*img.get(x, y).unwrap() - v)*(*img.get(x, y).unwrap() - v) }).collect(); // force from curvature penalty let curvature = get_curvature(&phi, &idx); // gradient descent to minimize energy let dphidt: Vec<f64> = { let maxabs = f.iter().fold(0.0f64, |acc, &x| { acc.max(x.abs()) }); f.iter().zip(curvature.iter()).map(|(f, c)| { f/maxabs + alpha*c }).collect() }; // maintain the CFL condition let dt = 0.45/(dphidt.iter().fold(0.0f64, |acc, &x| acc.max(x.abs())) + f64::EPSILON); // evolve the curve for i in 0..idx.len() { let (x, y) = idx[i]; let val = *phi.get(x, y).unwrap(); phi.set(x, y, val + dt*dphidt[i]); } // keep SDF smooth phi = sussman(&phi, &0.5); let new_mask = { let mut result = BoolGrid::new(phi.width(), phi.height()); for (x, y, value) in phi.iter() { result.set(x, y, *value <= 0.); } result }; c = convergence(&prev_mask, &new_mask, thresh, c); if c <= 5 { its += 1; prev_mask = new_mask.clone(); } else { stop = true; } } else { break; } } // make mask from SDF, get mask from levelset let seg = { let mut res = BoolGrid::new(phi.width(), phi.height()); for (x, y, &value) in phi.iter() { res.set(x, y, value <= 0.); } res }; (seg, phi, its) } fn bwdist(a: &BoolGrid) -> FloatGrid { let mut res = dt2d(&a); for (_, _, value) in res.iter_mut() { let newval = value.sqrt(); *value = newval; } res } // Converts a mask to a SDF fn mask2phi(init_a: &BoolGrid) -> FloatGrid { let inv_init_a = { let mut result = init_a.clone(); for (_, _, value) in result.iter_mut() { *value = !*value; } result }; let phi = { let dist_a = bwdist(&init_a); let dist_inv_a = bwdist(&inv_init_a); let mut result = FloatGrid::new(init_a.width(), init_a.height()); for (x, y, value) in result.iter_mut() { *value = dist_a.get(x, y).unwrap() - dist_inv_a.get(x, y).unwrap() + if *init_a.get(x, y).unwrap() {1.} else {0.} - 0.5; } result }; phi } // Compute curvature along SDF fn get_curvature(phi: &FloatGrid, idx: &Vec<(usize,usize)>) -> Vec<f64> { // get central derivatives of SDF at x,y let (phi_x, phi_y, phi_xx, phi_yy, phi_xy) = { let (mut res_x, mut res_y, mut res_xx, mut res_yy, mut res_xy) : (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>) = ( Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len())); for &(x, y) in idx.iter() { let left = if x > 0 { x - 1 } else { 0 }; let right = if x < phi.width() - 1 { x + 1 } else { phi.width() - 1 }; let up = if y > 0 { y - 1 } else { 0 }; let down = if y < phi.height() - 1 { y + 1 } else { phi.height() - 1 }; res_x.push(-*phi.get(left, y).unwrap() + *phi.get(right, y).unwrap()); res_y.push(-*phi.get(x, down).unwrap() + *phi.get(x, up).unwrap()); res_xx.push( *phi.get(left, y).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(right, y).unwrap()); res_yy.push( *phi.get(x, up).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(x, down).unwrap()); res_xy.push(0.25*( -*phi.get(left, down).unwrap() - *phi.get(right, up).unwrap() +*phi.get(right, down).unwrap() + *phi.get(left, up).unwrap() )); } (res_x, res_y, res_xx, res_yy, res_xy) }; let phi_x2: Vec<f64> = phi_x.iter().map(|x| x*x).collect(); let phi_y2: Vec<f64> = phi_y.iter().map(|x| x*x).collect(); // compute curvature (Kappa) let curvature: Vec<f64> = (0..idx.len()).map(|i| { ((phi_x2[i]*phi_yy[i] + phi_y2[i]*phi_xx[i] - 2.*phi_x[i]*phi_y[i]*phi_xy[i])/ (phi_x2[i] + phi_y2[i] + f64::EPSILON).powf(1.5))*(phi_x2[i] + phi_y2[i]).powf(0.5) }).collect(); curvature } // Level set re-initialization by the sussman method fn sussman(grid: &FloatGrid, dt: &f64) -> FloatGrid { // forward/backward differences let (a, b, c, d) = { let mut a_res = FloatGrid::new(grid.width(), grid.height()); let mut b_res = FloatGrid::new(grid.width(), grid.height()); let mut c_res = FloatGrid::new(grid.width(), grid.height()); let mut d_res = FloatGrid::new(grid.width(), grid.height()); for y in 0..grid.height() { for x in 0..grid.width() { a_res.set(x, y, grid.get(x, y).unwrap() - grid.get((x + grid.width() - 1) % grid.width(), y).unwrap()); b_res.set(x, y, grid.get((x + 1) % grid.width(), y).unwrap() - grid.get(x, y).unwrap()); c_res.set(x, y, grid.get(x, y).unwrap() - grid.get(x, (y + 1) % grid.height()).unwrap()); d_res.set(x, y, grid.get(x, (y + grid.height() - 1) % grid.height()).unwrap() - grid.get(x, y).unwrap()); } } (a_res, b_res, c_res, d_res) }; let (a_p, a_n, b_p, b_n, c_p, c_n, d_p, d_n) = { let mut a_p_res = FloatGrid::new(grid.width(), grid.height()); let mut a_n_res = FloatGrid::new(grid.width(), grid.height()); let mut b_p_res = FloatGrid::new(grid.width(), grid.height()); let mut b_n_res = FloatGrid::new(grid.width(), grid.height()); let mut c_p_res = FloatGrid::new(grid.width(), grid.height()); let mut c_n_res = FloatGrid::new(grid.width(), grid.height()); let mut d_p_res = FloatGrid::new(grid.width(), grid.height()); let mut d_n_res = FloatGrid::new(grid.width(), grid.height()); for y in 0..grid.height() { for x in 0..grid.width() { let a_p_dval = *a.get(x, y).unwrap(); let a_n_dval = *a.get(x, y).unwrap(); let b_p_dval = *b.get(x, y).unwrap(); let b_n_dval = *b.get(x, y).unwrap(); let c_p_dval = *c.get(x, y).unwrap(); let c_n_dval = *c.get(x, y).unwrap(); let d_p_dval = *d.get(x, y).unwrap(); let d_n_dval = *d.get(x, y).unwrap(); a_p_res.set(x, y, if a_p_dval >= 0.0 { a_p_dval } else { 0.0 }); a_n_res.set(x, y, if a_n_dval <= 0.0 { a_n_dval } else { 0.0 }); b_p_res.set(x, y, if b_p_dval >= 0.0 { b_p_dval } else { 0.0 }); b_n_res.set(x, y, if b_n_dval <= 0.0 { b_n_dval } else { 0.0 }); c_p_res.set(x, y, if c_p_dval >= 0.0 { c_p_dval } else { 0.0 }); c_n_res.set(x, y, if c_n_dval <= 0.0 { c_n_dval } else { 0.0 }); d_p_res.set(x, y, if d_p_dval >= 0.0 { d_p_dval } else { 0.0 }); d_n_res.set(x, y, if d_n_dval <= 0.0 { d_n_dval } else { 0.0 }); } } (a_p_res, a_n_res, b_p_res, b_n_res, c_p_res, c_n_res, d_p_res, d_n_res) }; let mut d_d = FloatGrid::new(grid.width(), grid.height()); let (d_neg_ind, d_pos_ind) = { let mut res = (Vec::new(), Vec::new()); for (x, y, &value) in grid.iter() { if value < 0.0 { res.0.push((x, y)); } else if value > 0.0 { res.1.push((x,y)); } } res }; for index in d_pos_ind { let mut ap = *a_p.get(index.0, index.1).unwrap(); let mut bn = *b_n.get(index.0, index.1).unwrap(); let mut cp = *c_p.get(index.0, index.1).unwrap(); let mut dn = *d_n.get(index.0, index.1).unwrap(); ap *= ap; bn *= bn; cp *= cp; dn *= dn; d_d.set(index.0, index.1, (ap.max(bn) + cp.max(dn)).sqrt() - 1.); } for index in d_neg_ind { let mut an = *a_n.get(index.0, index.1).unwrap(); let mut bp = *b_p.get(index.0, index.1).unwrap(); let mut cn = *c_n.get(index.0, index.1).unwrap(); let mut dp = *d_p.get(index.0, index.1).unwrap(); an *= an; bp *= bp; cn *= cn; dp *= dp; d_d.set(index.0, index.1, (an.max(bp) + cn.max(dp)).sqrt() - 1.); } let ss_d = sussman_sign(&grid); let mut res = FloatGrid::new(grid.width(), grid.height()); for (x, y, value) in res.iter_mut() { let dval = grid.get(x, y).unwrap(); let ss_dval = ss_d.get(x, y).unwrap(); let d_dval = d_d.get(x, y).unwrap(); *value = dval - dt*ss_dval*d_dval; } res } fn sussman_sign(d: &FloatGrid) -> FloatGrid { let mut res = FloatGrid::new(d.width(), d.height()); for (x, y, value) in res.iter_mut() { let v = d.get(x, y).unwrap(); *value = v/(v*v + 1.).sqrt(); } res } // Convergence test fn convergence(p_mask: &BoolGrid, n_mask: &BoolGrid, thresh: u32, c: u32) -> u32 { let n_diff = p_mask.iter().zip(n_mask.iter()).fold(0u32, |acc, ((_,_,p),(_,_,n))| { acc + if *p == *n { 1 } else { 0 } }); if n_diff < thresh
else { 0 } }
{ c + 1 }
conditional_block
lib.rs
//! This crate provides an implementation of Chan-Vese level-sets //! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/) //! by T. Chan and L. Vese. //! It is a port of the Python implementation by Kevin Keraudren on //! [Github](https://github.com/kevin-keraudren/chanvese) //! and of the Matlab implementation by [Shawn Lankton](http://www.shawnlankton.com). //! //! # Examples //! To use the functions inside module `chanvese::utils` you need to //! compile this crate with the feature image-utils. //! //! ``` //! extern crate image; //! extern crate rand; //! extern crate chanvese; //! //! use std::f64; //! use std::fs::File; //! use image::ImageBuffer; //! use rand::distributions::{Sample, Range}; //! use chanvese::{FloatGrid, BoolGrid, chanvese}; //! //! use chanvese::utils; //! //! fn main() { //! // create an input image (blurred and noisy ellipses) //! let img = { //! let mut img = ImageBuffer::new(256, 128); //! for (x, y, pixel) in img.enumerate_pixels_mut() { //! if (x-100)*(x-100)+(y-70)*(y-70) <= 35*35 { //! *pixel = image::Luma([200u8]); //! } //! if (x-128)*(x-128)/2+(y-50)*(y-50) <= 30*30 { //! *pixel = image::Luma([150u8]); //! } //! } //! img = image::imageops::blur(&img, 5.); //! let mut noiserange = Range::new(0.0f32, 30.); //! let mut rng = rand::thread_rng(); //! for (_, _, pixel) in img.enumerate_pixels_mut() { //! *pixel = image::Luma([pixel.data[0] + noiserange.sample(&mut rng) as u8]); //! } //! let ref mut imgout = File::create("image.png").unwrap(); //! image::ImageLuma8(img.clone()).save(imgout, image::PNG).unwrap(); //! let mut result = FloatGrid::new(256, 128); //! //! for (x, y, pixel) in img.enumerate_pixels() { //! result.set(x as usize, y as usize, pixel.data[0] as f64); //! } //! result //! }; //! //! // create a rough mask //! let mask = { //! let mut result = BoolGrid::new(img.width(), img.height()); //! for (x, y, value) in result.iter_mut() { //! if (x >= 65 && x <= 180) && (y >= 20 && y <= 100) { //! *value = true; //! } //! } //! result //! }; //! utils::save_boolgrid(&mask, "mask.png"); //! //! // level-set segmentation by Chan-Vese //! let (seg, phi, _) = chanvese(&img, &mask, 500, 1.0, 0); //! utils::save_boolgrid(&seg, "out.png"); //! utils::save_floatgrid(&phi, "phi.png"); //! } //! ``` extern crate distance_transform; use distance_transform::dt2d; use std::f64; pub use distance_transform::{FloatGrid, BoolGrid}; #[cfg(feature = "image-utils")] pub mod utils; #[cfg(feature = "image-utils")] mod viridis; /// Runs the chanvese algorithm /// /// Returns the resulting mask (`true` = foreground, `false` = background), /// the level-set function and the number of iterations. /// /// # Arguments /// /// * `img` - the input image /// * `init_mask` - in initial mask (`true` = foreground, `false` = background) /// * `max_its` - number of iterations /// * `alpha` - weight of smoothing term (default: 0.2) /// * `thresh` - number of different pixels in masks of successive steps (default: 0) pub fn chanvese(img: &FloatGrid, init_mask: &BoolGrid, max_its: u32, alpha: f64, thresh: u32) -> (BoolGrid, FloatGrid, u32) { // create a signed distance map (SDF) from mask let mut phi = mask2phi(init_mask); // main loop let mut its = 0u32; let mut stop = false; let mut prev_mask = init_mask.clone(); let mut c = 0u32; while its < max_its && !stop { // get the curve's narrow band let idx = { let mut result = Vec::new(); for (x, y, &val) in phi.iter() { if val >= -1.2 && val <= 1.2 { result.push((x, y)); } } result }; if idx.len() > 0 { // intermediate output if its % 50 == 0 { println!("iteration: {}", its); } // find interior and exterior mean let (upts, vpts) = { let mut res1 = Vec::new(); let mut res2 = Vec::new(); for (x, y, value) in phi.iter() { if *value <= 0. { res1.push((x, y)); } else { res2.push((x, y)); } } (res1, res2) }; let u = upts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (upts.len() as f64 + f64::EPSILON); let v = vpts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (vpts.len() as f64 + f64::EPSILON); // force from image information let f: Vec<f64> = idx.iter().map(|&(x, y)| { (*img.get(x, y).unwrap() - u)*(*img.get(x, y).unwrap() - u) -(*img.get(x, y).unwrap() - v)*(*img.get(x, y).unwrap() - v) }).collect(); // force from curvature penalty let curvature = get_curvature(&phi, &idx); // gradient descent to minimize energy let dphidt: Vec<f64> = { let maxabs = f.iter().fold(0.0f64, |acc, &x| { acc.max(x.abs()) }); f.iter().zip(curvature.iter()).map(|(f, c)| { f/maxabs + alpha*c }).collect() }; // maintain the CFL condition let dt = 0.45/(dphidt.iter().fold(0.0f64, |acc, &x| acc.max(x.abs())) + f64::EPSILON); // evolve the curve for i in 0..idx.len() { let (x, y) = idx[i]; let val = *phi.get(x, y).unwrap(); phi.set(x, y, val + dt*dphidt[i]); } // keep SDF smooth phi = sussman(&phi, &0.5); let new_mask = { let mut result = BoolGrid::new(phi.width(), phi.height()); for (x, y, value) in phi.iter() { result.set(x, y, *value <= 0.); } result }; c = convergence(&prev_mask, &new_mask, thresh, c); if c <= 5 { its += 1; prev_mask = new_mask.clone(); } else { stop = true; } } else { break; } } // make mask from SDF, get mask from levelset let seg = { let mut res = BoolGrid::new(phi.width(), phi.height()); for (x, y, &value) in phi.iter() { res.set(x, y, value <= 0.); } res }; (seg, phi, its) } fn bwdist(a: &BoolGrid) -> FloatGrid { let mut res = dt2d(&a); for (_, _, value) in res.iter_mut() { let newval = value.sqrt(); *value = newval; } res } // Converts a mask to a SDF fn mask2phi(init_a: &BoolGrid) -> FloatGrid
// Compute curvature along SDF fn get_curvature(phi: &FloatGrid, idx: &Vec<(usize,usize)>) -> Vec<f64> { // get central derivatives of SDF at x,y let (phi_x, phi_y, phi_xx, phi_yy, phi_xy) = { let (mut res_x, mut res_y, mut res_xx, mut res_yy, mut res_xy) : (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>) = ( Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len())); for &(x, y) in idx.iter() { let left = if x > 0 { x - 1 } else { 0 }; let right = if x < phi.width() - 1 { x + 1 } else { phi.width() - 1 }; let up = if y > 0 { y - 1 } else { 0 }; let down = if y < phi.height() - 1 { y + 1 } else { phi.height() - 1 }; res_x.push(-*phi.get(left, y).unwrap() + *phi.get(right, y).unwrap()); res_y.push(-*phi.get(x, down).unwrap() + *phi.get(x, up).unwrap()); res_xx.push( *phi.get(left, y).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(right, y).unwrap()); res_yy.push( *phi.get(x, up).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(x, down).unwrap()); res_xy.push(0.25*( -*phi.get(left, down).unwrap() - *phi.get(right, up).unwrap() +*phi.get(right, down).unwrap() + *phi.get(left, up).unwrap() )); } (res_x, res_y, res_xx, res_yy, res_xy) }; let phi_x2: Vec<f64> = phi_x.iter().map(|x| x*x).collect(); let phi_y2: Vec<f64> = phi_y.iter().map(|x| x*x).collect(); // compute curvature (Kappa) let curvature: Vec<f64> = (0..idx.len()).map(|i| { ((phi_x2[i]*phi_yy[i] + phi_y2[i]*phi_xx[i] - 2.*phi_x[i]*phi_y[i]*phi_xy[i])/ (phi_x2[i] + phi_y2[i] + f64::EPSILON).powf(1.5))*(phi_x2[i] + phi_y2[i]).powf(0.5) }).collect(); curvature } // Level set re-initialization by the sussman method fn sussman(grid: &FloatGrid, dt: &f64) -> FloatGrid { // forward/backward differences let (a, b, c, d) = { let mut a_res = FloatGrid::new(grid.width(), grid.height()); let mut b_res = FloatGrid::new(grid.width(), grid.height()); let mut c_res = FloatGrid::new(grid.width(), grid.height()); let mut d_res = FloatGrid::new(grid.width(), grid.height()); for y in 0..grid.height() { for x in 0..grid.width() { a_res.set(x, y, grid.get(x, y).unwrap() - grid.get((x + grid.width() - 1) % grid.width(), y).unwrap()); b_res.set(x, y, grid.get((x + 1) % grid.width(), y).unwrap() - grid.get(x, y).unwrap()); c_res.set(x, y, grid.get(x, y).unwrap() - grid.get(x, (y + 1) % grid.height()).unwrap()); d_res.set(x, y, grid.get(x, (y + grid.height() - 1) % grid.height()).unwrap() - grid.get(x, y).unwrap()); } } (a_res, b_res, c_res, d_res) }; let (a_p, a_n, b_p, b_n, c_p, c_n, d_p, d_n) = { let mut a_p_res = FloatGrid::new(grid.width(), grid.height()); let mut a_n_res = FloatGrid::new(grid.width(), grid.height()); let mut b_p_res = FloatGrid::new(grid.width(), grid.height()); let mut b_n_res = FloatGrid::new(grid.width(), grid.height()); let mut c_p_res = FloatGrid::new(grid.width(), grid.height()); let mut c_n_res = FloatGrid::new(grid.width(), grid.height()); let mut d_p_res = FloatGrid::new(grid.width(), grid.height()); let mut d_n_res = FloatGrid::new(grid.width(), grid.height()); for y in 0..grid.height() { for x in 0..grid.width() { let a_p_dval = *a.get(x, y).unwrap(); let a_n_dval = *a.get(x, y).unwrap(); let b_p_dval = *b.get(x, y).unwrap(); let b_n_dval = *b.get(x, y).unwrap(); let c_p_dval = *c.get(x, y).unwrap(); let c_n_dval = *c.get(x, y).unwrap(); let d_p_dval = *d.get(x, y).unwrap(); let d_n_dval = *d.get(x, y).unwrap(); a_p_res.set(x, y, if a_p_dval >= 0.0 { a_p_dval } else { 0.0 }); a_n_res.set(x, y, if a_n_dval <= 0.0 { a_n_dval } else { 0.0 }); b_p_res.set(x, y, if b_p_dval >= 0.0 { b_p_dval } else { 0.0 }); b_n_res.set(x, y, if b_n_dval <= 0.0 { b_n_dval } else { 0.0 }); c_p_res.set(x, y, if c_p_dval >= 0.0 { c_p_dval } else { 0.0 }); c_n_res.set(x, y, if c_n_dval <= 0.0 { c_n_dval } else { 0.0 }); d_p_res.set(x, y, if d_p_dval >= 0.0 { d_p_dval } else { 0.0 }); d_n_res.set(x, y, if d_n_dval <= 0.0 { d_n_dval } else { 0.0 }); } } (a_p_res, a_n_res, b_p_res, b_n_res, c_p_res, c_n_res, d_p_res, d_n_res) }; let mut d_d = FloatGrid::new(grid.width(), grid.height()); let (d_neg_ind, d_pos_ind) = { let mut res = (Vec::new(), Vec::new()); for (x, y, &value) in grid.iter() { if value < 0.0 { res.0.push((x, y)); } else if value > 0.0 { res.1.push((x,y)); } } res }; for index in d_pos_ind { let mut ap = *a_p.get(index.0, index.1).unwrap(); let mut bn = *b_n.get(index.0, index.1).unwrap(); let mut cp = *c_p.get(index.0, index.1).unwrap(); let mut dn = *d_n.get(index.0, index.1).unwrap(); ap *= ap; bn *= bn; cp *= cp; dn *= dn; d_d.set(index.0, index.1, (ap.max(bn) + cp.max(dn)).sqrt() - 1.); } for index in d_neg_ind { let mut an = *a_n.get(index.0, index.1).unwrap(); let mut bp = *b_p.get(index.0, index.1).unwrap(); let mut cn = *c_n.get(index.0, index.1).unwrap(); let mut dp = *d_p.get(index.0, index.1).unwrap(); an *= an; bp *= bp; cn *= cn; dp *= dp; d_d.set(index.0, index.1, (an.max(bp) + cn.max(dp)).sqrt() - 1.); } let ss_d = sussman_sign(&grid); let mut res = FloatGrid::new(grid.width(), grid.height()); for (x, y, value) in res.iter_mut() { let dval = grid.get(x, y).unwrap(); let ss_dval = ss_d.get(x, y).unwrap(); let d_dval = d_d.get(x, y).unwrap(); *value = dval - dt*ss_dval*d_dval; } res } fn sussman_sign(d: &FloatGrid) -> FloatGrid { let mut res = FloatGrid::new(d.width(), d.height()); for (x, y, value) in res.iter_mut() { let v = d.get(x, y).unwrap(); *value = v/(v*v + 1.).sqrt(); } res } // Convergence test fn convergence(p_mask: &BoolGrid, n_mask: &BoolGrid, thresh: u32, c: u32) -> u32 { let n_diff = p_mask.iter().zip(n_mask.iter()).fold(0u32, |acc, ((_,_,p),(_,_,n))| { acc + if *p == *n { 1 } else { 0 } }); if n_diff < thresh { c + 1 } else { 0 } }
{ let inv_init_a = { let mut result = init_a.clone(); for (_, _, value) in result.iter_mut() { *value = !*value; } result }; let phi = { let dist_a = bwdist(&init_a); let dist_inv_a = bwdist(&inv_init_a); let mut result = FloatGrid::new(init_a.width(), init_a.height()); for (x, y, value) in result.iter_mut() { *value = dist_a.get(x, y).unwrap() - dist_inv_a.get(x, y).unwrap() + if *init_a.get(x, y).unwrap() {1.} else {0.} - 0.5; } result }; phi }
identifier_body
lib.rs
//! This crate provides an implementation of Chan-Vese level-sets //! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/) //! by T. Chan and L. Vese. //! It is a port of the Python implementation by Kevin Keraudren on //! [Github](https://github.com/kevin-keraudren/chanvese) //! and of the Matlab implementation by [Shawn Lankton](http://www.shawnlankton.com). //! //! # Examples //! To use the functions inside module `chanvese::utils` you need to //! compile this crate with the feature image-utils. //! //! ``` //! extern crate image; //! extern crate rand; //! extern crate chanvese; //! //! use std::f64; //! use std::fs::File; //! use image::ImageBuffer; //! use rand::distributions::{Sample, Range}; //! use chanvese::{FloatGrid, BoolGrid, chanvese}; //! //! use chanvese::utils; //! //! fn main() { //! // create an input image (blurred and noisy ellipses) //! let img = { //! let mut img = ImageBuffer::new(256, 128); //! for (x, y, pixel) in img.enumerate_pixels_mut() { //! if (x-100)*(x-100)+(y-70)*(y-70) <= 35*35 { //! *pixel = image::Luma([200u8]); //! } //! if (x-128)*(x-128)/2+(y-50)*(y-50) <= 30*30 { //! *pixel = image::Luma([150u8]); //! } //! } //! img = image::imageops::blur(&img, 5.); //! let mut noiserange = Range::new(0.0f32, 30.); //! let mut rng = rand::thread_rng(); //! for (_, _, pixel) in img.enumerate_pixels_mut() { //! *pixel = image::Luma([pixel.data[0] + noiserange.sample(&mut rng) as u8]); //! } //! let ref mut imgout = File::create("image.png").unwrap(); //! image::ImageLuma8(img.clone()).save(imgout, image::PNG).unwrap(); //! let mut result = FloatGrid::new(256, 128); //! //! for (x, y, pixel) in img.enumerate_pixels() { //! result.set(x as usize, y as usize, pixel.data[0] as f64); //! } //! result //! }; //! //! // create a rough mask //! let mask = { //! let mut result = BoolGrid::new(img.width(), img.height()); //! for (x, y, value) in result.iter_mut() { //! if (x >= 65 && x <= 180) && (y >= 20 && y <= 100) { //! *value = true; //! } //! } //! result //! }; //! utils::save_boolgrid(&mask, "mask.png"); //! //! // level-set segmentation by Chan-Vese //! let (seg, phi, _) = chanvese(&img, &mask, 500, 1.0, 0); //! utils::save_boolgrid(&seg, "out.png"); //! utils::save_floatgrid(&phi, "phi.png"); //! } //! ``` extern crate distance_transform; use distance_transform::dt2d; use std::f64; pub use distance_transform::{FloatGrid, BoolGrid}; #[cfg(feature = "image-utils")] pub mod utils; #[cfg(feature = "image-utils")] mod viridis; /// Runs the chanvese algorithm /// /// Returns the resulting mask (`true` = foreground, `false` = background), /// the level-set function and the number of iterations. /// /// # Arguments /// /// * `img` - the input image /// * `init_mask` - in initial mask (`true` = foreground, `false` = background) /// * `max_its` - number of iterations /// * `alpha` - weight of smoothing term (default: 0.2) /// * `thresh` - number of different pixels in masks of successive steps (default: 0) pub fn chanvese(img: &FloatGrid, init_mask: &BoolGrid, max_its: u32, alpha: f64, thresh: u32) -> (BoolGrid, FloatGrid, u32) { // create a signed distance map (SDF) from mask let mut phi = mask2phi(init_mask); // main loop let mut its = 0u32; let mut stop = false; let mut prev_mask = init_mask.clone(); let mut c = 0u32; while its < max_its && !stop { // get the curve's narrow band let idx = { let mut result = Vec::new(); for (x, y, &val) in phi.iter() { if val >= -1.2 && val <= 1.2 { result.push((x, y)); } } result }; if idx.len() > 0 { // intermediate output if its % 50 == 0 { println!("iteration: {}", its); } // find interior and exterior mean let (upts, vpts) = { let mut res1 = Vec::new(); let mut res2 = Vec::new(); for (x, y, value) in phi.iter() { if *value <= 0. { res1.push((x, y)); } else { res2.push((x, y)); } } (res1, res2) }; let u = upts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (upts.len() as f64 + f64::EPSILON); let v = vpts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (vpts.len() as f64 + f64::EPSILON); // force from image information let f: Vec<f64> = idx.iter().map(|&(x, y)| { (*img.get(x, y).unwrap() - u)*(*img.get(x, y).unwrap() - u) -(*img.get(x, y).unwrap() - v)*(*img.get(x, y).unwrap() - v) }).collect(); // force from curvature penalty let curvature = get_curvature(&phi, &idx); // gradient descent to minimize energy let dphidt: Vec<f64> = { let maxabs = f.iter().fold(0.0f64, |acc, &x| { acc.max(x.abs()) }); f.iter().zip(curvature.iter()).map(|(f, c)| { f/maxabs + alpha*c }).collect() }; // maintain the CFL condition let dt = 0.45/(dphidt.iter().fold(0.0f64, |acc, &x| acc.max(x.abs())) + f64::EPSILON); // evolve the curve for i in 0..idx.len() { let (x, y) = idx[i]; let val = *phi.get(x, y).unwrap(); phi.set(x, y, val + dt*dphidt[i]); } // keep SDF smooth phi = sussman(&phi, &0.5); let new_mask = { let mut result = BoolGrid::new(phi.width(), phi.height()); for (x, y, value) in phi.iter() { result.set(x, y, *value <= 0.); } result }; c = convergence(&prev_mask, &new_mask, thresh, c); if c <= 5 { its += 1; prev_mask = new_mask.clone(); } else { stop = true; } } else { break; } } // make mask from SDF, get mask from levelset let seg = { let mut res = BoolGrid::new(phi.width(), phi.height()); for (x, y, &value) in phi.iter() { res.set(x, y, value <= 0.); } res }; (seg, phi, its) } fn bwdist(a: &BoolGrid) -> FloatGrid { let mut res = dt2d(&a); for (_, _, value) in res.iter_mut() { let newval = value.sqrt(); *value = newval; } res } // Converts a mask to a SDF fn mask2phi(init_a: &BoolGrid) -> FloatGrid { let inv_init_a = { let mut result = init_a.clone(); for (_, _, value) in result.iter_mut() { *value = !*value; } result }; let phi = { let dist_a = bwdist(&init_a); let dist_inv_a = bwdist(&inv_init_a); let mut result = FloatGrid::new(init_a.width(), init_a.height()); for (x, y, value) in result.iter_mut() { *value = dist_a.get(x, y).unwrap() - dist_inv_a.get(x, y).unwrap() + if *init_a.get(x, y).unwrap() {1.} else {0.} - 0.5; } result }; phi } // Compute curvature along SDF fn get_curvature(phi: &FloatGrid, idx: &Vec<(usize,usize)>) -> Vec<f64> { // get central derivatives of SDF at x,y let (phi_x, phi_y, phi_xx, phi_yy, phi_xy) = { let (mut res_x, mut res_y, mut res_xx, mut res_yy, mut res_xy) : (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>) = ( Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len())); for &(x, y) in idx.iter() { let left = if x > 0 { x - 1 } else { 0 }; let right = if x < phi.width() - 1 { x + 1 } else { phi.width() - 1 }; let up = if y > 0 { y - 1 } else { 0 }; let down = if y < phi.height() - 1 { y + 1 } else { phi.height() - 1 }; res_x.push(-*phi.get(left, y).unwrap() + *phi.get(right, y).unwrap()); res_y.push(-*phi.get(x, down).unwrap() + *phi.get(x, up).unwrap()); res_xx.push( *phi.get(left, y).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(right, y).unwrap()); res_yy.push( *phi.get(x, up).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(x, down).unwrap()); res_xy.push(0.25*( -*phi.get(left, down).unwrap() - *phi.get(right, up).unwrap() +*phi.get(right, down).unwrap() + *phi.get(left, up).unwrap() )); } (res_x, res_y, res_xx, res_yy, res_xy) }; let phi_x2: Vec<f64> = phi_x.iter().map(|x| x*x).collect(); let phi_y2: Vec<f64> = phi_y.iter().map(|x| x*x).collect(); // compute curvature (Kappa) let curvature: Vec<f64> = (0..idx.len()).map(|i| { ((phi_x2[i]*phi_yy[i] + phi_y2[i]*phi_xx[i] - 2.*phi_x[i]*phi_y[i]*phi_xy[i])/ (phi_x2[i] + phi_y2[i] + f64::EPSILON).powf(1.5))*(phi_x2[i] + phi_y2[i]).powf(0.5) }).collect(); curvature } // Level set re-initialization by the sussman method fn sussman(grid: &FloatGrid, dt: &f64) -> FloatGrid { // forward/backward differences let (a, b, c, d) = { let mut a_res = FloatGrid::new(grid.width(), grid.height()); let mut b_res = FloatGrid::new(grid.width(), grid.height()); let mut c_res = FloatGrid::new(grid.width(), grid.height()); let mut d_res = FloatGrid::new(grid.width(), grid.height()); for y in 0..grid.height() { for x in 0..grid.width() { a_res.set(x, y, grid.get(x, y).unwrap() - grid.get((x + grid.width() - 1) % grid.width(), y).unwrap()); b_res.set(x, y, grid.get((x + 1) % grid.width(), y).unwrap() - grid.get(x, y).unwrap()); c_res.set(x, y, grid.get(x, y).unwrap() - grid.get(x, (y + 1) % grid.height()).unwrap()); d_res.set(x, y, grid.get(x, (y + grid.height() - 1) % grid.height()).unwrap() - grid.get(x, y).unwrap()); } } (a_res, b_res, c_res, d_res) }; let (a_p, a_n, b_p, b_n, c_p, c_n, d_p, d_n) = { let mut a_p_res = FloatGrid::new(grid.width(), grid.height()); let mut a_n_res = FloatGrid::new(grid.width(), grid.height()); let mut b_p_res = FloatGrid::new(grid.width(), grid.height()); let mut b_n_res = FloatGrid::new(grid.width(), grid.height()); let mut c_p_res = FloatGrid::new(grid.width(), grid.height()); let mut c_n_res = FloatGrid::new(grid.width(), grid.height()); let mut d_p_res = FloatGrid::new(grid.width(), grid.height());
for y in 0..grid.height() { for x in 0..grid.width() { let a_p_dval = *a.get(x, y).unwrap(); let a_n_dval = *a.get(x, y).unwrap(); let b_p_dval = *b.get(x, y).unwrap(); let b_n_dval = *b.get(x, y).unwrap(); let c_p_dval = *c.get(x, y).unwrap(); let c_n_dval = *c.get(x, y).unwrap(); let d_p_dval = *d.get(x, y).unwrap(); let d_n_dval = *d.get(x, y).unwrap(); a_p_res.set(x, y, if a_p_dval >= 0.0 { a_p_dval } else { 0.0 }); a_n_res.set(x, y, if a_n_dval <= 0.0 { a_n_dval } else { 0.0 }); b_p_res.set(x, y, if b_p_dval >= 0.0 { b_p_dval } else { 0.0 }); b_n_res.set(x, y, if b_n_dval <= 0.0 { b_n_dval } else { 0.0 }); c_p_res.set(x, y, if c_p_dval >= 0.0 { c_p_dval } else { 0.0 }); c_n_res.set(x, y, if c_n_dval <= 0.0 { c_n_dval } else { 0.0 }); d_p_res.set(x, y, if d_p_dval >= 0.0 { d_p_dval } else { 0.0 }); d_n_res.set(x, y, if d_n_dval <= 0.0 { d_n_dval } else { 0.0 }); } } (a_p_res, a_n_res, b_p_res, b_n_res, c_p_res, c_n_res, d_p_res, d_n_res) }; let mut d_d = FloatGrid::new(grid.width(), grid.height()); let (d_neg_ind, d_pos_ind) = { let mut res = (Vec::new(), Vec::new()); for (x, y, &value) in grid.iter() { if value < 0.0 { res.0.push((x, y)); } else if value > 0.0 { res.1.push((x,y)); } } res }; for index in d_pos_ind { let mut ap = *a_p.get(index.0, index.1).unwrap(); let mut bn = *b_n.get(index.0, index.1).unwrap(); let mut cp = *c_p.get(index.0, index.1).unwrap(); let mut dn = *d_n.get(index.0, index.1).unwrap(); ap *= ap; bn *= bn; cp *= cp; dn *= dn; d_d.set(index.0, index.1, (ap.max(bn) + cp.max(dn)).sqrt() - 1.); } for index in d_neg_ind { let mut an = *a_n.get(index.0, index.1).unwrap(); let mut bp = *b_p.get(index.0, index.1).unwrap(); let mut cn = *c_n.get(index.0, index.1).unwrap(); let mut dp = *d_p.get(index.0, index.1).unwrap(); an *= an; bp *= bp; cn *= cn; dp *= dp; d_d.set(index.0, index.1, (an.max(bp) + cn.max(dp)).sqrt() - 1.); } let ss_d = sussman_sign(&grid); let mut res = FloatGrid::new(grid.width(), grid.height()); for (x, y, value) in res.iter_mut() { let dval = grid.get(x, y).unwrap(); let ss_dval = ss_d.get(x, y).unwrap(); let d_dval = d_d.get(x, y).unwrap(); *value = dval - dt*ss_dval*d_dval; } res } fn sussman_sign(d: &FloatGrid) -> FloatGrid { let mut res = FloatGrid::new(d.width(), d.height()); for (x, y, value) in res.iter_mut() { let v = d.get(x, y).unwrap(); *value = v/(v*v + 1.).sqrt(); } res } // Convergence test fn convergence(p_mask: &BoolGrid, n_mask: &BoolGrid, thresh: u32, c: u32) -> u32 { let n_diff = p_mask.iter().zip(n_mask.iter()).fold(0u32, |acc, ((_,_,p),(_,_,n))| { acc + if *p == *n { 1 } else { 0 } }); if n_diff < thresh { c + 1 } else { 0 } }
let mut d_n_res = FloatGrid::new(grid.width(), grid.height());
random_line_split
lib.rs
//! This crate provides an implementation of Chan-Vese level-sets //! described in [Active contours without edges](http://ieeexplore.ieee.org/document/902291/) //! by T. Chan and L. Vese. //! It is a port of the Python implementation by Kevin Keraudren on //! [Github](https://github.com/kevin-keraudren/chanvese) //! and of the Matlab implementation by [Shawn Lankton](http://www.shawnlankton.com). //! //! # Examples //! To use the functions inside module `chanvese::utils` you need to //! compile this crate with the feature image-utils. //! //! ``` //! extern crate image; //! extern crate rand; //! extern crate chanvese; //! //! use std::f64; //! use std::fs::File; //! use image::ImageBuffer; //! use rand::distributions::{Sample, Range}; //! use chanvese::{FloatGrid, BoolGrid, chanvese}; //! //! use chanvese::utils; //! //! fn main() { //! // create an input image (blurred and noisy ellipses) //! let img = { //! let mut img = ImageBuffer::new(256, 128); //! for (x, y, pixel) in img.enumerate_pixels_mut() { //! if (x-100)*(x-100)+(y-70)*(y-70) <= 35*35 { //! *pixel = image::Luma([200u8]); //! } //! if (x-128)*(x-128)/2+(y-50)*(y-50) <= 30*30 { //! *pixel = image::Luma([150u8]); //! } //! } //! img = image::imageops::blur(&img, 5.); //! let mut noiserange = Range::new(0.0f32, 30.); //! let mut rng = rand::thread_rng(); //! for (_, _, pixel) in img.enumerate_pixels_mut() { //! *pixel = image::Luma([pixel.data[0] + noiserange.sample(&mut rng) as u8]); //! } //! let ref mut imgout = File::create("image.png").unwrap(); //! image::ImageLuma8(img.clone()).save(imgout, image::PNG).unwrap(); //! let mut result = FloatGrid::new(256, 128); //! //! for (x, y, pixel) in img.enumerate_pixels() { //! result.set(x as usize, y as usize, pixel.data[0] as f64); //! } //! result //! }; //! //! // create a rough mask //! let mask = { //! let mut result = BoolGrid::new(img.width(), img.height()); //! for (x, y, value) in result.iter_mut() { //! if (x >= 65 && x <= 180) && (y >= 20 && y <= 100) { //! *value = true; //! } //! } //! result //! }; //! utils::save_boolgrid(&mask, "mask.png"); //! //! // level-set segmentation by Chan-Vese //! let (seg, phi, _) = chanvese(&img, &mask, 500, 1.0, 0); //! utils::save_boolgrid(&seg, "out.png"); //! utils::save_floatgrid(&phi, "phi.png"); //! } //! ``` extern crate distance_transform; use distance_transform::dt2d; use std::f64; pub use distance_transform::{FloatGrid, BoolGrid}; #[cfg(feature = "image-utils")] pub mod utils; #[cfg(feature = "image-utils")] mod viridis; /// Runs the chanvese algorithm /// /// Returns the resulting mask (`true` = foreground, `false` = background), /// the level-set function and the number of iterations. /// /// # Arguments /// /// * `img` - the input image /// * `init_mask` - in initial mask (`true` = foreground, `false` = background) /// * `max_its` - number of iterations /// * `alpha` - weight of smoothing term (default: 0.2) /// * `thresh` - number of different pixels in masks of successive steps (default: 0) pub fn chanvese(img: &FloatGrid, init_mask: &BoolGrid, max_its: u32, alpha: f64, thresh: u32) -> (BoolGrid, FloatGrid, u32) { // create a signed distance map (SDF) from mask let mut phi = mask2phi(init_mask); // main loop let mut its = 0u32; let mut stop = false; let mut prev_mask = init_mask.clone(); let mut c = 0u32; while its < max_its && !stop { // get the curve's narrow band let idx = { let mut result = Vec::new(); for (x, y, &val) in phi.iter() { if val >= -1.2 && val <= 1.2 { result.push((x, y)); } } result }; if idx.len() > 0 { // intermediate output if its % 50 == 0 { println!("iteration: {}", its); } // find interior and exterior mean let (upts, vpts) = { let mut res1 = Vec::new(); let mut res2 = Vec::new(); for (x, y, value) in phi.iter() { if *value <= 0. { res1.push((x, y)); } else { res2.push((x, y)); } } (res1, res2) }; let u = upts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (upts.len() as f64 + f64::EPSILON); let v = vpts.iter().fold(0f64, |acc, &(x, y)| { acc + *img.get(x, y).unwrap() }) / (vpts.len() as f64 + f64::EPSILON); // force from image information let f: Vec<f64> = idx.iter().map(|&(x, y)| { (*img.get(x, y).unwrap() - u)*(*img.get(x, y).unwrap() - u) -(*img.get(x, y).unwrap() - v)*(*img.get(x, y).unwrap() - v) }).collect(); // force from curvature penalty let curvature = get_curvature(&phi, &idx); // gradient descent to minimize energy let dphidt: Vec<f64> = { let maxabs = f.iter().fold(0.0f64, |acc, &x| { acc.max(x.abs()) }); f.iter().zip(curvature.iter()).map(|(f, c)| { f/maxabs + alpha*c }).collect() }; // maintain the CFL condition let dt = 0.45/(dphidt.iter().fold(0.0f64, |acc, &x| acc.max(x.abs())) + f64::EPSILON); // evolve the curve for i in 0..idx.len() { let (x, y) = idx[i]; let val = *phi.get(x, y).unwrap(); phi.set(x, y, val + dt*dphidt[i]); } // keep SDF smooth phi = sussman(&phi, &0.5); let new_mask = { let mut result = BoolGrid::new(phi.width(), phi.height()); for (x, y, value) in phi.iter() { result.set(x, y, *value <= 0.); } result }; c = convergence(&prev_mask, &new_mask, thresh, c); if c <= 5 { its += 1; prev_mask = new_mask.clone(); } else { stop = true; } } else { break; } } // make mask from SDF, get mask from levelset let seg = { let mut res = BoolGrid::new(phi.width(), phi.height()); for (x, y, &value) in phi.iter() { res.set(x, y, value <= 0.); } res }; (seg, phi, its) } fn bwdist(a: &BoolGrid) -> FloatGrid { let mut res = dt2d(&a); for (_, _, value) in res.iter_mut() { let newval = value.sqrt(); *value = newval; } res } // Converts a mask to a SDF fn mask2phi(init_a: &BoolGrid) -> FloatGrid { let inv_init_a = { let mut result = init_a.clone(); for (_, _, value) in result.iter_mut() { *value = !*value; } result }; let phi = { let dist_a = bwdist(&init_a); let dist_inv_a = bwdist(&inv_init_a); let mut result = FloatGrid::new(init_a.width(), init_a.height()); for (x, y, value) in result.iter_mut() { *value = dist_a.get(x, y).unwrap() - dist_inv_a.get(x, y).unwrap() + if *init_a.get(x, y).unwrap() {1.} else {0.} - 0.5; } result }; phi } // Compute curvature along SDF fn get_curvature(phi: &FloatGrid, idx: &Vec<(usize,usize)>) -> Vec<f64> { // get central derivatives of SDF at x,y let (phi_x, phi_y, phi_xx, phi_yy, phi_xy) = { let (mut res_x, mut res_y, mut res_xx, mut res_yy, mut res_xy) : (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>) = ( Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len()), Vec::with_capacity(idx.len())); for &(x, y) in idx.iter() { let left = if x > 0 { x - 1 } else { 0 }; let right = if x < phi.width() - 1 { x + 1 } else { phi.width() - 1 }; let up = if y > 0 { y - 1 } else { 0 }; let down = if y < phi.height() - 1 { y + 1 } else { phi.height() - 1 }; res_x.push(-*phi.get(left, y).unwrap() + *phi.get(right, y).unwrap()); res_y.push(-*phi.get(x, down).unwrap() + *phi.get(x, up).unwrap()); res_xx.push( *phi.get(left, y).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(right, y).unwrap()); res_yy.push( *phi.get(x, up).unwrap() - 2.0 * *phi.get(x, y).unwrap() + *phi.get(x, down).unwrap()); res_xy.push(0.25*( -*phi.get(left, down).unwrap() - *phi.get(right, up).unwrap() +*phi.get(right, down).unwrap() + *phi.get(left, up).unwrap() )); } (res_x, res_y, res_xx, res_yy, res_xy) }; let phi_x2: Vec<f64> = phi_x.iter().map(|x| x*x).collect(); let phi_y2: Vec<f64> = phi_y.iter().map(|x| x*x).collect(); // compute curvature (Kappa) let curvature: Vec<f64> = (0..idx.len()).map(|i| { ((phi_x2[i]*phi_yy[i] + phi_y2[i]*phi_xx[i] - 2.*phi_x[i]*phi_y[i]*phi_xy[i])/ (phi_x2[i] + phi_y2[i] + f64::EPSILON).powf(1.5))*(phi_x2[i] + phi_y2[i]).powf(0.5) }).collect(); curvature } // Level set re-initialization by the sussman method fn sussman(grid: &FloatGrid, dt: &f64) -> FloatGrid { // forward/backward differences let (a, b, c, d) = { let mut a_res = FloatGrid::new(grid.width(), grid.height()); let mut b_res = FloatGrid::new(grid.width(), grid.height()); let mut c_res = FloatGrid::new(grid.width(), grid.height()); let mut d_res = FloatGrid::new(grid.width(), grid.height()); for y in 0..grid.height() { for x in 0..grid.width() { a_res.set(x, y, grid.get(x, y).unwrap() - grid.get((x + grid.width() - 1) % grid.width(), y).unwrap()); b_res.set(x, y, grid.get((x + 1) % grid.width(), y).unwrap() - grid.get(x, y).unwrap()); c_res.set(x, y, grid.get(x, y).unwrap() - grid.get(x, (y + 1) % grid.height()).unwrap()); d_res.set(x, y, grid.get(x, (y + grid.height() - 1) % grid.height()).unwrap() - grid.get(x, y).unwrap()); } } (a_res, b_res, c_res, d_res) }; let (a_p, a_n, b_p, b_n, c_p, c_n, d_p, d_n) = { let mut a_p_res = FloatGrid::new(grid.width(), grid.height()); let mut a_n_res = FloatGrid::new(grid.width(), grid.height()); let mut b_p_res = FloatGrid::new(grid.width(), grid.height()); let mut b_n_res = FloatGrid::new(grid.width(), grid.height()); let mut c_p_res = FloatGrid::new(grid.width(), grid.height()); let mut c_n_res = FloatGrid::new(grid.width(), grid.height()); let mut d_p_res = FloatGrid::new(grid.width(), grid.height()); let mut d_n_res = FloatGrid::new(grid.width(), grid.height()); for y in 0..grid.height() { for x in 0..grid.width() { let a_p_dval = *a.get(x, y).unwrap(); let a_n_dval = *a.get(x, y).unwrap(); let b_p_dval = *b.get(x, y).unwrap(); let b_n_dval = *b.get(x, y).unwrap(); let c_p_dval = *c.get(x, y).unwrap(); let c_n_dval = *c.get(x, y).unwrap(); let d_p_dval = *d.get(x, y).unwrap(); let d_n_dval = *d.get(x, y).unwrap(); a_p_res.set(x, y, if a_p_dval >= 0.0 { a_p_dval } else { 0.0 }); a_n_res.set(x, y, if a_n_dval <= 0.0 { a_n_dval } else { 0.0 }); b_p_res.set(x, y, if b_p_dval >= 0.0 { b_p_dval } else { 0.0 }); b_n_res.set(x, y, if b_n_dval <= 0.0 { b_n_dval } else { 0.0 }); c_p_res.set(x, y, if c_p_dval >= 0.0 { c_p_dval } else { 0.0 }); c_n_res.set(x, y, if c_n_dval <= 0.0 { c_n_dval } else { 0.0 }); d_p_res.set(x, y, if d_p_dval >= 0.0 { d_p_dval } else { 0.0 }); d_n_res.set(x, y, if d_n_dval <= 0.0 { d_n_dval } else { 0.0 }); } } (a_p_res, a_n_res, b_p_res, b_n_res, c_p_res, c_n_res, d_p_res, d_n_res) }; let mut d_d = FloatGrid::new(grid.width(), grid.height()); let (d_neg_ind, d_pos_ind) = { let mut res = (Vec::new(), Vec::new()); for (x, y, &value) in grid.iter() { if value < 0.0 { res.0.push((x, y)); } else if value > 0.0 { res.1.push((x,y)); } } res }; for index in d_pos_ind { let mut ap = *a_p.get(index.0, index.1).unwrap(); let mut bn = *b_n.get(index.0, index.1).unwrap(); let mut cp = *c_p.get(index.0, index.1).unwrap(); let mut dn = *d_n.get(index.0, index.1).unwrap(); ap *= ap; bn *= bn; cp *= cp; dn *= dn; d_d.set(index.0, index.1, (ap.max(bn) + cp.max(dn)).sqrt() - 1.); } for index in d_neg_ind { let mut an = *a_n.get(index.0, index.1).unwrap(); let mut bp = *b_p.get(index.0, index.1).unwrap(); let mut cn = *c_n.get(index.0, index.1).unwrap(); let mut dp = *d_p.get(index.0, index.1).unwrap(); an *= an; bp *= bp; cn *= cn; dp *= dp; d_d.set(index.0, index.1, (an.max(bp) + cn.max(dp)).sqrt() - 1.); } let ss_d = sussman_sign(&grid); let mut res = FloatGrid::new(grid.width(), grid.height()); for (x, y, value) in res.iter_mut() { let dval = grid.get(x, y).unwrap(); let ss_dval = ss_d.get(x, y).unwrap(); let d_dval = d_d.get(x, y).unwrap(); *value = dval - dt*ss_dval*d_dval; } res } fn
(d: &FloatGrid) -> FloatGrid { let mut res = FloatGrid::new(d.width(), d.height()); for (x, y, value) in res.iter_mut() { let v = d.get(x, y).unwrap(); *value = v/(v*v + 1.).sqrt(); } res } // Convergence test fn convergence(p_mask: &BoolGrid, n_mask: &BoolGrid, thresh: u32, c: u32) -> u32 { let n_diff = p_mask.iter().zip(n_mask.iter()).fold(0u32, |acc, ((_,_,p),(_,_,n))| { acc + if *p == *n { 1 } else { 0 } }); if n_diff < thresh { c + 1 } else { 0 } }
sussman_sign
identifier_name
controller.rs
//! Contains ZX Spectrum System contrller (like ula or so) of emulator use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; // use almost everything :D use utils::{split_word, Clocks}; use utils::screen::*; use utils::events::*; use utils::InstantFlag; use z80::Z80Bus; use zx::{ZXMemory, RomType, RamType}; use zx::memory::{Page, PAGE_SIZE}; use zx::machine::ZXMachine; use zx::tape::*; use zx::ZXKey; use zx::screen::canvas::ZXCanvas; use zx::screen::border::ZXBorder; use zx::screen::colors::{ZXColor, ZXPalette}; use zx::roms::*; use zx::constants::*; use zx::sound::mixer::ZXMixer; use settings::RustzxSettings; use zx::joy::kempston::*; /// ZX System controller pub struct ZXController { // parts of ZX Spectum. pub machine: ZXMachine, pub memory: ZXMemory, pub canvas: ZXCanvas, pub tape: Box<ZXTape>, pub border: ZXBorder, pub kempston: Option<KempstonJoy>, //pub beeper: ZXBeeper, pub mixer: ZXMixer, pub keyboard: [u8; 8], // current border color border_color: u8, // clocls count from frame start frame_clocks: Clocks, // frames count, which passed during emulation invokation passed_frames: usize, // main event queue events: EventQueue, // flag, which signals emulator to break emulation and process last event immediately instant_event: InstantFlag, // audio in mic: bool, // audio out ear: bool, paging_enabled: bool, screen_bank: u8, } impl ZXController { /// Returns new ZXController from settings pub fn new(settings: &RustzxSettings) -> ZXController { let (memory, paging, screen_bank); match settings.machine { ZXMachine::Sinclair48K => { memory = ZXMemory::new(RomType::K16, RamType::K48); paging = false; screen_bank = 0; } ZXMachine::Sinclair128K => { memory = ZXMemory::new(RomType::K32, RamType::K128); paging = true; screen_bank = 5; } }; let kempston = if settings.kempston { Some(KempstonJoy::new()) } else { None }; let mut out = ZXController { machine: settings.machine, memory: memory, canvas: ZXCanvas::new(settings.machine), border: ZXBorder::new(settings.machine, ZXPalette::default()), kempston: kempston, mixer: ZXMixer::new(settings.beeper_enabled, settings.ay_enabled), keyboard: [0xFF; 8], border_color: 0x00, frame_clocks: Clocks(0), passed_frames: 0, tape: Box::new(Tap::new()), events: EventQueue::new(), instant_event: InstantFlag::new(false), mic: false, ear: false, paging_enabled: paging, screen_bank: screen_bank, }; out.mixer.ay.mode(settings.ay_mode); out.mixer.volume(settings.volume as f64 / 200.0);
fn frame_pos(&self) -> f64 { let val = self.frame_clocks.count() as f64 / self.machine.specs().clocks_frame as f64; if val > 1.0 { 1.0 } else { val } } /// loads rom from file /// for 128-K machines path must contain ".0" in the tail /// and second rom bank will be loaded automatically pub fn load_rom(&mut self, path: impl AsRef<Path>) { match self.machine { // Single ROM file ZXMachine::Sinclair48K => { let mut rom = Vec::new(); File::open(path).ok().expect("[ERROR] ROM not found").read_to_end(&mut rom) .unwrap(); self.memory.load_rom(0, &rom); } // Two ROM's ZXMachine::Sinclair128K => { let mut rom0 = Vec::new(); let mut rom1 = Vec::new(); if !path.as_ref().extension().map_or(false, |e| e == "0") { println!("[Warning] ROM0 filename should end with .0"); } File::open(path.as_ref()).ok().expect("[ERROR] ROM0 not found").read_to_end(&mut rom0) .unwrap(); let mut second_path: PathBuf = path.as_ref().to_path_buf(); second_path.set_extension("1"); File::open(second_path).ok().expect("[ERROR] ROM1 not found").read_to_end(&mut rom1) .unwrap(); self.memory.load_rom(0, &rom0) .load_rom(1, &rom1); println!("ROM's Loaded"); } } } /// loads builted-in ROM pub fn load_default_rom(&mut self) { match self.machine { ZXMachine::Sinclair48K => { self.memory.load_rom(0, ROM_48K); } ZXMachine::Sinclair128K => { self.memory.load_rom(0, ROM_128K_0) .load_rom(1, ROM_128K_1); } } } /// Changes key state in controller pub fn send_key(&mut self, key: ZXKey, pressed: bool) { // TODO: Move row detection to ZXKey type let rownum = match key.half_port { 0xFE => Some(0), 0xFD => Some(1), 0xFB => Some(2), 0xF7 => Some(3), 0xEF => Some(4), 0xDF => Some(5), 0xBF => Some(6), 0x7F => Some(7), _ => None, }; if let Some(rownum) = rownum { self.keyboard[rownum] = self.keyboard[rownum] & (!key.mask); if !pressed { self.keyboard[rownum] |= key.mask; } } } /// Dumps memory space pub fn dump(&self) -> Vec<u8> { self.memory.dump() } /// Returns current bus floating value fn floating_bus_value(&self) -> u8 { let specs = self.machine.specs(); let clocks = self.frame_clocks; if clocks.count() < specs.clocks_first_pixel + 2 { return 0xFF; } let clocks = clocks.count() - (specs.clocks_first_pixel + 2); let row = clocks / specs.clocks_line; let clocks = clocks % specs.clocks_line; let col = (clocks / 8) * 2 + (clocks % 8) / 2; if row < CANVAS_HEIGHT && clocks < specs.clocks_screen_row - CLOCKS_PER_COL && ((clocks & 0x04) == 0) { if clocks % 2 == 0 { return self.memory.read(bitmap_line_addr(row) + col as u16); } else { let byte = (row / 8) * 32 + col; return self.memory.read(0x5800 + byte as u16); }; } return 0xFF; } /// make contention fn do_contention(&mut self) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention); } ///make contention + wait some clocks fn do_contention_and_wait(&mut self, wait_time: Clocks) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention + wait_time); } // check addr contention fn addr_is_contended(&self, addr: u16) -> bool { return if let Page::Ram(bank) = self.memory.get_page(addr) { self.machine.bank_is_contended(bank as usize) } else { false } } /// Returns early IO contention clocks fn io_contention_first(&mut self, port: u16) { if self.addr_is_contended(port) { self.do_contention(); }; self.wait_internal(Clocks(1)); } /// Returns late IO contention clocks fn io_contention_last(&mut self, port: u16) { if self.machine.port_is_contended(port) { self.do_contention_and_wait(Clocks(2)); } else { if self.addr_is_contended(port) { self.do_contention_and_wait(Clocks(1)); self.do_contention_and_wait(Clocks(1)); self.do_contention(); } else { self.wait_internal(Clocks(2)); } } } /// Starts a new frame fn new_frame(&mut self) { self.frame_clocks -= self.machine.specs().clocks_frame; self.canvas.new_frame(); self.border.new_frame(); self.mixer.new_frame(); } /// force clears all events pub fn clear_events(&mut self) { self.events.clear(); } /// check events count pub fn no_events(&self) -> bool { self.events.is_empty() } /// Returns last event pub fn pop_event(&mut self) -> Option<Event> { self.events.receive_event() } /// Returns true if all frame clocks has been passed pub fn frames_count(&self) -> usize { self.passed_frames } pub fn reset_frame_counter(&mut self) { self.passed_frames = 0; } /// Returns current clocks from frame start pub fn clocks(&self) -> Clocks { self.frame_clocks } fn write_7ffd(&mut self, val: u8) { if !self.paging_enabled { return; } // remap top 16K of the ram self.memory.remap(3, Page::Ram(val & 0x07)); // third block is not pageable // second block is screen buffer, not pageable. but we need to change active buffer let new_screen_bank = if val & 0x08 == 0 { 5 } else { 7 }; self.canvas.switch_bank(new_screen_bank as usize); self.screen_bank = new_screen_bank; // remap ROM self.memory.remap(0, Page::Rom((val >> 4) & 0x01)); // check paging allow bit if val & 0x20 != 0 { self.paging_enabled = false; } } } impl Z80Bus for ZXController { /// we need to check different breakpoints like tape /// loading detection breakpoint fn pc_callback(&mut self, addr: u16) { // check mapped memory page at 0x0000 .. 0x3FFF let check_fast_load = match self.machine { ZXMachine::Sinclair48K if self.memory.get_bank_type(0) == Page::Rom(0) => true, ZXMachine::Sinclair128K if self.memory.get_bank_type(0) == Page::Rom(1) => true, _ => false, }; if check_fast_load { // Tape LOAD/VERIFY if addr == ADDR_LD_BREAK { // Add event (Fast tape loading request) it must be executed // by emulator immediately self.events.send_event(Event::new(EventKind::FastTapeLoad, self.frame_clocks)); self.instant_event.set(); } } } /// read data without taking onto account contention fn read_internal(&mut self, addr: u16) -> u8 { self.memory.read(addr) } /// write data without taking onto account contention fn write_internal(&mut self, addr: u16, data: u8) { self.memory.write(addr, data); // if ram then compare bank to screen bank if let Page::Ram(bank) = self.memory.get_page(addr) { self.canvas.update(addr % PAGE_SIZE as u16, bank as usize, data); } } /// Cahnges internal state on clocks count change (emualtion processing) fn wait_internal(&mut self, clk: Clocks) { self.frame_clocks += clk; (*self.tape).process_clocks(clk); let mic = (*self.tape).current_bit(); self.mic = mic; let pos = self.frame_pos(); self.mixer.beeper.change_bit(self.mic | self.ear); self.mixer.process(pos); self.canvas.process_clocks(self.frame_clocks); if self.frame_clocks.count() >= self.machine.specs().clocks_frame { self.new_frame(); self.passed_frames += 1; } } // wait with memory request pin active fn wait_mreq(&mut self, addr: u16, clk: Clocks) { match self.machine { ZXMachine::Sinclair48K | ZXMachine::Sinclair128K=> { // contention in low 16k RAM if self.addr_is_contended(addr) { self.do_contention(); } } } self.wait_internal(clk); } /// wait without memory request pin active fn wait_no_mreq(&mut self, addr: u16, clk: Clocks) { // only for 48 K! self.wait_mreq(addr, clk); } /// read io from hardware fn read_io(&mut self, port: u16) -> u8 { // all contentions check self.io_contention_first(port); self.io_contention_last(port); // find out what we need to do let (h, _) = split_word(port); let output = if port & 0x0001 == 0 { // ULA port let mut tmp: u8 = 0xFF; for n in 0..8 { // if bit of row reset if ((h >> n) & 0x01) == 0 { tmp &= self.keyboard[n]; } } // invert bit 6 if mic_hw active; if self.mic { tmp ^= 0x40; } // 5 and 7 unused tmp } else if port & 0xC002 == 0xC000 { // AY regs self.mixer.ay.read() } else if self.kempston.is_some() && (port & 0x0020 == 0) { if let Some(ref joy) = self.kempston { joy.read() } else { unreachable!() } } else { self.floating_bus_value() }; // add one clock after operation self.wait_internal(Clocks(1)); output } /// write value to hardware port fn write_io(&mut self, port: u16, data: u8) { // first contention self.io_contention_first(port); // find active port if port & 0xC002 == 0xC000 { self.mixer.ay.select_reg(data); } else if port & 0xC002 == 0x8000 { self.mixer.ay.write(data); } else if port & 0x0001 == 0 { self.border_color = data & 0x07; self.border.set_border(self.frame_clocks, ZXColor::from_bits(data & 0x07)); self.mic = data & 0x08 != 0; self.ear = data & 0x10 != 0; self.mixer.beeper.change_bit(self.mic | self.ear); } else if (port & 0x8002 == 0) && (self.machine == ZXMachine::Sinclair128K) { self.write_7ffd(data); } // last contention after byte write self.io_contention_last(port); // add one clock after operation self.wait_internal(Clocks(1)); } /// value, requested during `INT0` interrupt fn read_interrupt(&mut self) -> u8 { 0xFF } /// checks system maskable interrupt pin state fn int_active(&self) -> bool { self.frame_clocks.count() % self.machine.specs().clocks_frame < self.machine.specs().interrupt_length } /// checks non-maskable interrupt pin state fn nmi_active(&self) -> bool { false } /// CPU calls it when RETI instruction was processed fn reti(&mut self) {} /// CPU calls when was being halted fn halt(&mut self, _: bool) {} /// checks instant events fn instant_event(&self) -> bool { self.instant_event.pick() } }
out } /// returns current frame emulation pos in percents
random_line_split
controller.rs
//! Contains ZX Spectrum System contrller (like ula or so) of emulator use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; // use almost everything :D use utils::{split_word, Clocks}; use utils::screen::*; use utils::events::*; use utils::InstantFlag; use z80::Z80Bus; use zx::{ZXMemory, RomType, RamType}; use zx::memory::{Page, PAGE_SIZE}; use zx::machine::ZXMachine; use zx::tape::*; use zx::ZXKey; use zx::screen::canvas::ZXCanvas; use zx::screen::border::ZXBorder; use zx::screen::colors::{ZXColor, ZXPalette}; use zx::roms::*; use zx::constants::*; use zx::sound::mixer::ZXMixer; use settings::RustzxSettings; use zx::joy::kempston::*; /// ZX System controller pub struct ZXController { // parts of ZX Spectum. pub machine: ZXMachine, pub memory: ZXMemory, pub canvas: ZXCanvas, pub tape: Box<ZXTape>, pub border: ZXBorder, pub kempston: Option<KempstonJoy>, //pub beeper: ZXBeeper, pub mixer: ZXMixer, pub keyboard: [u8; 8], // current border color border_color: u8, // clocls count from frame start frame_clocks: Clocks, // frames count, which passed during emulation invokation passed_frames: usize, // main event queue events: EventQueue, // flag, which signals emulator to break emulation and process last event immediately instant_event: InstantFlag, // audio in mic: bool, // audio out ear: bool, paging_enabled: bool, screen_bank: u8, } impl ZXController { /// Returns new ZXController from settings pub fn new(settings: &RustzxSettings) -> ZXController { let (memory, paging, screen_bank); match settings.machine { ZXMachine::Sinclair48K => { memory = ZXMemory::new(RomType::K16, RamType::K48); paging = false; screen_bank = 0; } ZXMachine::Sinclair128K => { memory = ZXMemory::new(RomType::K32, RamType::K128); paging = true; screen_bank = 5; } }; let kempston = if settings.kempston { Some(KempstonJoy::new()) } else { None }; let mut out = ZXController { machine: settings.machine, memory: memory, canvas: ZXCanvas::new(settings.machine), border: ZXBorder::new(settings.machine, ZXPalette::default()), kempston: kempston, mixer: ZXMixer::new(settings.beeper_enabled, settings.ay_enabled), keyboard: [0xFF; 8], border_color: 0x00, frame_clocks: Clocks(0), passed_frames: 0, tape: Box::new(Tap::new()), events: EventQueue::new(), instant_event: InstantFlag::new(false), mic: false, ear: false, paging_enabled: paging, screen_bank: screen_bank, }; out.mixer.ay.mode(settings.ay_mode); out.mixer.volume(settings.volume as f64 / 200.0); out } /// returns current frame emulation pos in percents fn frame_pos(&self) -> f64 { let val = self.frame_clocks.count() as f64 / self.machine.specs().clocks_frame as f64; if val > 1.0 { 1.0 } else { val } } /// loads rom from file /// for 128-K machines path must contain ".0" in the tail /// and second rom bank will be loaded automatically pub fn load_rom(&mut self, path: impl AsRef<Path>) { match self.machine { // Single ROM file ZXMachine::Sinclair48K => { let mut rom = Vec::new(); File::open(path).ok().expect("[ERROR] ROM not found").read_to_end(&mut rom) .unwrap(); self.memory.load_rom(0, &rom); } // Two ROM's ZXMachine::Sinclair128K => { let mut rom0 = Vec::new(); let mut rom1 = Vec::new(); if !path.as_ref().extension().map_or(false, |e| e == "0") { println!("[Warning] ROM0 filename should end with .0"); } File::open(path.as_ref()).ok().expect("[ERROR] ROM0 not found").read_to_end(&mut rom0) .unwrap(); let mut second_path: PathBuf = path.as_ref().to_path_buf(); second_path.set_extension("1"); File::open(second_path).ok().expect("[ERROR] ROM1 not found").read_to_end(&mut rom1) .unwrap(); self.memory.load_rom(0, &rom0) .load_rom(1, &rom1); println!("ROM's Loaded"); } } } /// loads builted-in ROM pub fn load_default_rom(&mut self) { match self.machine { ZXMachine::Sinclair48K => { self.memory.load_rom(0, ROM_48K); } ZXMachine::Sinclair128K => { self.memory.load_rom(0, ROM_128K_0) .load_rom(1, ROM_128K_1); } } } /// Changes key state in controller pub fn send_key(&mut self, key: ZXKey, pressed: bool) { // TODO: Move row detection to ZXKey type let rownum = match key.half_port { 0xFE => Some(0), 0xFD => Some(1), 0xFB => Some(2), 0xF7 => Some(3), 0xEF => Some(4), 0xDF => Some(5), 0xBF => Some(6), 0x7F => Some(7), _ => None, }; if let Some(rownum) = rownum { self.keyboard[rownum] = self.keyboard[rownum] & (!key.mask); if !pressed { self.keyboard[rownum] |= key.mask; } } } /// Dumps memory space pub fn dump(&self) -> Vec<u8> { self.memory.dump() } /// Returns current bus floating value fn floating_bus_value(&self) -> u8 { let specs = self.machine.specs(); let clocks = self.frame_clocks; if clocks.count() < specs.clocks_first_pixel + 2 { return 0xFF; } let clocks = clocks.count() - (specs.clocks_first_pixel + 2); let row = clocks / specs.clocks_line; let clocks = clocks % specs.clocks_line; let col = (clocks / 8) * 2 + (clocks % 8) / 2; if row < CANVAS_HEIGHT && clocks < specs.clocks_screen_row - CLOCKS_PER_COL && ((clocks & 0x04) == 0) { if clocks % 2 == 0 { return self.memory.read(bitmap_line_addr(row) + col as u16); } else { let byte = (row / 8) * 32 + col; return self.memory.read(0x5800 + byte as u16); }; } return 0xFF; } /// make contention fn do_contention(&mut self) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention); } ///make contention + wait some clocks fn do_contention_and_wait(&mut self, wait_time: Clocks) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention + wait_time); } // check addr contention fn addr_is_contended(&self, addr: u16) -> bool { return if let Page::Ram(bank) = self.memory.get_page(addr) { self.machine.bank_is_contended(bank as usize) } else { false } } /// Returns early IO contention clocks fn io_contention_first(&mut self, port: u16) { if self.addr_is_contended(port) { self.do_contention(); }; self.wait_internal(Clocks(1)); } /// Returns late IO contention clocks fn io_contention_last(&mut self, port: u16) { if self.machine.port_is_contended(port) { self.do_contention_and_wait(Clocks(2)); } else { if self.addr_is_contended(port) { self.do_contention_and_wait(Clocks(1)); self.do_contention_and_wait(Clocks(1)); self.do_contention(); } else { self.wait_internal(Clocks(2)); } } } /// Starts a new frame fn new_frame(&mut self) { self.frame_clocks -= self.machine.specs().clocks_frame; self.canvas.new_frame(); self.border.new_frame(); self.mixer.new_frame(); } /// force clears all events pub fn clear_events(&mut self)
/// check events count pub fn no_events(&self) -> bool { self.events.is_empty() } /// Returns last event pub fn pop_event(&mut self) -> Option<Event> { self.events.receive_event() } /// Returns true if all frame clocks has been passed pub fn frames_count(&self) -> usize { self.passed_frames } pub fn reset_frame_counter(&mut self) { self.passed_frames = 0; } /// Returns current clocks from frame start pub fn clocks(&self) -> Clocks { self.frame_clocks } fn write_7ffd(&mut self, val: u8) { if !self.paging_enabled { return; } // remap top 16K of the ram self.memory.remap(3, Page::Ram(val & 0x07)); // third block is not pageable // second block is screen buffer, not pageable. but we need to change active buffer let new_screen_bank = if val & 0x08 == 0 { 5 } else { 7 }; self.canvas.switch_bank(new_screen_bank as usize); self.screen_bank = new_screen_bank; // remap ROM self.memory.remap(0, Page::Rom((val >> 4) & 0x01)); // check paging allow bit if val & 0x20 != 0 { self.paging_enabled = false; } } } impl Z80Bus for ZXController { /// we need to check different breakpoints like tape /// loading detection breakpoint fn pc_callback(&mut self, addr: u16) { // check mapped memory page at 0x0000 .. 0x3FFF let check_fast_load = match self.machine { ZXMachine::Sinclair48K if self.memory.get_bank_type(0) == Page::Rom(0) => true, ZXMachine::Sinclair128K if self.memory.get_bank_type(0) == Page::Rom(1) => true, _ => false, }; if check_fast_load { // Tape LOAD/VERIFY if addr == ADDR_LD_BREAK { // Add event (Fast tape loading request) it must be executed // by emulator immediately self.events.send_event(Event::new(EventKind::FastTapeLoad, self.frame_clocks)); self.instant_event.set(); } } } /// read data without taking onto account contention fn read_internal(&mut self, addr: u16) -> u8 { self.memory.read(addr) } /// write data without taking onto account contention fn write_internal(&mut self, addr: u16, data: u8) { self.memory.write(addr, data); // if ram then compare bank to screen bank if let Page::Ram(bank) = self.memory.get_page(addr) { self.canvas.update(addr % PAGE_SIZE as u16, bank as usize, data); } } /// Cahnges internal state on clocks count change (emualtion processing) fn wait_internal(&mut self, clk: Clocks) { self.frame_clocks += clk; (*self.tape).process_clocks(clk); let mic = (*self.tape).current_bit(); self.mic = mic; let pos = self.frame_pos(); self.mixer.beeper.change_bit(self.mic | self.ear); self.mixer.process(pos); self.canvas.process_clocks(self.frame_clocks); if self.frame_clocks.count() >= self.machine.specs().clocks_frame { self.new_frame(); self.passed_frames += 1; } } // wait with memory request pin active fn wait_mreq(&mut self, addr: u16, clk: Clocks) { match self.machine { ZXMachine::Sinclair48K | ZXMachine::Sinclair128K=> { // contention in low 16k RAM if self.addr_is_contended(addr) { self.do_contention(); } } } self.wait_internal(clk); } /// wait without memory request pin active fn wait_no_mreq(&mut self, addr: u16, clk: Clocks) { // only for 48 K! self.wait_mreq(addr, clk); } /// read io from hardware fn read_io(&mut self, port: u16) -> u8 { // all contentions check self.io_contention_first(port); self.io_contention_last(port); // find out what we need to do let (h, _) = split_word(port); let output = if port & 0x0001 == 0 { // ULA port let mut tmp: u8 = 0xFF; for n in 0..8 { // if bit of row reset if ((h >> n) & 0x01) == 0 { tmp &= self.keyboard[n]; } } // invert bit 6 if mic_hw active; if self.mic { tmp ^= 0x40; } // 5 and 7 unused tmp } else if port & 0xC002 == 0xC000 { // AY regs self.mixer.ay.read() } else if self.kempston.is_some() && (port & 0x0020 == 0) { if let Some(ref joy) = self.kempston { joy.read() } else { unreachable!() } } else { self.floating_bus_value() }; // add one clock after operation self.wait_internal(Clocks(1)); output } /// write value to hardware port fn write_io(&mut self, port: u16, data: u8) { // first contention self.io_contention_first(port); // find active port if port & 0xC002 == 0xC000 { self.mixer.ay.select_reg(data); } else if port & 0xC002 == 0x8000 { self.mixer.ay.write(data); } else if port & 0x0001 == 0 { self.border_color = data & 0x07; self.border.set_border(self.frame_clocks, ZXColor::from_bits(data & 0x07)); self.mic = data & 0x08 != 0; self.ear = data & 0x10 != 0; self.mixer.beeper.change_bit(self.mic | self.ear); } else if (port & 0x8002 == 0) && (self.machine == ZXMachine::Sinclair128K) { self.write_7ffd(data); } // last contention after byte write self.io_contention_last(port); // add one clock after operation self.wait_internal(Clocks(1)); } /// value, requested during `INT0` interrupt fn read_interrupt(&mut self) -> u8 { 0xFF } /// checks system maskable interrupt pin state fn int_active(&self) -> bool { self.frame_clocks.count() % self.machine.specs().clocks_frame < self.machine.specs().interrupt_length } /// checks non-maskable interrupt pin state fn nmi_active(&self) -> bool { false } /// CPU calls it when RETI instruction was processed fn reti(&mut self) {} /// CPU calls when was being halted fn halt(&mut self, _: bool) {} /// checks instant events fn instant_event(&self) -> bool { self.instant_event.pick() } }
{ self.events.clear(); }
identifier_body
controller.rs
//! Contains ZX Spectrum System contrller (like ula or so) of emulator use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; // use almost everything :D use utils::{split_word, Clocks}; use utils::screen::*; use utils::events::*; use utils::InstantFlag; use z80::Z80Bus; use zx::{ZXMemory, RomType, RamType}; use zx::memory::{Page, PAGE_SIZE}; use zx::machine::ZXMachine; use zx::tape::*; use zx::ZXKey; use zx::screen::canvas::ZXCanvas; use zx::screen::border::ZXBorder; use zx::screen::colors::{ZXColor, ZXPalette}; use zx::roms::*; use zx::constants::*; use zx::sound::mixer::ZXMixer; use settings::RustzxSettings; use zx::joy::kempston::*; /// ZX System controller pub struct ZXController { // parts of ZX Spectum. pub machine: ZXMachine, pub memory: ZXMemory, pub canvas: ZXCanvas, pub tape: Box<ZXTape>, pub border: ZXBorder, pub kempston: Option<KempstonJoy>, //pub beeper: ZXBeeper, pub mixer: ZXMixer, pub keyboard: [u8; 8], // current border color border_color: u8, // clocls count from frame start frame_clocks: Clocks, // frames count, which passed during emulation invokation passed_frames: usize, // main event queue events: EventQueue, // flag, which signals emulator to break emulation and process last event immediately instant_event: InstantFlag, // audio in mic: bool, // audio out ear: bool, paging_enabled: bool, screen_bank: u8, } impl ZXController { /// Returns new ZXController from settings pub fn new(settings: &RustzxSettings) -> ZXController { let (memory, paging, screen_bank); match settings.machine { ZXMachine::Sinclair48K => { memory = ZXMemory::new(RomType::K16, RamType::K48); paging = false; screen_bank = 0; } ZXMachine::Sinclair128K => { memory = ZXMemory::new(RomType::K32, RamType::K128); paging = true; screen_bank = 5; } }; let kempston = if settings.kempston { Some(KempstonJoy::new()) } else { None }; let mut out = ZXController { machine: settings.machine, memory: memory, canvas: ZXCanvas::new(settings.machine), border: ZXBorder::new(settings.machine, ZXPalette::default()), kempston: kempston, mixer: ZXMixer::new(settings.beeper_enabled, settings.ay_enabled), keyboard: [0xFF; 8], border_color: 0x00, frame_clocks: Clocks(0), passed_frames: 0, tape: Box::new(Tap::new()), events: EventQueue::new(), instant_event: InstantFlag::new(false), mic: false, ear: false, paging_enabled: paging, screen_bank: screen_bank, }; out.mixer.ay.mode(settings.ay_mode); out.mixer.volume(settings.volume as f64 / 200.0); out } /// returns current frame emulation pos in percents fn frame_pos(&self) -> f64 { let val = self.frame_clocks.count() as f64 / self.machine.specs().clocks_frame as f64; if val > 1.0 { 1.0 } else { val } } /// loads rom from file /// for 128-K machines path must contain ".0" in the tail /// and second rom bank will be loaded automatically pub fn load_rom(&mut self, path: impl AsRef<Path>) { match self.machine { // Single ROM file ZXMachine::Sinclair48K => { let mut rom = Vec::new(); File::open(path).ok().expect("[ERROR] ROM not found").read_to_end(&mut rom) .unwrap(); self.memory.load_rom(0, &rom); } // Two ROM's ZXMachine::Sinclair128K => { let mut rom0 = Vec::new(); let mut rom1 = Vec::new(); if !path.as_ref().extension().map_or(false, |e| e == "0") { println!("[Warning] ROM0 filename should end with .0"); } File::open(path.as_ref()).ok().expect("[ERROR] ROM0 not found").read_to_end(&mut rom0) .unwrap(); let mut second_path: PathBuf = path.as_ref().to_path_buf(); second_path.set_extension("1"); File::open(second_path).ok().expect("[ERROR] ROM1 not found").read_to_end(&mut rom1) .unwrap(); self.memory.load_rom(0, &rom0) .load_rom(1, &rom1); println!("ROM's Loaded"); } } } /// loads builted-in ROM pub fn load_default_rom(&mut self) { match self.machine { ZXMachine::Sinclair48K => { self.memory.load_rom(0, ROM_48K); } ZXMachine::Sinclair128K => { self.memory.load_rom(0, ROM_128K_0) .load_rom(1, ROM_128K_1); } } } /// Changes key state in controller pub fn send_key(&mut self, key: ZXKey, pressed: bool) { // TODO: Move row detection to ZXKey type let rownum = match key.half_port { 0xFE => Some(0), 0xFD => Some(1), 0xFB => Some(2), 0xF7 => Some(3), 0xEF => Some(4), 0xDF => Some(5), 0xBF => Some(6), 0x7F => Some(7), _ => None, }; if let Some(rownum) = rownum { self.keyboard[rownum] = self.keyboard[rownum] & (!key.mask); if !pressed { self.keyboard[rownum] |= key.mask; } } } /// Dumps memory space pub fn dump(&self) -> Vec<u8> { self.memory.dump() } /// Returns current bus floating value fn floating_bus_value(&self) -> u8 { let specs = self.machine.specs(); let clocks = self.frame_clocks; if clocks.count() < specs.clocks_first_pixel + 2 { return 0xFF; } let clocks = clocks.count() - (specs.clocks_first_pixel + 2); let row = clocks / specs.clocks_line; let clocks = clocks % specs.clocks_line; let col = (clocks / 8) * 2 + (clocks % 8) / 2; if row < CANVAS_HEIGHT && clocks < specs.clocks_screen_row - CLOCKS_PER_COL && ((clocks & 0x04) == 0)
return 0xFF; } /// make contention fn do_contention(&mut self) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention); } ///make contention + wait some clocks fn do_contention_and_wait(&mut self, wait_time: Clocks) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention + wait_time); } // check addr contention fn addr_is_contended(&self, addr: u16) -> bool { return if let Page::Ram(bank) = self.memory.get_page(addr) { self.machine.bank_is_contended(bank as usize) } else { false } } /// Returns early IO contention clocks fn io_contention_first(&mut self, port: u16) { if self.addr_is_contended(port) { self.do_contention(); }; self.wait_internal(Clocks(1)); } /// Returns late IO contention clocks fn io_contention_last(&mut self, port: u16) { if self.machine.port_is_contended(port) { self.do_contention_and_wait(Clocks(2)); } else { if self.addr_is_contended(port) { self.do_contention_and_wait(Clocks(1)); self.do_contention_and_wait(Clocks(1)); self.do_contention(); } else { self.wait_internal(Clocks(2)); } } } /// Starts a new frame fn new_frame(&mut self) { self.frame_clocks -= self.machine.specs().clocks_frame; self.canvas.new_frame(); self.border.new_frame(); self.mixer.new_frame(); } /// force clears all events pub fn clear_events(&mut self) { self.events.clear(); } /// check events count pub fn no_events(&self) -> bool { self.events.is_empty() } /// Returns last event pub fn pop_event(&mut self) -> Option<Event> { self.events.receive_event() } /// Returns true if all frame clocks has been passed pub fn frames_count(&self) -> usize { self.passed_frames } pub fn reset_frame_counter(&mut self) { self.passed_frames = 0; } /// Returns current clocks from frame start pub fn clocks(&self) -> Clocks { self.frame_clocks } fn write_7ffd(&mut self, val: u8) { if !self.paging_enabled { return; } // remap top 16K of the ram self.memory.remap(3, Page::Ram(val & 0x07)); // third block is not pageable // second block is screen buffer, not pageable. but we need to change active buffer let new_screen_bank = if val & 0x08 == 0 { 5 } else { 7 }; self.canvas.switch_bank(new_screen_bank as usize); self.screen_bank = new_screen_bank; // remap ROM self.memory.remap(0, Page::Rom((val >> 4) & 0x01)); // check paging allow bit if val & 0x20 != 0 { self.paging_enabled = false; } } } impl Z80Bus for ZXController { /// we need to check different breakpoints like tape /// loading detection breakpoint fn pc_callback(&mut self, addr: u16) { // check mapped memory page at 0x0000 .. 0x3FFF let check_fast_load = match self.machine { ZXMachine::Sinclair48K if self.memory.get_bank_type(0) == Page::Rom(0) => true, ZXMachine::Sinclair128K if self.memory.get_bank_type(0) == Page::Rom(1) => true, _ => false, }; if check_fast_load { // Tape LOAD/VERIFY if addr == ADDR_LD_BREAK { // Add event (Fast tape loading request) it must be executed // by emulator immediately self.events.send_event(Event::new(EventKind::FastTapeLoad, self.frame_clocks)); self.instant_event.set(); } } } /// read data without taking onto account contention fn read_internal(&mut self, addr: u16) -> u8 { self.memory.read(addr) } /// write data without taking onto account contention fn write_internal(&mut self, addr: u16, data: u8) { self.memory.write(addr, data); // if ram then compare bank to screen bank if let Page::Ram(bank) = self.memory.get_page(addr) { self.canvas.update(addr % PAGE_SIZE as u16, bank as usize, data); } } /// Cahnges internal state on clocks count change (emualtion processing) fn wait_internal(&mut self, clk: Clocks) { self.frame_clocks += clk; (*self.tape).process_clocks(clk); let mic = (*self.tape).current_bit(); self.mic = mic; let pos = self.frame_pos(); self.mixer.beeper.change_bit(self.mic | self.ear); self.mixer.process(pos); self.canvas.process_clocks(self.frame_clocks); if self.frame_clocks.count() >= self.machine.specs().clocks_frame { self.new_frame(); self.passed_frames += 1; } } // wait with memory request pin active fn wait_mreq(&mut self, addr: u16, clk: Clocks) { match self.machine { ZXMachine::Sinclair48K | ZXMachine::Sinclair128K=> { // contention in low 16k RAM if self.addr_is_contended(addr) { self.do_contention(); } } } self.wait_internal(clk); } /// wait without memory request pin active fn wait_no_mreq(&mut self, addr: u16, clk: Clocks) { // only for 48 K! self.wait_mreq(addr, clk); } /// read io from hardware fn read_io(&mut self, port: u16) -> u8 { // all contentions check self.io_contention_first(port); self.io_contention_last(port); // find out what we need to do let (h, _) = split_word(port); let output = if port & 0x0001 == 0 { // ULA port let mut tmp: u8 = 0xFF; for n in 0..8 { // if bit of row reset if ((h >> n) & 0x01) == 0 { tmp &= self.keyboard[n]; } } // invert bit 6 if mic_hw active; if self.mic { tmp ^= 0x40; } // 5 and 7 unused tmp } else if port & 0xC002 == 0xC000 { // AY regs self.mixer.ay.read() } else if self.kempston.is_some() && (port & 0x0020 == 0) { if let Some(ref joy) = self.kempston { joy.read() } else { unreachable!() } } else { self.floating_bus_value() }; // add one clock after operation self.wait_internal(Clocks(1)); output } /// write value to hardware port fn write_io(&mut self, port: u16, data: u8) { // first contention self.io_contention_first(port); // find active port if port & 0xC002 == 0xC000 { self.mixer.ay.select_reg(data); } else if port & 0xC002 == 0x8000 { self.mixer.ay.write(data); } else if port & 0x0001 == 0 { self.border_color = data & 0x07; self.border.set_border(self.frame_clocks, ZXColor::from_bits(data & 0x07)); self.mic = data & 0x08 != 0; self.ear = data & 0x10 != 0; self.mixer.beeper.change_bit(self.mic | self.ear); } else if (port & 0x8002 == 0) && (self.machine == ZXMachine::Sinclair128K) { self.write_7ffd(data); } // last contention after byte write self.io_contention_last(port); // add one clock after operation self.wait_internal(Clocks(1)); } /// value, requested during `INT0` interrupt fn read_interrupt(&mut self) -> u8 { 0xFF } /// checks system maskable interrupt pin state fn int_active(&self) -> bool { self.frame_clocks.count() % self.machine.specs().clocks_frame < self.machine.specs().interrupt_length } /// checks non-maskable interrupt pin state fn nmi_active(&self) -> bool { false } /// CPU calls it when RETI instruction was processed fn reti(&mut self) {} /// CPU calls when was being halted fn halt(&mut self, _: bool) {} /// checks instant events fn instant_event(&self) -> bool { self.instant_event.pick() } }
{ if clocks % 2 == 0 { return self.memory.read(bitmap_line_addr(row) + col as u16); } else { let byte = (row / 8) * 32 + col; return self.memory.read(0x5800 + byte as u16); }; }
conditional_block
controller.rs
//! Contains ZX Spectrum System contrller (like ula or so) of emulator use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; // use almost everything :D use utils::{split_word, Clocks}; use utils::screen::*; use utils::events::*; use utils::InstantFlag; use z80::Z80Bus; use zx::{ZXMemory, RomType, RamType}; use zx::memory::{Page, PAGE_SIZE}; use zx::machine::ZXMachine; use zx::tape::*; use zx::ZXKey; use zx::screen::canvas::ZXCanvas; use zx::screen::border::ZXBorder; use zx::screen::colors::{ZXColor, ZXPalette}; use zx::roms::*; use zx::constants::*; use zx::sound::mixer::ZXMixer; use settings::RustzxSettings; use zx::joy::kempston::*; /// ZX System controller pub struct ZXController { // parts of ZX Spectum. pub machine: ZXMachine, pub memory: ZXMemory, pub canvas: ZXCanvas, pub tape: Box<ZXTape>, pub border: ZXBorder, pub kempston: Option<KempstonJoy>, //pub beeper: ZXBeeper, pub mixer: ZXMixer, pub keyboard: [u8; 8], // current border color border_color: u8, // clocls count from frame start frame_clocks: Clocks, // frames count, which passed during emulation invokation passed_frames: usize, // main event queue events: EventQueue, // flag, which signals emulator to break emulation and process last event immediately instant_event: InstantFlag, // audio in mic: bool, // audio out ear: bool, paging_enabled: bool, screen_bank: u8, } impl ZXController { /// Returns new ZXController from settings pub fn new(settings: &RustzxSettings) -> ZXController { let (memory, paging, screen_bank); match settings.machine { ZXMachine::Sinclair48K => { memory = ZXMemory::new(RomType::K16, RamType::K48); paging = false; screen_bank = 0; } ZXMachine::Sinclair128K => { memory = ZXMemory::new(RomType::K32, RamType::K128); paging = true; screen_bank = 5; } }; let kempston = if settings.kempston { Some(KempstonJoy::new()) } else { None }; let mut out = ZXController { machine: settings.machine, memory: memory, canvas: ZXCanvas::new(settings.machine), border: ZXBorder::new(settings.machine, ZXPalette::default()), kempston: kempston, mixer: ZXMixer::new(settings.beeper_enabled, settings.ay_enabled), keyboard: [0xFF; 8], border_color: 0x00, frame_clocks: Clocks(0), passed_frames: 0, tape: Box::new(Tap::new()), events: EventQueue::new(), instant_event: InstantFlag::new(false), mic: false, ear: false, paging_enabled: paging, screen_bank: screen_bank, }; out.mixer.ay.mode(settings.ay_mode); out.mixer.volume(settings.volume as f64 / 200.0); out } /// returns current frame emulation pos in percents fn frame_pos(&self) -> f64 { let val = self.frame_clocks.count() as f64 / self.machine.specs().clocks_frame as f64; if val > 1.0 { 1.0 } else { val } } /// loads rom from file /// for 128-K machines path must contain ".0" in the tail /// and second rom bank will be loaded automatically pub fn load_rom(&mut self, path: impl AsRef<Path>) { match self.machine { // Single ROM file ZXMachine::Sinclair48K => { let mut rom = Vec::new(); File::open(path).ok().expect("[ERROR] ROM not found").read_to_end(&mut rom) .unwrap(); self.memory.load_rom(0, &rom); } // Two ROM's ZXMachine::Sinclair128K => { let mut rom0 = Vec::new(); let mut rom1 = Vec::new(); if !path.as_ref().extension().map_or(false, |e| e == "0") { println!("[Warning] ROM0 filename should end with .0"); } File::open(path.as_ref()).ok().expect("[ERROR] ROM0 not found").read_to_end(&mut rom0) .unwrap(); let mut second_path: PathBuf = path.as_ref().to_path_buf(); second_path.set_extension("1"); File::open(second_path).ok().expect("[ERROR] ROM1 not found").read_to_end(&mut rom1) .unwrap(); self.memory.load_rom(0, &rom0) .load_rom(1, &rom1); println!("ROM's Loaded"); } } } /// loads builted-in ROM pub fn load_default_rom(&mut self) { match self.machine { ZXMachine::Sinclair48K => { self.memory.load_rom(0, ROM_48K); } ZXMachine::Sinclair128K => { self.memory.load_rom(0, ROM_128K_0) .load_rom(1, ROM_128K_1); } } } /// Changes key state in controller pub fn send_key(&mut self, key: ZXKey, pressed: bool) { // TODO: Move row detection to ZXKey type let rownum = match key.half_port { 0xFE => Some(0), 0xFD => Some(1), 0xFB => Some(2), 0xF7 => Some(3), 0xEF => Some(4), 0xDF => Some(5), 0xBF => Some(6), 0x7F => Some(7), _ => None, }; if let Some(rownum) = rownum { self.keyboard[rownum] = self.keyboard[rownum] & (!key.mask); if !pressed { self.keyboard[rownum] |= key.mask; } } } /// Dumps memory space pub fn dump(&self) -> Vec<u8> { self.memory.dump() } /// Returns current bus floating value fn floating_bus_value(&self) -> u8 { let specs = self.machine.specs(); let clocks = self.frame_clocks; if clocks.count() < specs.clocks_first_pixel + 2 { return 0xFF; } let clocks = clocks.count() - (specs.clocks_first_pixel + 2); let row = clocks / specs.clocks_line; let clocks = clocks % specs.clocks_line; let col = (clocks / 8) * 2 + (clocks % 8) / 2; if row < CANVAS_HEIGHT && clocks < specs.clocks_screen_row - CLOCKS_PER_COL && ((clocks & 0x04) == 0) { if clocks % 2 == 0 { return self.memory.read(bitmap_line_addr(row) + col as u16); } else { let byte = (row / 8) * 32 + col; return self.memory.read(0x5800 + byte as u16); }; } return 0xFF; } /// make contention fn do_contention(&mut self) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention); } ///make contention + wait some clocks fn do_contention_and_wait(&mut self, wait_time: Clocks) { let contention = self.machine.contention_clocks(self.frame_clocks); self.wait_internal(contention + wait_time); } // check addr contention fn addr_is_contended(&self, addr: u16) -> bool { return if let Page::Ram(bank) = self.memory.get_page(addr) { self.machine.bank_is_contended(bank as usize) } else { false } } /// Returns early IO contention clocks fn
(&mut self, port: u16) { if self.addr_is_contended(port) { self.do_contention(); }; self.wait_internal(Clocks(1)); } /// Returns late IO contention clocks fn io_contention_last(&mut self, port: u16) { if self.machine.port_is_contended(port) { self.do_contention_and_wait(Clocks(2)); } else { if self.addr_is_contended(port) { self.do_contention_and_wait(Clocks(1)); self.do_contention_and_wait(Clocks(1)); self.do_contention(); } else { self.wait_internal(Clocks(2)); } } } /// Starts a new frame fn new_frame(&mut self) { self.frame_clocks -= self.machine.specs().clocks_frame; self.canvas.new_frame(); self.border.new_frame(); self.mixer.new_frame(); } /// force clears all events pub fn clear_events(&mut self) { self.events.clear(); } /// check events count pub fn no_events(&self) -> bool { self.events.is_empty() } /// Returns last event pub fn pop_event(&mut self) -> Option<Event> { self.events.receive_event() } /// Returns true if all frame clocks has been passed pub fn frames_count(&self) -> usize { self.passed_frames } pub fn reset_frame_counter(&mut self) { self.passed_frames = 0; } /// Returns current clocks from frame start pub fn clocks(&self) -> Clocks { self.frame_clocks } fn write_7ffd(&mut self, val: u8) { if !self.paging_enabled { return; } // remap top 16K of the ram self.memory.remap(3, Page::Ram(val & 0x07)); // third block is not pageable // second block is screen buffer, not pageable. but we need to change active buffer let new_screen_bank = if val & 0x08 == 0 { 5 } else { 7 }; self.canvas.switch_bank(new_screen_bank as usize); self.screen_bank = new_screen_bank; // remap ROM self.memory.remap(0, Page::Rom((val >> 4) & 0x01)); // check paging allow bit if val & 0x20 != 0 { self.paging_enabled = false; } } } impl Z80Bus for ZXController { /// we need to check different breakpoints like tape /// loading detection breakpoint fn pc_callback(&mut self, addr: u16) { // check mapped memory page at 0x0000 .. 0x3FFF let check_fast_load = match self.machine { ZXMachine::Sinclair48K if self.memory.get_bank_type(0) == Page::Rom(0) => true, ZXMachine::Sinclair128K if self.memory.get_bank_type(0) == Page::Rom(1) => true, _ => false, }; if check_fast_load { // Tape LOAD/VERIFY if addr == ADDR_LD_BREAK { // Add event (Fast tape loading request) it must be executed // by emulator immediately self.events.send_event(Event::new(EventKind::FastTapeLoad, self.frame_clocks)); self.instant_event.set(); } } } /// read data without taking onto account contention fn read_internal(&mut self, addr: u16) -> u8 { self.memory.read(addr) } /// write data without taking onto account contention fn write_internal(&mut self, addr: u16, data: u8) { self.memory.write(addr, data); // if ram then compare bank to screen bank if let Page::Ram(bank) = self.memory.get_page(addr) { self.canvas.update(addr % PAGE_SIZE as u16, bank as usize, data); } } /// Cahnges internal state on clocks count change (emualtion processing) fn wait_internal(&mut self, clk: Clocks) { self.frame_clocks += clk; (*self.tape).process_clocks(clk); let mic = (*self.tape).current_bit(); self.mic = mic; let pos = self.frame_pos(); self.mixer.beeper.change_bit(self.mic | self.ear); self.mixer.process(pos); self.canvas.process_clocks(self.frame_clocks); if self.frame_clocks.count() >= self.machine.specs().clocks_frame { self.new_frame(); self.passed_frames += 1; } } // wait with memory request pin active fn wait_mreq(&mut self, addr: u16, clk: Clocks) { match self.machine { ZXMachine::Sinclair48K | ZXMachine::Sinclair128K=> { // contention in low 16k RAM if self.addr_is_contended(addr) { self.do_contention(); } } } self.wait_internal(clk); } /// wait without memory request pin active fn wait_no_mreq(&mut self, addr: u16, clk: Clocks) { // only for 48 K! self.wait_mreq(addr, clk); } /// read io from hardware fn read_io(&mut self, port: u16) -> u8 { // all contentions check self.io_contention_first(port); self.io_contention_last(port); // find out what we need to do let (h, _) = split_word(port); let output = if port & 0x0001 == 0 { // ULA port let mut tmp: u8 = 0xFF; for n in 0..8 { // if bit of row reset if ((h >> n) & 0x01) == 0 { tmp &= self.keyboard[n]; } } // invert bit 6 if mic_hw active; if self.mic { tmp ^= 0x40; } // 5 and 7 unused tmp } else if port & 0xC002 == 0xC000 { // AY regs self.mixer.ay.read() } else if self.kempston.is_some() && (port & 0x0020 == 0) { if let Some(ref joy) = self.kempston { joy.read() } else { unreachable!() } } else { self.floating_bus_value() }; // add one clock after operation self.wait_internal(Clocks(1)); output } /// write value to hardware port fn write_io(&mut self, port: u16, data: u8) { // first contention self.io_contention_first(port); // find active port if port & 0xC002 == 0xC000 { self.mixer.ay.select_reg(data); } else if port & 0xC002 == 0x8000 { self.mixer.ay.write(data); } else if port & 0x0001 == 0 { self.border_color = data & 0x07; self.border.set_border(self.frame_clocks, ZXColor::from_bits(data & 0x07)); self.mic = data & 0x08 != 0; self.ear = data & 0x10 != 0; self.mixer.beeper.change_bit(self.mic | self.ear); } else if (port & 0x8002 == 0) && (self.machine == ZXMachine::Sinclair128K) { self.write_7ffd(data); } // last contention after byte write self.io_contention_last(port); // add one clock after operation self.wait_internal(Clocks(1)); } /// value, requested during `INT0` interrupt fn read_interrupt(&mut self) -> u8 { 0xFF } /// checks system maskable interrupt pin state fn int_active(&self) -> bool { self.frame_clocks.count() % self.machine.specs().clocks_frame < self.machine.specs().interrupt_length } /// checks non-maskable interrupt pin state fn nmi_active(&self) -> bool { false } /// CPU calls it when RETI instruction was processed fn reti(&mut self) {} /// CPU calls when was being halted fn halt(&mut self, _: bool) {} /// checks instant events fn instant_event(&self) -> bool { self.instant_event.pick() } }
io_contention_first
identifier_name
storage.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ smoke_test_environment::new_local_swarm, test_utils::{ assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins, }, workspace_builder, workspace_builder::workspace_root, }; use anyhow::{bail, Result}; use backup_cli::metadata::view::BackupStorageState; use diem_sdk::{ client::BlockingClient, transaction_builder::TransactionFactory, types::LocalAccount, }; use diem_temppath::TempPath; use diem_types::{transaction::Version, waypoint::Waypoint}; use forge::{NodeExt, Swarm, SwarmExt}; use rand::random; use std::{ fs, path::Path, process::Command, time::{Duration, Instant}, }; #[test] fn test_db_restore() { // pre-build tools workspace_builder::get_bin("db-backup"); workspace_builder::get_bin("db-restore"); workspace_builder::get_bin("db-backup-verify"); let mut swarm = new_local_swarm(4); let validator_peer_ids = swarm.validators().map(|v| v.peer_id()).collect::<Vec<_>>(); let client_1 = swarm .validator(validator_peer_ids[1]) .unwrap() .json_rpc_client(); let transaction_factory = swarm.chain_info().transaction_factory(); // set up: two accounts, a lot of money let mut account_0 = create_and_fund_account(&mut swarm, 1000000); let account_1 = create_and_fund_account(&mut swarm, 1000000); transfer_coins( &client_1, &transaction_factory, &mut account_0, &account_1, 1, ); let mut expected_balance_0 = 999999; let mut expected_balance_1 = 1000001; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); // make a backup from node 1 let node1_config = swarm.validator(validator_peer_ids[1]).unwrap().config(); let backup_path = db_backup( node1_config.storage.backup_service_address.port(), 1, 50, 20, 40, &[], ); // take down node 0 let node_to_restart = validator_peer_ids[0]; swarm.validator_mut(node_to_restart).unwrap().stop(); // nuke db let node0_config_path = swarm.validator(node_to_restart).unwrap().config_path(); let mut node0_config = swarm.validator(node_to_restart).unwrap().config().clone(); let genesis_waypoint = node0_config.base.waypoint.genesis_waypoint(); insert_waypoint(&mut node0_config, genesis_waypoint); node0_config.save(node0_config_path).unwrap(); let db_dir = node0_config.storage.dir(); fs::remove_dir_all(db_dir.join("diemdb")).unwrap(); fs::remove_dir_all(db_dir.join("consensusdb")).unwrap(); // restore db from backup db_restore(backup_path.path(), db_dir.as_path(), &[]); { transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); } // start node 0 on top of restored db swarm .validator_mut(node_to_restart) .unwrap() .start() .unwrap(); swarm .validator_mut(node_to_restart) .unwrap() .wait_until_healthy(Instant::now() + Duration::from_secs(10)) .unwrap(); // verify it's caught up swarm .wait_for_all_nodes_to_catchup(Instant::now() + Duration::from_secs(60)) .unwrap(); let client_0 = swarm.validator(node_to_restart).unwrap().json_rpc_client(); assert_balance(&client_0, &account_0, expected_balance_0); assert_balance(&client_0, &account_1, expected_balance_1); } fn db_backup_verify(backup_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup-verify"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap(); if !output.status.success() { panic!("db-backup-verify failed, output: {:?}", output); } println!("Backup verified in {} seconds.", now.elapsed().as_secs()); } fn wait_for_backups( target_epoch: u64, target_version: u64, now: Instant, bin_path: &Path, metadata_cache_path: &Path, backup_path: &Path, trusted_waypoints: &[Waypoint], ) -> Result<()> { for _ in 0..60 { // the verify should always succeed. db_backup_verify(backup_path, trusted_waypoints); let output = Command::new(bin_path) .current_dir(workspace_root()) .args(&[ "one-shot", "query", "backup-storage-state", "--metadata-cache-dir", metadata_cache_path.to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .output()? .stdout; let state: BackupStorageState = std::str::from_utf8(&output)?.parse()?; if state.latest_epoch_ending_epoch.is_some() && state.latest_transaction_version.is_some() && state.latest_state_snapshot_version.is_some() && state.latest_epoch_ending_epoch.unwrap() >= target_epoch && state.latest_transaction_version.unwrap() >= target_version { println!("Backup created in {} seconds.", now.elapsed().as_secs()); return Ok(()); } println!("Backup storage state: {}", state); std::thread::sleep(Duration::from_secs(1)); } bail!("Failed to create backup."); } pub(crate) fn db_backup( backup_service_port: u16, target_epoch: u64, target_version: Version, transaction_batch_size: usize, state_snapshot_interval: usize, trusted_waypoints: &[Waypoint], ) -> TempPath { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup"); let metadata_cache_path1 = TempPath::new(); let metadata_cache_path2 = TempPath::new(); let backup_path = TempPath::new(); metadata_cache_path1.create_as_dir().unwrap(); metadata_cache_path2.create_as_dir().unwrap(); backup_path.create_as_dir().unwrap(); // spawn the backup coordinator let mut backup_coordinator = Command::new(bin_path.as_path()) .current_dir(workspace_root()) .args(&[ "coordinator", "run", "--backup-service-address", &format!("http://localhost:{}", backup_service_port), "--transaction-batch-size", &transaction_batch_size.to_string(), "--state-snapshot-interval", &state_snapshot_interval.to_string(), "--metadata-cache-dir", metadata_cache_path1.path().to_str().unwrap(), "local-fs", "--dir", backup_path.path().to_str().unwrap(), ]) .spawn() .unwrap(); // watch the backup storage, wait for it to reach target epoch and version let wait_res = wait_for_backups( target_epoch, target_version, now, bin_path.as_path(), metadata_cache_path2.path(), backup_path.path(), trusted_waypoints, ); backup_coordinator.kill().unwrap(); wait_res.unwrap(); backup_path } pub(crate) fn db_restore(backup_path: &Path, db_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-restore"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--target-db-dir", db_path.to_str().unwrap(), "auto", "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap(); if !output.status.success() { panic!("db-restore failed, output: {:?}", output); } println!("Backup restored in {} seconds.", now.elapsed().as_secs()); } fn transfer_and_reconfig( client: &BlockingClient, transaction_factory: &TransactionFactory, root_account: &mut LocalAccount, account0: &mut LocalAccount, account1: &LocalAccount, transfers: usize, ) -> Result<()> { for _ in 0..transfers { if random::<u16>() % 10 == 0
transfer_coins(client, transaction_factory, account0, account1, 1); } Ok(()) }
{ let current_version = client.get_metadata()?.into_inner().diem_version.unwrap(); let txn = root_account.sign_with_transaction_builder( transaction_factory.update_diem_version(0, current_version + 1), ); client.submit(&txn)?; client.wait_for_signed_transaction(&txn, None, None)?; println!("Changing diem version to {}", current_version + 1,); }
conditional_block
storage.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ smoke_test_environment::new_local_swarm, test_utils::{ assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins, }, workspace_builder, workspace_builder::workspace_root, }; use anyhow::{bail, Result}; use backup_cli::metadata::view::BackupStorageState; use diem_sdk::{ client::BlockingClient, transaction_builder::TransactionFactory, types::LocalAccount, }; use diem_temppath::TempPath; use diem_types::{transaction::Version, waypoint::Waypoint}; use forge::{NodeExt, Swarm, SwarmExt}; use rand::random; use std::{ fs, path::Path, process::Command, time::{Duration, Instant}, }; #[test] fn test_db_restore() { // pre-build tools workspace_builder::get_bin("db-backup"); workspace_builder::get_bin("db-restore"); workspace_builder::get_bin("db-backup-verify"); let mut swarm = new_local_swarm(4); let validator_peer_ids = swarm.validators().map(|v| v.peer_id()).collect::<Vec<_>>(); let client_1 = swarm .validator(validator_peer_ids[1]) .unwrap() .json_rpc_client(); let transaction_factory = swarm.chain_info().transaction_factory(); // set up: two accounts, a lot of money let mut account_0 = create_and_fund_account(&mut swarm, 1000000); let account_1 = create_and_fund_account(&mut swarm, 1000000); transfer_coins( &client_1, &transaction_factory, &mut account_0, &account_1, 1, ); let mut expected_balance_0 = 999999; let mut expected_balance_1 = 1000001; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); // make a backup from node 1 let node1_config = swarm.validator(validator_peer_ids[1]).unwrap().config(); let backup_path = db_backup( node1_config.storage.backup_service_address.port(), 1, 50, 20, 40, &[], ); // take down node 0 let node_to_restart = validator_peer_ids[0]; swarm.validator_mut(node_to_restart).unwrap().stop(); // nuke db let node0_config_path = swarm.validator(node_to_restart).unwrap().config_path(); let mut node0_config = swarm.validator(node_to_restart).unwrap().config().clone(); let genesis_waypoint = node0_config.base.waypoint.genesis_waypoint(); insert_waypoint(&mut node0_config, genesis_waypoint); node0_config.save(node0_config_path).unwrap(); let db_dir = node0_config.storage.dir(); fs::remove_dir_all(db_dir.join("diemdb")).unwrap(); fs::remove_dir_all(db_dir.join("consensusdb")).unwrap(); // restore db from backup db_restore(backup_path.path(), db_dir.as_path(), &[]); { transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); } // start node 0 on top of restored db swarm .validator_mut(node_to_restart) .unwrap() .start() .unwrap(); swarm .validator_mut(node_to_restart) .unwrap() .wait_until_healthy(Instant::now() + Duration::from_secs(10)) .unwrap(); // verify it's caught up swarm .wait_for_all_nodes_to_catchup(Instant::now() + Duration::from_secs(60)) .unwrap(); let client_0 = swarm.validator(node_to_restart).unwrap().json_rpc_client(); assert_balance(&client_0, &account_0, expected_balance_0); assert_balance(&client_0, &account_1, expected_balance_1); } fn db_backup_verify(backup_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup-verify"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap(); if !output.status.success() { panic!("db-backup-verify failed, output: {:?}", output); } println!("Backup verified in {} seconds.", now.elapsed().as_secs()); } fn wait_for_backups( target_epoch: u64, target_version: u64, now: Instant, bin_path: &Path, metadata_cache_path: &Path, backup_path: &Path, trusted_waypoints: &[Waypoint], ) -> Result<()> { for _ in 0..60 { // the verify should always succeed. db_backup_verify(backup_path, trusted_waypoints); let output = Command::new(bin_path) .current_dir(workspace_root()) .args(&[ "one-shot", "query", "backup-storage-state", "--metadata-cache-dir", metadata_cache_path.to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .output()? .stdout; let state: BackupStorageState = std::str::from_utf8(&output)?.parse()?; if state.latest_epoch_ending_epoch.is_some() && state.latest_transaction_version.is_some() && state.latest_state_snapshot_version.is_some() && state.latest_epoch_ending_epoch.unwrap() >= target_epoch && state.latest_transaction_version.unwrap() >= target_version { println!("Backup created in {} seconds.", now.elapsed().as_secs()); return Ok(()); } println!("Backup storage state: {}", state); std::thread::sleep(Duration::from_secs(1)); } bail!("Failed to create backup."); } pub(crate) fn db_backup( backup_service_port: u16, target_epoch: u64, target_version: Version, transaction_batch_size: usize, state_snapshot_interval: usize, trusted_waypoints: &[Waypoint], ) -> TempPath
pub(crate) fn db_restore(backup_path: &Path, db_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-restore"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--target-db-dir", db_path.to_str().unwrap(), "auto", "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap(); if !output.status.success() { panic!("db-restore failed, output: {:?}", output); } println!("Backup restored in {} seconds.", now.elapsed().as_secs()); } fn transfer_and_reconfig( client: &BlockingClient, transaction_factory: &TransactionFactory, root_account: &mut LocalAccount, account0: &mut LocalAccount, account1: &LocalAccount, transfers: usize, ) -> Result<()> { for _ in 0..transfers { if random::<u16>() % 10 == 0 { let current_version = client.get_metadata()?.into_inner().diem_version.unwrap(); let txn = root_account.sign_with_transaction_builder( transaction_factory.update_diem_version(0, current_version + 1), ); client.submit(&txn)?; client.wait_for_signed_transaction(&txn, None, None)?; println!("Changing diem version to {}", current_version + 1,); } transfer_coins(client, transaction_factory, account0, account1, 1); } Ok(()) }
{ let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup"); let metadata_cache_path1 = TempPath::new(); let metadata_cache_path2 = TempPath::new(); let backup_path = TempPath::new(); metadata_cache_path1.create_as_dir().unwrap(); metadata_cache_path2.create_as_dir().unwrap(); backup_path.create_as_dir().unwrap(); // spawn the backup coordinator let mut backup_coordinator = Command::new(bin_path.as_path()) .current_dir(workspace_root()) .args(&[ "coordinator", "run", "--backup-service-address", &format!("http://localhost:{}", backup_service_port), "--transaction-batch-size", &transaction_batch_size.to_string(), "--state-snapshot-interval", &state_snapshot_interval.to_string(), "--metadata-cache-dir", metadata_cache_path1.path().to_str().unwrap(), "local-fs", "--dir", backup_path.path().to_str().unwrap(), ]) .spawn() .unwrap(); // watch the backup storage, wait for it to reach target epoch and version let wait_res = wait_for_backups( target_epoch, target_version, now, bin_path.as_path(), metadata_cache_path2.path(), backup_path.path(), trusted_waypoints, ); backup_coordinator.kill().unwrap(); wait_res.unwrap(); backup_path }
identifier_body
storage.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ smoke_test_environment::new_local_swarm, test_utils::{ assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins, }, workspace_builder, workspace_builder::workspace_root, }; use anyhow::{bail, Result}; use backup_cli::metadata::view::BackupStorageState; use diem_sdk::{ client::BlockingClient, transaction_builder::TransactionFactory, types::LocalAccount, }; use diem_temppath::TempPath; use diem_types::{transaction::Version, waypoint::Waypoint}; use forge::{NodeExt, Swarm, SwarmExt}; use rand::random; use std::{ fs, path::Path, process::Command, time::{Duration, Instant}, }; #[test] fn test_db_restore() { // pre-build tools workspace_builder::get_bin("db-backup"); workspace_builder::get_bin("db-restore"); workspace_builder::get_bin("db-backup-verify"); let mut swarm = new_local_swarm(4); let validator_peer_ids = swarm.validators().map(|v| v.peer_id()).collect::<Vec<_>>(); let client_1 = swarm .validator(validator_peer_ids[1]) .unwrap() .json_rpc_client(); let transaction_factory = swarm.chain_info().transaction_factory(); // set up: two accounts, a lot of money let mut account_0 = create_and_fund_account(&mut swarm, 1000000); let account_1 = create_and_fund_account(&mut swarm, 1000000); transfer_coins( &client_1, &transaction_factory, &mut account_0, &account_1, 1, ); let mut expected_balance_0 = 999999; let mut expected_balance_1 = 1000001; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); // make a backup from node 1 let node1_config = swarm.validator(validator_peer_ids[1]).unwrap().config(); let backup_path = db_backup( node1_config.storage.backup_service_address.port(), 1, 50, 20, 40, &[], ); // take down node 0 let node_to_restart = validator_peer_ids[0]; swarm.validator_mut(node_to_restart).unwrap().stop(); // nuke db let node0_config_path = swarm.validator(node_to_restart).unwrap().config_path(); let mut node0_config = swarm.validator(node_to_restart).unwrap().config().clone(); let genesis_waypoint = node0_config.base.waypoint.genesis_waypoint(); insert_waypoint(&mut node0_config, genesis_waypoint); node0_config.save(node0_config_path).unwrap(); let db_dir = node0_config.storage.dir(); fs::remove_dir_all(db_dir.join("diemdb")).unwrap(); fs::remove_dir_all(db_dir.join("consensusdb")).unwrap(); // restore db from backup db_restore(backup_path.path(), db_dir.as_path(), &[]); { transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); } // start node 0 on top of restored db swarm .validator_mut(node_to_restart) .unwrap() .start() .unwrap(); swarm .validator_mut(node_to_restart) .unwrap() .wait_until_healthy(Instant::now() + Duration::from_secs(10)) .unwrap(); // verify it's caught up swarm .wait_for_all_nodes_to_catchup(Instant::now() + Duration::from_secs(60)) .unwrap(); let client_0 = swarm.validator(node_to_restart).unwrap().json_rpc_client(); assert_balance(&client_0, &account_0, expected_balance_0); assert_balance(&client_0, &account_1, expected_balance_1); } fn db_backup_verify(backup_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup-verify"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap(); if !output.status.success() { panic!("db-backup-verify failed, output: {:?}", output); } println!("Backup verified in {} seconds.", now.elapsed().as_secs()); } fn wait_for_backups( target_epoch: u64, target_version: u64, now: Instant, bin_path: &Path, metadata_cache_path: &Path, backup_path: &Path, trusted_waypoints: &[Waypoint], ) -> Result<()> { for _ in 0..60 { // the verify should always succeed. db_backup_verify(backup_path, trusted_waypoints); let output = Command::new(bin_path) .current_dir(workspace_root()) .args(&[ "one-shot", "query", "backup-storage-state", "--metadata-cache-dir", metadata_cache_path.to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .output()? .stdout; let state: BackupStorageState = std::str::from_utf8(&output)?.parse()?; if state.latest_epoch_ending_epoch.is_some() && state.latest_transaction_version.is_some() && state.latest_state_snapshot_version.is_some() && state.latest_epoch_ending_epoch.unwrap() >= target_epoch && state.latest_transaction_version.unwrap() >= target_version { println!("Backup created in {} seconds.", now.elapsed().as_secs()); return Ok(()); } println!("Backup storage state: {}", state); std::thread::sleep(Duration::from_secs(1)); } bail!("Failed to create backup."); } pub(crate) fn db_backup( backup_service_port: u16, target_epoch: u64, target_version: Version, transaction_batch_size: usize, state_snapshot_interval: usize, trusted_waypoints: &[Waypoint], ) -> TempPath { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup"); let metadata_cache_path1 = TempPath::new(); let metadata_cache_path2 = TempPath::new(); let backup_path = TempPath::new(); metadata_cache_path1.create_as_dir().unwrap(); metadata_cache_path2.create_as_dir().unwrap(); backup_path.create_as_dir().unwrap(); // spawn the backup coordinator let mut backup_coordinator = Command::new(bin_path.as_path()) .current_dir(workspace_root()) .args(&[ "coordinator", "run", "--backup-service-address", &format!("http://localhost:{}", backup_service_port), "--transaction-batch-size", &transaction_batch_size.to_string(), "--state-snapshot-interval", &state_snapshot_interval.to_string(), "--metadata-cache-dir", metadata_cache_path1.path().to_str().unwrap(), "local-fs", "--dir", backup_path.path().to_str().unwrap(), ]) .spawn() .unwrap(); // watch the backup storage, wait for it to reach target epoch and version let wait_res = wait_for_backups( target_epoch, target_version, now, bin_path.as_path(), metadata_cache_path2.path(), backup_path.path(), trusted_waypoints, ); backup_coordinator.kill().unwrap(); wait_res.unwrap(); backup_path } pub(crate) fn db_restore(backup_path: &Path, db_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-restore"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--target-db-dir", db_path.to_str().unwrap(), "auto", "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap(); if !output.status.success() { panic!("db-restore failed, output: {:?}", output); } println!("Backup restored in {} seconds.", now.elapsed().as_secs()); } fn
( client: &BlockingClient, transaction_factory: &TransactionFactory, root_account: &mut LocalAccount, account0: &mut LocalAccount, account1: &LocalAccount, transfers: usize, ) -> Result<()> { for _ in 0..transfers { if random::<u16>() % 10 == 0 { let current_version = client.get_metadata()?.into_inner().diem_version.unwrap(); let txn = root_account.sign_with_transaction_builder( transaction_factory.update_diem_version(0, current_version + 1), ); client.submit(&txn)?; client.wait_for_signed_transaction(&txn, None, None)?; println!("Changing diem version to {}", current_version + 1,); } transfer_coins(client, transaction_factory, account0, account1, 1); } Ok(()) }
transfer_and_reconfig
identifier_name
storage.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ smoke_test_environment::new_local_swarm, test_utils::{ assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins, }, workspace_builder, workspace_builder::workspace_root, }; use anyhow::{bail, Result}; use backup_cli::metadata::view::BackupStorageState; use diem_sdk::{ client::BlockingClient, transaction_builder::TransactionFactory, types::LocalAccount, }; use diem_temppath::TempPath; use diem_types::{transaction::Version, waypoint::Waypoint}; use forge::{NodeExt, Swarm, SwarmExt}; use rand::random; use std::{ fs, path::Path, process::Command, time::{Duration, Instant}, }; #[test] fn test_db_restore() { // pre-build tools workspace_builder::get_bin("db-backup"); workspace_builder::get_bin("db-restore"); workspace_builder::get_bin("db-backup-verify"); let mut swarm = new_local_swarm(4); let validator_peer_ids = swarm.validators().map(|v| v.peer_id()).collect::<Vec<_>>(); let client_1 = swarm .validator(validator_peer_ids[1]) .unwrap() .json_rpc_client(); let transaction_factory = swarm.chain_info().transaction_factory(); // set up: two accounts, a lot of money let mut account_0 = create_and_fund_account(&mut swarm, 1000000); let account_1 = create_and_fund_account(&mut swarm, 1000000); transfer_coins( &client_1, &transaction_factory, &mut account_0, &account_1, 1, ); let mut expected_balance_0 = 999999; let mut expected_balance_1 = 1000001; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); // make a backup from node 1 let node1_config = swarm.validator(validator_peer_ids[1]).unwrap().config(); let backup_path = db_backup( node1_config.storage.backup_service_address.port(), 1, 50, 20, 40, &[], ); // take down node 0 let node_to_restart = validator_peer_ids[0]; swarm.validator_mut(node_to_restart).unwrap().stop(); // nuke db let node0_config_path = swarm.validator(node_to_restart).unwrap().config_path(); let mut node0_config = swarm.validator(node_to_restart).unwrap().config().clone(); let genesis_waypoint = node0_config.base.waypoint.genesis_waypoint(); insert_waypoint(&mut node0_config, genesis_waypoint); node0_config.save(node0_config_path).unwrap(); let db_dir = node0_config.storage.dir(); fs::remove_dir_all(db_dir.join("diemdb")).unwrap(); fs::remove_dir_all(db_dir.join("consensusdb")).unwrap(); // restore db from backup db_restore(backup_path.path(), db_dir.as_path(), &[]); { transfer_and_reconfig( &client_1, &transaction_factory, swarm.chain_info().root_account, &mut account_0, &account_1, 20, ) .unwrap(); expected_balance_0 -= 20; expected_balance_1 += 20; assert_balance(&client_1, &account_0, expected_balance_0); assert_balance(&client_1, &account_1, expected_balance_1); } // start node 0 on top of restored db swarm .validator_mut(node_to_restart) .unwrap() .start() .unwrap(); swarm .validator_mut(node_to_restart) .unwrap() .wait_until_healthy(Instant::now() + Duration::from_secs(10)) .unwrap(); // verify it's caught up swarm .wait_for_all_nodes_to_catchup(Instant::now() + Duration::from_secs(60)) .unwrap(); let client_0 = swarm.validator(node_to_restart).unwrap().json_rpc_client(); assert_balance(&client_0, &account_0, expected_balance_0); assert_balance(&client_0, &account_1, expected_balance_1); } fn db_backup_verify(backup_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup-verify"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap();
fn wait_for_backups( target_epoch: u64, target_version: u64, now: Instant, bin_path: &Path, metadata_cache_path: &Path, backup_path: &Path, trusted_waypoints: &[Waypoint], ) -> Result<()> { for _ in 0..60 { // the verify should always succeed. db_backup_verify(backup_path, trusted_waypoints); let output = Command::new(bin_path) .current_dir(workspace_root()) .args(&[ "one-shot", "query", "backup-storage-state", "--metadata-cache-dir", metadata_cache_path.to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .output()? .stdout; let state: BackupStorageState = std::str::from_utf8(&output)?.parse()?; if state.latest_epoch_ending_epoch.is_some() && state.latest_transaction_version.is_some() && state.latest_state_snapshot_version.is_some() && state.latest_epoch_ending_epoch.unwrap() >= target_epoch && state.latest_transaction_version.unwrap() >= target_version { println!("Backup created in {} seconds.", now.elapsed().as_secs()); return Ok(()); } println!("Backup storage state: {}", state); std::thread::sleep(Duration::from_secs(1)); } bail!("Failed to create backup."); } pub(crate) fn db_backup( backup_service_port: u16, target_epoch: u64, target_version: Version, transaction_batch_size: usize, state_snapshot_interval: usize, trusted_waypoints: &[Waypoint], ) -> TempPath { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-backup"); let metadata_cache_path1 = TempPath::new(); let metadata_cache_path2 = TempPath::new(); let backup_path = TempPath::new(); metadata_cache_path1.create_as_dir().unwrap(); metadata_cache_path2.create_as_dir().unwrap(); backup_path.create_as_dir().unwrap(); // spawn the backup coordinator let mut backup_coordinator = Command::new(bin_path.as_path()) .current_dir(workspace_root()) .args(&[ "coordinator", "run", "--backup-service-address", &format!("http://localhost:{}", backup_service_port), "--transaction-batch-size", &transaction_batch_size.to_string(), "--state-snapshot-interval", &state_snapshot_interval.to_string(), "--metadata-cache-dir", metadata_cache_path1.path().to_str().unwrap(), "local-fs", "--dir", backup_path.path().to_str().unwrap(), ]) .spawn() .unwrap(); // watch the backup storage, wait for it to reach target epoch and version let wait_res = wait_for_backups( target_epoch, target_version, now, bin_path.as_path(), metadata_cache_path2.path(), backup_path.path(), trusted_waypoints, ); backup_coordinator.kill().unwrap(); wait_res.unwrap(); backup_path } pub(crate) fn db_restore(backup_path: &Path, db_path: &Path, trusted_waypoints: &[Waypoint]) { let now = Instant::now(); let bin_path = workspace_builder::get_bin("db-restore"); let metadata_cache_path = TempPath::new(); metadata_cache_path.create_as_dir().unwrap(); let mut cmd = Command::new(bin_path.as_path()); trusted_waypoints.iter().for_each(|w| { cmd.arg("--trust-waypoint"); cmd.arg(&w.to_string()); }); let output = cmd .args(&[ "--target-db-dir", db_path.to_str().unwrap(), "auto", "--metadata-cache-dir", metadata_cache_path.path().to_str().unwrap(), "local-fs", "--dir", backup_path.to_str().unwrap(), ]) .current_dir(workspace_root()) .output() .unwrap(); if !output.status.success() { panic!("db-restore failed, output: {:?}", output); } println!("Backup restored in {} seconds.", now.elapsed().as_secs()); } fn transfer_and_reconfig( client: &BlockingClient, transaction_factory: &TransactionFactory, root_account: &mut LocalAccount, account0: &mut LocalAccount, account1: &LocalAccount, transfers: usize, ) -> Result<()> { for _ in 0..transfers { if random::<u16>() % 10 == 0 { let current_version = client.get_metadata()?.into_inner().diem_version.unwrap(); let txn = root_account.sign_with_transaction_builder( transaction_factory.update_diem_version(0, current_version + 1), ); client.submit(&txn)?; client.wait_for_signed_transaction(&txn, None, None)?; println!("Changing diem version to {}", current_version + 1,); } transfer_coins(client, transaction_factory, account0, account1, 1); } Ok(()) }
if !output.status.success() { panic!("db-backup-verify failed, output: {:?}", output); } println!("Backup verified in {} seconds.", now.elapsed().as_secs()); }
random_line_split
lib.rs
use crossbeam_channel as channel; use indexmap::IndexMap as Map; use isahc::{ config::{Configurable, RedirectPolicy}, HttpClient, }; use once_cell::sync::Lazy; use onig::Regex; use rayon::prelude::*; use select::{ document::Document, predicate::{Class, Name}, }; use std::{ borrow::Cow, env, fs::File, io::{BufReader, Write}, path::{Path, PathBuf}, thread, time::Duration, }; mod error; pub use error::Error; use error::ProcessingError; mod utils; const DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"; static USER_AGENT: Lazy<Cow<'static, str>> = Lazy::new(|| { env::var("USER_AGENT") .map(Cow::from) .unwrap_or_else(|_| Cow::from(DEFAULT_USER_AGENT)) }); #[derive(Debug, Clone)] pub struct LanguageData { subdomain: &'static str, code: &'static str, header: String, ids_map: Map<String, i64>, } #[derive(Debug, Clone)] pub struct Localizer { data: Vec<LanguageData>, output_dir: PathBuf, } impl Localizer { pub fn run<P: Into<PathBuf>>( ids_map: Map<String, i64>, module_name: &str, output_dir: P, force_all: bool, ) { let output_dir = output_dir.into(); let localizer = Self { data: Self::construct_language_data(vec![ // ("www", "enUS", String::from("L = mod:GetLocale()")), ("de", "deDE", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"deDE\")")), ("es", "esES", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"esES\") or BigWigs:NewBossLocale(\"{module_name}\", \"esMX\")")), ("fr", "frFR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"frFR\")")), ("it", "itIT", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"itIT\")")), ("pt", "ptBR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"ptBR\")")), ("ru", "ruRU", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"ruRU\")")), ("ko", "koKR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"koKR\")")), ("cn", "zhCN", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"zhCN\")")), ], &ids_map, if force_all { None } else { Some(&output_dir) }), output_dir, }; localizer.process_languages(); } fn construct_language_data( initial_data: Vec<(&'static str, &'static str, String)>, ids_map: &Map<String, i64>, output_dir: Option<&Path>, ) -> Vec<LanguageData> { initial_data .into_par_iter() .filter_map(|language| { let mut ids_map = ids_map.clone(); if let Some(output_dir) = output_dir { let file_path = output_dir.join(format!("{}.lua", language.1)); if let Ok(file) = File::open(file_path) { let mut file = BufReader::new(file); let _ = utils::discard_existing(&mut file, &language.2, &mut ids_map); } } if ids_map.is_empty() { None } else { Some(LanguageData { subdomain: language.0, code: language.1, header: language.2, ids_map, }) } }) .collect() } #[cfg(unix)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { use std::fs; use std::os::unix::fs::MetadataExt; let os_tmp = env::temp_dir(); match ( fs::metadata(output_dir).map(|v| v.dev()), fs::metadata(&os_tmp).map(|v| v.dev()), ) { (Ok(num1), Ok(num2)) if num1 == num2 => Cow::from(os_tmp), _ => Cow::from(output_dir), } } #[cfg(windows)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { use winapi_util::{file, Handle}; let os_tmp = env::temp_dir(); let serial_num = |path: &Path| { Handle::from_path_any(path) .and_then(|h| file::information(h)) .map(|v| v.volume_serial_number()) }; match (serial_num(output_dir), serial_num(&os_tmp)) { (Ok(num1), Ok(num2)) if num1 == num2 => Cow::from(os_tmp), _ => Cow::from(output_dir), } } #[cfg(not(any(unix, windows)))] #[inline(always)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { Cow::from(output_dir) } fn process_languages(self) { static TITLE_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r#"\s+<.+?>$"#).unwrap()); let total = self.data.iter().fold(0, |acc, el| acc + el.ids_map.len()); if total > 0 { let (tx, rx) = channel::bounded(total); let stderr_thread = thread::spawn(move || { let stderr = std::io::stderr(); let mut stderr = stderr.lock(); let mut processed = 0; let _ = write!(stderr, "\rProgress: 0 / {total}"); while let Ok(msg) = rx.recv() { match msg { Err(ProcessingError::IoError((path, e))) => { let _ = writeln!( stderr, "\rI/O error: {} ({})", e, path.to_string_lossy(), ); } Err(ProcessingError::DataError((language, mob_name, e))) => { let _ = writeln!( stderr, "\rFailed to collect data for \"{mob_name}\" ({language}), error: {e}" ); processed += 1; } _ => processed += 1, } let _ = write!(stderr, "\rProgress: {processed} / {total}"); } let _ = stderr.write(b"\n"); let _ = stderr.flush(); }); let output_dir = self.output_dir; let tmp_dir = Self::get_tmp_dir(&output_dir); self.data.into_par_iter().for_each({ |language| { let client = HttpClient::builder() .timeout(Duration::from_secs(30)) .redirect_policy(RedirectPolicy::Limit(5)) .default_header( "accept", "text/html,application/xhtml+xml,application/xml;q=0.9", ) .default_header("accept-encoding", "gzip, deflate") .default_header("accept-language", "en-US,en;q=0.9") .default_header("sec-fetch-dest", "document") .default_header("sec-fetch-mode", "navigate") .default_header("sec-fetch-site", "same-site") .default_header("sec-fetch-user", "?1") .default_header("upgrade-insecure-requests", "1") .default_header("user-agent", &**USER_AGENT) .build() .unwrap(); let code = language.code; let subdomain = language.subdomain; let map: Map<_, _> = language .ids_map .into_iter() .filter_map({ let client = &client; let tx = tx.clone(); move |(name, id)| { let result: Result<_, Error> = client .get(&format!("https://{subdomain}.wowhead.com/npc={id}")) .map_err(From::from) .and_then(|mut response| { Document::from_read(response.body_mut()).map_err(From::from) }) .and_then(|document| { document .find(Class("heading-size-1")) .next() .ok_or_else(|| { "Couldn't find an element .heading-size-1".into() }) .and_then(|node| { // Check if we were redirected to the search page. if let Some(parent) = node.parent().and_then(|n| n.parent()) { if parent.is(Name("form")) { return Err("Not a valid NPC ID".into()); } for child in parent.children() { if child.is(Class("database-detail-page-not-found-message")) { return Err("Not a valid NPC ID".into()); } } } Ok(node.text()) }) }); match result { Ok(translation) => { let _ = tx.send(Ok(())); let translation = utils::replace_owning(translation, &TITLE_REGEX, ""); let translation = if translation.contains('\"') { translation.replace('\"', "\\\"") } else { translation }; let (translation, is_valid) = match translation.as_bytes() { [b'[', rest @ .., b']'] => { (String::from_utf8(rest.to_vec()).unwrap(), false) } _ => (translation, true), }; Some((name, (translation, is_valid))) } Err(e) => { let _ = tx .send(Err(ProcessingError::DataError((code, name, e)))); None } } } }) .collect(); if let Err(e) = utils::write_to_dir( &output_dir, &tmp_dir, language.code, &language.header, map, ) { let _ = tx.send(Err(ProcessingError::IoError(e))); } } }); drop(tx); stderr_thread.join().unwrap(); if let Err(e) = File::open(&output_dir).and_then(|dir| dir.sync_all()) { eprintln!( "Failed to call fsync() on \"{}\": {}", output_dir.display(), e ); } } else { eprintln!("There's nothing to do.");
} } }
random_line_split
lib.rs
use crossbeam_channel as channel; use indexmap::IndexMap as Map; use isahc::{ config::{Configurable, RedirectPolicy}, HttpClient, }; use once_cell::sync::Lazy; use onig::Regex; use rayon::prelude::*; use select::{ document::Document, predicate::{Class, Name}, }; use std::{ borrow::Cow, env, fs::File, io::{BufReader, Write}, path::{Path, PathBuf}, thread, time::Duration, }; mod error; pub use error::Error; use error::ProcessingError; mod utils; const DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"; static USER_AGENT: Lazy<Cow<'static, str>> = Lazy::new(|| { env::var("USER_AGENT") .map(Cow::from) .unwrap_or_else(|_| Cow::from(DEFAULT_USER_AGENT)) }); #[derive(Debug, Clone)] pub struct LanguageData { subdomain: &'static str, code: &'static str, header: String, ids_map: Map<String, i64>, } #[derive(Debug, Clone)] pub struct Localizer { data: Vec<LanguageData>, output_dir: PathBuf, } impl Localizer { pub fn run<P: Into<PathBuf>>( ids_map: Map<String, i64>, module_name: &str, output_dir: P, force_all: bool, ) { let output_dir = output_dir.into(); let localizer = Self { data: Self::construct_language_data(vec![ // ("www", "enUS", String::from("L = mod:GetLocale()")), ("de", "deDE", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"deDE\")")), ("es", "esES", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"esES\") or BigWigs:NewBossLocale(\"{module_name}\", \"esMX\")")), ("fr", "frFR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"frFR\")")), ("it", "itIT", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"itIT\")")), ("pt", "ptBR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"ptBR\")")), ("ru", "ruRU", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"ruRU\")")), ("ko", "koKR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"koKR\")")), ("cn", "zhCN", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"zhCN\")")), ], &ids_map, if force_all { None } else { Some(&output_dir) }), output_dir, }; localizer.process_languages(); } fn construct_language_data( initial_data: Vec<(&'static str, &'static str, String)>, ids_map: &Map<String, i64>, output_dir: Option<&Path>, ) -> Vec<LanguageData> { initial_data .into_par_iter() .filter_map(|language| { let mut ids_map = ids_map.clone(); if let Some(output_dir) = output_dir { let file_path = output_dir.join(format!("{}.lua", language.1)); if let Ok(file) = File::open(file_path) { let mut file = BufReader::new(file); let _ = utils::discard_existing(&mut file, &language.2, &mut ids_map); } } if ids_map.is_empty() { None } else { Some(LanguageData { subdomain: language.0, code: language.1, header: language.2, ids_map, }) } }) .collect() } #[cfg(unix)] fn
(output_dir: &Path) -> Cow<'_, Path> { use std::fs; use std::os::unix::fs::MetadataExt; let os_tmp = env::temp_dir(); match ( fs::metadata(output_dir).map(|v| v.dev()), fs::metadata(&os_tmp).map(|v| v.dev()), ) { (Ok(num1), Ok(num2)) if num1 == num2 => Cow::from(os_tmp), _ => Cow::from(output_dir), } } #[cfg(windows)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { use winapi_util::{file, Handle}; let os_tmp = env::temp_dir(); let serial_num = |path: &Path| { Handle::from_path_any(path) .and_then(|h| file::information(h)) .map(|v| v.volume_serial_number()) }; match (serial_num(output_dir), serial_num(&os_tmp)) { (Ok(num1), Ok(num2)) if num1 == num2 => Cow::from(os_tmp), _ => Cow::from(output_dir), } } #[cfg(not(any(unix, windows)))] #[inline(always)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { Cow::from(output_dir) } fn process_languages(self) { static TITLE_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r#"\s+<.+?>$"#).unwrap()); let total = self.data.iter().fold(0, |acc, el| acc + el.ids_map.len()); if total > 0 { let (tx, rx) = channel::bounded(total); let stderr_thread = thread::spawn(move || { let stderr = std::io::stderr(); let mut stderr = stderr.lock(); let mut processed = 0; let _ = write!(stderr, "\rProgress: 0 / {total}"); while let Ok(msg) = rx.recv() { match msg { Err(ProcessingError::IoError((path, e))) => { let _ = writeln!( stderr, "\rI/O error: {} ({})", e, path.to_string_lossy(), ); } Err(ProcessingError::DataError((language, mob_name, e))) => { let _ = writeln!( stderr, "\rFailed to collect data for \"{mob_name}\" ({language}), error: {e}" ); processed += 1; } _ => processed += 1, } let _ = write!(stderr, "\rProgress: {processed} / {total}"); } let _ = stderr.write(b"\n"); let _ = stderr.flush(); }); let output_dir = self.output_dir; let tmp_dir = Self::get_tmp_dir(&output_dir); self.data.into_par_iter().for_each({ |language| { let client = HttpClient::builder() .timeout(Duration::from_secs(30)) .redirect_policy(RedirectPolicy::Limit(5)) .default_header( "accept", "text/html,application/xhtml+xml,application/xml;q=0.9", ) .default_header("accept-encoding", "gzip, deflate") .default_header("accept-language", "en-US,en;q=0.9") .default_header("sec-fetch-dest", "document") .default_header("sec-fetch-mode", "navigate") .default_header("sec-fetch-site", "same-site") .default_header("sec-fetch-user", "?1") .default_header("upgrade-insecure-requests", "1") .default_header("user-agent", &**USER_AGENT) .build() .unwrap(); let code = language.code; let subdomain = language.subdomain; let map: Map<_, _> = language .ids_map .into_iter() .filter_map({ let client = &client; let tx = tx.clone(); move |(name, id)| { let result: Result<_, Error> = client .get(&format!("https://{subdomain}.wowhead.com/npc={id}")) .map_err(From::from) .and_then(|mut response| { Document::from_read(response.body_mut()).map_err(From::from) }) .and_then(|document| { document .find(Class("heading-size-1")) .next() .ok_or_else(|| { "Couldn't find an element .heading-size-1".into() }) .and_then(|node| { // Check if we were redirected to the search page. if let Some(parent) = node.parent().and_then(|n| n.parent()) { if parent.is(Name("form")) { return Err("Not a valid NPC ID".into()); } for child in parent.children() { if child.is(Class("database-detail-page-not-found-message")) { return Err("Not a valid NPC ID".into()); } } } Ok(node.text()) }) }); match result { Ok(translation) => { let _ = tx.send(Ok(())); let translation = utils::replace_owning(translation, &TITLE_REGEX, ""); let translation = if translation.contains('\"') { translation.replace('\"', "\\\"") } else { translation }; let (translation, is_valid) = match translation.as_bytes() { [b'[', rest @ .., b']'] => { (String::from_utf8(rest.to_vec()).unwrap(), false) } _ => (translation, true), }; Some((name, (translation, is_valid))) } Err(e) => { let _ = tx .send(Err(ProcessingError::DataError((code, name, e)))); None } } } }) .collect(); if let Err(e) = utils::write_to_dir( &output_dir, &tmp_dir, language.code, &language.header, map, ) { let _ = tx.send(Err(ProcessingError::IoError(e))); } } }); drop(tx); stderr_thread.join().unwrap(); if let Err(e) = File::open(&output_dir).and_then(|dir| dir.sync_all()) { eprintln!( "Failed to call fsync() on \"{}\": {}", output_dir.display(), e ); } } else { eprintln!("There's nothing to do."); } } }
get_tmp_dir
identifier_name
lib.rs
use crossbeam_channel as channel; use indexmap::IndexMap as Map; use isahc::{ config::{Configurable, RedirectPolicy}, HttpClient, }; use once_cell::sync::Lazy; use onig::Regex; use rayon::prelude::*; use select::{ document::Document, predicate::{Class, Name}, }; use std::{ borrow::Cow, env, fs::File, io::{BufReader, Write}, path::{Path, PathBuf}, thread, time::Duration, }; mod error; pub use error::Error; use error::ProcessingError; mod utils; const DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"; static USER_AGENT: Lazy<Cow<'static, str>> = Lazy::new(|| { env::var("USER_AGENT") .map(Cow::from) .unwrap_or_else(|_| Cow::from(DEFAULT_USER_AGENT)) }); #[derive(Debug, Clone)] pub struct LanguageData { subdomain: &'static str, code: &'static str, header: String, ids_map: Map<String, i64>, } #[derive(Debug, Clone)] pub struct Localizer { data: Vec<LanguageData>, output_dir: PathBuf, } impl Localizer { pub fn run<P: Into<PathBuf>>( ids_map: Map<String, i64>, module_name: &str, output_dir: P, force_all: bool, ) { let output_dir = output_dir.into(); let localizer = Self { data: Self::construct_language_data(vec![ // ("www", "enUS", String::from("L = mod:GetLocale()")), ("de", "deDE", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"deDE\")")), ("es", "esES", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"esES\") or BigWigs:NewBossLocale(\"{module_name}\", \"esMX\")")), ("fr", "frFR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"frFR\")")), ("it", "itIT", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"itIT\")")), ("pt", "ptBR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"ptBR\")")), ("ru", "ruRU", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"ruRU\")")), ("ko", "koKR", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"koKR\")")), ("cn", "zhCN", format!("L = BigWigs:NewBossLocale(\"{module_name}\", \"zhCN\")")), ], &ids_map, if force_all { None } else { Some(&output_dir) }), output_dir, }; localizer.process_languages(); } fn construct_language_data( initial_data: Vec<(&'static str, &'static str, String)>, ids_map: &Map<String, i64>, output_dir: Option<&Path>, ) -> Vec<LanguageData> { initial_data .into_par_iter() .filter_map(|language| { let mut ids_map = ids_map.clone(); if let Some(output_dir) = output_dir { let file_path = output_dir.join(format!("{}.lua", language.1)); if let Ok(file) = File::open(file_path) { let mut file = BufReader::new(file); let _ = utils::discard_existing(&mut file, &language.2, &mut ids_map); } } if ids_map.is_empty() { None } else { Some(LanguageData { subdomain: language.0, code: language.1, header: language.2, ids_map, }) } }) .collect() } #[cfg(unix)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { use std::fs; use std::os::unix::fs::MetadataExt; let os_tmp = env::temp_dir(); match ( fs::metadata(output_dir).map(|v| v.dev()), fs::metadata(&os_tmp).map(|v| v.dev()), ) { (Ok(num1), Ok(num2)) if num1 == num2 => Cow::from(os_tmp), _ => Cow::from(output_dir), } } #[cfg(windows)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { use winapi_util::{file, Handle}; let os_tmp = env::temp_dir(); let serial_num = |path: &Path| { Handle::from_path_any(path) .and_then(|h| file::information(h)) .map(|v| v.volume_serial_number()) }; match (serial_num(output_dir), serial_num(&os_tmp)) { (Ok(num1), Ok(num2)) if num1 == num2 => Cow::from(os_tmp), _ => Cow::from(output_dir), } } #[cfg(not(any(unix, windows)))] #[inline(always)] fn get_tmp_dir(output_dir: &Path) -> Cow<'_, Path> { Cow::from(output_dir) } fn process_languages(self) { static TITLE_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r#"\s+<.+?>$"#).unwrap()); let total = self.data.iter().fold(0, |acc, el| acc + el.ids_map.len()); if total > 0 { let (tx, rx) = channel::bounded(total); let stderr_thread = thread::spawn(move || { let stderr = std::io::stderr(); let mut stderr = stderr.lock(); let mut processed = 0; let _ = write!(stderr, "\rProgress: 0 / {total}"); while let Ok(msg) = rx.recv() { match msg { Err(ProcessingError::IoError((path, e))) => { let _ = writeln!( stderr, "\rI/O error: {} ({})", e, path.to_string_lossy(), ); } Err(ProcessingError::DataError((language, mob_name, e))) => { let _ = writeln!( stderr, "\rFailed to collect data for \"{mob_name}\" ({language}), error: {e}" ); processed += 1; } _ => processed += 1, } let _ = write!(stderr, "\rProgress: {processed} / {total}"); } let _ = stderr.write(b"\n"); let _ = stderr.flush(); }); let output_dir = self.output_dir; let tmp_dir = Self::get_tmp_dir(&output_dir); self.data.into_par_iter().for_each({ |language| { let client = HttpClient::builder() .timeout(Duration::from_secs(30)) .redirect_policy(RedirectPolicy::Limit(5)) .default_header( "accept", "text/html,application/xhtml+xml,application/xml;q=0.9", ) .default_header("accept-encoding", "gzip, deflate") .default_header("accept-language", "en-US,en;q=0.9") .default_header("sec-fetch-dest", "document") .default_header("sec-fetch-mode", "navigate") .default_header("sec-fetch-site", "same-site") .default_header("sec-fetch-user", "?1") .default_header("upgrade-insecure-requests", "1") .default_header("user-agent", &**USER_AGENT) .build() .unwrap(); let code = language.code; let subdomain = language.subdomain; let map: Map<_, _> = language .ids_map .into_iter() .filter_map({ let client = &client; let tx = tx.clone(); move |(name, id)| { let result: Result<_, Error> = client .get(&format!("https://{subdomain}.wowhead.com/npc={id}")) .map_err(From::from) .and_then(|mut response| { Document::from_read(response.body_mut()).map_err(From::from) }) .and_then(|document| { document .find(Class("heading-size-1")) .next() .ok_or_else(|| { "Couldn't find an element .heading-size-1".into() }) .and_then(|node| { // Check if we were redirected to the search page. if let Some(parent) = node.parent().and_then(|n| n.parent()) { if parent.is(Name("form")) { return Err("Not a valid NPC ID".into()); } for child in parent.children() { if child.is(Class("database-detail-page-not-found-message"))
} } Ok(node.text()) }) }); match result { Ok(translation) => { let _ = tx.send(Ok(())); let translation = utils::replace_owning(translation, &TITLE_REGEX, ""); let translation = if translation.contains('\"') { translation.replace('\"', "\\\"") } else { translation }; let (translation, is_valid) = match translation.as_bytes() { [b'[', rest @ .., b']'] => { (String::from_utf8(rest.to_vec()).unwrap(), false) } _ => (translation, true), }; Some((name, (translation, is_valid))) } Err(e) => { let _ = tx .send(Err(ProcessingError::DataError((code, name, e)))); None } } } }) .collect(); if let Err(e) = utils::write_to_dir( &output_dir, &tmp_dir, language.code, &language.header, map, ) { let _ = tx.send(Err(ProcessingError::IoError(e))); } } }); drop(tx); stderr_thread.join().unwrap(); if let Err(e) = File::open(&output_dir).and_then(|dir| dir.sync_all()) { eprintln!( "Failed to call fsync() on \"{}\": {}", output_dir.display(), e ); } } else { eprintln!("There's nothing to do."); } } }
{ return Err("Not a valid NPC ID".into()); }
conditional_block
mmio.rs
#![cfg_attr(rustfmt, rustfmt::skip)] //! Contains all the MMIO address definitions for the GBA's components. //! //! This module contains *only* the MMIO addresses. The data type definitions //! for each MMIO control value are stored in the appropriate other modules such //! as [`video`](crate::video), [`interrupts`](crate::interrupts), etc. //! //! In general, the docs for each address are quite short. If you want to //! understand how a subsystem of the GBA works, you should read the docs for //! that system's module, and the data type used by the address. //! //! The GBATEK names (and thus mGBA names) are used for the MMIO addresses by //! default. However, in some cases (eg: sound) the GBATEK naming is excessively //! cryptic, and so new names have been created. Whenever a new name is used, //! the GBATEK name is still listed as a doc alias for that address. If //! necessary you can just search the GBATEK name in the rustdoc search bar and //! the search results will show you the new name. //! //! ## Safety //! //! The MMIO declarations and wrapper types in this module **must not** be used //! outside of a GBA. The read and write safety of each address are declared //! assuming that code is running on a GBA. On any other platform, the //! declarations are simply incorrect. use core::{ffi::c_void, mem::size_of}; use bitfrob::u8x2; use voladdress::{Safe, Unsafe, VolAddress, VolBlock, VolSeries, VolGrid2dStrided}; use crate::prelude::*; // Note(Lokathor): This macro lets us stick each address at the start of the // definition, which lets us easily keep each declaration in address order. macro_rules! def_mmio { ($addr:literal = $name:ident : $t:ty $(; $comment:expr )?) => { // redirect a call **without** an alias list to just pass an empty alias list def_mmio!($addr = $name/[]: $t $(; $comment)? ); }; ($addr:literal = $name:ident / [ $( $alias:literal ),* ]: $t:ty $(; $comment:expr )?) => { $(#[doc = $comment])? $(#[doc(alias = $alias)])* #[allow(missing_docs)] pub const $name: $t = unsafe { <$t>::new($addr) }; }; } // Video def_mmio!(0x0400_0000 = DISPCNT: VolAddress<DisplayControl, Safe, Safe>; "Display Control"); def_mmio!(0x0400_0004 = DISPSTAT: VolAddress<DisplayStatus, Safe, Safe>; "Display Status"); def_mmio!(0x0400_0006 = VCOUNT: VolAddress<u16, Safe, ()>; "Vertical Counter"); def_mmio!(0x0400_0008 = BG0CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 0 Control"); def_mmio!(0x0400_000A = BG1CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 1 Control"); def_mmio!(0x0400_000C = BG2CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 2 Control"); def_mmio!(0x0400_000E = BG3CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 3 Control"); def_mmio!(0x0400_0010 = BG0HOFS: VolAddress<u16, (), Safe>; "Background 0 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_0012 = BG0VOFS: VolAddress<u16, (), Safe>; "Background 0 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0014 = BG1HOFS: VolAddress<u16, (), Safe>; "Background 1 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_0016 = BG1VOFS: VolAddress<u16, (), Safe>; "Background 1 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0018 = BG2HOFS: VolAddress<u16, (), Safe>; "Background 2 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_001A = BG2VOFS: VolAddress<u16, (), Safe>; "Background 2 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_001C = BG3HOFS: VolAddress<u16, (), Safe>; "Background 3 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_001E = BG3VOFS: VolAddress<u16, (), Safe>; "Background 3 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0020 = BG2PA: VolAddress<i16fx8, (), Safe>; "Background 2 Param A (affine mode)"); def_mmio!(0x0400_0022 = BG2PB: VolAddress<i16fx8, (), Safe>; "Background 2 Param B (affine mode)"); def_mmio!(0x0400_0024 = BG2PC: VolAddress<i16fx8, (), Safe>; "Background 2 Param C (affine mode)"); def_mmio!(0x0400_0026 = BG2PD: VolAddress<i16fx8, (), Safe>; "Background 2 Param D (affine mode)"); def_mmio!(0x0400_0028 = BG2X/["BG2X_L", "BG2X_H"]: VolAddress<i32fx8, (), Safe>; "Background 2 X Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_002C = BG2Y/["BG2Y_L", "BG2Y_H"]: VolAddress<i32fx8, (), Safe>; "Background 2 Y Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_0030 = BG3PA: VolAddress<i16fx8, (), Safe>; "Background 3 Param A (affine mode)"); def_mmio!(0x0400_0032 = BG3PB: VolAddress<i16fx8, (), Safe>; "Background 3 Param B (affine mode)"); def_mmio!(0x0400_0034 = BG3PC: VolAddress<i16fx8, (), Safe>; "Background 3 Param C (affine mode)"); def_mmio!(0x0400_0036 = BG3PD: VolAddress<i16fx8, (), Safe>; "Background 3 Param D (affine mode)"); def_mmio!(0x0400_0038 = BG3X/["BG3X_L", "BG3X_H"]: VolAddress<i32fx8, (), Safe>; "Background 3 X Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_003C = BG3Y/["BG3Y_L", "BG3Y_H"]: VolAddress<i32fx8, (), Safe>; "Background 3 Y Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_0040 = WIN0H: VolAddress<u8x2, (), Safe>; "Window 0 Horizontal: high=left, low=(right+1)"); def_mmio!(0x0400_0042 = WIN1H: VolAddress<u8x2, (), Safe>; "Window 1 Horizontal: high=left, low=(right+1)"); def_mmio!(0x0400_0044 = WIN0V: VolAddress<u8x2, (), Safe>; "Window 0 Vertical: high=top, low=(bottom+1)"); def_mmio!(0x0400_0046 = WIN1V: VolAddress<u8x2, (), Safe>; "Window 1 Vertical: high=top, low=(bottom+1)"); def_mmio!(0x0400_0048 = WININ: VolAddress<WindowInside, Safe, Safe>; "Controls the inside Windows 0 and 1"); def_mmio!(0x0400_004A = WINOUT: VolAddress<WindowOutside, Safe, Safe>; "Controls inside the object window and outside of windows"); def_mmio!(0x0400_004C = MOSAIC: VolAddress<Mosaic, (), Safe>; "Sets the intensity of all mosaic effects"); def_mmio!(0x0400_0050 = BLDCNT: VolAddress<BlendControl, Safe, Safe>; "Sets color blend effects"); def_mmio!(0x0400_0052 = BLDALPHA: VolAddress<u8x2, Safe, Safe>;"Sets EVA(low) and EVB(high) alpha blend coefficients, allows `0..=16`, in 1/16th units"); def_mmio!(0x0400_0054 = BLDY: VolAddress<u8, (), Safe>;"Sets EVY brightness blend coefficient, allows `0..=16`, in 1/16th units"); // Sound def_mmio!(0x0400_0060 = TONE1_SWEEP/["SOUND1CNT_L","NR10"]: VolAddress<SweepControl, Safe, Safe>; "Tone 1 Sweep"); def_mmio!(0x0400_0062 = TONE1_PATTERN/["SOUND1CNT_H","NR11","NR12"]: VolAddress<TonePattern, Safe, Safe>; "Tone 1 Duty/Len/Envelope"); def_mmio!(0x0400_0064 = TONE1_FREQUENCY/["SOUND1CNT_X","NR13","NR14"]: VolAddress<ToneFrequency, Safe, Safe>; "Tone 1 Frequency/Control"); def_mmio!(0x0400_0068 = TONE2_PATTERN/["SOUND2CNT_L","NR21","NR22"]: VolAddress<TonePattern, Safe, Safe>; "Tone 2 Duty/Len/Envelope"); def_mmio!(0x0400_006C = TONE2_FREQUENCY/["SOUND2CNT_H","NR23","NR24"]: VolAddress<ToneFrequency, Safe, Safe>; "Tone 2 Frequency/Control"); def_mmio!(0x0400_0070 = WAVE_BANK/["SOUND3CNT_L","NR30"]: VolAddress<WaveBank, Safe, Safe>; "Wave banking controls"); def_mmio!(0x0400_0072 = WAVE_LEN_VOLUME/["SOUND3CNT_H","NR31","NR32"]: VolAddress<WaveLenVolume, Safe, Safe>; "Wave Length/Volume"); def_mmio!(0x0400_0074 = WAVE_FREQ/["SOUND3CNT_X","NR33","NR34"]: VolAddress<WaveFrequency, Safe, Safe>; "Wave Frequency/Control"); def_mmio!(0x0400_0078 = NOISE_LEN_ENV/["SOUND4CNT_L","NR41","NR42"]: VolAddress<NoiseLenEnvelope, Safe, Safe>; "Noise Length/Envelope"); def_mmio!(0x0400_007C = NOISE_FREQ/["SOUND4CNT_H","NR43","NR44"]: VolAddress<NoiseFrequency, Safe, Safe>; "Noise Frequency/Control"); def_mmio!(0x0400_0080 = LEFT_RIGHT_VOLUME/["SOUNDCNT_L","NR50","NR51"]: VolAddress<LeftRightVolume, Safe, Safe>;"Left/Right sound control (but GBAs only have one speaker each)."); def_mmio!(0x0400_0082 = SOUND_MIX/["SOUNDCNT_H"]: VolAddress<SoundMix, Safe, Safe>;"Mixes sound sources out to the left and right"); def_mmio!(0x0400_0084 = SOUND_ENABLED/["SOUNDCNT_X"]: VolAddress<SoundEnable, Safe, Safe>;"Sound active flags (r), as well as the sound primary enable (rw)."); def_mmio!(0x0400_0088 = SOUNDBIAS: VolAddress<SoundBias, Safe, Safe>;"Provides a bias to set the 'middle point' of sound output."); def_mmio!(0x0400_0090 = WAVE_RAM/["WAVE_RAM0_L","WAVE_RAM0_H","WAVE_RAM1_L","WAVE_RAM1_H","WAVE_RAM2_L","WAVE_RAM2_H","WAVE_RAM3_L","WAVE_RAM3_H"]: VolBlock<u32, Safe, Safe, 4>; "Wave memory, `u4`, plays MSB/LSB per byte."); def_mmio!(0x0400_00A0 = FIFO_A/["FIFO_A_L", "FIFO_A_H"]: VolAddress<u32, (), Safe>; "Pushes 4 `i8` samples into the Sound A buffer.\n\nThe buffer is 32 bytes max, playback is LSB first."); def_mmio!(0x0400_00A4 = FIFO_B/["FIFO_B_L", "FIFO_B_H"]: VolAddress<u32, (), Safe>; "Pushes 4 `i8` samples into the Sound B buffer.\n\nThe buffer is 32 bytes max, playback is LSB first."); // DMA def_mmio!(0x0400_00B0 = DMA0_SRC/["DMA0SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA0 Source Address (internal memory only)"); def_mmio!(0x0400_00B4 = DMA0_DEST/["DMA0DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA0 Destination Address (internal memory only)"); def_mmio!(0x0400_00B8 = DMA0_COUNT/["DMA0CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA0 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00BA = DMA0_CONTROL/["DMA0_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA0 Control Bits"); def_mmio!(0x0400_00BC = DMA1_SRC/["DMA1SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA1 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00C0 = DMA1_DEST/["DMA1DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA1 Destination Address (internal memory only)"); def_mmio!(0x0400_00C4 = DMA1_COUNT/["DMA1CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA1 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00C6 = DMA1_CONTROL/["DMA1_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA1 Control Bits"); def_mmio!(0x0400_00C8 = DMA2_SRC/["DMA2SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA2 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00CC = DMA2_DEST/["DMA2DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA2 Destination Address (internal memory only)"); def_mmio!(0x0400_00D0 = DMA2_COUNT/["DMA2CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA2 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00D2 = DMA2_CONTROL/["DMA2_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA2 Control Bits"); def_mmio!(0x0400_00D4 = DMA3_SRC/["DMA3SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA3 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00D8 = DMA3_DEST/["DMA3DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA3 Destination Address (non-SRAM memory)"); def_mmio!(0x0400_00DC = DMA3_COUNT/["DMA3CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA3 Transfer Count (16-bit, 0=max)");
// Timers def_mmio!(0x0400_0100 = TIMER0_COUNT/["TM0CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 0 Count read"); def_mmio!(0x0400_0100 = TIMER0_RELOAD/["TM0CNT_L"]: VolAddress<u16, (), Safe>; "Timer 0 Reload write"); def_mmio!(0x0400_0102 = TIMER0_CONTROL/["TM0CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 0 control"); def_mmio!(0x0400_0104 = TIMER1_COUNT/["TM1CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 1 Count read"); def_mmio!(0x0400_0104 = TIMER1_RELOAD/["TM1CNT_L"]: VolAddress<u16, (), Safe>; "Timer 1 Reload write"); def_mmio!(0x0400_0106 = TIMER1_CONTROL/["TM1CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 1 control"); def_mmio!(0x0400_0108 = TIMER2_COUNT/["TM2CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 2 Count read"); def_mmio!(0x0400_0108 = TIMER2_RELOAD/["TM2CNT_L"]: VolAddress<u16, (), Safe>; "Timer 2 Reload write"); def_mmio!(0x0400_010A = TIMER2_CONTROL/["TM2CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 2 control"); def_mmio!(0x0400_010C = TIMER3_COUNT/["TM3CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 3 Count read"); def_mmio!(0x0400_010C = TIMER3_RELOAD/["TM3CNT_L"]: VolAddress<u16, (), Safe>; "Timer 3 Reload write"); def_mmio!(0x0400_010E = TIMER3_CONTROL/["TM3CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 3 control"); // Serial (part 1) def_mmio!(0x0400_0120 = SIODATA32: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0120 = SIOMULTI0: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0122 = SIOMULTI1: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0124 = SIOMULTI2: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0126 = SIOMULTI3: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0128 = SIOCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_012A = SIOMLT_SEND: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_012A = SIODATA8: VolAddress<u8, Safe, Safe>); // Keys def_mmio!(0x0400_0130 = KEYINPUT: VolAddress<KeyInput, Safe, ()>; "Key state data."); def_mmio!(0x0400_0132 = KEYCNT: VolAddress<KeyControl, Safe, Safe>; "Key control to configure the key interrupt."); // Serial (part 2) def_mmio!(0x0400_0134 = RCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0140 = JOYCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0150 = JOY_RECV: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0154 = JOY_TRANS: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0158 = JOYSTAT: VolAddress<u8, Safe, Safe>); // Interrupts def_mmio!(0x0400_0200 = IE: VolAddress<IrqBits, Safe, Safe>; "Interrupts Enabled: sets which interrupts will be accepted when a subsystem fires an interrupt"); def_mmio!(0x0400_0202 = IF: VolAddress<IrqBits, Safe, Safe>; "Interrupts Flagged: reads which interrupts are pending, writing bit(s) will clear a pending interrupt."); def_mmio!(0x0400_0204 = WAITCNT: VolAddress<u16, Safe, Unsafe>; "Wait state control for interfacing with the ROM.\n\nThis can make reading the ROM give garbage when it's mis-configured!"); def_mmio!(0x0400_0208 = IME: VolAddress<bool, Safe, Safe>; "Interrupt Master Enable: Allows turning on/off all interrupts with a single access."); // mGBA Logging def_mmio!(0x04FF_F600 = MGBA_LOG_BUFFER: VolBlock<u8, Safe, Safe, 256>; "The buffer to put logging messages into.\n\nThe first 0 in the buffer is the end of each message."); def_mmio!(0x04FF_F700 = MGBA_LOG_SEND: VolAddress<MgbaMessageLevel, (), Safe>; "Write to this each time you want to reset a message (it also resets the buffer)."); def_mmio!(0x04FF_F780 = MGBA_LOG_ENABLE: VolAddress<u16, Safe, Safe>; "Allows you to attempt to activate mGBA logging."); // Palette RAM (PALRAM) def_mmio!(0x0500_0000 = BACKDROP_COLOR: VolAddress<Color, Safe, Safe>; "Color that's shown when no BG or OBJ draws to a pixel"); def_mmio!(0x0500_0000 = BG_PALETTE: VolBlock<Color, Safe, Safe, 256>; "Background tile palette entries."); def_mmio!(0x0500_0200 = OBJ_PALETTE: VolBlock<Color, Safe, Safe, 256>; "Object tile palette entries."); #[inline] #[must_use] #[cfg_attr(feature="track_caller", track_caller)] pub const fn bg_palbank(bank: usize) -> VolBlock<Color, Safe, Safe, 16> { let u = BG_PALETTE.index(bank * 16).as_usize(); unsafe { VolBlock::new(u) } } #[inline] #[must_use] #[cfg_attr(feature="track_caller", track_caller)] pub const fn obj_palbank(bank: usize) -> VolBlock<Color, Safe, Safe, 16> { let u = OBJ_PALETTE.index(bank * 16).as_usize(); unsafe { VolBlock::new(u) } } // Video RAM (VRAM) /// The VRAM byte offset per screenblock index. /// /// This is the same for all background types and sizes. pub const SCREENBLOCK_INDEX_OFFSET: usize = 2 * 1_024; /// The size of the background tile region of VRAM. /// /// Background tile index use will work between charblocks, but not past the end /// of BG tile memory into OBJ tile memory. pub const BG_TILE_REGION_SIZE: usize = 64 * 1_024; def_mmio!(0x0600_0000 = CHARBLOCK0_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 0, 4bpp view (512 tiles)."); def_mmio!(0x0600_4000 = CHARBLOCK1_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 1, 4bpp view (512 tiles)."); def_mmio!(0x0600_8000 = CHARBLOCK2_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 2, 4bpp view (512 tiles)."); def_mmio!(0x0600_C000 = CHARBLOCK3_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 3, 4bpp view (512 tiles)."); def_mmio!(0x0600_0000 = CHARBLOCK0_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 0, 8bpp view (256 tiles)."); def_mmio!(0x0600_4000 = CHARBLOCK1_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 1, 8bpp view (256 tiles)."); def_mmio!(0x0600_8000 = CHARBLOCK2_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 2, 8bpp view (256 tiles)."); def_mmio!(0x0600_C000 = CHARBLOCK3_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 3, 8bpp view (256 tiles)."); def_mmio!(0x0600_0000 = TEXT_SCREENBLOCKS: VolGrid2dStrided<TextEntry, Safe, Safe, 32, 32, 32, SCREENBLOCK_INDEX_OFFSET>; "Text mode screenblocks."); def_mmio!(0x0600_0000 = AFFINE0_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 8, 16, 32, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 0)."); def_mmio!(0x0600_0000 = AFFINE1_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 16, 32, 32, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 1)."); def_mmio!(0x0600_0000 = AFFINE2_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 32, 64, 31, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 2)."); def_mmio!(0x0600_0000 = AFFINE3_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 64, 128, 25, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 3)."); def_mmio!(0x0600_0000 = VIDEO3_VRAM: VolGrid2dStrided<Color, Safe, Safe, 240, 160, 2, 0xA000>; "Video mode 3 bitmap"); def_mmio!(0x0600_0000 = VIDEO4_VRAM: VolGrid2dStrided<u8x2, Safe, Safe, 120, 160, 2, 0xA000>; "Video mode 4 palette maps (frames 0 and 1). Each entry is two palette indexes."); def_mmio!(0x0600_0000 = VIDEO5_VRAM: VolGrid2dStrided<Color, Safe, Safe, 160, 128, 2, 0xA000>; "Video mode 5 bitmaps (frames 0 and 1)."); def_mmio!(0x0601_0000 = OBJ_TILES: VolBlock<Tile4, Safe, Safe, 1024>; "Object tiles. In video modes 3, 4, and 5 only indices 512..=1023 are available."); // Object Attribute Memory (OAM) def_mmio!(0x0700_0000 = OBJ_ATTR0: VolSeries<ObjAttr0, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 0."); def_mmio!(0x0700_0002 = OBJ_ATTR1: VolSeries<ObjAttr1, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 1."); def_mmio!(0x0700_0004 = OBJ_ATTR2: VolSeries<ObjAttr2, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 2."); def_mmio!(0x0700_0000 = OBJ_ATTR_ALL: VolSeries<ObjAttr, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes (all in one)."); def_mmio!(0x0700_0006 = AFFINE_PARAM_A: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters A."); def_mmio!(0x0700_000E = AFFINE_PARAM_B: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters B."); def_mmio!(0x0700_0016 = AFFINE_PARAM_C: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters C."); def_mmio!(0x0700_001E = AFFINE_PARAM_D: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters D."); // Cartridge IO port // https://problemkaputt.de/gbatek.htm#gbacartioportgpio def_mmio!(0x0800_00C4 = IO_PORT_DATA: VolAddress<u16, Safe, Safe>; "I/O port data"); def_mmio!(0x0800_00C6 = IO_PORT_DIRECTION: VolAddress<u16, Safe, Safe>; "I/O port direction"); def_mmio!(0x0800_00C8 = IO_PORT_CONTROL: VolAddress<u16, Safe, Safe>; "I/O port control");
def_mmio!(0x0400_00DE = DMA3_CONTROL/["DMA3_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA3 Control Bits");
random_line_split
mmio.rs
#![cfg_attr(rustfmt, rustfmt::skip)] //! Contains all the MMIO address definitions for the GBA's components. //! //! This module contains *only* the MMIO addresses. The data type definitions //! for each MMIO control value are stored in the appropriate other modules such //! as [`video`](crate::video), [`interrupts`](crate::interrupts), etc. //! //! In general, the docs for each address are quite short. If you want to //! understand how a subsystem of the GBA works, you should read the docs for //! that system's module, and the data type used by the address. //! //! The GBATEK names (and thus mGBA names) are used for the MMIO addresses by //! default. However, in some cases (eg: sound) the GBATEK naming is excessively //! cryptic, and so new names have been created. Whenever a new name is used, //! the GBATEK name is still listed as a doc alias for that address. If //! necessary you can just search the GBATEK name in the rustdoc search bar and //! the search results will show you the new name. //! //! ## Safety //! //! The MMIO declarations and wrapper types in this module **must not** be used //! outside of a GBA. The read and write safety of each address are declared //! assuming that code is running on a GBA. On any other platform, the //! declarations are simply incorrect. use core::{ffi::c_void, mem::size_of}; use bitfrob::u8x2; use voladdress::{Safe, Unsafe, VolAddress, VolBlock, VolSeries, VolGrid2dStrided}; use crate::prelude::*; // Note(Lokathor): This macro lets us stick each address at the start of the // definition, which lets us easily keep each declaration in address order. macro_rules! def_mmio { ($addr:literal = $name:ident : $t:ty $(; $comment:expr )?) => { // redirect a call **without** an alias list to just pass an empty alias list def_mmio!($addr = $name/[]: $t $(; $comment)? ); }; ($addr:literal = $name:ident / [ $( $alias:literal ),* ]: $t:ty $(; $comment:expr )?) => { $(#[doc = $comment])? $(#[doc(alias = $alias)])* #[allow(missing_docs)] pub const $name: $t = unsafe { <$t>::new($addr) }; }; } // Video def_mmio!(0x0400_0000 = DISPCNT: VolAddress<DisplayControl, Safe, Safe>; "Display Control"); def_mmio!(0x0400_0004 = DISPSTAT: VolAddress<DisplayStatus, Safe, Safe>; "Display Status"); def_mmio!(0x0400_0006 = VCOUNT: VolAddress<u16, Safe, ()>; "Vertical Counter"); def_mmio!(0x0400_0008 = BG0CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 0 Control"); def_mmio!(0x0400_000A = BG1CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 1 Control"); def_mmio!(0x0400_000C = BG2CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 2 Control"); def_mmio!(0x0400_000E = BG3CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 3 Control"); def_mmio!(0x0400_0010 = BG0HOFS: VolAddress<u16, (), Safe>; "Background 0 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_0012 = BG0VOFS: VolAddress<u16, (), Safe>; "Background 0 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0014 = BG1HOFS: VolAddress<u16, (), Safe>; "Background 1 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_0016 = BG1VOFS: VolAddress<u16, (), Safe>; "Background 1 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0018 = BG2HOFS: VolAddress<u16, (), Safe>; "Background 2 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_001A = BG2VOFS: VolAddress<u16, (), Safe>; "Background 2 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_001C = BG3HOFS: VolAddress<u16, (), Safe>; "Background 3 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_001E = BG3VOFS: VolAddress<u16, (), Safe>; "Background 3 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0020 = BG2PA: VolAddress<i16fx8, (), Safe>; "Background 2 Param A (affine mode)"); def_mmio!(0x0400_0022 = BG2PB: VolAddress<i16fx8, (), Safe>; "Background 2 Param B (affine mode)"); def_mmio!(0x0400_0024 = BG2PC: VolAddress<i16fx8, (), Safe>; "Background 2 Param C (affine mode)"); def_mmio!(0x0400_0026 = BG2PD: VolAddress<i16fx8, (), Safe>; "Background 2 Param D (affine mode)"); def_mmio!(0x0400_0028 = BG2X/["BG2X_L", "BG2X_H"]: VolAddress<i32fx8, (), Safe>; "Background 2 X Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_002C = BG2Y/["BG2Y_L", "BG2Y_H"]: VolAddress<i32fx8, (), Safe>; "Background 2 Y Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_0030 = BG3PA: VolAddress<i16fx8, (), Safe>; "Background 3 Param A (affine mode)"); def_mmio!(0x0400_0032 = BG3PB: VolAddress<i16fx8, (), Safe>; "Background 3 Param B (affine mode)"); def_mmio!(0x0400_0034 = BG3PC: VolAddress<i16fx8, (), Safe>; "Background 3 Param C (affine mode)"); def_mmio!(0x0400_0036 = BG3PD: VolAddress<i16fx8, (), Safe>; "Background 3 Param D (affine mode)"); def_mmio!(0x0400_0038 = BG3X/["BG3X_L", "BG3X_H"]: VolAddress<i32fx8, (), Safe>; "Background 3 X Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_003C = BG3Y/["BG3Y_L", "BG3Y_H"]: VolAddress<i32fx8, (), Safe>; "Background 3 Y Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_0040 = WIN0H: VolAddress<u8x2, (), Safe>; "Window 0 Horizontal: high=left, low=(right+1)"); def_mmio!(0x0400_0042 = WIN1H: VolAddress<u8x2, (), Safe>; "Window 1 Horizontal: high=left, low=(right+1)"); def_mmio!(0x0400_0044 = WIN0V: VolAddress<u8x2, (), Safe>; "Window 0 Vertical: high=top, low=(bottom+1)"); def_mmio!(0x0400_0046 = WIN1V: VolAddress<u8x2, (), Safe>; "Window 1 Vertical: high=top, low=(bottom+1)"); def_mmio!(0x0400_0048 = WININ: VolAddress<WindowInside, Safe, Safe>; "Controls the inside Windows 0 and 1"); def_mmio!(0x0400_004A = WINOUT: VolAddress<WindowOutside, Safe, Safe>; "Controls inside the object window and outside of windows"); def_mmio!(0x0400_004C = MOSAIC: VolAddress<Mosaic, (), Safe>; "Sets the intensity of all mosaic effects"); def_mmio!(0x0400_0050 = BLDCNT: VolAddress<BlendControl, Safe, Safe>; "Sets color blend effects"); def_mmio!(0x0400_0052 = BLDALPHA: VolAddress<u8x2, Safe, Safe>;"Sets EVA(low) and EVB(high) alpha blend coefficients, allows `0..=16`, in 1/16th units"); def_mmio!(0x0400_0054 = BLDY: VolAddress<u8, (), Safe>;"Sets EVY brightness blend coefficient, allows `0..=16`, in 1/16th units"); // Sound def_mmio!(0x0400_0060 = TONE1_SWEEP/["SOUND1CNT_L","NR10"]: VolAddress<SweepControl, Safe, Safe>; "Tone 1 Sweep"); def_mmio!(0x0400_0062 = TONE1_PATTERN/["SOUND1CNT_H","NR11","NR12"]: VolAddress<TonePattern, Safe, Safe>; "Tone 1 Duty/Len/Envelope"); def_mmio!(0x0400_0064 = TONE1_FREQUENCY/["SOUND1CNT_X","NR13","NR14"]: VolAddress<ToneFrequency, Safe, Safe>; "Tone 1 Frequency/Control"); def_mmio!(0x0400_0068 = TONE2_PATTERN/["SOUND2CNT_L","NR21","NR22"]: VolAddress<TonePattern, Safe, Safe>; "Tone 2 Duty/Len/Envelope"); def_mmio!(0x0400_006C = TONE2_FREQUENCY/["SOUND2CNT_H","NR23","NR24"]: VolAddress<ToneFrequency, Safe, Safe>; "Tone 2 Frequency/Control"); def_mmio!(0x0400_0070 = WAVE_BANK/["SOUND3CNT_L","NR30"]: VolAddress<WaveBank, Safe, Safe>; "Wave banking controls"); def_mmio!(0x0400_0072 = WAVE_LEN_VOLUME/["SOUND3CNT_H","NR31","NR32"]: VolAddress<WaveLenVolume, Safe, Safe>; "Wave Length/Volume"); def_mmio!(0x0400_0074 = WAVE_FREQ/["SOUND3CNT_X","NR33","NR34"]: VolAddress<WaveFrequency, Safe, Safe>; "Wave Frequency/Control"); def_mmio!(0x0400_0078 = NOISE_LEN_ENV/["SOUND4CNT_L","NR41","NR42"]: VolAddress<NoiseLenEnvelope, Safe, Safe>; "Noise Length/Envelope"); def_mmio!(0x0400_007C = NOISE_FREQ/["SOUND4CNT_H","NR43","NR44"]: VolAddress<NoiseFrequency, Safe, Safe>; "Noise Frequency/Control"); def_mmio!(0x0400_0080 = LEFT_RIGHT_VOLUME/["SOUNDCNT_L","NR50","NR51"]: VolAddress<LeftRightVolume, Safe, Safe>;"Left/Right sound control (but GBAs only have one speaker each)."); def_mmio!(0x0400_0082 = SOUND_MIX/["SOUNDCNT_H"]: VolAddress<SoundMix, Safe, Safe>;"Mixes sound sources out to the left and right"); def_mmio!(0x0400_0084 = SOUND_ENABLED/["SOUNDCNT_X"]: VolAddress<SoundEnable, Safe, Safe>;"Sound active flags (r), as well as the sound primary enable (rw)."); def_mmio!(0x0400_0088 = SOUNDBIAS: VolAddress<SoundBias, Safe, Safe>;"Provides a bias to set the 'middle point' of sound output."); def_mmio!(0x0400_0090 = WAVE_RAM/["WAVE_RAM0_L","WAVE_RAM0_H","WAVE_RAM1_L","WAVE_RAM1_H","WAVE_RAM2_L","WAVE_RAM2_H","WAVE_RAM3_L","WAVE_RAM3_H"]: VolBlock<u32, Safe, Safe, 4>; "Wave memory, `u4`, plays MSB/LSB per byte."); def_mmio!(0x0400_00A0 = FIFO_A/["FIFO_A_L", "FIFO_A_H"]: VolAddress<u32, (), Safe>; "Pushes 4 `i8` samples into the Sound A buffer.\n\nThe buffer is 32 bytes max, playback is LSB first."); def_mmio!(0x0400_00A4 = FIFO_B/["FIFO_B_L", "FIFO_B_H"]: VolAddress<u32, (), Safe>; "Pushes 4 `i8` samples into the Sound B buffer.\n\nThe buffer is 32 bytes max, playback is LSB first."); // DMA def_mmio!(0x0400_00B0 = DMA0_SRC/["DMA0SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA0 Source Address (internal memory only)"); def_mmio!(0x0400_00B4 = DMA0_DEST/["DMA0DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA0 Destination Address (internal memory only)"); def_mmio!(0x0400_00B8 = DMA0_COUNT/["DMA0CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA0 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00BA = DMA0_CONTROL/["DMA0_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA0 Control Bits"); def_mmio!(0x0400_00BC = DMA1_SRC/["DMA1SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA1 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00C0 = DMA1_DEST/["DMA1DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA1 Destination Address (internal memory only)"); def_mmio!(0x0400_00C4 = DMA1_COUNT/["DMA1CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA1 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00C6 = DMA1_CONTROL/["DMA1_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA1 Control Bits"); def_mmio!(0x0400_00C8 = DMA2_SRC/["DMA2SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA2 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00CC = DMA2_DEST/["DMA2DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA2 Destination Address (internal memory only)"); def_mmio!(0x0400_00D0 = DMA2_COUNT/["DMA2CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA2 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00D2 = DMA2_CONTROL/["DMA2_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA2 Control Bits"); def_mmio!(0x0400_00D4 = DMA3_SRC/["DMA3SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA3 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00D8 = DMA3_DEST/["DMA3DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA3 Destination Address (non-SRAM memory)"); def_mmio!(0x0400_00DC = DMA3_COUNT/["DMA3CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA3 Transfer Count (16-bit, 0=max)"); def_mmio!(0x0400_00DE = DMA3_CONTROL/["DMA3_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA3 Control Bits"); // Timers def_mmio!(0x0400_0100 = TIMER0_COUNT/["TM0CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 0 Count read"); def_mmio!(0x0400_0100 = TIMER0_RELOAD/["TM0CNT_L"]: VolAddress<u16, (), Safe>; "Timer 0 Reload write"); def_mmio!(0x0400_0102 = TIMER0_CONTROL/["TM0CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 0 control"); def_mmio!(0x0400_0104 = TIMER1_COUNT/["TM1CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 1 Count read"); def_mmio!(0x0400_0104 = TIMER1_RELOAD/["TM1CNT_L"]: VolAddress<u16, (), Safe>; "Timer 1 Reload write"); def_mmio!(0x0400_0106 = TIMER1_CONTROL/["TM1CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 1 control"); def_mmio!(0x0400_0108 = TIMER2_COUNT/["TM2CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 2 Count read"); def_mmio!(0x0400_0108 = TIMER2_RELOAD/["TM2CNT_L"]: VolAddress<u16, (), Safe>; "Timer 2 Reload write"); def_mmio!(0x0400_010A = TIMER2_CONTROL/["TM2CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 2 control"); def_mmio!(0x0400_010C = TIMER3_COUNT/["TM3CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 3 Count read"); def_mmio!(0x0400_010C = TIMER3_RELOAD/["TM3CNT_L"]: VolAddress<u16, (), Safe>; "Timer 3 Reload write"); def_mmio!(0x0400_010E = TIMER3_CONTROL/["TM3CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 3 control"); // Serial (part 1) def_mmio!(0x0400_0120 = SIODATA32: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0120 = SIOMULTI0: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0122 = SIOMULTI1: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0124 = SIOMULTI2: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0126 = SIOMULTI3: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0128 = SIOCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_012A = SIOMLT_SEND: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_012A = SIODATA8: VolAddress<u8, Safe, Safe>); // Keys def_mmio!(0x0400_0130 = KEYINPUT: VolAddress<KeyInput, Safe, ()>; "Key state data."); def_mmio!(0x0400_0132 = KEYCNT: VolAddress<KeyControl, Safe, Safe>; "Key control to configure the key interrupt."); // Serial (part 2) def_mmio!(0x0400_0134 = RCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0140 = JOYCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0150 = JOY_RECV: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0154 = JOY_TRANS: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0158 = JOYSTAT: VolAddress<u8, Safe, Safe>); // Interrupts def_mmio!(0x0400_0200 = IE: VolAddress<IrqBits, Safe, Safe>; "Interrupts Enabled: sets which interrupts will be accepted when a subsystem fires an interrupt"); def_mmio!(0x0400_0202 = IF: VolAddress<IrqBits, Safe, Safe>; "Interrupts Flagged: reads which interrupts are pending, writing bit(s) will clear a pending interrupt."); def_mmio!(0x0400_0204 = WAITCNT: VolAddress<u16, Safe, Unsafe>; "Wait state control for interfacing with the ROM.\n\nThis can make reading the ROM give garbage when it's mis-configured!"); def_mmio!(0x0400_0208 = IME: VolAddress<bool, Safe, Safe>; "Interrupt Master Enable: Allows turning on/off all interrupts with a single access."); // mGBA Logging def_mmio!(0x04FF_F600 = MGBA_LOG_BUFFER: VolBlock<u8, Safe, Safe, 256>; "The buffer to put logging messages into.\n\nThe first 0 in the buffer is the end of each message."); def_mmio!(0x04FF_F700 = MGBA_LOG_SEND: VolAddress<MgbaMessageLevel, (), Safe>; "Write to this each time you want to reset a message (it also resets the buffer)."); def_mmio!(0x04FF_F780 = MGBA_LOG_ENABLE: VolAddress<u16, Safe, Safe>; "Allows you to attempt to activate mGBA logging."); // Palette RAM (PALRAM) def_mmio!(0x0500_0000 = BACKDROP_COLOR: VolAddress<Color, Safe, Safe>; "Color that's shown when no BG or OBJ draws to a pixel"); def_mmio!(0x0500_0000 = BG_PALETTE: VolBlock<Color, Safe, Safe, 256>; "Background tile palette entries."); def_mmio!(0x0500_0200 = OBJ_PALETTE: VolBlock<Color, Safe, Safe, 256>; "Object tile palette entries."); #[inline] #[must_use] #[cfg_attr(feature="track_caller", track_caller)] pub const fn bg_palbank(bank: usize) -> VolBlock<Color, Safe, Safe, 16>
#[inline] #[must_use] #[cfg_attr(feature="track_caller", track_caller)] pub const fn obj_palbank(bank: usize) -> VolBlock<Color, Safe, Safe, 16> { let u = OBJ_PALETTE.index(bank * 16).as_usize(); unsafe { VolBlock::new(u) } } // Video RAM (VRAM) /// The VRAM byte offset per screenblock index. /// /// This is the same for all background types and sizes. pub const SCREENBLOCK_INDEX_OFFSET: usize = 2 * 1_024; /// The size of the background tile region of VRAM. /// /// Background tile index use will work between charblocks, but not past the end /// of BG tile memory into OBJ tile memory. pub const BG_TILE_REGION_SIZE: usize = 64 * 1_024; def_mmio!(0x0600_0000 = CHARBLOCK0_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 0, 4bpp view (512 tiles)."); def_mmio!(0x0600_4000 = CHARBLOCK1_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 1, 4bpp view (512 tiles)."); def_mmio!(0x0600_8000 = CHARBLOCK2_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 2, 4bpp view (512 tiles)."); def_mmio!(0x0600_C000 = CHARBLOCK3_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 3, 4bpp view (512 tiles)."); def_mmio!(0x0600_0000 = CHARBLOCK0_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 0, 8bpp view (256 tiles)."); def_mmio!(0x0600_4000 = CHARBLOCK1_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 1, 8bpp view (256 tiles)."); def_mmio!(0x0600_8000 = CHARBLOCK2_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 2, 8bpp view (256 tiles)."); def_mmio!(0x0600_C000 = CHARBLOCK3_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 3, 8bpp view (256 tiles)."); def_mmio!(0x0600_0000 = TEXT_SCREENBLOCKS: VolGrid2dStrided<TextEntry, Safe, Safe, 32, 32, 32, SCREENBLOCK_INDEX_OFFSET>; "Text mode screenblocks."); def_mmio!(0x0600_0000 = AFFINE0_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 8, 16, 32, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 0)."); def_mmio!(0x0600_0000 = AFFINE1_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 16, 32, 32, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 1)."); def_mmio!(0x0600_0000 = AFFINE2_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 32, 64, 31, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 2)."); def_mmio!(0x0600_0000 = AFFINE3_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 64, 128, 25, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 3)."); def_mmio!(0x0600_0000 = VIDEO3_VRAM: VolGrid2dStrided<Color, Safe, Safe, 240, 160, 2, 0xA000>; "Video mode 3 bitmap"); def_mmio!(0x0600_0000 = VIDEO4_VRAM: VolGrid2dStrided<u8x2, Safe, Safe, 120, 160, 2, 0xA000>; "Video mode 4 palette maps (frames 0 and 1). Each entry is two palette indexes."); def_mmio!(0x0600_0000 = VIDEO5_VRAM: VolGrid2dStrided<Color, Safe, Safe, 160, 128, 2, 0xA000>; "Video mode 5 bitmaps (frames 0 and 1)."); def_mmio!(0x0601_0000 = OBJ_TILES: VolBlock<Tile4, Safe, Safe, 1024>; "Object tiles. In video modes 3, 4, and 5 only indices 512..=1023 are available."); // Object Attribute Memory (OAM) def_mmio!(0x0700_0000 = OBJ_ATTR0: VolSeries<ObjAttr0, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 0."); def_mmio!(0x0700_0002 = OBJ_ATTR1: VolSeries<ObjAttr1, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 1."); def_mmio!(0x0700_0004 = OBJ_ATTR2: VolSeries<ObjAttr2, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 2."); def_mmio!(0x0700_0000 = OBJ_ATTR_ALL: VolSeries<ObjAttr, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes (all in one)."); def_mmio!(0x0700_0006 = AFFINE_PARAM_A: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters A."); def_mmio!(0x0700_000E = AFFINE_PARAM_B: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters B."); def_mmio!(0x0700_0016 = AFFINE_PARAM_C: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters C."); def_mmio!(0x0700_001E = AFFINE_PARAM_D: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters D."); // Cartridge IO port // https://problemkaputt.de/gbatek.htm#gbacartioportgpio def_mmio!(0x0800_00C4 = IO_PORT_DATA: VolAddress<u16, Safe, Safe>; "I/O port data"); def_mmio!(0x0800_00C6 = IO_PORT_DIRECTION: VolAddress<u16, Safe, Safe>; "I/O port direction"); def_mmio!(0x0800_00C8 = IO_PORT_CONTROL: VolAddress<u16, Safe, Safe>; "I/O port control");
{ let u = BG_PALETTE.index(bank * 16).as_usize(); unsafe { VolBlock::new(u) } }
identifier_body
mmio.rs
#![cfg_attr(rustfmt, rustfmt::skip)] //! Contains all the MMIO address definitions for the GBA's components. //! //! This module contains *only* the MMIO addresses. The data type definitions //! for each MMIO control value are stored in the appropriate other modules such //! as [`video`](crate::video), [`interrupts`](crate::interrupts), etc. //! //! In general, the docs for each address are quite short. If you want to //! understand how a subsystem of the GBA works, you should read the docs for //! that system's module, and the data type used by the address. //! //! The GBATEK names (and thus mGBA names) are used for the MMIO addresses by //! default. However, in some cases (eg: sound) the GBATEK naming is excessively //! cryptic, and so new names have been created. Whenever a new name is used, //! the GBATEK name is still listed as a doc alias for that address. If //! necessary you can just search the GBATEK name in the rustdoc search bar and //! the search results will show you the new name. //! //! ## Safety //! //! The MMIO declarations and wrapper types in this module **must not** be used //! outside of a GBA. The read and write safety of each address are declared //! assuming that code is running on a GBA. On any other platform, the //! declarations are simply incorrect. use core::{ffi::c_void, mem::size_of}; use bitfrob::u8x2; use voladdress::{Safe, Unsafe, VolAddress, VolBlock, VolSeries, VolGrid2dStrided}; use crate::prelude::*; // Note(Lokathor): This macro lets us stick each address at the start of the // definition, which lets us easily keep each declaration in address order. macro_rules! def_mmio { ($addr:literal = $name:ident : $t:ty $(; $comment:expr )?) => { // redirect a call **without** an alias list to just pass an empty alias list def_mmio!($addr = $name/[]: $t $(; $comment)? ); }; ($addr:literal = $name:ident / [ $( $alias:literal ),* ]: $t:ty $(; $comment:expr )?) => { $(#[doc = $comment])? $(#[doc(alias = $alias)])* #[allow(missing_docs)] pub const $name: $t = unsafe { <$t>::new($addr) }; }; } // Video def_mmio!(0x0400_0000 = DISPCNT: VolAddress<DisplayControl, Safe, Safe>; "Display Control"); def_mmio!(0x0400_0004 = DISPSTAT: VolAddress<DisplayStatus, Safe, Safe>; "Display Status"); def_mmio!(0x0400_0006 = VCOUNT: VolAddress<u16, Safe, ()>; "Vertical Counter"); def_mmio!(0x0400_0008 = BG0CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 0 Control"); def_mmio!(0x0400_000A = BG1CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 1 Control"); def_mmio!(0x0400_000C = BG2CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 2 Control"); def_mmio!(0x0400_000E = BG3CNT: VolAddress<BackgroundControl, Safe, Safe>; "Background 3 Control"); def_mmio!(0x0400_0010 = BG0HOFS: VolAddress<u16, (), Safe>; "Background 0 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_0012 = BG0VOFS: VolAddress<u16, (), Safe>; "Background 0 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0014 = BG1HOFS: VolAddress<u16, (), Safe>; "Background 1 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_0016 = BG1VOFS: VolAddress<u16, (), Safe>; "Background 1 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0018 = BG2HOFS: VolAddress<u16, (), Safe>; "Background 2 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_001A = BG2VOFS: VolAddress<u16, (), Safe>; "Background 2 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_001C = BG3HOFS: VolAddress<u16, (), Safe>; "Background 3 Horizontal Offset (9-bit, text mode)"); def_mmio!(0x0400_001E = BG3VOFS: VolAddress<u16, (), Safe>; "Background 3 Vertical Offset (9-bit, text mode)"); def_mmio!(0x0400_0020 = BG2PA: VolAddress<i16fx8, (), Safe>; "Background 2 Param A (affine mode)"); def_mmio!(0x0400_0022 = BG2PB: VolAddress<i16fx8, (), Safe>; "Background 2 Param B (affine mode)"); def_mmio!(0x0400_0024 = BG2PC: VolAddress<i16fx8, (), Safe>; "Background 2 Param C (affine mode)"); def_mmio!(0x0400_0026 = BG2PD: VolAddress<i16fx8, (), Safe>; "Background 2 Param D (affine mode)"); def_mmio!(0x0400_0028 = BG2X/["BG2X_L", "BG2X_H"]: VolAddress<i32fx8, (), Safe>; "Background 2 X Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_002C = BG2Y/["BG2Y_L", "BG2Y_H"]: VolAddress<i32fx8, (), Safe>; "Background 2 Y Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_0030 = BG3PA: VolAddress<i16fx8, (), Safe>; "Background 3 Param A (affine mode)"); def_mmio!(0x0400_0032 = BG3PB: VolAddress<i16fx8, (), Safe>; "Background 3 Param B (affine mode)"); def_mmio!(0x0400_0034 = BG3PC: VolAddress<i16fx8, (), Safe>; "Background 3 Param C (affine mode)"); def_mmio!(0x0400_0036 = BG3PD: VolAddress<i16fx8, (), Safe>; "Background 3 Param D (affine mode)"); def_mmio!(0x0400_0038 = BG3X/["BG3X_L", "BG3X_H"]: VolAddress<i32fx8, (), Safe>; "Background 3 X Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_003C = BG3Y/["BG3Y_L", "BG3Y_H"]: VolAddress<i32fx8, (), Safe>; "Background 3 Y Reference Point (affine/bitmap modes)"); def_mmio!(0x0400_0040 = WIN0H: VolAddress<u8x2, (), Safe>; "Window 0 Horizontal: high=left, low=(right+1)"); def_mmio!(0x0400_0042 = WIN1H: VolAddress<u8x2, (), Safe>; "Window 1 Horizontal: high=left, low=(right+1)"); def_mmio!(0x0400_0044 = WIN0V: VolAddress<u8x2, (), Safe>; "Window 0 Vertical: high=top, low=(bottom+1)"); def_mmio!(0x0400_0046 = WIN1V: VolAddress<u8x2, (), Safe>; "Window 1 Vertical: high=top, low=(bottom+1)"); def_mmio!(0x0400_0048 = WININ: VolAddress<WindowInside, Safe, Safe>; "Controls the inside Windows 0 and 1"); def_mmio!(0x0400_004A = WINOUT: VolAddress<WindowOutside, Safe, Safe>; "Controls inside the object window and outside of windows"); def_mmio!(0x0400_004C = MOSAIC: VolAddress<Mosaic, (), Safe>; "Sets the intensity of all mosaic effects"); def_mmio!(0x0400_0050 = BLDCNT: VolAddress<BlendControl, Safe, Safe>; "Sets color blend effects"); def_mmio!(0x0400_0052 = BLDALPHA: VolAddress<u8x2, Safe, Safe>;"Sets EVA(low) and EVB(high) alpha blend coefficients, allows `0..=16`, in 1/16th units"); def_mmio!(0x0400_0054 = BLDY: VolAddress<u8, (), Safe>;"Sets EVY brightness blend coefficient, allows `0..=16`, in 1/16th units"); // Sound def_mmio!(0x0400_0060 = TONE1_SWEEP/["SOUND1CNT_L","NR10"]: VolAddress<SweepControl, Safe, Safe>; "Tone 1 Sweep"); def_mmio!(0x0400_0062 = TONE1_PATTERN/["SOUND1CNT_H","NR11","NR12"]: VolAddress<TonePattern, Safe, Safe>; "Tone 1 Duty/Len/Envelope"); def_mmio!(0x0400_0064 = TONE1_FREQUENCY/["SOUND1CNT_X","NR13","NR14"]: VolAddress<ToneFrequency, Safe, Safe>; "Tone 1 Frequency/Control"); def_mmio!(0x0400_0068 = TONE2_PATTERN/["SOUND2CNT_L","NR21","NR22"]: VolAddress<TonePattern, Safe, Safe>; "Tone 2 Duty/Len/Envelope"); def_mmio!(0x0400_006C = TONE2_FREQUENCY/["SOUND2CNT_H","NR23","NR24"]: VolAddress<ToneFrequency, Safe, Safe>; "Tone 2 Frequency/Control"); def_mmio!(0x0400_0070 = WAVE_BANK/["SOUND3CNT_L","NR30"]: VolAddress<WaveBank, Safe, Safe>; "Wave banking controls"); def_mmio!(0x0400_0072 = WAVE_LEN_VOLUME/["SOUND3CNT_H","NR31","NR32"]: VolAddress<WaveLenVolume, Safe, Safe>; "Wave Length/Volume"); def_mmio!(0x0400_0074 = WAVE_FREQ/["SOUND3CNT_X","NR33","NR34"]: VolAddress<WaveFrequency, Safe, Safe>; "Wave Frequency/Control"); def_mmio!(0x0400_0078 = NOISE_LEN_ENV/["SOUND4CNT_L","NR41","NR42"]: VolAddress<NoiseLenEnvelope, Safe, Safe>; "Noise Length/Envelope"); def_mmio!(0x0400_007C = NOISE_FREQ/["SOUND4CNT_H","NR43","NR44"]: VolAddress<NoiseFrequency, Safe, Safe>; "Noise Frequency/Control"); def_mmio!(0x0400_0080 = LEFT_RIGHT_VOLUME/["SOUNDCNT_L","NR50","NR51"]: VolAddress<LeftRightVolume, Safe, Safe>;"Left/Right sound control (but GBAs only have one speaker each)."); def_mmio!(0x0400_0082 = SOUND_MIX/["SOUNDCNT_H"]: VolAddress<SoundMix, Safe, Safe>;"Mixes sound sources out to the left and right"); def_mmio!(0x0400_0084 = SOUND_ENABLED/["SOUNDCNT_X"]: VolAddress<SoundEnable, Safe, Safe>;"Sound active flags (r), as well as the sound primary enable (rw)."); def_mmio!(0x0400_0088 = SOUNDBIAS: VolAddress<SoundBias, Safe, Safe>;"Provides a bias to set the 'middle point' of sound output."); def_mmio!(0x0400_0090 = WAVE_RAM/["WAVE_RAM0_L","WAVE_RAM0_H","WAVE_RAM1_L","WAVE_RAM1_H","WAVE_RAM2_L","WAVE_RAM2_H","WAVE_RAM3_L","WAVE_RAM3_H"]: VolBlock<u32, Safe, Safe, 4>; "Wave memory, `u4`, plays MSB/LSB per byte."); def_mmio!(0x0400_00A0 = FIFO_A/["FIFO_A_L", "FIFO_A_H"]: VolAddress<u32, (), Safe>; "Pushes 4 `i8` samples into the Sound A buffer.\n\nThe buffer is 32 bytes max, playback is LSB first."); def_mmio!(0x0400_00A4 = FIFO_B/["FIFO_B_L", "FIFO_B_H"]: VolAddress<u32, (), Safe>; "Pushes 4 `i8` samples into the Sound B buffer.\n\nThe buffer is 32 bytes max, playback is LSB first."); // DMA def_mmio!(0x0400_00B0 = DMA0_SRC/["DMA0SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA0 Source Address (internal memory only)"); def_mmio!(0x0400_00B4 = DMA0_DEST/["DMA0DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA0 Destination Address (internal memory only)"); def_mmio!(0x0400_00B8 = DMA0_COUNT/["DMA0CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA0 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00BA = DMA0_CONTROL/["DMA0_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA0 Control Bits"); def_mmio!(0x0400_00BC = DMA1_SRC/["DMA1SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA1 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00C0 = DMA1_DEST/["DMA1DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA1 Destination Address (internal memory only)"); def_mmio!(0x0400_00C4 = DMA1_COUNT/["DMA1CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA1 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00C6 = DMA1_CONTROL/["DMA1_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA1 Control Bits"); def_mmio!(0x0400_00C8 = DMA2_SRC/["DMA2SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA2 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00CC = DMA2_DEST/["DMA2DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA2 Destination Address (internal memory only)"); def_mmio!(0x0400_00D0 = DMA2_COUNT/["DMA2CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA2 Transfer Count (14-bit, 0=max)"); def_mmio!(0x0400_00D2 = DMA2_CONTROL/["DMA2_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA2 Control Bits"); def_mmio!(0x0400_00D4 = DMA3_SRC/["DMA3SAD"]: VolAddress<*const c_void, (), Unsafe>; "DMA3 Source Address (non-SRAM memory)"); def_mmio!(0x0400_00D8 = DMA3_DEST/["DMA3DAD"]: VolAddress<*mut c_void, (), Unsafe>; "DMA3 Destination Address (non-SRAM memory)"); def_mmio!(0x0400_00DC = DMA3_COUNT/["DMA3CNT_L"]: VolAddress<u16, (), Unsafe>; "DMA3 Transfer Count (16-bit, 0=max)"); def_mmio!(0x0400_00DE = DMA3_CONTROL/["DMA3_CNT_H"]: VolAddress<DmaControl, Safe, Unsafe>; "DMA3 Control Bits"); // Timers def_mmio!(0x0400_0100 = TIMER0_COUNT/["TM0CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 0 Count read"); def_mmio!(0x0400_0100 = TIMER0_RELOAD/["TM0CNT_L"]: VolAddress<u16, (), Safe>; "Timer 0 Reload write"); def_mmio!(0x0400_0102 = TIMER0_CONTROL/["TM0CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 0 control"); def_mmio!(0x0400_0104 = TIMER1_COUNT/["TM1CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 1 Count read"); def_mmio!(0x0400_0104 = TIMER1_RELOAD/["TM1CNT_L"]: VolAddress<u16, (), Safe>; "Timer 1 Reload write"); def_mmio!(0x0400_0106 = TIMER1_CONTROL/["TM1CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 1 control"); def_mmio!(0x0400_0108 = TIMER2_COUNT/["TM2CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 2 Count read"); def_mmio!(0x0400_0108 = TIMER2_RELOAD/["TM2CNT_L"]: VolAddress<u16, (), Safe>; "Timer 2 Reload write"); def_mmio!(0x0400_010A = TIMER2_CONTROL/["TM2CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 2 control"); def_mmio!(0x0400_010C = TIMER3_COUNT/["TM3CNT_L"]: VolAddress<u16, Safe, ()>; "Timer 3 Count read"); def_mmio!(0x0400_010C = TIMER3_RELOAD/["TM3CNT_L"]: VolAddress<u16, (), Safe>; "Timer 3 Reload write"); def_mmio!(0x0400_010E = TIMER3_CONTROL/["TM3CNT_H"]: VolAddress<TimerControl, Safe, Safe>; "Timer 3 control"); // Serial (part 1) def_mmio!(0x0400_0120 = SIODATA32: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0120 = SIOMULTI0: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0122 = SIOMULTI1: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0124 = SIOMULTI2: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0126 = SIOMULTI3: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0128 = SIOCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_012A = SIOMLT_SEND: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_012A = SIODATA8: VolAddress<u8, Safe, Safe>); // Keys def_mmio!(0x0400_0130 = KEYINPUT: VolAddress<KeyInput, Safe, ()>; "Key state data."); def_mmio!(0x0400_0132 = KEYCNT: VolAddress<KeyControl, Safe, Safe>; "Key control to configure the key interrupt."); // Serial (part 2) def_mmio!(0x0400_0134 = RCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0140 = JOYCNT: VolAddress<u16, Safe, Safe>); def_mmio!(0x0400_0150 = JOY_RECV: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0154 = JOY_TRANS: VolAddress<u32, Safe, Safe>); def_mmio!(0x0400_0158 = JOYSTAT: VolAddress<u8, Safe, Safe>); // Interrupts def_mmio!(0x0400_0200 = IE: VolAddress<IrqBits, Safe, Safe>; "Interrupts Enabled: sets which interrupts will be accepted when a subsystem fires an interrupt"); def_mmio!(0x0400_0202 = IF: VolAddress<IrqBits, Safe, Safe>; "Interrupts Flagged: reads which interrupts are pending, writing bit(s) will clear a pending interrupt."); def_mmio!(0x0400_0204 = WAITCNT: VolAddress<u16, Safe, Unsafe>; "Wait state control for interfacing with the ROM.\n\nThis can make reading the ROM give garbage when it's mis-configured!"); def_mmio!(0x0400_0208 = IME: VolAddress<bool, Safe, Safe>; "Interrupt Master Enable: Allows turning on/off all interrupts with a single access."); // mGBA Logging def_mmio!(0x04FF_F600 = MGBA_LOG_BUFFER: VolBlock<u8, Safe, Safe, 256>; "The buffer to put logging messages into.\n\nThe first 0 in the buffer is the end of each message."); def_mmio!(0x04FF_F700 = MGBA_LOG_SEND: VolAddress<MgbaMessageLevel, (), Safe>; "Write to this each time you want to reset a message (it also resets the buffer)."); def_mmio!(0x04FF_F780 = MGBA_LOG_ENABLE: VolAddress<u16, Safe, Safe>; "Allows you to attempt to activate mGBA logging."); // Palette RAM (PALRAM) def_mmio!(0x0500_0000 = BACKDROP_COLOR: VolAddress<Color, Safe, Safe>; "Color that's shown when no BG or OBJ draws to a pixel"); def_mmio!(0x0500_0000 = BG_PALETTE: VolBlock<Color, Safe, Safe, 256>; "Background tile palette entries."); def_mmio!(0x0500_0200 = OBJ_PALETTE: VolBlock<Color, Safe, Safe, 256>; "Object tile palette entries."); #[inline] #[must_use] #[cfg_attr(feature="track_caller", track_caller)] pub const fn bg_palbank(bank: usize) -> VolBlock<Color, Safe, Safe, 16> { let u = BG_PALETTE.index(bank * 16).as_usize(); unsafe { VolBlock::new(u) } } #[inline] #[must_use] #[cfg_attr(feature="track_caller", track_caller)] pub const fn
(bank: usize) -> VolBlock<Color, Safe, Safe, 16> { let u = OBJ_PALETTE.index(bank * 16).as_usize(); unsafe { VolBlock::new(u) } } // Video RAM (VRAM) /// The VRAM byte offset per screenblock index. /// /// This is the same for all background types and sizes. pub const SCREENBLOCK_INDEX_OFFSET: usize = 2 * 1_024; /// The size of the background tile region of VRAM. /// /// Background tile index use will work between charblocks, but not past the end /// of BG tile memory into OBJ tile memory. pub const BG_TILE_REGION_SIZE: usize = 64 * 1_024; def_mmio!(0x0600_0000 = CHARBLOCK0_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 0, 4bpp view (512 tiles)."); def_mmio!(0x0600_4000 = CHARBLOCK1_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 1, 4bpp view (512 tiles)."); def_mmio!(0x0600_8000 = CHARBLOCK2_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 2, 4bpp view (512 tiles)."); def_mmio!(0x0600_C000 = CHARBLOCK3_4BPP: VolBlock<Tile4, Safe, Safe, 512>; "Charblock 3, 4bpp view (512 tiles)."); def_mmio!(0x0600_0000 = CHARBLOCK0_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 0, 8bpp view (256 tiles)."); def_mmio!(0x0600_4000 = CHARBLOCK1_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 1, 8bpp view (256 tiles)."); def_mmio!(0x0600_8000 = CHARBLOCK2_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 2, 8bpp view (256 tiles)."); def_mmio!(0x0600_C000 = CHARBLOCK3_8BPP: VolBlock<Tile8, Safe, Safe, 256>; "Charblock 3, 8bpp view (256 tiles)."); def_mmio!(0x0600_0000 = TEXT_SCREENBLOCKS: VolGrid2dStrided<TextEntry, Safe, Safe, 32, 32, 32, SCREENBLOCK_INDEX_OFFSET>; "Text mode screenblocks."); def_mmio!(0x0600_0000 = AFFINE0_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 8, 16, 32, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 0)."); def_mmio!(0x0600_0000 = AFFINE1_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 16, 32, 32, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 1)."); def_mmio!(0x0600_0000 = AFFINE2_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 32, 64, 31, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 2)."); def_mmio!(0x0600_0000 = AFFINE3_SCREENBLOCKS: VolGrid2dStrided<u8x2, Safe, Safe, 64, 128, 25, SCREENBLOCK_INDEX_OFFSET>; "Affine screenblocks (size 3)."); def_mmio!(0x0600_0000 = VIDEO3_VRAM: VolGrid2dStrided<Color, Safe, Safe, 240, 160, 2, 0xA000>; "Video mode 3 bitmap"); def_mmio!(0x0600_0000 = VIDEO4_VRAM: VolGrid2dStrided<u8x2, Safe, Safe, 120, 160, 2, 0xA000>; "Video mode 4 palette maps (frames 0 and 1). Each entry is two palette indexes."); def_mmio!(0x0600_0000 = VIDEO5_VRAM: VolGrid2dStrided<Color, Safe, Safe, 160, 128, 2, 0xA000>; "Video mode 5 bitmaps (frames 0 and 1)."); def_mmio!(0x0601_0000 = OBJ_TILES: VolBlock<Tile4, Safe, Safe, 1024>; "Object tiles. In video modes 3, 4, and 5 only indices 512..=1023 are available."); // Object Attribute Memory (OAM) def_mmio!(0x0700_0000 = OBJ_ATTR0: VolSeries<ObjAttr0, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 0."); def_mmio!(0x0700_0002 = OBJ_ATTR1: VolSeries<ObjAttr1, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 1."); def_mmio!(0x0700_0004 = OBJ_ATTR2: VolSeries<ObjAttr2, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes 2."); def_mmio!(0x0700_0000 = OBJ_ATTR_ALL: VolSeries<ObjAttr, Safe, Safe, 128, {size_of::<[u16;4]>()}>; "Object attributes (all in one)."); def_mmio!(0x0700_0006 = AFFINE_PARAM_A: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters A."); def_mmio!(0x0700_000E = AFFINE_PARAM_B: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters B."); def_mmio!(0x0700_0016 = AFFINE_PARAM_C: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters C."); def_mmio!(0x0700_001E = AFFINE_PARAM_D: VolSeries<i16fx8, Safe, Safe, 32, {size_of::<[u16;16]>()}>; "Affine parameters D."); // Cartridge IO port // https://problemkaputt.de/gbatek.htm#gbacartioportgpio def_mmio!(0x0800_00C4 = IO_PORT_DATA: VolAddress<u16, Safe, Safe>; "I/O port data"); def_mmio!(0x0800_00C6 = IO_PORT_DIRECTION: VolAddress<u16, Safe, Safe>; "I/O port direction"); def_mmio!(0x0800_00C8 = IO_PORT_CONTROL: VolAddress<u16, Safe, Safe>; "I/O port control");
obj_palbank
identifier_name
domain_models.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. import re import structlog from flask import current_app from inspire_service_orcid import exceptions as orcid_client_exceptions from inspire_service_orcid.client import OrcidClient from invenio_db import db from invenio_pidstore.errors import PIDDoesNotExistError from time_execution import time_execution from inspirehep.records.api import LiteratureRecord from inspirehep.utils import distributed_lock from . import exceptions, push_access_tokens, utils from .cache import OrcidCache from .converter import OrcidConverter from .putcode_getter import OrcidPutcodeGetter LOGGER = structlog.getLogger() ORCID_REGEX = r"\d{4}-\d{4}-\d{4}-\d{3}[0-9X]" class OrcidPusher(object): def
( self, orcid, recid, oauth_token, pushing_duplicated_identifier=False, record_db_version=None, ): self.orcid = orcid self.recid = str(recid) self.oauth_token = oauth_token self.pushing_duplicated_identifier = pushing_duplicated_identifier self.record_db_version = record_db_version self.inspire_record = self._get_inspire_record() self.cache = OrcidCache(orcid, recid) self.lock_name = "orcid:{}".format(self.orcid) self.client = OrcidClient(self.oauth_token, self.orcid) self.converter = None self.cached_author_putcodes = {} @time_execution def _get_inspire_record(self): try: inspire_record = LiteratureRecord.get_record_by_pid_value( self.recid, original_record=True ) except PIDDoesNotExistError as exc: raise exceptions.RecordNotFoundException( "recid={} not found for pid_type=lit".format(self.recid), from_exc=exc ) # If the record_db_version was given, then ensure we are about to push # the right record version. # This check is related to the fact the orcid push at this moment is # triggered by the signal after_record_update (which happens after a # InspireRecord.commit()). This is not the actual commit to the db which # might happen at a later stage or not at all. # Note that connecting to the proper SQLAlchemy signal would also # have issues: https://github.com/mitsuhiko/flask-sqlalchemy/issues/645 if ( self.record_db_version and inspire_record.model.version_id < self.record_db_version ): raise exceptions.StaleRecordDBVersionException( "Requested push for db version={}, but actual record db" " version={}".format( self.record_db_version, inspire_record.model.version_id ) ) return inspire_record @property def _do_force_cache_miss(self): """ Hook to force a cache miss. This can be leveraged in feature tests. """ for note in self.inspire_record.get("_private_notes", []): if note.get("value") == "orcid-push-force-cache-miss": LOGGER.debug( "OrcidPusher force cache miss", recid=self.recid, orcid=self.orcid ) return True return False @property def _is_record_deleted(self): # Hook to force a delete. This can be leveraged in feature tests. for note in self.inspire_record.get("_private_notes", []): if note.get("value") == "orcid-push-force-delete": LOGGER.debug( "OrcidPusher force delete", recid=self.recid, orcid=self.orcid ) return True return self.inspire_record.get("deleted", False) @time_execution def push(self): # noqa: C901 putcode = None if not self._do_force_cache_miss: putcode = self.cache.read_work_putcode() if not self._is_record_deleted and not self.cache.has_work_content_changed( self.inspire_record ): LOGGER.debug( "OrcidPusher cache hit", recid=self.recid, orcid=self.orcid ) return putcode LOGGER.debug("OrcidPusher cache miss", recid=self.recid, orcid=self.orcid) # If the record is deleted, then delete it. if self._is_record_deleted: self._delete_work(putcode) return None self.converter = OrcidConverter( record=self.inspire_record, url_pattern=current_app.config["LEGACY_RECORD_URL_PATTERN"], put_code=putcode, ) try: putcode = self._post_or_put_work(putcode) except orcid_client_exceptions.WorkAlreadyExistsException: # We POSTed the record as new work, but it failed because # a work with the same identifier is already in ORCID. # This can mean two things: # 1. the record itself is already in ORCID, but we don't have the putcode; # 2. a different record with the same external identifier is already in ORCID. # We first try to fix 1. by caching all author's putcodes and PUT the work again. # If the putcode wasn't found we are probably facing case 2. # so we try to push once again works with clashing identifiers # to update them and resolve the potential conflict. if self.pushing_duplicated_identifier: raise exceptions.DuplicatedExternalIdentifierPusherException putcode = self._cache_all_author_putcodes() if not putcode: try: self._push_work_with_clashing_identifier() putcode = self._post_or_put_work(putcode) except orcid_client_exceptions.WorkAlreadyExistsException: # The PUT/POST failed despite pushing works with clashing identifiers # and we can't do anything about this. raise exceptions.DuplicatedExternalIdentifierPusherException else: self._post_or_put_work(putcode) except orcid_client_exceptions.DuplicatedExternalIdentifierException: # We PUT a record changing its identifier, but there is another work # in ORCID with the same identifier. We need to find out the recid # of the clashing work in ORCID and push a fresh version of that # record. # This scenario might be triggered by a merge of 2 records in Inspire. if not self.pushing_duplicated_identifier: self._push_work_with_clashing_identifier() # Raised exception will cause retry of celery task raise exceptions.DuplicatedExternalIdentifierPusherException except orcid_client_exceptions.PutcodeNotFoundPutException: # We try to push the work with invalid putcode, so we delete # its putcode and push it without any putcode. # If it turns out that the record already exists # in ORCID we search for the putcode by caching # all author's putcodes and PUT the work again. self.cache.delete_work_putcode() self.converter = OrcidConverter( record=self.inspire_record, url_pattern=current_app.config["LEGACY_RECORD_URL_PATTERN"], put_code=None, ) putcode = self._cache_all_author_putcodes() putcode = self._post_or_put_work(putcode) except ( orcid_client_exceptions.TokenInvalidException, orcid_client_exceptions.TokenMismatchException, orcid_client_exceptions.TokenWithWrongPermissionException, ): LOGGER.info( "Deleting Orcid push access", token=self.oauth_token, orcid=self.orcid ) push_access_tokens.delete_access_token(self.oauth_token, self.orcid) db.session.commit() raise exceptions.TokenInvalidDeletedException except orcid_client_exceptions.MovedPermanentlyException as exc: old_orcid, new_orcid = re.findall(ORCID_REGEX, exc.args[0]) utils.update_moved_orcid(old_orcid, new_orcid) raise except orcid_client_exceptions.BaseOrcidClientJsonException as exc: raise exceptions.InputDataInvalidException(from_exc=exc) self.cache.write_work_putcode(putcode, self.inspire_record) return putcode @time_execution def _post_or_put_work(self, putcode=None): # Note: if putcode is None, then it's a POST (it means the work is new). # Otherwise a PUT (it means the work already exists and it has the given # putcode). xml_element = self.converter.get_xml(do_add_bibtex_citation=True) # ORCID API allows 1 non-idempotent call only for the same orcid at # the same time. Using `distributed_lock` to achieve this. with distributed_lock(self.lock_name, blocking=True): if putcode: response = self.client.put_updated_work(xml_element, putcode) else: response = self.client.post_new_work(xml_element) LOGGER.info("POST/PUT ORCID work", recid=self.recid) response.raise_for_result() return response["putcode"] def _delete_works_with_duplicated_putcodes(self, cached_putcodes_recids): unique_recids_putcodes = {} for fetched_putcode, fetched_recid in cached_putcodes_recids: if fetched_recid in unique_recids_putcodes: self._delete_work(fetched_putcode) else: unique_recids_putcodes[fetched_recid] = fetched_putcode return unique_recids_putcodes @time_execution def _cache_all_author_putcodes(self): LOGGER.debug("New OrcidPusher cache all author putcodes", orcid=self.orcid) if not self.cached_author_putcodes: putcode_getter = OrcidPutcodeGetter(self.orcid, self.oauth_token) putcodes_recids = list( putcode_getter.get_all_inspire_putcodes_and_recids_iter() ) self.cached_author_putcodes = self._delete_works_with_duplicated_putcodes( putcodes_recids ) putcode = None for fetched_recid, fetched_putcode in self.cached_author_putcodes.items(): if fetched_recid == self.recid: putcode = int(fetched_putcode) cache = OrcidCache(self.orcid, fetched_recid) cache.write_work_putcode(fetched_putcode) # Ensure the putcode is actually in cache. # Note: this step is not really necessary and it can be skipped, but # at this moment it helps isolate a potential issue. if putcode and not self.cache.read_work_putcode(): raise exceptions.PutcodeNotFoundInCacheAfterCachingAllPutcodes( "No putcode={} found in cache for recid={} after having" " cached all author putcodes for orcid={}".format( self.putcode, self.recid, self.orcid ) ) return putcode @time_execution def _delete_work(self, putcode=None): putcode = putcode or self._cache_all_author_putcodes() if not putcode: # Such recid does not exists (anymore?) in ORCID API. return # ORCID API allows 1 non-idempotent call only for the same orcid at # the same time. Using `distributed_lock` to achieve this. with distributed_lock(self.lock_name, blocking=True): response = self.client.delete_work(putcode) try: response.raise_for_result() except orcid_client_exceptions.PutcodeNotFoundDeleteException: # Such putcode does not exists (anymore?) in orcid. pass except orcid_client_exceptions.BaseOrcidClientJsonException as exc: raise exceptions.InputDataInvalidException(from_exc=exc) self.cache.delete_work_putcode() @time_execution def _push_work_with_clashing_identifier(self): putcode_getter = OrcidPutcodeGetter(self.orcid, self.oauth_token) ids = self.converter.added_external_identifiers putcodes_recids = putcode_getter.get_putcodes_and_recids_by_identifiers_iter( ids ) updated_putcodes_recid = self._delete_works_with_duplicated_putcodes( putcodes_recids ) for (recid, putcode) in updated_putcodes_recid.items(): if not putcode or not recid: continue if recid == self.recid: continue # Local import to avoid import error. from inspirehep.orcid import tasks tasks.orcid_push( self.orcid, recid, self.oauth_token, dict( pushing_duplicated_identifier=True, ), )
__init__
identifier_name
domain_models.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details.
from flask import current_app from inspire_service_orcid import exceptions as orcid_client_exceptions from inspire_service_orcid.client import OrcidClient from invenio_db import db from invenio_pidstore.errors import PIDDoesNotExistError from time_execution import time_execution from inspirehep.records.api import LiteratureRecord from inspirehep.utils import distributed_lock from . import exceptions, push_access_tokens, utils from .cache import OrcidCache from .converter import OrcidConverter from .putcode_getter import OrcidPutcodeGetter LOGGER = structlog.getLogger() ORCID_REGEX = r"\d{4}-\d{4}-\d{4}-\d{3}[0-9X]" class OrcidPusher(object): def __init__( self, orcid, recid, oauth_token, pushing_duplicated_identifier=False, record_db_version=None, ): self.orcid = orcid self.recid = str(recid) self.oauth_token = oauth_token self.pushing_duplicated_identifier = pushing_duplicated_identifier self.record_db_version = record_db_version self.inspire_record = self._get_inspire_record() self.cache = OrcidCache(orcid, recid) self.lock_name = "orcid:{}".format(self.orcid) self.client = OrcidClient(self.oauth_token, self.orcid) self.converter = None self.cached_author_putcodes = {} @time_execution def _get_inspire_record(self): try: inspire_record = LiteratureRecord.get_record_by_pid_value( self.recid, original_record=True ) except PIDDoesNotExistError as exc: raise exceptions.RecordNotFoundException( "recid={} not found for pid_type=lit".format(self.recid), from_exc=exc ) # If the record_db_version was given, then ensure we are about to push # the right record version. # This check is related to the fact the orcid push at this moment is # triggered by the signal after_record_update (which happens after a # InspireRecord.commit()). This is not the actual commit to the db which # might happen at a later stage or not at all. # Note that connecting to the proper SQLAlchemy signal would also # have issues: https://github.com/mitsuhiko/flask-sqlalchemy/issues/645 if ( self.record_db_version and inspire_record.model.version_id < self.record_db_version ): raise exceptions.StaleRecordDBVersionException( "Requested push for db version={}, but actual record db" " version={}".format( self.record_db_version, inspire_record.model.version_id ) ) return inspire_record @property def _do_force_cache_miss(self): """ Hook to force a cache miss. This can be leveraged in feature tests. """ for note in self.inspire_record.get("_private_notes", []): if note.get("value") == "orcid-push-force-cache-miss": LOGGER.debug( "OrcidPusher force cache miss", recid=self.recid, orcid=self.orcid ) return True return False @property def _is_record_deleted(self): # Hook to force a delete. This can be leveraged in feature tests. for note in self.inspire_record.get("_private_notes", []): if note.get("value") == "orcid-push-force-delete": LOGGER.debug( "OrcidPusher force delete", recid=self.recid, orcid=self.orcid ) return True return self.inspire_record.get("deleted", False) @time_execution def push(self): # noqa: C901 putcode = None if not self._do_force_cache_miss: putcode = self.cache.read_work_putcode() if not self._is_record_deleted and not self.cache.has_work_content_changed( self.inspire_record ): LOGGER.debug( "OrcidPusher cache hit", recid=self.recid, orcid=self.orcid ) return putcode LOGGER.debug("OrcidPusher cache miss", recid=self.recid, orcid=self.orcid) # If the record is deleted, then delete it. if self._is_record_deleted: self._delete_work(putcode) return None self.converter = OrcidConverter( record=self.inspire_record, url_pattern=current_app.config["LEGACY_RECORD_URL_PATTERN"], put_code=putcode, ) try: putcode = self._post_or_put_work(putcode) except orcid_client_exceptions.WorkAlreadyExistsException: # We POSTed the record as new work, but it failed because # a work with the same identifier is already in ORCID. # This can mean two things: # 1. the record itself is already in ORCID, but we don't have the putcode; # 2. a different record with the same external identifier is already in ORCID. # We first try to fix 1. by caching all author's putcodes and PUT the work again. # If the putcode wasn't found we are probably facing case 2. # so we try to push once again works with clashing identifiers # to update them and resolve the potential conflict. if self.pushing_duplicated_identifier: raise exceptions.DuplicatedExternalIdentifierPusherException putcode = self._cache_all_author_putcodes() if not putcode: try: self._push_work_with_clashing_identifier() putcode = self._post_or_put_work(putcode) except orcid_client_exceptions.WorkAlreadyExistsException: # The PUT/POST failed despite pushing works with clashing identifiers # and we can't do anything about this. raise exceptions.DuplicatedExternalIdentifierPusherException else: self._post_or_put_work(putcode) except orcid_client_exceptions.DuplicatedExternalIdentifierException: # We PUT a record changing its identifier, but there is another work # in ORCID with the same identifier. We need to find out the recid # of the clashing work in ORCID and push a fresh version of that # record. # This scenario might be triggered by a merge of 2 records in Inspire. if not self.pushing_duplicated_identifier: self._push_work_with_clashing_identifier() # Raised exception will cause retry of celery task raise exceptions.DuplicatedExternalIdentifierPusherException except orcid_client_exceptions.PutcodeNotFoundPutException: # We try to push the work with invalid putcode, so we delete # its putcode and push it without any putcode. # If it turns out that the record already exists # in ORCID we search for the putcode by caching # all author's putcodes and PUT the work again. self.cache.delete_work_putcode() self.converter = OrcidConverter( record=self.inspire_record, url_pattern=current_app.config["LEGACY_RECORD_URL_PATTERN"], put_code=None, ) putcode = self._cache_all_author_putcodes() putcode = self._post_or_put_work(putcode) except ( orcid_client_exceptions.TokenInvalidException, orcid_client_exceptions.TokenMismatchException, orcid_client_exceptions.TokenWithWrongPermissionException, ): LOGGER.info( "Deleting Orcid push access", token=self.oauth_token, orcid=self.orcid ) push_access_tokens.delete_access_token(self.oauth_token, self.orcid) db.session.commit() raise exceptions.TokenInvalidDeletedException except orcid_client_exceptions.MovedPermanentlyException as exc: old_orcid, new_orcid = re.findall(ORCID_REGEX, exc.args[0]) utils.update_moved_orcid(old_orcid, new_orcid) raise except orcid_client_exceptions.BaseOrcidClientJsonException as exc: raise exceptions.InputDataInvalidException(from_exc=exc) self.cache.write_work_putcode(putcode, self.inspire_record) return putcode @time_execution def _post_or_put_work(self, putcode=None): # Note: if putcode is None, then it's a POST (it means the work is new). # Otherwise a PUT (it means the work already exists and it has the given # putcode). xml_element = self.converter.get_xml(do_add_bibtex_citation=True) # ORCID API allows 1 non-idempotent call only for the same orcid at # the same time. Using `distributed_lock` to achieve this. with distributed_lock(self.lock_name, blocking=True): if putcode: response = self.client.put_updated_work(xml_element, putcode) else: response = self.client.post_new_work(xml_element) LOGGER.info("POST/PUT ORCID work", recid=self.recid) response.raise_for_result() return response["putcode"] def _delete_works_with_duplicated_putcodes(self, cached_putcodes_recids): unique_recids_putcodes = {} for fetched_putcode, fetched_recid in cached_putcodes_recids: if fetched_recid in unique_recids_putcodes: self._delete_work(fetched_putcode) else: unique_recids_putcodes[fetched_recid] = fetched_putcode return unique_recids_putcodes @time_execution def _cache_all_author_putcodes(self): LOGGER.debug("New OrcidPusher cache all author putcodes", orcid=self.orcid) if not self.cached_author_putcodes: putcode_getter = OrcidPutcodeGetter(self.orcid, self.oauth_token) putcodes_recids = list( putcode_getter.get_all_inspire_putcodes_and_recids_iter() ) self.cached_author_putcodes = self._delete_works_with_duplicated_putcodes( putcodes_recids ) putcode = None for fetched_recid, fetched_putcode in self.cached_author_putcodes.items(): if fetched_recid == self.recid: putcode = int(fetched_putcode) cache = OrcidCache(self.orcid, fetched_recid) cache.write_work_putcode(fetched_putcode) # Ensure the putcode is actually in cache. # Note: this step is not really necessary and it can be skipped, but # at this moment it helps isolate a potential issue. if putcode and not self.cache.read_work_putcode(): raise exceptions.PutcodeNotFoundInCacheAfterCachingAllPutcodes( "No putcode={} found in cache for recid={} after having" " cached all author putcodes for orcid={}".format( self.putcode, self.recid, self.orcid ) ) return putcode @time_execution def _delete_work(self, putcode=None): putcode = putcode or self._cache_all_author_putcodes() if not putcode: # Such recid does not exists (anymore?) in ORCID API. return # ORCID API allows 1 non-idempotent call only for the same orcid at # the same time. Using `distributed_lock` to achieve this. with distributed_lock(self.lock_name, blocking=True): response = self.client.delete_work(putcode) try: response.raise_for_result() except orcid_client_exceptions.PutcodeNotFoundDeleteException: # Such putcode does not exists (anymore?) in orcid. pass except orcid_client_exceptions.BaseOrcidClientJsonException as exc: raise exceptions.InputDataInvalidException(from_exc=exc) self.cache.delete_work_putcode() @time_execution def _push_work_with_clashing_identifier(self): putcode_getter = OrcidPutcodeGetter(self.orcid, self.oauth_token) ids = self.converter.added_external_identifiers putcodes_recids = putcode_getter.get_putcodes_and_recids_by_identifiers_iter( ids ) updated_putcodes_recid = self._delete_works_with_duplicated_putcodes( putcodes_recids ) for (recid, putcode) in updated_putcodes_recid.items(): if not putcode or not recid: continue if recid == self.recid: continue # Local import to avoid import error. from inspirehep.orcid import tasks tasks.orcid_push( self.orcid, recid, self.oauth_token, dict( pushing_duplicated_identifier=True, ), )
import re import structlog
random_line_split
domain_models.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. import re import structlog from flask import current_app from inspire_service_orcid import exceptions as orcid_client_exceptions from inspire_service_orcid.client import OrcidClient from invenio_db import db from invenio_pidstore.errors import PIDDoesNotExistError from time_execution import time_execution from inspirehep.records.api import LiteratureRecord from inspirehep.utils import distributed_lock from . import exceptions, push_access_tokens, utils from .cache import OrcidCache from .converter import OrcidConverter from .putcode_getter import OrcidPutcodeGetter LOGGER = structlog.getLogger() ORCID_REGEX = r"\d{4}-\d{4}-\d{4}-\d{3}[0-9X]" class OrcidPusher(object): def __init__( self, orcid, recid, oauth_token, pushing_duplicated_identifier=False, record_db_version=None, ): self.orcid = orcid self.recid = str(recid) self.oauth_token = oauth_token self.pushing_duplicated_identifier = pushing_duplicated_identifier self.record_db_version = record_db_version self.inspire_record = self._get_inspire_record() self.cache = OrcidCache(orcid, recid) self.lock_name = "orcid:{}".format(self.orcid) self.client = OrcidClient(self.oauth_token, self.orcid) self.converter = None self.cached_author_putcodes = {} @time_execution def _get_inspire_record(self): try: inspire_record = LiteratureRecord.get_record_by_pid_value( self.recid, original_record=True ) except PIDDoesNotExistError as exc: raise exceptions.RecordNotFoundException( "recid={} not found for pid_type=lit".format(self.recid), from_exc=exc ) # If the record_db_version was given, then ensure we are about to push # the right record version. # This check is related to the fact the orcid push at this moment is # triggered by the signal after_record_update (which happens after a # InspireRecord.commit()). This is not the actual commit to the db which # might happen at a later stage or not at all. # Note that connecting to the proper SQLAlchemy signal would also # have issues: https://github.com/mitsuhiko/flask-sqlalchemy/issues/645 if ( self.record_db_version and inspire_record.model.version_id < self.record_db_version ): raise exceptions.StaleRecordDBVersionException( "Requested push for db version={}, but actual record db" " version={}".format( self.record_db_version, inspire_record.model.version_id ) ) return inspire_record @property def _do_force_cache_miss(self): """ Hook to force a cache miss. This can be leveraged in feature tests. """ for note in self.inspire_record.get("_private_notes", []): if note.get("value") == "orcid-push-force-cache-miss": LOGGER.debug( "OrcidPusher force cache miss", recid=self.recid, orcid=self.orcid ) return True return False @property def _is_record_deleted(self): # Hook to force a delete. This can be leveraged in feature tests. for note in self.inspire_record.get("_private_notes", []): if note.get("value") == "orcid-push-force-delete":
return self.inspire_record.get("deleted", False) @time_execution def push(self): # noqa: C901 putcode = None if not self._do_force_cache_miss: putcode = self.cache.read_work_putcode() if not self._is_record_deleted and not self.cache.has_work_content_changed( self.inspire_record ): LOGGER.debug( "OrcidPusher cache hit", recid=self.recid, orcid=self.orcid ) return putcode LOGGER.debug("OrcidPusher cache miss", recid=self.recid, orcid=self.orcid) # If the record is deleted, then delete it. if self._is_record_deleted: self._delete_work(putcode) return None self.converter = OrcidConverter( record=self.inspire_record, url_pattern=current_app.config["LEGACY_RECORD_URL_PATTERN"], put_code=putcode, ) try: putcode = self._post_or_put_work(putcode) except orcid_client_exceptions.WorkAlreadyExistsException: # We POSTed the record as new work, but it failed because # a work with the same identifier is already in ORCID. # This can mean two things: # 1. the record itself is already in ORCID, but we don't have the putcode; # 2. a different record with the same external identifier is already in ORCID. # We first try to fix 1. by caching all author's putcodes and PUT the work again. # If the putcode wasn't found we are probably facing case 2. # so we try to push once again works with clashing identifiers # to update them and resolve the potential conflict. if self.pushing_duplicated_identifier: raise exceptions.DuplicatedExternalIdentifierPusherException putcode = self._cache_all_author_putcodes() if not putcode: try: self._push_work_with_clashing_identifier() putcode = self._post_or_put_work(putcode) except orcid_client_exceptions.WorkAlreadyExistsException: # The PUT/POST failed despite pushing works with clashing identifiers # and we can't do anything about this. raise exceptions.DuplicatedExternalIdentifierPusherException else: self._post_or_put_work(putcode) except orcid_client_exceptions.DuplicatedExternalIdentifierException: # We PUT a record changing its identifier, but there is another work # in ORCID with the same identifier. We need to find out the recid # of the clashing work in ORCID and push a fresh version of that # record. # This scenario might be triggered by a merge of 2 records in Inspire. if not self.pushing_duplicated_identifier: self._push_work_with_clashing_identifier() # Raised exception will cause retry of celery task raise exceptions.DuplicatedExternalIdentifierPusherException except orcid_client_exceptions.PutcodeNotFoundPutException: # We try to push the work with invalid putcode, so we delete # its putcode and push it without any putcode. # If it turns out that the record already exists # in ORCID we search for the putcode by caching # all author's putcodes and PUT the work again. self.cache.delete_work_putcode() self.converter = OrcidConverter( record=self.inspire_record, url_pattern=current_app.config["LEGACY_RECORD_URL_PATTERN"], put_code=None, ) putcode = self._cache_all_author_putcodes() putcode = self._post_or_put_work(putcode) except ( orcid_client_exceptions.TokenInvalidException, orcid_client_exceptions.TokenMismatchException, orcid_client_exceptions.TokenWithWrongPermissionException, ): LOGGER.info( "Deleting Orcid push access", token=self.oauth_token, orcid=self.orcid ) push_access_tokens.delete_access_token(self.oauth_token, self.orcid) db.session.commit() raise exceptions.TokenInvalidDeletedException except orcid_client_exceptions.MovedPermanentlyException as exc: old_orcid, new_orcid = re.findall(ORCID_REGEX, exc.args[0]) utils.update_moved_orcid(old_orcid, new_orcid) raise except orcid_client_exceptions.BaseOrcidClientJsonException as exc: raise exceptions.InputDataInvalidException(from_exc=exc) self.cache.write_work_putcode(putcode, self.inspire_record) return putcode @time_execution def _post_or_put_work(self, putcode=None): # Note: if putcode is None, then it's a POST (it means the work is new). # Otherwise a PUT (it means the work already exists and it has the given # putcode). xml_element = self.converter.get_xml(do_add_bibtex_citation=True) # ORCID API allows 1 non-idempotent call only for the same orcid at # the same time. Using `distributed_lock` to achieve this. with distributed_lock(self.lock_name, blocking=True): if putcode: response = self.client.put_updated_work(xml_element, putcode) else: response = self.client.post_new_work(xml_element) LOGGER.info("POST/PUT ORCID work", recid=self.recid) response.raise_for_result() return response["putcode"] def _delete_works_with_duplicated_putcodes(self, cached_putcodes_recids): unique_recids_putcodes = {} for fetched_putcode, fetched_recid in cached_putcodes_recids: if fetched_recid in unique_recids_putcodes: self._delete_work(fetched_putcode) else: unique_recids_putcodes[fetched_recid] = fetched_putcode return unique_recids_putcodes @time_execution def _cache_all_author_putcodes(self): LOGGER.debug("New OrcidPusher cache all author putcodes", orcid=self.orcid) if not self.cached_author_putcodes: putcode_getter = OrcidPutcodeGetter(self.orcid, self.oauth_token) putcodes_recids = list( putcode_getter.get_all_inspire_putcodes_and_recids_iter() ) self.cached_author_putcodes = self._delete_works_with_duplicated_putcodes( putcodes_recids ) putcode = None for fetched_recid, fetched_putcode in self.cached_author_putcodes.items(): if fetched_recid == self.recid: putcode = int(fetched_putcode) cache = OrcidCache(self.orcid, fetched_recid) cache.write_work_putcode(fetched_putcode) # Ensure the putcode is actually in cache. # Note: this step is not really necessary and it can be skipped, but # at this moment it helps isolate a potential issue. if putcode and not self.cache.read_work_putcode(): raise exceptions.PutcodeNotFoundInCacheAfterCachingAllPutcodes( "No putcode={} found in cache for recid={} after having" " cached all author putcodes for orcid={}".format( self.putcode, self.recid, self.orcid ) ) return putcode @time_execution def _delete_work(self, putcode=None): putcode = putcode or self._cache_all_author_putcodes() if not putcode: # Such recid does not exists (anymore?) in ORCID API. return # ORCID API allows 1 non-idempotent call only for the same orcid at # the same time. Using `distributed_lock` to achieve this. with distributed_lock(self.lock_name, blocking=True): response = self.client.delete_work(putcode) try: response.raise_for_result() except orcid_client_exceptions.PutcodeNotFoundDeleteException: # Such putcode does not exists (anymore?) in orcid. pass except orcid_client_exceptions.BaseOrcidClientJsonException as exc: raise exceptions.InputDataInvalidException(from_exc=exc) self.cache.delete_work_putcode() @time_execution def _push_work_with_clashing_identifier(self): putcode_getter = OrcidPutcodeGetter(self.orcid, self.oauth_token) ids = self.converter.added_external_identifiers putcodes_recids = putcode_getter.get_putcodes_and_recids_by_identifiers_iter( ids ) updated_putcodes_recid = self._delete_works_with_duplicated_putcodes( putcodes_recids ) for (recid, putcode) in updated_putcodes_recid.items(): if not putcode or not recid: continue if recid == self.recid: continue # Local import to avoid import error. from inspirehep.orcid import tasks tasks.orcid_push( self.orcid, recid, self.oauth_token, dict( pushing_duplicated_identifier=True, ), )
LOGGER.debug( "OrcidPusher force delete", recid=self.recid, orcid=self.orcid ) return True
conditional_block
domain_models.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. import re import structlog from flask import current_app from inspire_service_orcid import exceptions as orcid_client_exceptions from inspire_service_orcid.client import OrcidClient from invenio_db import db from invenio_pidstore.errors import PIDDoesNotExistError from time_execution import time_execution from inspirehep.records.api import LiteratureRecord from inspirehep.utils import distributed_lock from . import exceptions, push_access_tokens, utils from .cache import OrcidCache from .converter import OrcidConverter from .putcode_getter import OrcidPutcodeGetter LOGGER = structlog.getLogger() ORCID_REGEX = r"\d{4}-\d{4}-\d{4}-\d{3}[0-9X]" class OrcidPusher(object): def __init__( self, orcid, recid, oauth_token, pushing_duplicated_identifier=False, record_db_version=None, ): self.orcid = orcid self.recid = str(recid) self.oauth_token = oauth_token self.pushing_duplicated_identifier = pushing_duplicated_identifier self.record_db_version = record_db_version self.inspire_record = self._get_inspire_record() self.cache = OrcidCache(orcid, recid) self.lock_name = "orcid:{}".format(self.orcid) self.client = OrcidClient(self.oauth_token, self.orcid) self.converter = None self.cached_author_putcodes = {} @time_execution def _get_inspire_record(self): try: inspire_record = LiteratureRecord.get_record_by_pid_value( self.recid, original_record=True ) except PIDDoesNotExistError as exc: raise exceptions.RecordNotFoundException( "recid={} not found for pid_type=lit".format(self.recid), from_exc=exc ) # If the record_db_version was given, then ensure we are about to push # the right record version. # This check is related to the fact the orcid push at this moment is # triggered by the signal after_record_update (which happens after a # InspireRecord.commit()). This is not the actual commit to the db which # might happen at a later stage or not at all. # Note that connecting to the proper SQLAlchemy signal would also # have issues: https://github.com/mitsuhiko/flask-sqlalchemy/issues/645 if ( self.record_db_version and inspire_record.model.version_id < self.record_db_version ): raise exceptions.StaleRecordDBVersionException( "Requested push for db version={}, but actual record db" " version={}".format( self.record_db_version, inspire_record.model.version_id ) ) return inspire_record @property def _do_force_cache_miss(self): """ Hook to force a cache miss. This can be leveraged in feature tests. """ for note in self.inspire_record.get("_private_notes", []): if note.get("value") == "orcid-push-force-cache-miss": LOGGER.debug( "OrcidPusher force cache miss", recid=self.recid, orcid=self.orcid ) return True return False @property def _is_record_deleted(self): # Hook to force a delete. This can be leveraged in feature tests. for note in self.inspire_record.get("_private_notes", []): if note.get("value") == "orcid-push-force-delete": LOGGER.debug( "OrcidPusher force delete", recid=self.recid, orcid=self.orcid ) return True return self.inspire_record.get("deleted", False) @time_execution def push(self): # noqa: C901 putcode = None if not self._do_force_cache_miss: putcode = self.cache.read_work_putcode() if not self._is_record_deleted and not self.cache.has_work_content_changed( self.inspire_record ): LOGGER.debug( "OrcidPusher cache hit", recid=self.recid, orcid=self.orcid ) return putcode LOGGER.debug("OrcidPusher cache miss", recid=self.recid, orcid=self.orcid) # If the record is deleted, then delete it. if self._is_record_deleted: self._delete_work(putcode) return None self.converter = OrcidConverter( record=self.inspire_record, url_pattern=current_app.config["LEGACY_RECORD_URL_PATTERN"], put_code=putcode, ) try: putcode = self._post_or_put_work(putcode) except orcid_client_exceptions.WorkAlreadyExistsException: # We POSTed the record as new work, but it failed because # a work with the same identifier is already in ORCID. # This can mean two things: # 1. the record itself is already in ORCID, but we don't have the putcode; # 2. a different record with the same external identifier is already in ORCID. # We first try to fix 1. by caching all author's putcodes and PUT the work again. # If the putcode wasn't found we are probably facing case 2. # so we try to push once again works with clashing identifiers # to update them and resolve the potential conflict. if self.pushing_duplicated_identifier: raise exceptions.DuplicatedExternalIdentifierPusherException putcode = self._cache_all_author_putcodes() if not putcode: try: self._push_work_with_clashing_identifier() putcode = self._post_or_put_work(putcode) except orcid_client_exceptions.WorkAlreadyExistsException: # The PUT/POST failed despite pushing works with clashing identifiers # and we can't do anything about this. raise exceptions.DuplicatedExternalIdentifierPusherException else: self._post_or_put_work(putcode) except orcid_client_exceptions.DuplicatedExternalIdentifierException: # We PUT a record changing its identifier, but there is another work # in ORCID with the same identifier. We need to find out the recid # of the clashing work in ORCID and push a fresh version of that # record. # This scenario might be triggered by a merge of 2 records in Inspire. if not self.pushing_duplicated_identifier: self._push_work_with_clashing_identifier() # Raised exception will cause retry of celery task raise exceptions.DuplicatedExternalIdentifierPusherException except orcid_client_exceptions.PutcodeNotFoundPutException: # We try to push the work with invalid putcode, so we delete # its putcode and push it without any putcode. # If it turns out that the record already exists # in ORCID we search for the putcode by caching # all author's putcodes and PUT the work again. self.cache.delete_work_putcode() self.converter = OrcidConverter( record=self.inspire_record, url_pattern=current_app.config["LEGACY_RECORD_URL_PATTERN"], put_code=None, ) putcode = self._cache_all_author_putcodes() putcode = self._post_or_put_work(putcode) except ( orcid_client_exceptions.TokenInvalidException, orcid_client_exceptions.TokenMismatchException, orcid_client_exceptions.TokenWithWrongPermissionException, ): LOGGER.info( "Deleting Orcid push access", token=self.oauth_token, orcid=self.orcid ) push_access_tokens.delete_access_token(self.oauth_token, self.orcid) db.session.commit() raise exceptions.TokenInvalidDeletedException except orcid_client_exceptions.MovedPermanentlyException as exc: old_orcid, new_orcid = re.findall(ORCID_REGEX, exc.args[0]) utils.update_moved_orcid(old_orcid, new_orcid) raise except orcid_client_exceptions.BaseOrcidClientJsonException as exc: raise exceptions.InputDataInvalidException(from_exc=exc) self.cache.write_work_putcode(putcode, self.inspire_record) return putcode @time_execution def _post_or_put_work(self, putcode=None): # Note: if putcode is None, then it's a POST (it means the work is new). # Otherwise a PUT (it means the work already exists and it has the given # putcode). xml_element = self.converter.get_xml(do_add_bibtex_citation=True) # ORCID API allows 1 non-idempotent call only for the same orcid at # the same time. Using `distributed_lock` to achieve this. with distributed_lock(self.lock_name, blocking=True): if putcode: response = self.client.put_updated_work(xml_element, putcode) else: response = self.client.post_new_work(xml_element) LOGGER.info("POST/PUT ORCID work", recid=self.recid) response.raise_for_result() return response["putcode"] def _delete_works_with_duplicated_putcodes(self, cached_putcodes_recids): unique_recids_putcodes = {} for fetched_putcode, fetched_recid in cached_putcodes_recids: if fetched_recid in unique_recids_putcodes: self._delete_work(fetched_putcode) else: unique_recids_putcodes[fetched_recid] = fetched_putcode return unique_recids_putcodes @time_execution def _cache_all_author_putcodes(self):
@time_execution def _delete_work(self, putcode=None): putcode = putcode or self._cache_all_author_putcodes() if not putcode: # Such recid does not exists (anymore?) in ORCID API. return # ORCID API allows 1 non-idempotent call only for the same orcid at # the same time. Using `distributed_lock` to achieve this. with distributed_lock(self.lock_name, blocking=True): response = self.client.delete_work(putcode) try: response.raise_for_result() except orcid_client_exceptions.PutcodeNotFoundDeleteException: # Such putcode does not exists (anymore?) in orcid. pass except orcid_client_exceptions.BaseOrcidClientJsonException as exc: raise exceptions.InputDataInvalidException(from_exc=exc) self.cache.delete_work_putcode() @time_execution def _push_work_with_clashing_identifier(self): putcode_getter = OrcidPutcodeGetter(self.orcid, self.oauth_token) ids = self.converter.added_external_identifiers putcodes_recids = putcode_getter.get_putcodes_and_recids_by_identifiers_iter( ids ) updated_putcodes_recid = self._delete_works_with_duplicated_putcodes( putcodes_recids ) for (recid, putcode) in updated_putcodes_recid.items(): if not putcode or not recid: continue if recid == self.recid: continue # Local import to avoid import error. from inspirehep.orcid import tasks tasks.orcid_push( self.orcid, recid, self.oauth_token, dict( pushing_duplicated_identifier=True, ), )
LOGGER.debug("New OrcidPusher cache all author putcodes", orcid=self.orcid) if not self.cached_author_putcodes: putcode_getter = OrcidPutcodeGetter(self.orcid, self.oauth_token) putcodes_recids = list( putcode_getter.get_all_inspire_putcodes_and_recids_iter() ) self.cached_author_putcodes = self._delete_works_with_duplicated_putcodes( putcodes_recids ) putcode = None for fetched_recid, fetched_putcode in self.cached_author_putcodes.items(): if fetched_recid == self.recid: putcode = int(fetched_putcode) cache = OrcidCache(self.orcid, fetched_recid) cache.write_work_putcode(fetched_putcode) # Ensure the putcode is actually in cache. # Note: this step is not really necessary and it can be skipped, but # at this moment it helps isolate a potential issue. if putcode and not self.cache.read_work_putcode(): raise exceptions.PutcodeNotFoundInCacheAfterCachingAllPutcodes( "No putcode={} found in cache for recid={} after having" " cached all author putcodes for orcid={}".format( self.putcode, self.recid, self.orcid ) ) return putcode
identifier_body
lib.rs
//! This crate adds support for subscriptions as defined in [here]. //! //! [here]: https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB extern crate futures; extern crate jsonrpc_client_core; extern crate jsonrpc_client_utils; #[macro_use] extern crate serde; extern crate serde_json; extern crate tokio; #[macro_use] extern crate log; #[macro_use] extern crate error_chain; use futures::{future, future::Either, sync::mpsc, Async, Future, Poll, Sink, Stream}; use jsonrpc_client_core::server::{ types::Params, Handler, HandlerSettingError, Server, ServerHandle, }; use jsonrpc_client_core::{ ClientHandle, DuplexTransport, Error as CoreError, ErrorKind as CoreErrorKind, }; use serde_json::Value; use std::collections::BTreeMap; use std::fmt; use std::marker::PhantomData; use tokio::prelude::future::Executor; use jsonrpc_client_utils::select_weak::{SelectWithWeak, SelectWithWeakExt}; error_chain! { links { Core(CoreError, CoreErrorKind); } foreign_links { HandlerError(HandlerSettingError); SpawnError(tokio::executor::SpawnError); } } #[derive(Debug, Deserialize)] struct SubscriptionMessage { subscription: SubscriptionId, result: Value, } /// A stream of messages from a subscription. #[derive(Debug)] pub struct Subscription<T: serde::de::DeserializeOwned> { rx: mpsc::Receiver<Value>, id: Option<SubscriptionId>, handler_chan: mpsc::UnboundedSender<SubscriberMsg>, _marker: PhantomData<T>, } impl<T: serde::de::DeserializeOwned> Stream for Subscription<T> { type Item = T; type Error = CoreError; fn poll(&mut self) -> Poll<Option<T>, CoreError> { match self.rx.poll().map_err(|_: ()| CoreErrorKind::Shutdown)? { Async::Ready(Some(v)) => Ok(Async::Ready(Some( serde_json::from_value(v).map_err(|_| CoreErrorKind::DeserializeError)?, ))), Async::Ready(None) => Ok(Async::Ready(None)), Async::NotReady => Ok(Async::NotReady), } } } impl<T: serde::de::DeserializeOwned> Drop for Subscription<T> { fn drop(&mut self) { if let Some(id) = self.id.take() { let _ = self .handler_chan .unbounded_send(SubscriberMsg::RemoveSubscriber(id)); } } } /// A subscriber creates new subscriptions. #[derive(Debug)] pub struct Subscriber<E: Executor<Box<Future<Item = (), Error = ()> + Send>>> { client_handle: ClientHandle, handlers: ServerHandle, notification_handlers: BTreeMap<String, mpsc::UnboundedSender<SubscriberMsg>>, executor: E, } impl<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sized> Subscriber<E> { /// Constructs a new subscriber with the provided executor. pub fn new(executor: E, client_handle: ClientHandle, handlers: ServerHandle) -> Self { let notification_handlers = BTreeMap::new(); Self { client_handle, handlers, notification_handlers, executor, } } /// Creates a new subscription with the given method names and parameters. Parameters /// `sub_method` and `unsub_method` are only taken into account if this is the first time a /// subscription for `notification` has been created in the lifetime of this `Subscriber`. pub fn subscribe<T, P>( &mut self, sub_method: String, unsub_method: String, notification_method: String, buffer_size: usize, sub_parameters: P, ) -> impl Future<Item = Subscription<T>, Error = Error> where T: serde::de::DeserializeOwned + 'static, P: serde::Serialize + 'static, { // Get a channel to an existing notification handler or spawn a new one. let chan = self .notification_handlers .get(&notification_method) .filter(|c| c.is_closed()) .map(|chan| Ok(chan.clone())) .unwrap_or_else(|| { self.spawn_notification_handler(notification_method.clone(), unsub_method) }); let (sub_tx, sub_rx) = mpsc::channel(buffer_size); match chan { Ok(chan) => Either::A( self.client_handle .call_method(sub_method, &sub_parameters) .map_err(|e| e.into()) .and_then(move |id: SubscriptionId| { if let Err(_) = chan.unbounded_send(SubscriberMsg::NewSubscriber(id.clone(), sub_tx)) { debug!( "Notificaton handler for {} - {} already closed", notification_method, id ); }; Ok(Subscription { rx: sub_rx, id: Some(id), handler_chan: chan.clone(), _marker: PhantomData::<T>, }) }), ), Err(e) => Either::B(future::err(e)), } } fn spawn_notification_handler( &mut self, notification_method: String, unsub_method: String, ) -> Result<mpsc::UnboundedSender<SubscriberMsg>> { let (msg_tx, msg_rx) = mpsc::channel(0); self.handlers .add( notification_method.clone(), Handler::Notification(Box::new(move |notification| { let fut = match params_to_subscription_message(notification.params) { Some(msg) => Either::A( msg_tx .clone() .send(msg) .map(|_| ()) .map_err(|_| CoreErrorKind::Shutdown.into()), ), None => { error!( "Received notification with invalid parameters for subscription - {}", notification.method ); Either::B(futures::future::ok(())) } }; Box::new(fut) })), ) .wait()?; let (control_tx, control_rx) = mpsc::unbounded(); let notification_handler = NotificationHandler::new( notification_method.clone(), self.handlers.clone(), self.client_handle.clone(), unsub_method, msg_rx, control_rx, ); if let Err(e) = self .executor .execute(Box::new(notification_handler.map_err(|_| ()))) { error!("Failed to spawn notification handler - {:?}", e); }; self.notification_handlers .insert(notification_method, control_tx.clone()); Ok(control_tx) } } fn params_to_subscription_message(params: Option<Params>) -> Option<SubscriberMsg> { params .and_then(|p| p.parse().ok()) .map(SubscriberMsg::NewMessage) } #[derive(Ord, PartialOrd, Eq, PartialEq, Clone, Debug, Deserialize)] #[serde(untagged)] enum SubscriptionId { Num(u64), String(String), } impl fmt::Display for SubscriptionId { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { SubscriptionId::Num(n) => write!(f, "{}", n), SubscriptionId::String(s) => write!(f, "{}", s), } } } #[derive(Debug)] enum SubscriberMsg { NewMessage(SubscriptionMessage), NewSubscriber(SubscriptionId, mpsc::Sender<Value>), RemoveSubscriber(SubscriptionId), } // A single notification can receive messages for different subscribers for the same notification. struct NotificationHandler { notification_method: String, subscribers: BTreeMap<SubscriptionId, mpsc::Sender<Value>>, messages: SelectWithWeak<mpsc::Receiver<SubscriberMsg>, mpsc::UnboundedReceiver<SubscriberMsg>>, unsub_method: String, client_handle: ClientHandle, current_future: Option<Box<dyn Future<Item = (), Error = ()> + Send>>, server_handlers: ServerHandle, should_shut_down: bool, } impl Drop for NotificationHandler { fn drop(&mut self) { let _ = self .server_handlers .remove(self.notification_method.clone()); } } impl NotificationHandler { fn new( notification_method: String, server_handlers: ServerHandle, client_handle: ClientHandle, unsub_method: String, subscription_messages: mpsc::Receiver<SubscriberMsg>, control_messages: mpsc::UnboundedReceiver<SubscriberMsg>, ) -> Self { let messages = subscription_messages.select_with_weak(control_messages); Self { notification_method, messages, server_handlers, unsub_method, subscribers: BTreeMap::new(), client_handle, current_future: None, should_shut_down: false, } } fn handle_new_subscription(&mut self, id: SubscriptionId, chan: mpsc::Sender<Value>) { self.subscribers.insert(id, chan); } fn handle_removal(&mut self, id: SubscriptionId) { if let None = self.subscribers.remove(&id) { debug!("Removing non-existant subscriber - {}", &id); }; let fut = self .client_handle .call_method(self.unsub_method.clone(), &[0u8; 0]) .map(|_r: bool| ()) .map_err(|e| trace!("Failed to unsubscribe - {}", e)); self.should_shut_down = self.subscribers.len() < 1; self.current_future = Some(Box::new(fut)); } fn handle_new_message(&mut self, id: SubscriptionId, message: Value) { match self.subscribers.get(&id) { Some(chan) => { let fut = chan .clone() .send(message) .map_err(move |_| trace!("Subscriber already gone: {}", id)) .map(|_| ()); self.current_future = Some(Box::new(fut)); } None => trace!("Received message for non existant subscription - {}", id), } } fn ready_for_next_connection(&mut self) -> bool { match self.current_future.take() { None => true, Some(mut fut) => match fut.poll() { Ok(Async::NotReady) => { self.current_future = Some(fut); false } _ => true, }, } } } impl Future for NotificationHandler { type Item = (); type Error = (); fn poll(&mut self) -> Poll<(), ()> { while self.ready_for_next_connection() { match self.messages.poll()? { Async::NotReady => { break; } Async::Ready(None) => { return Ok(Async::Ready(())); } Async::Ready(Some(SubscriberMsg::NewMessage(msg))) => { self.handle_new_message(msg.subscription, msg.result); } Async::Ready(Some(SubscriberMsg::NewSubscriber(id, chan))) => { self.handle_new_subscription(id, chan); } Async::Ready(Some(SubscriberMsg::RemoveSubscriber(id))) => { self.handle_removal(id); } } } if self.should_shut_down { trace!( "shutting down notification handler for notification '{}'", self.notification_method ); Ok(Async::Ready(())) } else { Ok(Async::NotReady) } } } /// A trait for constructing the usual client handles with coupled `Subscriber` structs. pub trait SubscriberTransport: DuplexTransport { /// Constructs a new client, client handle and a subscriber. fn subscriber_client<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sized>( self, executor: E, ) -> ( jsonrpc_client_core::Client<Self, Server>, ClientHandle, Subscriber<E>, ); } /// Subscriber transport trait allows one to create a client future, a subscriber and a client /// handle from a valid JSON-RPC transport. impl<T: DuplexTransport> SubscriberTransport for T { /// Constructs a new client, client handle and a subscriber. fn subscriber_client<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send>( self, executor: E, ) -> ( jsonrpc_client_core::Client<Self, Server>, ClientHandle, Subscriber<E>, ) { let (server, server_handle) = Server::new(); let (client, client_handle) = self.with_server(server); let subscriber = Subscriber::new(executor, client_handle.clone(), server_handle); (client, client_handle, subscriber) } }
fmt
identifier_name
lib.rs
//! This crate adds support for subscriptions as defined in [here]. //! //! [here]: https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB extern crate futures; extern crate jsonrpc_client_core; extern crate jsonrpc_client_utils; #[macro_use] extern crate serde; extern crate serde_json; extern crate tokio; #[macro_use] extern crate log; #[macro_use] extern crate error_chain; use futures::{future, future::Either, sync::mpsc, Async, Future, Poll, Sink, Stream}; use jsonrpc_client_core::server::{ types::Params, Handler, HandlerSettingError, Server, ServerHandle, }; use jsonrpc_client_core::{ ClientHandle, DuplexTransport, Error as CoreError, ErrorKind as CoreErrorKind, }; use serde_json::Value; use std::collections::BTreeMap; use std::fmt; use std::marker::PhantomData; use tokio::prelude::future::Executor; use jsonrpc_client_utils::select_weak::{SelectWithWeak, SelectWithWeakExt}; error_chain! { links { Core(CoreError, CoreErrorKind); } foreign_links { HandlerError(HandlerSettingError); SpawnError(tokio::executor::SpawnError); } } #[derive(Debug, Deserialize)] struct SubscriptionMessage { subscription: SubscriptionId, result: Value, } /// A stream of messages from a subscription. #[derive(Debug)] pub struct Subscription<T: serde::de::DeserializeOwned> { rx: mpsc::Receiver<Value>, id: Option<SubscriptionId>, handler_chan: mpsc::UnboundedSender<SubscriberMsg>, _marker: PhantomData<T>, } impl<T: serde::de::DeserializeOwned> Stream for Subscription<T> { type Item = T; type Error = CoreError; fn poll(&mut self) -> Poll<Option<T>, CoreError> { match self.rx.poll().map_err(|_: ()| CoreErrorKind::Shutdown)? { Async::Ready(Some(v)) => Ok(Async::Ready(Some( serde_json::from_value(v).map_err(|_| CoreErrorKind::DeserializeError)?, ))), Async::Ready(None) => Ok(Async::Ready(None)), Async::NotReady => Ok(Async::NotReady), } } } impl<T: serde::de::DeserializeOwned> Drop for Subscription<T> { fn drop(&mut self) { if let Some(id) = self.id.take() { let _ = self .handler_chan .unbounded_send(SubscriberMsg::RemoveSubscriber(id)); } } } /// A subscriber creates new subscriptions. #[derive(Debug)] pub struct Subscriber<E: Executor<Box<Future<Item = (), Error = ()> + Send>>> { client_handle: ClientHandle, handlers: ServerHandle, notification_handlers: BTreeMap<String, mpsc::UnboundedSender<SubscriberMsg>>, executor: E, } impl<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sized> Subscriber<E> { /// Constructs a new subscriber with the provided executor. pub fn new(executor: E, client_handle: ClientHandle, handlers: ServerHandle) -> Self { let notification_handlers = BTreeMap::new(); Self { client_handle, handlers, notification_handlers, executor, } } /// Creates a new subscription with the given method names and parameters. Parameters /// `sub_method` and `unsub_method` are only taken into account if this is the first time a /// subscription for `notification` has been created in the lifetime of this `Subscriber`. pub fn subscribe<T, P>( &mut self, sub_method: String, unsub_method: String, notification_method: String, buffer_size: usize, sub_parameters: P, ) -> impl Future<Item = Subscription<T>, Error = Error> where T: serde::de::DeserializeOwned + 'static, P: serde::Serialize + 'static, { // Get a channel to an existing notification handler or spawn a new one. let chan = self .notification_handlers .get(&notification_method) .filter(|c| c.is_closed()) .map(|chan| Ok(chan.clone())) .unwrap_or_else(|| { self.spawn_notification_handler(notification_method.clone(), unsub_method) }); let (sub_tx, sub_rx) = mpsc::channel(buffer_size); match chan { Ok(chan) => Either::A( self.client_handle .call_method(sub_method, &sub_parameters) .map_err(|e| e.into()) .and_then(move |id: SubscriptionId| { if let Err(_) = chan.unbounded_send(SubscriberMsg::NewSubscriber(id.clone(), sub_tx)) { debug!( "Notificaton handler for {} - {} already closed", notification_method, id ); }; Ok(Subscription { rx: sub_rx, id: Some(id), handler_chan: chan.clone(), _marker: PhantomData::<T>, }) }), ), Err(e) => Either::B(future::err(e)), } } fn spawn_notification_handler( &mut self, notification_method: String, unsub_method: String, ) -> Result<mpsc::UnboundedSender<SubscriberMsg>> { let (msg_tx, msg_rx) = mpsc::channel(0); self.handlers .add( notification_method.clone(), Handler::Notification(Box::new(move |notification| { let fut = match params_to_subscription_message(notification.params) { Some(msg) => Either::A( msg_tx .clone() .send(msg) .map(|_| ()) .map_err(|_| CoreErrorKind::Shutdown.into()), ), None => { error!( "Received notification with invalid parameters for subscription - {}", notification.method ); Either::B(futures::future::ok(())) } }; Box::new(fut) })), ) .wait()?; let (control_tx, control_rx) = mpsc::unbounded(); let notification_handler = NotificationHandler::new( notification_method.clone(), self.handlers.clone(), self.client_handle.clone(), unsub_method, msg_rx, control_rx, ); if let Err(e) = self .executor .execute(Box::new(notification_handler.map_err(|_| ()))) { error!("Failed to spawn notification handler - {:?}", e); }; self.notification_handlers .insert(notification_method, control_tx.clone()); Ok(control_tx) } } fn params_to_subscription_message(params: Option<Params>) -> Option<SubscriberMsg> { params .and_then(|p| p.parse().ok()) .map(SubscriberMsg::NewMessage) } #[derive(Ord, PartialOrd, Eq, PartialEq, Clone, Debug, Deserialize)] #[serde(untagged)] enum SubscriptionId { Num(u64), String(String), } impl fmt::Display for SubscriptionId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { SubscriptionId::Num(n) => write!(f, "{}", n), SubscriptionId::String(s) => write!(f, "{}", s), } } } #[derive(Debug)] enum SubscriberMsg { NewMessage(SubscriptionMessage), NewSubscriber(SubscriptionId, mpsc::Sender<Value>), RemoveSubscriber(SubscriptionId), } // A single notification can receive messages for different subscribers for the same notification. struct NotificationHandler { notification_method: String, subscribers: BTreeMap<SubscriptionId, mpsc::Sender<Value>>, messages: SelectWithWeak<mpsc::Receiver<SubscriberMsg>, mpsc::UnboundedReceiver<SubscriberMsg>>, unsub_method: String, client_handle: ClientHandle, current_future: Option<Box<dyn Future<Item = (), Error = ()> + Send>>, server_handlers: ServerHandle, should_shut_down: bool, } impl Drop for NotificationHandler { fn drop(&mut self) { let _ = self .server_handlers .remove(self.notification_method.clone()); } } impl NotificationHandler { fn new( notification_method: String, server_handlers: ServerHandle, client_handle: ClientHandle, unsub_method: String, subscription_messages: mpsc::Receiver<SubscriberMsg>, control_messages: mpsc::UnboundedReceiver<SubscriberMsg>, ) -> Self { let messages = subscription_messages.select_with_weak(control_messages); Self { notification_method, messages, server_handlers, unsub_method, subscribers: BTreeMap::new(), client_handle, current_future: None, should_shut_down: false, } } fn handle_new_subscription(&mut self, id: SubscriptionId, chan: mpsc::Sender<Value>) { self.subscribers.insert(id, chan); } fn handle_removal(&mut self, id: SubscriptionId) { if let None = self.subscribers.remove(&id) { debug!("Removing non-existant subscriber - {}", &id); }; let fut = self .client_handle .call_method(self.unsub_method.clone(), &[0u8; 0]) .map(|_r: bool| ()) .map_err(|e| trace!("Failed to unsubscribe - {}", e)); self.should_shut_down = self.subscribers.len() < 1; self.current_future = Some(Box::new(fut)); } fn handle_new_message(&mut self, id: SubscriptionId, message: Value) { match self.subscribers.get(&id) { Some(chan) => { let fut = chan .clone() .send(message) .map_err(move |_| trace!("Subscriber already gone: {}", id)) .map(|_| ()); self.current_future = Some(Box::new(fut)); } None => trace!("Received message for non existant subscription - {}", id), } } fn ready_for_next_connection(&mut self) -> bool { match self.current_future.take() { None => true, Some(mut fut) => match fut.poll() { Ok(Async::NotReady) =>
_ => true, }, } } } impl Future for NotificationHandler { type Item = (); type Error = (); fn poll(&mut self) -> Poll<(), ()> { while self.ready_for_next_connection() { match self.messages.poll()? { Async::NotReady => { break; } Async::Ready(None) => { return Ok(Async::Ready(())); } Async::Ready(Some(SubscriberMsg::NewMessage(msg))) => { self.handle_new_message(msg.subscription, msg.result); } Async::Ready(Some(SubscriberMsg::NewSubscriber(id, chan))) => { self.handle_new_subscription(id, chan); } Async::Ready(Some(SubscriberMsg::RemoveSubscriber(id))) => { self.handle_removal(id); } } } if self.should_shut_down { trace!( "shutting down notification handler for notification '{}'", self.notification_method ); Ok(Async::Ready(())) } else { Ok(Async::NotReady) } } } /// A trait for constructing the usual client handles with coupled `Subscriber` structs. pub trait SubscriberTransport: DuplexTransport { /// Constructs a new client, client handle and a subscriber. fn subscriber_client<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sized>( self, executor: E, ) -> ( jsonrpc_client_core::Client<Self, Server>, ClientHandle, Subscriber<E>, ); } /// Subscriber transport trait allows one to create a client future, a subscriber and a client /// handle from a valid JSON-RPC transport. impl<T: DuplexTransport> SubscriberTransport for T { /// Constructs a new client, client handle and a subscriber. fn subscriber_client<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send>( self, executor: E, ) -> ( jsonrpc_client_core::Client<Self, Server>, ClientHandle, Subscriber<E>, ) { let (server, server_handle) = Server::new(); let (client, client_handle) = self.with_server(server); let subscriber = Subscriber::new(executor, client_handle.clone(), server_handle); (client, client_handle, subscriber) } }
{ self.current_future = Some(fut); false }
conditional_block
lib.rs
//! This crate adds support for subscriptions as defined in [here].
extern crate jsonrpc_client_utils; #[macro_use] extern crate serde; extern crate serde_json; extern crate tokio; #[macro_use] extern crate log; #[macro_use] extern crate error_chain; use futures::{future, future::Either, sync::mpsc, Async, Future, Poll, Sink, Stream}; use jsonrpc_client_core::server::{ types::Params, Handler, HandlerSettingError, Server, ServerHandle, }; use jsonrpc_client_core::{ ClientHandle, DuplexTransport, Error as CoreError, ErrorKind as CoreErrorKind, }; use serde_json::Value; use std::collections::BTreeMap; use std::fmt; use std::marker::PhantomData; use tokio::prelude::future::Executor; use jsonrpc_client_utils::select_weak::{SelectWithWeak, SelectWithWeakExt}; error_chain! { links { Core(CoreError, CoreErrorKind); } foreign_links { HandlerError(HandlerSettingError); SpawnError(tokio::executor::SpawnError); } } #[derive(Debug, Deserialize)] struct SubscriptionMessage { subscription: SubscriptionId, result: Value, } /// A stream of messages from a subscription. #[derive(Debug)] pub struct Subscription<T: serde::de::DeserializeOwned> { rx: mpsc::Receiver<Value>, id: Option<SubscriptionId>, handler_chan: mpsc::UnboundedSender<SubscriberMsg>, _marker: PhantomData<T>, } impl<T: serde::de::DeserializeOwned> Stream for Subscription<T> { type Item = T; type Error = CoreError; fn poll(&mut self) -> Poll<Option<T>, CoreError> { match self.rx.poll().map_err(|_: ()| CoreErrorKind::Shutdown)? { Async::Ready(Some(v)) => Ok(Async::Ready(Some( serde_json::from_value(v).map_err(|_| CoreErrorKind::DeserializeError)?, ))), Async::Ready(None) => Ok(Async::Ready(None)), Async::NotReady => Ok(Async::NotReady), } } } impl<T: serde::de::DeserializeOwned> Drop for Subscription<T> { fn drop(&mut self) { if let Some(id) = self.id.take() { let _ = self .handler_chan .unbounded_send(SubscriberMsg::RemoveSubscriber(id)); } } } /// A subscriber creates new subscriptions. #[derive(Debug)] pub struct Subscriber<E: Executor<Box<Future<Item = (), Error = ()> + Send>>> { client_handle: ClientHandle, handlers: ServerHandle, notification_handlers: BTreeMap<String, mpsc::UnboundedSender<SubscriberMsg>>, executor: E, } impl<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sized> Subscriber<E> { /// Constructs a new subscriber with the provided executor. pub fn new(executor: E, client_handle: ClientHandle, handlers: ServerHandle) -> Self { let notification_handlers = BTreeMap::new(); Self { client_handle, handlers, notification_handlers, executor, } } /// Creates a new subscription with the given method names and parameters. Parameters /// `sub_method` and `unsub_method` are only taken into account if this is the first time a /// subscription for `notification` has been created in the lifetime of this `Subscriber`. pub fn subscribe<T, P>( &mut self, sub_method: String, unsub_method: String, notification_method: String, buffer_size: usize, sub_parameters: P, ) -> impl Future<Item = Subscription<T>, Error = Error> where T: serde::de::DeserializeOwned + 'static, P: serde::Serialize + 'static, { // Get a channel to an existing notification handler or spawn a new one. let chan = self .notification_handlers .get(&notification_method) .filter(|c| c.is_closed()) .map(|chan| Ok(chan.clone())) .unwrap_or_else(|| { self.spawn_notification_handler(notification_method.clone(), unsub_method) }); let (sub_tx, sub_rx) = mpsc::channel(buffer_size); match chan { Ok(chan) => Either::A( self.client_handle .call_method(sub_method, &sub_parameters) .map_err(|e| e.into()) .and_then(move |id: SubscriptionId| { if let Err(_) = chan.unbounded_send(SubscriberMsg::NewSubscriber(id.clone(), sub_tx)) { debug!( "Notificaton handler for {} - {} already closed", notification_method, id ); }; Ok(Subscription { rx: sub_rx, id: Some(id), handler_chan: chan.clone(), _marker: PhantomData::<T>, }) }), ), Err(e) => Either::B(future::err(e)), } } fn spawn_notification_handler( &mut self, notification_method: String, unsub_method: String, ) -> Result<mpsc::UnboundedSender<SubscriberMsg>> { let (msg_tx, msg_rx) = mpsc::channel(0); self.handlers .add( notification_method.clone(), Handler::Notification(Box::new(move |notification| { let fut = match params_to_subscription_message(notification.params) { Some(msg) => Either::A( msg_tx .clone() .send(msg) .map(|_| ()) .map_err(|_| CoreErrorKind::Shutdown.into()), ), None => { error!( "Received notification with invalid parameters for subscription - {}", notification.method ); Either::B(futures::future::ok(())) } }; Box::new(fut) })), ) .wait()?; let (control_tx, control_rx) = mpsc::unbounded(); let notification_handler = NotificationHandler::new( notification_method.clone(), self.handlers.clone(), self.client_handle.clone(), unsub_method, msg_rx, control_rx, ); if let Err(e) = self .executor .execute(Box::new(notification_handler.map_err(|_| ()))) { error!("Failed to spawn notification handler - {:?}", e); }; self.notification_handlers .insert(notification_method, control_tx.clone()); Ok(control_tx) } } fn params_to_subscription_message(params: Option<Params>) -> Option<SubscriberMsg> { params .and_then(|p| p.parse().ok()) .map(SubscriberMsg::NewMessage) } #[derive(Ord, PartialOrd, Eq, PartialEq, Clone, Debug, Deserialize)] #[serde(untagged)] enum SubscriptionId { Num(u64), String(String), } impl fmt::Display for SubscriptionId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { SubscriptionId::Num(n) => write!(f, "{}", n), SubscriptionId::String(s) => write!(f, "{}", s), } } } #[derive(Debug)] enum SubscriberMsg { NewMessage(SubscriptionMessage), NewSubscriber(SubscriptionId, mpsc::Sender<Value>), RemoveSubscriber(SubscriptionId), } // A single notification can receive messages for different subscribers for the same notification. struct NotificationHandler { notification_method: String, subscribers: BTreeMap<SubscriptionId, mpsc::Sender<Value>>, messages: SelectWithWeak<mpsc::Receiver<SubscriberMsg>, mpsc::UnboundedReceiver<SubscriberMsg>>, unsub_method: String, client_handle: ClientHandle, current_future: Option<Box<dyn Future<Item = (), Error = ()> + Send>>, server_handlers: ServerHandle, should_shut_down: bool, } impl Drop for NotificationHandler { fn drop(&mut self) { let _ = self .server_handlers .remove(self.notification_method.clone()); } } impl NotificationHandler { fn new( notification_method: String, server_handlers: ServerHandle, client_handle: ClientHandle, unsub_method: String, subscription_messages: mpsc::Receiver<SubscriberMsg>, control_messages: mpsc::UnboundedReceiver<SubscriberMsg>, ) -> Self { let messages = subscription_messages.select_with_weak(control_messages); Self { notification_method, messages, server_handlers, unsub_method, subscribers: BTreeMap::new(), client_handle, current_future: None, should_shut_down: false, } } fn handle_new_subscription(&mut self, id: SubscriptionId, chan: mpsc::Sender<Value>) { self.subscribers.insert(id, chan); } fn handle_removal(&mut self, id: SubscriptionId) { if let None = self.subscribers.remove(&id) { debug!("Removing non-existant subscriber - {}", &id); }; let fut = self .client_handle .call_method(self.unsub_method.clone(), &[0u8; 0]) .map(|_r: bool| ()) .map_err(|e| trace!("Failed to unsubscribe - {}", e)); self.should_shut_down = self.subscribers.len() < 1; self.current_future = Some(Box::new(fut)); } fn handle_new_message(&mut self, id: SubscriptionId, message: Value) { match self.subscribers.get(&id) { Some(chan) => { let fut = chan .clone() .send(message) .map_err(move |_| trace!("Subscriber already gone: {}", id)) .map(|_| ()); self.current_future = Some(Box::new(fut)); } None => trace!("Received message for non existant subscription - {}", id), } } fn ready_for_next_connection(&mut self) -> bool { match self.current_future.take() { None => true, Some(mut fut) => match fut.poll() { Ok(Async::NotReady) => { self.current_future = Some(fut); false } _ => true, }, } } } impl Future for NotificationHandler { type Item = (); type Error = (); fn poll(&mut self) -> Poll<(), ()> { while self.ready_for_next_connection() { match self.messages.poll()? { Async::NotReady => { break; } Async::Ready(None) => { return Ok(Async::Ready(())); } Async::Ready(Some(SubscriberMsg::NewMessage(msg))) => { self.handle_new_message(msg.subscription, msg.result); } Async::Ready(Some(SubscriberMsg::NewSubscriber(id, chan))) => { self.handle_new_subscription(id, chan); } Async::Ready(Some(SubscriberMsg::RemoveSubscriber(id))) => { self.handle_removal(id); } } } if self.should_shut_down { trace!( "shutting down notification handler for notification '{}'", self.notification_method ); Ok(Async::Ready(())) } else { Ok(Async::NotReady) } } } /// A trait for constructing the usual client handles with coupled `Subscriber` structs. pub trait SubscriberTransport: DuplexTransport { /// Constructs a new client, client handle and a subscriber. fn subscriber_client<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send + Sized>( self, executor: E, ) -> ( jsonrpc_client_core::Client<Self, Server>, ClientHandle, Subscriber<E>, ); } /// Subscriber transport trait allows one to create a client future, a subscriber and a client /// handle from a valid JSON-RPC transport. impl<T: DuplexTransport> SubscriberTransport for T { /// Constructs a new client, client handle and a subscriber. fn subscriber_client<E: Executor<Box<Future<Item = (), Error = ()> + Send>> + Send>( self, executor: E, ) -> ( jsonrpc_client_core::Client<Self, Server>, ClientHandle, Subscriber<E>, ) { let (server, server_handle) = Server::new(); let (client, client_handle) = self.with_server(server); let subscriber = Subscriber::new(executor, client_handle.clone(), server_handle); (client, client_handle, subscriber) } }
//! //! [here]: https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB extern crate futures; extern crate jsonrpc_client_core;
random_line_split
boxed.rs
#![allow(unsafe_code)] use crate::ffi::sodium; use crate::traits::*; use std::cell::Cell; use std::fmt::{self, Debug}; use std::ptr::NonNull; use std::slice; use std::thread; /// The page protection applied to the memory underlying a [`Box`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Prot { /// Any attempt to read, write, or execute this memory will result /// in a segfault. NoAccess, /// Any attempt to write to or execute the contents of this memory /// will result in a segfault. Reads are permitted. ReadOnly, /// Any attempt to execute the contents of this memory will result /// in a segfault. Reads and writes are permitted. ReadWrite, } /// The type used for storing ref counts. Overflowing this type by /// borrowing too many times will cause a runtime panic. It seems /// implausible that there would be many legitimate use-cases where /// someone needs more than 255 simultaneous borrows of secret data. /// /// TODO: Perhaps this could be moved to an associated type on a trait, /// such that a user who did need a larger value could provide a /// larger replacement. type RefCount = u8; /// NOTE: This implementation is not meant to be exposed directly to /// end-users, and user-facing wrappers must be written with care to /// ensure they statically enforce the required invariants. These /// invariants are asserted with `debug_assert` in order to catch bugs /// at development-time, but these assertions will be compiled out in /// release-mode due to the expectation that they are enforced /// statically. /// /// TODO: document invariants #[derive(Eq)] pub(crate) struct Box<T: Bytes> { /// the non-null pointer to the underlying protected memory ptr: NonNull<T>, /// the number of elements of `T` that can be stored in `ptr` len: usize, /// the pointer's current protection level prot: Cell<Prot>, /// the number of outstanding borrows; mutable borrows are tracked /// here even though there is a max of one, so that asserts can /// ensure invariants are obeyed refs: Cell<RefCount>, } impl<T: Bytes> Box<T> { /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. The callback `F` will be used for initialization and will /// be called with a mutable reference to the unlocked [`Box`]. The /// [`Box`] will be locked before it is returned from this function. pub(crate) fn new<F>(len: usize, init: F) -> Self where F: FnOnce(&mut Self), { let mut boxed = Self::new_unlocked(len); proven!(boxed.ptr != std::ptr::NonNull::dangling()); proven!(boxed.len == len); init(&mut boxed); boxed.lock(); boxed } /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. The callback `F` will be used for initialization and will /// be called with a mutable reference to the unlocked [`Box`]. This /// callback must return a [`Result`] indicating whether or not the /// initialization succeeded (the [`Ok`] value is ignored). The /// [`Box`] will be locked before it is returned from this function. pub(crate) fn try_new<U, E, F>(len: usize, init: F) -> Result<Self, E> where F: FnOnce(&mut Self) -> Result<U, E> { let mut boxed = Self::new_unlocked(len); proven!(boxed.ptr != std::ptr::NonNull::dangling()); proven!(boxed.len == len); let result = init(&mut boxed); boxed.lock(); result.map(|_| boxed) } /// Returns the number of elements in the [`Box`]. #[allow(clippy::missing_const_for_fn)] // not usable on min supported Rust pub(crate) fn len(&self) -> usize { self.len } /// Returns true if the [`Box`] is empty. #[allow(clippy::missing_const_for_fn)] // not usable on min supported Rust pub(crate) fn is_empty(&self) -> bool { self.len == 0 } /// Returns the size in bytes of the data contained in the [`Box`]. /// This does not include incidental metadata used in the /// implementation of [`Box`] itself, only the size of the data /// allocated on behalf of the user. /// /// It is the maximum number of bytes that can be read from the /// internal pointer. pub(crate) fn size(&self) -> usize { self.len * T::size() } /// Allows the contents of the [`Box`] to be read from. Any call to /// this function *must* be balanced with a call to /// [`lock`](Box::lock). Mirroring Rust's borrowing rules, there may /// be any number of outstanding immutable unlocks (technically, /// limited by the max value of [`RefCount`]) *or* one mutable /// unlock. pub(crate) fn unlock(&self) -> &Self { self.retain(Prot::ReadOnly); self } /// Allows the contents of the [`Box`] to be read from and written /// to. Any call to this function *must* be balanced with a call to /// [`lock`](Box::lock). Mirroring Rust's borrowing rules, there may /// be any number of outstanding immutable unlocks (technically, /// limited by the max value of [`RefCount`]) *or* one mutable /// unlock. pub(crate) fn unlock_mut(&mut self) -> &mut Self { self.retain(Prot::ReadWrite); self } /// Disables all access to the underlying memory. Must only be /// called to precisely balance prior calls to [`unlock`](Box::unlock) /// and [`unlock_mut`](Box::unlock_mut). /// /// Calling this method in excess of the number of outstanding /// unlocks will result in a runtime panic. Omitting a call to this /// method and leaving an outstanding unlock will result in a /// runtime panic when this object is dropped. pub(crate) fn lock(&self) { self.release(); } /// Converts the [`Box`]'s contents into a reference. This must only /// happen while it is unlocked, and the reference must go out of /// scope before it is locked. /// /// Panics if `len == 0`, in which case it would be unsafe to /// dereference the internal pointer. pub(crate) fn as_ref(&self) -> &T { // we use never! here to ensure that panics happen in both debug // and release builds since it would be a violation of memory- // safety if a zero-length dereference happens never!(self.is_empty(), "secrets: attempted to dereference a zero-length pointer"); proven!(self.prot.get() != Prot::NoAccess, "secrets: may not call Box::as_ref while locked"); unsafe { self.ptr.as_ref() } } /// Converts the [`Box`]'s contents into a mutable reference. This /// must only happen while it is mutably unlocked, and the slice /// must go out of scope before it is locked. /// /// Panics if `len == 0`, in which case it would be unsafe to /// dereference the internal pointer. pub(crate) fn as_mut(&mut self) -> &mut T { // we use never! here to ensure that panics happen in both debug // and release builds since it would be a violation of memory- // safety if a zero-length dereference happens never!(self.is_empty(), "secrets: attempted to dereference a zero-length pointer"); proven!(self.prot.get() == Prot::ReadWrite, "secrets: may not call Box::as_mut unless mutably unlocked"); unsafe { self.ptr.as_mut() } } /// Converts the [`Box`]'s contents into a slice. This must only /// happen while it is unlocked, and the slice must go out of scope /// before it is locked. pub(crate) fn as_slice(&self) -> &[T] { // NOTE: after some consideration, I've decided that this method // and its as_mut_slice() sister *are* safe. // // Using the retuned ref might cause a SIGSEGV, but this is not // UB (in fact, it's explicitly defined behavior!), cannot cause // a data race, cannot produce an invalid primitive, nor can it // break any other guarantee of "safe Rust". Just a SIGSEGV. // // However, as currently used by wrappers in this crate, these // methods are *never* called on unlocked data. Doing so would // be indicative of a bug, so we want to detect this during // development. If it happens in release mode, it's not // explicitly unsafe so we don't need to enable this check. proven!(self.prot.get() != Prot::NoAccess, "secrets: may not call Box::as_slice while locked"); unsafe { slice::from_raw_parts( self.ptr.as_ptr(), self.len, ) } } /// Converts the [`Box`]'s contents into a mutable slice. This must /// only happen while it is mutably unlocked, and the slice must go /// out of scope before it is locked. pub(crate) fn as_mut_slice(&mut self) -> &mut [T] { proven!(self.prot.get() == Prot::ReadWrite, "secrets: may not call Box::as_mut_slice unless mutably unlocked"); unsafe { slice::from_raw_parts_mut( self.ptr.as_ptr(), self.len, ) } } /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. This [`Box`] will be unlocked and *must* be locked before /// it is dropped. /// /// TODO: make `len` a `NonZero` when it's stabilized and remove the /// related panic. fn new_unlocked(len: usize) -> Self { tested!(len == 0); tested!(std::mem::size_of::<T>() == 0); assert!(sodium::init(), "secrets: failed to initialize libsodium"); // `sodium::allocarray` returns a memory location that already // allows r/w access let ptr = NonNull::new(unsafe { sodium::allocarray::<T>(len) }) .expect("secrets: failed to allocate memory"); // NOTE: We technically could save a little extra work here by // initializing the struct with [`Prot::NoAccess`] and a zero // refcount, and manually calling `mprotect` when finished with // initialization. However, the `as_mut()` call performs sanity // checks that ensure it's [`Prot::ReadWrite`] so it's easier to // just send everything through the "normal" code paths. Self { ptr, len, prot: Cell::new(Prot::ReadWrite), refs: Cell::new(1), } } /// Performs the underlying retain half of the retain/release logic /// for monitoring outstanding calls to unlock. fn retain(&self, prot: Prot) { let refs = self.refs.get(); tested!(refs == RefCount::min_value()); tested!(refs == RefCount::max_value()); tested!(prot == Prot::NoAccess); if refs == 0 { // when retaining, we must retain to a protection level with // some access proven!(prot != Prot::NoAccess, "secrets: must retain readably or writably"); // allow access to the pointer and record what level of // access is being permitted // // ordering probably doesn't matter here, but we set our // internal protection flag first so we never run the risk // of believing that memory is protected when it isn't self.prot.set(prot); mprotect(self.ptr.as_ptr(), prot); } else { // if we have a nonzero retain count, there is nothing to // change, but we can assert some invariants: // // * our current protection level *must not* be // [`Prot::NoAccess`] or we have underflowed the ref // counter // * our current protection level *must not* be // [`Prot::ReadWrite`] because that would imply non- // exclusive mutable access // * our target protection level *must* be `ReadOnly` // since otherwise would involve changing the protection // level of a currently-borrowed resource proven!(Prot::NoAccess != self.prot.get(), "secrets: out-of-order retain/release detected"); proven!(Prot::ReadWrite != self.prot.get(), "secrets: cannot unlock mutably more than once"); proven!(Prot::ReadOnly == prot, "secrets: cannot unlock mutably while unlocked immutably"); } // "255 retains ought to be enough for anybody" // // We use `checked_add` to ensure we don't overflow our ref // counter. This is ensured even in production builds because // it's infeasible for consumers of this API to actually enforce // this. That said, it's unlikely that anyone would need to // have more than 255 outstanding retains at one time. // // This also protects us in the event of balanced, out-of-order // retain/release code. If an out-of-order `release` causes the // ref counter to wrap around below zero, the subsequent // `retain` will panic here. match refs.checked_add(1) { Some(v) => self.refs.set(v), None if self.is_locked() => panic!("secrets: out-of-order retain/release detected"), None => panic!("secrets: retained too many times"), }; } /// Removes one outsdanding retain, and changes the memory /// protection level back to [`Prot::NoAccess`] when the number of /// outstanding retains reaches zero. fn release(&self) { // When releasing, we should always have at least one retain // outstanding. This is enforced by all users through // refcounting on allocation and drop. proven!(self.refs.get() != 0, "secrets: releases exceeded retains"); // When releasing, our protection level must allow some kind of // access. If this condition isn't true, it was already // [`Prot::NoAccess`] so at least the memory was protected. proven!(self.prot.get() != Prot::NoAccess, "secrets: releasing memory that's already locked"); // Deciding whether or not to use `checked_sub` or // `wrapping_sub` here has pros and cons. The `proven!`s above // help us catch this kind of accident in development, but if // a released library has a bug that has imbalanced // retains/releases, `wrapping_sub` will cause the refcount to // underflow and wrap. // // `checked_sub` ensures that wrapping won't happen, but will // cause consistency issues in the event of balanced but // *out-of-order* calls to retain/release. In such a scenario, // this will cause the retain count to be nonzero at drop time, // leaving the memory unlocked for an indeterminate period of // time. // // We choose `wrapped_sub` here because, by undeflowing, it will // ensure that a subsequent `retain` will not unlock the memory // and will trigger a `checked_add` runtime panic which we find // preferable for safety purposes. let refs = self.refs.get().wrapping_sub(1); self.refs.set(refs); if refs == 0 { mprotect(self.ptr.as_ptr(), Prot::NoAccess); self.prot.set(Prot::NoAccess); } } /// Returns true if the protection level is [`NoAccess`]. Ignores /// ref count. fn is_locked(&self) -> bool { self.prot.get() == Prot::NoAccess } } impl<T: Bytes + Randomizable> Box<T> { /// Instantiates a new [`Box`] with crypotgraphically-randomized /// contents. pub(crate) fn random(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().randomize()) } } impl<T: Bytes + Zeroable> Box<T> { /// Instantiates a new [`Box`] whose backing memory is zeroed. pub(crate) fn zero(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().zero()) } } impl<T: Bytes> Drop for Box<T> { fn drop(&mut self) { // [`Drop::drop`] is called during stack unwinding, so we may be // in a panic already. if !thread::panicking() { // If this value is being dropped, we want to ensure that // every retain has been balanced with a release. If this // is not true in release, the memory will be freed // momentarily so we don't need to worry about it. proven!(self.refs.get() == 0, "secrets: retains exceeded releases"); // Similarly, any dropped value should have previously been // set to deny any access. proven!(self.prot.get() == Prot::NoAccess, "secrets: dropped secret was still accessible"); } unsafe { sodium::free(self.ptr.as_mut()) } } } impl<T: Bytes> Debug for Box<T> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{{ {} bytes redacted }}", self.size()) } } impl<T: Bytes> Clone for Box<T> { fn clone(&self) -> Self { Self::new(self.len, |b| { b.as_mut_slice().copy_from_slice(self.unlock().as_slice()); self.lock(); }) } } impl<T: Bytes + ConstantEq> PartialEq for Box<T> { fn eq(&self, other: &Self) -> bool { if self.len != other.len { return false; } let lhs = self.unlock().as_slice(); let rhs = other.unlock().as_slice(); let ret = lhs.constant_eq(rhs); self.lock(); other.lock(); ret } } impl<T: Bytes + Zeroable> From<&mut T> for Box<T> { fn from(data: &mut T) -> Self { // this is safe since the secret and data can never overlap Self::new(1, |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut()) } }) } } impl<T: Bytes + Zeroable> From<&mut [T]> for Box<T> { fn from(data: &mut [T]) -> Self { // this is safe since the secret and data can never overlap Self::new(data.len(), |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut_slice()) } }) } } unsafe impl<T: Bytes + Send> Send for Box<T> {} /// Immediately changes the page protection level on `ptr` to `prot`. fn mprotect<T>(ptr: *mut T, prot: Prot) { if !match prot { Prot::NoAccess => unsafe { sodium::mprotect_noaccess(ptr) }, Prot::ReadOnly => unsafe { sodium::mprotect_readonly(ptr) }, Prot::ReadWrite => unsafe { sodium::mprotect_readwrite(ptr) }, } { panic!("secrets: error setting memory protection to {:?}", prot); } } // LCOV_EXCL_START #[cfg(test)] mod tests { use super::*; #[test] fn it_allows_custom_initialization() { let boxed = Box::<u8>::new(1, |secret| { secret.as_mut_slice().clone_from_slice(b"\x04"); }); assert_eq!(boxed.unlock().as_slice(), [0x04]); boxed.lock(); } #[test] fn it_initializes_with_garbage() { let boxed = Box::<u8>::new(4, |_| {}); let unboxed = boxed.unlock().as_slice(); // sodium changed the value of the garbage byte they used, so we // allocate a byte and see what's inside to probe for the // specific value let garbage = unsafe { let garbage_ptr = sodium::allocarray::<u8>(1); let garbage_byte = *garbage_ptr; sodium::free(garbage_ptr); vec![garbage_byte; unboxed.len()] }; // sanity-check the garbage byte in case we have a bug in how we // probe for it assert_ne!(garbage, vec![0; garbage.len()]); assert_eq!(unboxed, &garbage[..]); boxed.lock(); } #[test] fn it_initializes_with_zero() { let boxed = Box::<u32>::zero(4); assert_eq!(boxed.unlock().as_slice(), [0, 0, 0, 0]); boxed.lock(); } #[test] fn it_initializes_from_values() { let mut value = [4_u64]; let boxed = Box::from(&mut value[..]); assert_eq!(value, [0]); assert_eq!(boxed.unlock().as_slice(), [4]); boxed.lock(); } #[test] fn it_compares_equality() { let boxed_1 = Box::<u8>::random(1); let boxed_2 = boxed_1.clone(); assert_eq!(boxed_1, boxed_2); assert_eq!(boxed_2, boxed_1); } #[test] fn it_compares_inequality() { let boxed_1 = Box::<u128>::random(32); let boxed_2 = Box::<u128>::random(32); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); } #[test] fn it_compares_inequality_using_size() { let boxed_1 = Box::<u8>::from(&mut [0, 0, 0, 0][..]); let boxed_2 = Box::<u8>::from(&mut [0, 0, 0, 0, 0][..]); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); } #[test] fn it_initializes_with_zero_refs() { let boxed = Box::<u8>::zero(10); assert_eq!(0, boxed.refs.get()); } #[test] fn it_tracks_ref_counts_accurately() { let mut boxed = Box::<u8>::random(10); let _ = boxed.unlock(); let _ = boxed.unlock(); let _ = boxed.unlock(); assert_eq!(3, boxed.refs.get()); boxed.lock(); boxed.lock(); boxed.lock(); assert_eq!(0, boxed.refs.get()); let _ = boxed.unlock_mut(); assert_eq!(1, boxed.refs.get()); boxed.lock(); assert_eq!(0, boxed.refs.get()); } #[test] fn it_doesnt_overflow_early() { let boxed = Box::<u64>::zero(4); for _ in 0..u8::max_value() { let _ = boxed.unlock(); } for _ in 0..u8::max_value() { boxed.lock(); } } #[test] fn it_allows_arbitrary_readers() { let boxed = Box::<u8>::zero(1); let mut count = 0_u8; sodium::memrandom(count.as_mut_bytes()); for _ in 0..count { let _ = boxed.unlock(); } for _ in 0..count { boxed.lock() } } #[test] fn it_can_be_sent_between_threads() { use std::sync::mpsc; use std::thread; let (tx, rx) = mpsc::channel(); let child = thread::spawn(move || { let boxed = Box::<u64>::random(1); let value = boxed.unlock().as_slice().to_vec(); // here we send an *unlocked* Box to the rx side; this lets // us make sure that the sent Box isn't dropped when this // thread exits, and that the other thread gets an unlocked // Box that it's responsible for locking tx.send((boxed, value)).expect("failed to send to channel"); }); let (boxed, value) = rx.recv().expect("failed to read from channel"); assert_eq!(Prot::ReadOnly, boxed.prot.get()); assert_eq!(value, boxed.as_slice()); child.join().expect("child terminated"); boxed.lock(); } #[test] #[should_panic(expected = "secrets: retained too many times")] fn it_doesnt_allow_overflowing_readers() { let boxed = Box::<[u64; 8]>::zero(4); for _ in 0..=u8::max_value() { let _ = boxed.unlock(); } // this ensures that we *don't* inadvertently panic if we // somehow made it through the above statement for _ in 0..boxed.refs.get() { boxed.lock() } } #[test] #[should_panic(expected = "secrets: out-of-order retain/release detected")] fn it_detects_out_of_order_retains_and_releases_that_underflow() { let boxed = Box::<u8>::zero(5); // manually set up this condition, since doing it using the // wrappers will cause other panics to happen boxed.refs.set(boxed.refs.get().wrapping_sub(1)); boxed.prot.set(Prot::NoAccess); boxed.retain(Prot::ReadOnly); } #[test] #[should_panic(expected = "secrets: failed to initialize libsodium")] fn it_detects_sodium_init_failure() { sodium::fail(); let _ = Box::<u8>::zero(0); } #[test] #[should_panic(expected = "secrets: error setting memory protection to NoAccess")] fn it_detects_sodium_mprotect_failure() { sodium::fail(); mprotect(std::ptr::null_mut::<u8>(), Prot::NoAccess); } } // There isn't a great way to run these tests on systems that don't have a native `fork()` call, so // we'll just skip them for now. #[cfg(all(test, target_family = "unix"))] mod tests_sigsegv { use super::*; use std::process; fn assert_sigsegv<F>(f: F) where F: FnOnce(), { unsafe { let pid : libc::pid_t = libc::fork(); let mut stat : libc::c_int = 0; match pid { -1 => panic!("`fork(2)` failed"), 0 => { f(); process::exit(0) }, _ => { if libc::waitpid(pid, &mut stat, 0) == -1 { panic!("`waitpid(2)` failed"); }; // assert that the process terminated due to a signal assert!(libc::WIFSIGNALED(stat)); // assert that we received a SIGBUS or SIGSEGV, // either of which can be sent by an attempt to // access protected memory regions assert!( libc::WTERMSIG(stat) == libc::SIGBUS || libc::WTERMSIG(stat) == libc::SIGSEGV ); } } } } #[test] fn it_kills_attempts_to_read_while_locked() { assert_sigsegv(|| { let val = unsafe { Box::<u32>::zero(1).ptr.as_ptr().read() }; // TODO: replace with [`test::black_box`] when stable let _ = sodium::memcmp(val.as_bytes(), val.as_bytes()); }); } #[test] fn it_kills_attempts_to_write_while_locked() { assert_sigsegv(|| { unsafe { Box::<u64>::zero(1).ptr.as_ptr().write(1) }; }); } #[test] fn it_kills_attempts_to_read_after_explicitly_locked() { assert_sigsegv(|| { let boxed = Box::<u32>::random(4); let val = boxed.unlock().as_slice(); let _ = boxed.unlock(); boxed.lock(); boxed.lock(); let _ = sodium::memcmp( val.as_bytes(), val.as_bytes(), ); }); } } #[cfg(all(test, profile = "debug"))] mod tests_proven_statements { use super::*; #[test] #[should_panic(expected = "secrets: attempted to dereference a zero-length pointer")] fn it_doesnt_allow_referencing_zero_length() { let boxed = Box::<u8>::new_unlocked(0); let _ = boxed.as_ref(); } #[test] #[should_panic(expected = "secrets: cannot unlock mutably more than once")] fn it_doesnt_allow_multiple_writers() { let mut boxed = Box::<u64>::zero(1); let _ = boxed.unlock_mut(); let _ = boxed.unlock_mut(); } #[test]
#[test] #[should_panic(expected = "secrets: releases exceeded retains")] fn it_doesnt_allow_unbalanced_locking() { let boxed = Box::<u64>::zero(4); let _ = boxed.unlock(); boxed.lock(); boxed.lock(); } #[test] #[should_panic(expected = "secrets: cannot unlock mutably while unlocked immutably")] fn it_doesnt_allow_different_access_types() { let mut boxed = Box::<[u128; 128]>::zero(5); let _ = boxed.unlock(); let _ = boxed.unlock_mut(); } #[test] #[should_panic(expected = "secrets: retains exceeded releases")] fn it_doesnt_allow_outstanding_readers() { let _ = Box::<u8>::zero(1).unlock(); } #[test] #[should_panic(expected = "secrets: retains exceeded releases")] fn it_doesnt_allow_outstanding_writers() { let _ = Box::<u8>::zero(1).unlock_mut(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_ref while locked")] fn it_doesnt_allow_as_ref_while_locked() { let _ = Box::<u8>::zero(1).as_ref(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut unless mutably unlocked")] fn it_doesnt_allow_as_mut_while_locked() { let _ = Box::<u8>::zero(1).as_mut(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut unless mutably unlocked")] fn it_doesnt_allow_as_mut_while_readonly() { let mut boxed = Box::<u8>::zero(1); let _ = boxed.unlock(); let _ = boxed.as_mut(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_slice while locked")] fn it_doesnt_allow_as_slice_while_locked() { let _ = Box::<u8>::zero(1).as_slice(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut_slice unless mutably unlocked")] fn it_doesnt_allow_as_mut_slice_while_locked() { let _ = Box::<u8>::zero(1).as_mut_slice(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut_slice unless mutably unlocked")] fn it_doesnt_allow_as_mut_slice_while_readonly() { let mut boxed = Box::<u8>::zero(1); let _ = boxed.unlock(); let _ = boxed.as_mut_slice(); } } // LCOV_EXCL_STOP
#[should_panic(expected = "secrets: releases exceeded retains")] fn it_doesnt_allow_negative_users() { Box::<u64>::zero(10).lock(); }
random_line_split
boxed.rs
#![allow(unsafe_code)] use crate::ffi::sodium; use crate::traits::*; use std::cell::Cell; use std::fmt::{self, Debug}; use std::ptr::NonNull; use std::slice; use std::thread; /// The page protection applied to the memory underlying a [`Box`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Prot { /// Any attempt to read, write, or execute this memory will result /// in a segfault. NoAccess, /// Any attempt to write to or execute the contents of this memory /// will result in a segfault. Reads are permitted. ReadOnly, /// Any attempt to execute the contents of this memory will result /// in a segfault. Reads and writes are permitted. ReadWrite, } /// The type used for storing ref counts. Overflowing this type by /// borrowing too many times will cause a runtime panic. It seems /// implausible that there would be many legitimate use-cases where /// someone needs more than 255 simultaneous borrows of secret data. /// /// TODO: Perhaps this could be moved to an associated type on a trait, /// such that a user who did need a larger value could provide a /// larger replacement. type RefCount = u8; /// NOTE: This implementation is not meant to be exposed directly to /// end-users, and user-facing wrappers must be written with care to /// ensure they statically enforce the required invariants. These /// invariants are asserted with `debug_assert` in order to catch bugs /// at development-time, but these assertions will be compiled out in /// release-mode due to the expectation that they are enforced /// statically. /// /// TODO: document invariants #[derive(Eq)] pub(crate) struct Box<T: Bytes> { /// the non-null pointer to the underlying protected memory ptr: NonNull<T>, /// the number of elements of `T` that can be stored in `ptr` len: usize, /// the pointer's current protection level prot: Cell<Prot>, /// the number of outstanding borrows; mutable borrows are tracked /// here even though there is a max of one, so that asserts can /// ensure invariants are obeyed refs: Cell<RefCount>, } impl<T: Bytes> Box<T> { /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. The callback `F` will be used for initialization and will /// be called with a mutable reference to the unlocked [`Box`]. The /// [`Box`] will be locked before it is returned from this function. pub(crate) fn new<F>(len: usize, init: F) -> Self where F: FnOnce(&mut Self), { let mut boxed = Self::new_unlocked(len); proven!(boxed.ptr != std::ptr::NonNull::dangling()); proven!(boxed.len == len); init(&mut boxed); boxed.lock(); boxed } /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. The callback `F` will be used for initialization and will /// be called with a mutable reference to the unlocked [`Box`]. This /// callback must return a [`Result`] indicating whether or not the /// initialization succeeded (the [`Ok`] value is ignored). The /// [`Box`] will be locked before it is returned from this function. pub(crate) fn try_new<U, E, F>(len: usize, init: F) -> Result<Self, E> where F: FnOnce(&mut Self) -> Result<U, E> { let mut boxed = Self::new_unlocked(len); proven!(boxed.ptr != std::ptr::NonNull::dangling()); proven!(boxed.len == len); let result = init(&mut boxed); boxed.lock(); result.map(|_| boxed) } /// Returns the number of elements in the [`Box`]. #[allow(clippy::missing_const_for_fn)] // not usable on min supported Rust pub(crate) fn len(&self) -> usize { self.len } /// Returns true if the [`Box`] is empty. #[allow(clippy::missing_const_for_fn)] // not usable on min supported Rust pub(crate) fn is_empty(&self) -> bool { self.len == 0 } /// Returns the size in bytes of the data contained in the [`Box`]. /// This does not include incidental metadata used in the /// implementation of [`Box`] itself, only the size of the data /// allocated on behalf of the user. /// /// It is the maximum number of bytes that can be read from the /// internal pointer. pub(crate) fn size(&self) -> usize { self.len * T::size() } /// Allows the contents of the [`Box`] to be read from. Any call to /// this function *must* be balanced with a call to /// [`lock`](Box::lock). Mirroring Rust's borrowing rules, there may /// be any number of outstanding immutable unlocks (technically, /// limited by the max value of [`RefCount`]) *or* one mutable /// unlock. pub(crate) fn unlock(&self) -> &Self { self.retain(Prot::ReadOnly); self } /// Allows the contents of the [`Box`] to be read from and written /// to. Any call to this function *must* be balanced with a call to /// [`lock`](Box::lock). Mirroring Rust's borrowing rules, there may /// be any number of outstanding immutable unlocks (technically, /// limited by the max value of [`RefCount`]) *or* one mutable /// unlock. pub(crate) fn unlock_mut(&mut self) -> &mut Self { self.retain(Prot::ReadWrite); self } /// Disables all access to the underlying memory. Must only be /// called to precisely balance prior calls to [`unlock`](Box::unlock) /// and [`unlock_mut`](Box::unlock_mut). /// /// Calling this method in excess of the number of outstanding /// unlocks will result in a runtime panic. Omitting a call to this /// method and leaving an outstanding unlock will result in a /// runtime panic when this object is dropped. pub(crate) fn lock(&self) { self.release(); } /// Converts the [`Box`]'s contents into a reference. This must only /// happen while it is unlocked, and the reference must go out of /// scope before it is locked. /// /// Panics if `len == 0`, in which case it would be unsafe to /// dereference the internal pointer. pub(crate) fn as_ref(&self) -> &T { // we use never! here to ensure that panics happen in both debug // and release builds since it would be a violation of memory- // safety if a zero-length dereference happens never!(self.is_empty(), "secrets: attempted to dereference a zero-length pointer"); proven!(self.prot.get() != Prot::NoAccess, "secrets: may not call Box::as_ref while locked"); unsafe { self.ptr.as_ref() } } /// Converts the [`Box`]'s contents into a mutable reference. This /// must only happen while it is mutably unlocked, and the slice /// must go out of scope before it is locked. /// /// Panics if `len == 0`, in which case it would be unsafe to /// dereference the internal pointer. pub(crate) fn as_mut(&mut self) -> &mut T { // we use never! here to ensure that panics happen in both debug // and release builds since it would be a violation of memory- // safety if a zero-length dereference happens never!(self.is_empty(), "secrets: attempted to dereference a zero-length pointer"); proven!(self.prot.get() == Prot::ReadWrite, "secrets: may not call Box::as_mut unless mutably unlocked"); unsafe { self.ptr.as_mut() } } /// Converts the [`Box`]'s contents into a slice. This must only /// happen while it is unlocked, and the slice must go out of scope /// before it is locked. pub(crate) fn as_slice(&self) -> &[T] { // NOTE: after some consideration, I've decided that this method // and its as_mut_slice() sister *are* safe. // // Using the retuned ref might cause a SIGSEGV, but this is not // UB (in fact, it's explicitly defined behavior!), cannot cause // a data race, cannot produce an invalid primitive, nor can it // break any other guarantee of "safe Rust". Just a SIGSEGV. // // However, as currently used by wrappers in this crate, these // methods are *never* called on unlocked data. Doing so would // be indicative of a bug, so we want to detect this during // development. If it happens in release mode, it's not // explicitly unsafe so we don't need to enable this check. proven!(self.prot.get() != Prot::NoAccess, "secrets: may not call Box::as_slice while locked"); unsafe { slice::from_raw_parts( self.ptr.as_ptr(), self.len, ) } } /// Converts the [`Box`]'s contents into a mutable slice. This must /// only happen while it is mutably unlocked, and the slice must go /// out of scope before it is locked. pub(crate) fn as_mut_slice(&mut self) -> &mut [T] { proven!(self.prot.get() == Prot::ReadWrite, "secrets: may not call Box::as_mut_slice unless mutably unlocked"); unsafe { slice::from_raw_parts_mut( self.ptr.as_ptr(), self.len, ) } } /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. This [`Box`] will be unlocked and *must* be locked before /// it is dropped. /// /// TODO: make `len` a `NonZero` when it's stabilized and remove the /// related panic. fn new_unlocked(len: usize) -> Self { tested!(len == 0); tested!(std::mem::size_of::<T>() == 0); assert!(sodium::init(), "secrets: failed to initialize libsodium"); // `sodium::allocarray` returns a memory location that already // allows r/w access let ptr = NonNull::new(unsafe { sodium::allocarray::<T>(len) }) .expect("secrets: failed to allocate memory"); // NOTE: We technically could save a little extra work here by // initializing the struct with [`Prot::NoAccess`] and a zero // refcount, and manually calling `mprotect` when finished with // initialization. However, the `as_mut()` call performs sanity // checks that ensure it's [`Prot::ReadWrite`] so it's easier to // just send everything through the "normal" code paths. Self { ptr, len, prot: Cell::new(Prot::ReadWrite), refs: Cell::new(1), } } /// Performs the underlying retain half of the retain/release logic /// for monitoring outstanding calls to unlock. fn retain(&self, prot: Prot) { let refs = self.refs.get(); tested!(refs == RefCount::min_value()); tested!(refs == RefCount::max_value()); tested!(prot == Prot::NoAccess); if refs == 0 { // when retaining, we must retain to a protection level with // some access proven!(prot != Prot::NoAccess, "secrets: must retain readably or writably"); // allow access to the pointer and record what level of // access is being permitted // // ordering probably doesn't matter here, but we set our // internal protection flag first so we never run the risk // of believing that memory is protected when it isn't self.prot.set(prot); mprotect(self.ptr.as_ptr(), prot); } else { // if we have a nonzero retain count, there is nothing to // change, but we can assert some invariants: // // * our current protection level *must not* be // [`Prot::NoAccess`] or we have underflowed the ref // counter // * our current protection level *must not* be // [`Prot::ReadWrite`] because that would imply non- // exclusive mutable access // * our target protection level *must* be `ReadOnly` // since otherwise would involve changing the protection // level of a currently-borrowed resource proven!(Prot::NoAccess != self.prot.get(), "secrets: out-of-order retain/release detected"); proven!(Prot::ReadWrite != self.prot.get(), "secrets: cannot unlock mutably more than once"); proven!(Prot::ReadOnly == prot, "secrets: cannot unlock mutably while unlocked immutably"); } // "255 retains ought to be enough for anybody" // // We use `checked_add` to ensure we don't overflow our ref // counter. This is ensured even in production builds because // it's infeasible for consumers of this API to actually enforce // this. That said, it's unlikely that anyone would need to // have more than 255 outstanding retains at one time. // // This also protects us in the event of balanced, out-of-order // retain/release code. If an out-of-order `release` causes the // ref counter to wrap around below zero, the subsequent // `retain` will panic here. match refs.checked_add(1) { Some(v) => self.refs.set(v), None if self.is_locked() => panic!("secrets: out-of-order retain/release detected"), None => panic!("secrets: retained too many times"), }; } /// Removes one outsdanding retain, and changes the memory /// protection level back to [`Prot::NoAccess`] when the number of /// outstanding retains reaches zero. fn release(&self) { // When releasing, we should always have at least one retain // outstanding. This is enforced by all users through // refcounting on allocation and drop. proven!(self.refs.get() != 0, "secrets: releases exceeded retains"); // When releasing, our protection level must allow some kind of // access. If this condition isn't true, it was already // [`Prot::NoAccess`] so at least the memory was protected. proven!(self.prot.get() != Prot::NoAccess, "secrets: releasing memory that's already locked"); // Deciding whether or not to use `checked_sub` or // `wrapping_sub` here has pros and cons. The `proven!`s above // help us catch this kind of accident in development, but if // a released library has a bug that has imbalanced // retains/releases, `wrapping_sub` will cause the refcount to // underflow and wrap. // // `checked_sub` ensures that wrapping won't happen, but will // cause consistency issues in the event of balanced but // *out-of-order* calls to retain/release. In such a scenario, // this will cause the retain count to be nonzero at drop time, // leaving the memory unlocked for an indeterminate period of // time. // // We choose `wrapped_sub` here because, by undeflowing, it will // ensure that a subsequent `retain` will not unlock the memory // and will trigger a `checked_add` runtime panic which we find // preferable for safety purposes. let refs = self.refs.get().wrapping_sub(1); self.refs.set(refs); if refs == 0 { mprotect(self.ptr.as_ptr(), Prot::NoAccess); self.prot.set(Prot::NoAccess); } } /// Returns true if the protection level is [`NoAccess`]. Ignores /// ref count. fn is_locked(&self) -> bool { self.prot.get() == Prot::NoAccess } } impl<T: Bytes + Randomizable> Box<T> { /// Instantiates a new [`Box`] with crypotgraphically-randomized /// contents. pub(crate) fn random(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().randomize()) } } impl<T: Bytes + Zeroable> Box<T> { /// Instantiates a new [`Box`] whose backing memory is zeroed. pub(crate) fn zero(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().zero()) } } impl<T: Bytes> Drop for Box<T> { fn drop(&mut self) { // [`Drop::drop`] is called during stack unwinding, so we may be // in a panic already. if !thread::panicking() { // If this value is being dropped, we want to ensure that // every retain has been balanced with a release. If this // is not true in release, the memory will be freed // momentarily so we don't need to worry about it. proven!(self.refs.get() == 0, "secrets: retains exceeded releases"); // Similarly, any dropped value should have previously been // set to deny any access. proven!(self.prot.get() == Prot::NoAccess, "secrets: dropped secret was still accessible"); } unsafe { sodium::free(self.ptr.as_mut()) } } } impl<T: Bytes> Debug for Box<T> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{{ {} bytes redacted }}", self.size()) } } impl<T: Bytes> Clone for Box<T> { fn clone(&self) -> Self { Self::new(self.len, |b| { b.as_mut_slice().copy_from_slice(self.unlock().as_slice()); self.lock(); }) } } impl<T: Bytes + ConstantEq> PartialEq for Box<T> { fn eq(&self, other: &Self) -> bool { if self.len != other.len { return false; } let lhs = self.unlock().as_slice(); let rhs = other.unlock().as_slice(); let ret = lhs.constant_eq(rhs); self.lock(); other.lock(); ret } } impl<T: Bytes + Zeroable> From<&mut T> for Box<T> { fn from(data: &mut T) -> Self { // this is safe since the secret and data can never overlap Self::new(1, |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut()) } }) } } impl<T: Bytes + Zeroable> From<&mut [T]> for Box<T> { fn from(data: &mut [T]) -> Self { // this is safe since the secret and data can never overlap Self::new(data.len(), |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut_slice()) } }) } } unsafe impl<T: Bytes + Send> Send for Box<T> {} /// Immediately changes the page protection level on `ptr` to `prot`. fn mprotect<T>(ptr: *mut T, prot: Prot) { if !match prot { Prot::NoAccess => unsafe { sodium::mprotect_noaccess(ptr) }, Prot::ReadOnly => unsafe { sodium::mprotect_readonly(ptr) }, Prot::ReadWrite => unsafe { sodium::mprotect_readwrite(ptr) }, } { panic!("secrets: error setting memory protection to {:?}", prot); } } // LCOV_EXCL_START #[cfg(test)] mod tests { use super::*; #[test] fn it_allows_custom_initialization() { let boxed = Box::<u8>::new(1, |secret| { secret.as_mut_slice().clone_from_slice(b"\x04"); }); assert_eq!(boxed.unlock().as_slice(), [0x04]); boxed.lock(); } #[test] fn it_initializes_with_garbage() { let boxed = Box::<u8>::new(4, |_| {}); let unboxed = boxed.unlock().as_slice(); // sodium changed the value of the garbage byte they used, so we // allocate a byte and see what's inside to probe for the // specific value let garbage = unsafe { let garbage_ptr = sodium::allocarray::<u8>(1); let garbage_byte = *garbage_ptr; sodium::free(garbage_ptr); vec![garbage_byte; unboxed.len()] }; // sanity-check the garbage byte in case we have a bug in how we // probe for it assert_ne!(garbage, vec![0; garbage.len()]); assert_eq!(unboxed, &garbage[..]); boxed.lock(); } #[test] fn it_initializes_with_zero() { let boxed = Box::<u32>::zero(4); assert_eq!(boxed.unlock().as_slice(), [0, 0, 0, 0]); boxed.lock(); } #[test] fn it_initializes_from_values() { let mut value = [4_u64]; let boxed = Box::from(&mut value[..]); assert_eq!(value, [0]); assert_eq!(boxed.unlock().as_slice(), [4]); boxed.lock(); } #[test] fn it_compares_equality() { let boxed_1 = Box::<u8>::random(1); let boxed_2 = boxed_1.clone(); assert_eq!(boxed_1, boxed_2); assert_eq!(boxed_2, boxed_1); } #[test] fn it_compares_inequality() { let boxed_1 = Box::<u128>::random(32); let boxed_2 = Box::<u128>::random(32); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); } #[test] fn it_compares_inequality_using_size()
#[test] fn it_initializes_with_zero_refs() { let boxed = Box::<u8>::zero(10); assert_eq!(0, boxed.refs.get()); } #[test] fn it_tracks_ref_counts_accurately() { let mut boxed = Box::<u8>::random(10); let _ = boxed.unlock(); let _ = boxed.unlock(); let _ = boxed.unlock(); assert_eq!(3, boxed.refs.get()); boxed.lock(); boxed.lock(); boxed.lock(); assert_eq!(0, boxed.refs.get()); let _ = boxed.unlock_mut(); assert_eq!(1, boxed.refs.get()); boxed.lock(); assert_eq!(0, boxed.refs.get()); } #[test] fn it_doesnt_overflow_early() { let boxed = Box::<u64>::zero(4); for _ in 0..u8::max_value() { let _ = boxed.unlock(); } for _ in 0..u8::max_value() { boxed.lock(); } } #[test] fn it_allows_arbitrary_readers() { let boxed = Box::<u8>::zero(1); let mut count = 0_u8; sodium::memrandom(count.as_mut_bytes()); for _ in 0..count { let _ = boxed.unlock(); } for _ in 0..count { boxed.lock() } } #[test] fn it_can_be_sent_between_threads() { use std::sync::mpsc; use std::thread; let (tx, rx) = mpsc::channel(); let child = thread::spawn(move || { let boxed = Box::<u64>::random(1); let value = boxed.unlock().as_slice().to_vec(); // here we send an *unlocked* Box to the rx side; this lets // us make sure that the sent Box isn't dropped when this // thread exits, and that the other thread gets an unlocked // Box that it's responsible for locking tx.send((boxed, value)).expect("failed to send to channel"); }); let (boxed, value) = rx.recv().expect("failed to read from channel"); assert_eq!(Prot::ReadOnly, boxed.prot.get()); assert_eq!(value, boxed.as_slice()); child.join().expect("child terminated"); boxed.lock(); } #[test] #[should_panic(expected = "secrets: retained too many times")] fn it_doesnt_allow_overflowing_readers() { let boxed = Box::<[u64; 8]>::zero(4); for _ in 0..=u8::max_value() { let _ = boxed.unlock(); } // this ensures that we *don't* inadvertently panic if we // somehow made it through the above statement for _ in 0..boxed.refs.get() { boxed.lock() } } #[test] #[should_panic(expected = "secrets: out-of-order retain/release detected")] fn it_detects_out_of_order_retains_and_releases_that_underflow() { let boxed = Box::<u8>::zero(5); // manually set up this condition, since doing it using the // wrappers will cause other panics to happen boxed.refs.set(boxed.refs.get().wrapping_sub(1)); boxed.prot.set(Prot::NoAccess); boxed.retain(Prot::ReadOnly); } #[test] #[should_panic(expected = "secrets: failed to initialize libsodium")] fn it_detects_sodium_init_failure() { sodium::fail(); let _ = Box::<u8>::zero(0); } #[test] #[should_panic(expected = "secrets: error setting memory protection to NoAccess")] fn it_detects_sodium_mprotect_failure() { sodium::fail(); mprotect(std::ptr::null_mut::<u8>(), Prot::NoAccess); } } // There isn't a great way to run these tests on systems that don't have a native `fork()` call, so // we'll just skip them for now. #[cfg(all(test, target_family = "unix"))] mod tests_sigsegv { use super::*; use std::process; fn assert_sigsegv<F>(f: F) where F: FnOnce(), { unsafe { let pid : libc::pid_t = libc::fork(); let mut stat : libc::c_int = 0; match pid { -1 => panic!("`fork(2)` failed"), 0 => { f(); process::exit(0) }, _ => { if libc::waitpid(pid, &mut stat, 0) == -1 { panic!("`waitpid(2)` failed"); }; // assert that the process terminated due to a signal assert!(libc::WIFSIGNALED(stat)); // assert that we received a SIGBUS or SIGSEGV, // either of which can be sent by an attempt to // access protected memory regions assert!( libc::WTERMSIG(stat) == libc::SIGBUS || libc::WTERMSIG(stat) == libc::SIGSEGV ); } } } } #[test] fn it_kills_attempts_to_read_while_locked() { assert_sigsegv(|| { let val = unsafe { Box::<u32>::zero(1).ptr.as_ptr().read() }; // TODO: replace with [`test::black_box`] when stable let _ = sodium::memcmp(val.as_bytes(), val.as_bytes()); }); } #[test] fn it_kills_attempts_to_write_while_locked() { assert_sigsegv(|| { unsafe { Box::<u64>::zero(1).ptr.as_ptr().write(1) }; }); } #[test] fn it_kills_attempts_to_read_after_explicitly_locked() { assert_sigsegv(|| { let boxed = Box::<u32>::random(4); let val = boxed.unlock().as_slice(); let _ = boxed.unlock(); boxed.lock(); boxed.lock(); let _ = sodium::memcmp( val.as_bytes(), val.as_bytes(), ); }); } } #[cfg(all(test, profile = "debug"))] mod tests_proven_statements { use super::*; #[test] #[should_panic(expected = "secrets: attempted to dereference a zero-length pointer")] fn it_doesnt_allow_referencing_zero_length() { let boxed = Box::<u8>::new_unlocked(0); let _ = boxed.as_ref(); } #[test] #[should_panic(expected = "secrets: cannot unlock mutably more than once")] fn it_doesnt_allow_multiple_writers() { let mut boxed = Box::<u64>::zero(1); let _ = boxed.unlock_mut(); let _ = boxed.unlock_mut(); } #[test] #[should_panic(expected = "secrets: releases exceeded retains")] fn it_doesnt_allow_negative_users() { Box::<u64>::zero(10).lock(); } #[test] #[should_panic(expected = "secrets: releases exceeded retains")] fn it_doesnt_allow_unbalanced_locking() { let boxed = Box::<u64>::zero(4); let _ = boxed.unlock(); boxed.lock(); boxed.lock(); } #[test] #[should_panic(expected = "secrets: cannot unlock mutably while unlocked immutably")] fn it_doesnt_allow_different_access_types() { let mut boxed = Box::<[u128; 128]>::zero(5); let _ = boxed.unlock(); let _ = boxed.unlock_mut(); } #[test] #[should_panic(expected = "secrets: retains exceeded releases")] fn it_doesnt_allow_outstanding_readers() { let _ = Box::<u8>::zero(1).unlock(); } #[test] #[should_panic(expected = "secrets: retains exceeded releases")] fn it_doesnt_allow_outstanding_writers() { let _ = Box::<u8>::zero(1).unlock_mut(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_ref while locked")] fn it_doesnt_allow_as_ref_while_locked() { let _ = Box::<u8>::zero(1).as_ref(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut unless mutably unlocked")] fn it_doesnt_allow_as_mut_while_locked() { let _ = Box::<u8>::zero(1).as_mut(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut unless mutably unlocked")] fn it_doesnt_allow_as_mut_while_readonly() { let mut boxed = Box::<u8>::zero(1); let _ = boxed.unlock(); let _ = boxed.as_mut(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_slice while locked")] fn it_doesnt_allow_as_slice_while_locked() { let _ = Box::<u8>::zero(1).as_slice(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut_slice unless mutably unlocked")] fn it_doesnt_allow_as_mut_slice_while_locked() { let _ = Box::<u8>::zero(1).as_mut_slice(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut_slice unless mutably unlocked")] fn it_doesnt_allow_as_mut_slice_while_readonly() { let mut boxed = Box::<u8>::zero(1); let _ = boxed.unlock(); let _ = boxed.as_mut_slice(); } } // LCOV_EXCL_STOP
{ let boxed_1 = Box::<u8>::from(&mut [0, 0, 0, 0][..]); let boxed_2 = Box::<u8>::from(&mut [0, 0, 0, 0, 0][..]); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); }
identifier_body
boxed.rs
#![allow(unsafe_code)] use crate::ffi::sodium; use crate::traits::*; use std::cell::Cell; use std::fmt::{self, Debug}; use std::ptr::NonNull; use std::slice; use std::thread; /// The page protection applied to the memory underlying a [`Box`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Prot { /// Any attempt to read, write, or execute this memory will result /// in a segfault. NoAccess, /// Any attempt to write to or execute the contents of this memory /// will result in a segfault. Reads are permitted. ReadOnly, /// Any attempt to execute the contents of this memory will result /// in a segfault. Reads and writes are permitted. ReadWrite, } /// The type used for storing ref counts. Overflowing this type by /// borrowing too many times will cause a runtime panic. It seems /// implausible that there would be many legitimate use-cases where /// someone needs more than 255 simultaneous borrows of secret data. /// /// TODO: Perhaps this could be moved to an associated type on a trait, /// such that a user who did need a larger value could provide a /// larger replacement. type RefCount = u8; /// NOTE: This implementation is not meant to be exposed directly to /// end-users, and user-facing wrappers must be written with care to /// ensure they statically enforce the required invariants. These /// invariants are asserted with `debug_assert` in order to catch bugs /// at development-time, but these assertions will be compiled out in /// release-mode due to the expectation that they are enforced /// statically. /// /// TODO: document invariants #[derive(Eq)] pub(crate) struct Box<T: Bytes> { /// the non-null pointer to the underlying protected memory ptr: NonNull<T>, /// the number of elements of `T` that can be stored in `ptr` len: usize, /// the pointer's current protection level prot: Cell<Prot>, /// the number of outstanding borrows; mutable borrows are tracked /// here even though there is a max of one, so that asserts can /// ensure invariants are obeyed refs: Cell<RefCount>, } impl<T: Bytes> Box<T> { /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. The callback `F` will be used for initialization and will /// be called with a mutable reference to the unlocked [`Box`]. The /// [`Box`] will be locked before it is returned from this function. pub(crate) fn new<F>(len: usize, init: F) -> Self where F: FnOnce(&mut Self), { let mut boxed = Self::new_unlocked(len); proven!(boxed.ptr != std::ptr::NonNull::dangling()); proven!(boxed.len == len); init(&mut boxed); boxed.lock(); boxed } /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. The callback `F` will be used for initialization and will /// be called with a mutable reference to the unlocked [`Box`]. This /// callback must return a [`Result`] indicating whether or not the /// initialization succeeded (the [`Ok`] value is ignored). The /// [`Box`] will be locked before it is returned from this function. pub(crate) fn try_new<U, E, F>(len: usize, init: F) -> Result<Self, E> where F: FnOnce(&mut Self) -> Result<U, E> { let mut boxed = Self::new_unlocked(len); proven!(boxed.ptr != std::ptr::NonNull::dangling()); proven!(boxed.len == len); let result = init(&mut boxed); boxed.lock(); result.map(|_| boxed) } /// Returns the number of elements in the [`Box`]. #[allow(clippy::missing_const_for_fn)] // not usable on min supported Rust pub(crate) fn len(&self) -> usize { self.len } /// Returns true if the [`Box`] is empty. #[allow(clippy::missing_const_for_fn)] // not usable on min supported Rust pub(crate) fn is_empty(&self) -> bool { self.len == 0 } /// Returns the size in bytes of the data contained in the [`Box`]. /// This does not include incidental metadata used in the /// implementation of [`Box`] itself, only the size of the data /// allocated on behalf of the user. /// /// It is the maximum number of bytes that can be read from the /// internal pointer. pub(crate) fn size(&self) -> usize { self.len * T::size() } /// Allows the contents of the [`Box`] to be read from. Any call to /// this function *must* be balanced with a call to /// [`lock`](Box::lock). Mirroring Rust's borrowing rules, there may /// be any number of outstanding immutable unlocks (technically, /// limited by the max value of [`RefCount`]) *or* one mutable /// unlock. pub(crate) fn unlock(&self) -> &Self { self.retain(Prot::ReadOnly); self } /// Allows the contents of the [`Box`] to be read from and written /// to. Any call to this function *must* be balanced with a call to /// [`lock`](Box::lock). Mirroring Rust's borrowing rules, there may /// be any number of outstanding immutable unlocks (technically, /// limited by the max value of [`RefCount`]) *or* one mutable /// unlock. pub(crate) fn unlock_mut(&mut self) -> &mut Self { self.retain(Prot::ReadWrite); self } /// Disables all access to the underlying memory. Must only be /// called to precisely balance prior calls to [`unlock`](Box::unlock) /// and [`unlock_mut`](Box::unlock_mut). /// /// Calling this method in excess of the number of outstanding /// unlocks will result in a runtime panic. Omitting a call to this /// method and leaving an outstanding unlock will result in a /// runtime panic when this object is dropped. pub(crate) fn lock(&self) { self.release(); } /// Converts the [`Box`]'s contents into a reference. This must only /// happen while it is unlocked, and the reference must go out of /// scope before it is locked. /// /// Panics if `len == 0`, in which case it would be unsafe to /// dereference the internal pointer. pub(crate) fn as_ref(&self) -> &T { // we use never! here to ensure that panics happen in both debug // and release builds since it would be a violation of memory- // safety if a zero-length dereference happens never!(self.is_empty(), "secrets: attempted to dereference a zero-length pointer"); proven!(self.prot.get() != Prot::NoAccess, "secrets: may not call Box::as_ref while locked"); unsafe { self.ptr.as_ref() } } /// Converts the [`Box`]'s contents into a mutable reference. This /// must only happen while it is mutably unlocked, and the slice /// must go out of scope before it is locked. /// /// Panics if `len == 0`, in which case it would be unsafe to /// dereference the internal pointer. pub(crate) fn as_mut(&mut self) -> &mut T { // we use never! here to ensure that panics happen in both debug // and release builds since it would be a violation of memory- // safety if a zero-length dereference happens never!(self.is_empty(), "secrets: attempted to dereference a zero-length pointer"); proven!(self.prot.get() == Prot::ReadWrite, "secrets: may not call Box::as_mut unless mutably unlocked"); unsafe { self.ptr.as_mut() } } /// Converts the [`Box`]'s contents into a slice. This must only /// happen while it is unlocked, and the slice must go out of scope /// before it is locked. pub(crate) fn as_slice(&self) -> &[T] { // NOTE: after some consideration, I've decided that this method // and its as_mut_slice() sister *are* safe. // // Using the retuned ref might cause a SIGSEGV, but this is not // UB (in fact, it's explicitly defined behavior!), cannot cause // a data race, cannot produce an invalid primitive, nor can it // break any other guarantee of "safe Rust". Just a SIGSEGV. // // However, as currently used by wrappers in this crate, these // methods are *never* called on unlocked data. Doing so would // be indicative of a bug, so we want to detect this during // development. If it happens in release mode, it's not // explicitly unsafe so we don't need to enable this check. proven!(self.prot.get() != Prot::NoAccess, "secrets: may not call Box::as_slice while locked"); unsafe { slice::from_raw_parts( self.ptr.as_ptr(), self.len, ) } } /// Converts the [`Box`]'s contents into a mutable slice. This must /// only happen while it is mutably unlocked, and the slice must go /// out of scope before it is locked. pub(crate) fn as_mut_slice(&mut self) -> &mut [T] { proven!(self.prot.get() == Prot::ReadWrite, "secrets: may not call Box::as_mut_slice unless mutably unlocked"); unsafe { slice::from_raw_parts_mut( self.ptr.as_ptr(), self.len, ) } } /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. This [`Box`] will be unlocked and *must* be locked before /// it is dropped. /// /// TODO: make `len` a `NonZero` when it's stabilized and remove the /// related panic. fn new_unlocked(len: usize) -> Self { tested!(len == 0); tested!(std::mem::size_of::<T>() == 0); assert!(sodium::init(), "secrets: failed to initialize libsodium"); // `sodium::allocarray` returns a memory location that already // allows r/w access let ptr = NonNull::new(unsafe { sodium::allocarray::<T>(len) }) .expect("secrets: failed to allocate memory"); // NOTE: We technically could save a little extra work here by // initializing the struct with [`Prot::NoAccess`] and a zero // refcount, and manually calling `mprotect` when finished with // initialization. However, the `as_mut()` call performs sanity // checks that ensure it's [`Prot::ReadWrite`] so it's easier to // just send everything through the "normal" code paths. Self { ptr, len, prot: Cell::new(Prot::ReadWrite), refs: Cell::new(1), } } /// Performs the underlying retain half of the retain/release logic /// for monitoring outstanding calls to unlock. fn retain(&self, prot: Prot) { let refs = self.refs.get(); tested!(refs == RefCount::min_value()); tested!(refs == RefCount::max_value()); tested!(prot == Prot::NoAccess); if refs == 0 { // when retaining, we must retain to a protection level with // some access proven!(prot != Prot::NoAccess, "secrets: must retain readably or writably"); // allow access to the pointer and record what level of // access is being permitted // // ordering probably doesn't matter here, but we set our // internal protection flag first so we never run the risk // of believing that memory is protected when it isn't self.prot.set(prot); mprotect(self.ptr.as_ptr(), prot); } else { // if we have a nonzero retain count, there is nothing to // change, but we can assert some invariants: // // * our current protection level *must not* be // [`Prot::NoAccess`] or we have underflowed the ref // counter // * our current protection level *must not* be // [`Prot::ReadWrite`] because that would imply non- // exclusive mutable access // * our target protection level *must* be `ReadOnly` // since otherwise would involve changing the protection // level of a currently-borrowed resource proven!(Prot::NoAccess != self.prot.get(), "secrets: out-of-order retain/release detected"); proven!(Prot::ReadWrite != self.prot.get(), "secrets: cannot unlock mutably more than once"); proven!(Prot::ReadOnly == prot, "secrets: cannot unlock mutably while unlocked immutably"); } // "255 retains ought to be enough for anybody" // // We use `checked_add` to ensure we don't overflow our ref // counter. This is ensured even in production builds because // it's infeasible for consumers of this API to actually enforce // this. That said, it's unlikely that anyone would need to // have more than 255 outstanding retains at one time. // // This also protects us in the event of balanced, out-of-order // retain/release code. If an out-of-order `release` causes the // ref counter to wrap around below zero, the subsequent // `retain` will panic here. match refs.checked_add(1) { Some(v) => self.refs.set(v), None if self.is_locked() => panic!("secrets: out-of-order retain/release detected"), None => panic!("secrets: retained too many times"), }; } /// Removes one outsdanding retain, and changes the memory /// protection level back to [`Prot::NoAccess`] when the number of /// outstanding retains reaches zero. fn
(&self) { // When releasing, we should always have at least one retain // outstanding. This is enforced by all users through // refcounting on allocation and drop. proven!(self.refs.get() != 0, "secrets: releases exceeded retains"); // When releasing, our protection level must allow some kind of // access. If this condition isn't true, it was already // [`Prot::NoAccess`] so at least the memory was protected. proven!(self.prot.get() != Prot::NoAccess, "secrets: releasing memory that's already locked"); // Deciding whether or not to use `checked_sub` or // `wrapping_sub` here has pros and cons. The `proven!`s above // help us catch this kind of accident in development, but if // a released library has a bug that has imbalanced // retains/releases, `wrapping_sub` will cause the refcount to // underflow and wrap. // // `checked_sub` ensures that wrapping won't happen, but will // cause consistency issues in the event of balanced but // *out-of-order* calls to retain/release. In such a scenario, // this will cause the retain count to be nonzero at drop time, // leaving the memory unlocked for an indeterminate period of // time. // // We choose `wrapped_sub` here because, by undeflowing, it will // ensure that a subsequent `retain` will not unlock the memory // and will trigger a `checked_add` runtime panic which we find // preferable for safety purposes. let refs = self.refs.get().wrapping_sub(1); self.refs.set(refs); if refs == 0 { mprotect(self.ptr.as_ptr(), Prot::NoAccess); self.prot.set(Prot::NoAccess); } } /// Returns true if the protection level is [`NoAccess`]. Ignores /// ref count. fn is_locked(&self) -> bool { self.prot.get() == Prot::NoAccess } } impl<T: Bytes + Randomizable> Box<T> { /// Instantiates a new [`Box`] with crypotgraphically-randomized /// contents. pub(crate) fn random(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().randomize()) } } impl<T: Bytes + Zeroable> Box<T> { /// Instantiates a new [`Box`] whose backing memory is zeroed. pub(crate) fn zero(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().zero()) } } impl<T: Bytes> Drop for Box<T> { fn drop(&mut self) { // [`Drop::drop`] is called during stack unwinding, so we may be // in a panic already. if !thread::panicking() { // If this value is being dropped, we want to ensure that // every retain has been balanced with a release. If this // is not true in release, the memory will be freed // momentarily so we don't need to worry about it. proven!(self.refs.get() == 0, "secrets: retains exceeded releases"); // Similarly, any dropped value should have previously been // set to deny any access. proven!(self.prot.get() == Prot::NoAccess, "secrets: dropped secret was still accessible"); } unsafe { sodium::free(self.ptr.as_mut()) } } } impl<T: Bytes> Debug for Box<T> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{{ {} bytes redacted }}", self.size()) } } impl<T: Bytes> Clone for Box<T> { fn clone(&self) -> Self { Self::new(self.len, |b| { b.as_mut_slice().copy_from_slice(self.unlock().as_slice()); self.lock(); }) } } impl<T: Bytes + ConstantEq> PartialEq for Box<T> { fn eq(&self, other: &Self) -> bool { if self.len != other.len { return false; } let lhs = self.unlock().as_slice(); let rhs = other.unlock().as_slice(); let ret = lhs.constant_eq(rhs); self.lock(); other.lock(); ret } } impl<T: Bytes + Zeroable> From<&mut T> for Box<T> { fn from(data: &mut T) -> Self { // this is safe since the secret and data can never overlap Self::new(1, |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut()) } }) } } impl<T: Bytes + Zeroable> From<&mut [T]> for Box<T> { fn from(data: &mut [T]) -> Self { // this is safe since the secret and data can never overlap Self::new(data.len(), |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut_slice()) } }) } } unsafe impl<T: Bytes + Send> Send for Box<T> {} /// Immediately changes the page protection level on `ptr` to `prot`. fn mprotect<T>(ptr: *mut T, prot: Prot) { if !match prot { Prot::NoAccess => unsafe { sodium::mprotect_noaccess(ptr) }, Prot::ReadOnly => unsafe { sodium::mprotect_readonly(ptr) }, Prot::ReadWrite => unsafe { sodium::mprotect_readwrite(ptr) }, } { panic!("secrets: error setting memory protection to {:?}", prot); } } // LCOV_EXCL_START #[cfg(test)] mod tests { use super::*; #[test] fn it_allows_custom_initialization() { let boxed = Box::<u8>::new(1, |secret| { secret.as_mut_slice().clone_from_slice(b"\x04"); }); assert_eq!(boxed.unlock().as_slice(), [0x04]); boxed.lock(); } #[test] fn it_initializes_with_garbage() { let boxed = Box::<u8>::new(4, |_| {}); let unboxed = boxed.unlock().as_slice(); // sodium changed the value of the garbage byte they used, so we // allocate a byte and see what's inside to probe for the // specific value let garbage = unsafe { let garbage_ptr = sodium::allocarray::<u8>(1); let garbage_byte = *garbage_ptr; sodium::free(garbage_ptr); vec![garbage_byte; unboxed.len()] }; // sanity-check the garbage byte in case we have a bug in how we // probe for it assert_ne!(garbage, vec![0; garbage.len()]); assert_eq!(unboxed, &garbage[..]); boxed.lock(); } #[test] fn it_initializes_with_zero() { let boxed = Box::<u32>::zero(4); assert_eq!(boxed.unlock().as_slice(), [0, 0, 0, 0]); boxed.lock(); } #[test] fn it_initializes_from_values() { let mut value = [4_u64]; let boxed = Box::from(&mut value[..]); assert_eq!(value, [0]); assert_eq!(boxed.unlock().as_slice(), [4]); boxed.lock(); } #[test] fn it_compares_equality() { let boxed_1 = Box::<u8>::random(1); let boxed_2 = boxed_1.clone(); assert_eq!(boxed_1, boxed_2); assert_eq!(boxed_2, boxed_1); } #[test] fn it_compares_inequality() { let boxed_1 = Box::<u128>::random(32); let boxed_2 = Box::<u128>::random(32); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); } #[test] fn it_compares_inequality_using_size() { let boxed_1 = Box::<u8>::from(&mut [0, 0, 0, 0][..]); let boxed_2 = Box::<u8>::from(&mut [0, 0, 0, 0, 0][..]); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); } #[test] fn it_initializes_with_zero_refs() { let boxed = Box::<u8>::zero(10); assert_eq!(0, boxed.refs.get()); } #[test] fn it_tracks_ref_counts_accurately() { let mut boxed = Box::<u8>::random(10); let _ = boxed.unlock(); let _ = boxed.unlock(); let _ = boxed.unlock(); assert_eq!(3, boxed.refs.get()); boxed.lock(); boxed.lock(); boxed.lock(); assert_eq!(0, boxed.refs.get()); let _ = boxed.unlock_mut(); assert_eq!(1, boxed.refs.get()); boxed.lock(); assert_eq!(0, boxed.refs.get()); } #[test] fn it_doesnt_overflow_early() { let boxed = Box::<u64>::zero(4); for _ in 0..u8::max_value() { let _ = boxed.unlock(); } for _ in 0..u8::max_value() { boxed.lock(); } } #[test] fn it_allows_arbitrary_readers() { let boxed = Box::<u8>::zero(1); let mut count = 0_u8; sodium::memrandom(count.as_mut_bytes()); for _ in 0..count { let _ = boxed.unlock(); } for _ in 0..count { boxed.lock() } } #[test] fn it_can_be_sent_between_threads() { use std::sync::mpsc; use std::thread; let (tx, rx) = mpsc::channel(); let child = thread::spawn(move || { let boxed = Box::<u64>::random(1); let value = boxed.unlock().as_slice().to_vec(); // here we send an *unlocked* Box to the rx side; this lets // us make sure that the sent Box isn't dropped when this // thread exits, and that the other thread gets an unlocked // Box that it's responsible for locking tx.send((boxed, value)).expect("failed to send to channel"); }); let (boxed, value) = rx.recv().expect("failed to read from channel"); assert_eq!(Prot::ReadOnly, boxed.prot.get()); assert_eq!(value, boxed.as_slice()); child.join().expect("child terminated"); boxed.lock(); } #[test] #[should_panic(expected = "secrets: retained too many times")] fn it_doesnt_allow_overflowing_readers() { let boxed = Box::<[u64; 8]>::zero(4); for _ in 0..=u8::max_value() { let _ = boxed.unlock(); } // this ensures that we *don't* inadvertently panic if we // somehow made it through the above statement for _ in 0..boxed.refs.get() { boxed.lock() } } #[test] #[should_panic(expected = "secrets: out-of-order retain/release detected")] fn it_detects_out_of_order_retains_and_releases_that_underflow() { let boxed = Box::<u8>::zero(5); // manually set up this condition, since doing it using the // wrappers will cause other panics to happen boxed.refs.set(boxed.refs.get().wrapping_sub(1)); boxed.prot.set(Prot::NoAccess); boxed.retain(Prot::ReadOnly); } #[test] #[should_panic(expected = "secrets: failed to initialize libsodium")] fn it_detects_sodium_init_failure() { sodium::fail(); let _ = Box::<u8>::zero(0); } #[test] #[should_panic(expected = "secrets: error setting memory protection to NoAccess")] fn it_detects_sodium_mprotect_failure() { sodium::fail(); mprotect(std::ptr::null_mut::<u8>(), Prot::NoAccess); } } // There isn't a great way to run these tests on systems that don't have a native `fork()` call, so // we'll just skip them for now. #[cfg(all(test, target_family = "unix"))] mod tests_sigsegv { use super::*; use std::process; fn assert_sigsegv<F>(f: F) where F: FnOnce(), { unsafe { let pid : libc::pid_t = libc::fork(); let mut stat : libc::c_int = 0; match pid { -1 => panic!("`fork(2)` failed"), 0 => { f(); process::exit(0) }, _ => { if libc::waitpid(pid, &mut stat, 0) == -1 { panic!("`waitpid(2)` failed"); }; // assert that the process terminated due to a signal assert!(libc::WIFSIGNALED(stat)); // assert that we received a SIGBUS or SIGSEGV, // either of which can be sent by an attempt to // access protected memory regions assert!( libc::WTERMSIG(stat) == libc::SIGBUS || libc::WTERMSIG(stat) == libc::SIGSEGV ); } } } } #[test] fn it_kills_attempts_to_read_while_locked() { assert_sigsegv(|| { let val = unsafe { Box::<u32>::zero(1).ptr.as_ptr().read() }; // TODO: replace with [`test::black_box`] when stable let _ = sodium::memcmp(val.as_bytes(), val.as_bytes()); }); } #[test] fn it_kills_attempts_to_write_while_locked() { assert_sigsegv(|| { unsafe { Box::<u64>::zero(1).ptr.as_ptr().write(1) }; }); } #[test] fn it_kills_attempts_to_read_after_explicitly_locked() { assert_sigsegv(|| { let boxed = Box::<u32>::random(4); let val = boxed.unlock().as_slice(); let _ = boxed.unlock(); boxed.lock(); boxed.lock(); let _ = sodium::memcmp( val.as_bytes(), val.as_bytes(), ); }); } } #[cfg(all(test, profile = "debug"))] mod tests_proven_statements { use super::*; #[test] #[should_panic(expected = "secrets: attempted to dereference a zero-length pointer")] fn it_doesnt_allow_referencing_zero_length() { let boxed = Box::<u8>::new_unlocked(0); let _ = boxed.as_ref(); } #[test] #[should_panic(expected = "secrets: cannot unlock mutably more than once")] fn it_doesnt_allow_multiple_writers() { let mut boxed = Box::<u64>::zero(1); let _ = boxed.unlock_mut(); let _ = boxed.unlock_mut(); } #[test] #[should_panic(expected = "secrets: releases exceeded retains")] fn it_doesnt_allow_negative_users() { Box::<u64>::zero(10).lock(); } #[test] #[should_panic(expected = "secrets: releases exceeded retains")] fn it_doesnt_allow_unbalanced_locking() { let boxed = Box::<u64>::zero(4); let _ = boxed.unlock(); boxed.lock(); boxed.lock(); } #[test] #[should_panic(expected = "secrets: cannot unlock mutably while unlocked immutably")] fn it_doesnt_allow_different_access_types() { let mut boxed = Box::<[u128; 128]>::zero(5); let _ = boxed.unlock(); let _ = boxed.unlock_mut(); } #[test] #[should_panic(expected = "secrets: retains exceeded releases")] fn it_doesnt_allow_outstanding_readers() { let _ = Box::<u8>::zero(1).unlock(); } #[test] #[should_panic(expected = "secrets: retains exceeded releases")] fn it_doesnt_allow_outstanding_writers() { let _ = Box::<u8>::zero(1).unlock_mut(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_ref while locked")] fn it_doesnt_allow_as_ref_while_locked() { let _ = Box::<u8>::zero(1).as_ref(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut unless mutably unlocked")] fn it_doesnt_allow_as_mut_while_locked() { let _ = Box::<u8>::zero(1).as_mut(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut unless mutably unlocked")] fn it_doesnt_allow_as_mut_while_readonly() { let mut boxed = Box::<u8>::zero(1); let _ = boxed.unlock(); let _ = boxed.as_mut(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_slice while locked")] fn it_doesnt_allow_as_slice_while_locked() { let _ = Box::<u8>::zero(1).as_slice(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut_slice unless mutably unlocked")] fn it_doesnt_allow_as_mut_slice_while_locked() { let _ = Box::<u8>::zero(1).as_mut_slice(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut_slice unless mutably unlocked")] fn it_doesnt_allow_as_mut_slice_while_readonly() { let mut boxed = Box::<u8>::zero(1); let _ = boxed.unlock(); let _ = boxed.as_mut_slice(); } } // LCOV_EXCL_STOP
release
identifier_name
boxed.rs
#![allow(unsafe_code)] use crate::ffi::sodium; use crate::traits::*; use std::cell::Cell; use std::fmt::{self, Debug}; use std::ptr::NonNull; use std::slice; use std::thread; /// The page protection applied to the memory underlying a [`Box`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Prot { /// Any attempt to read, write, or execute this memory will result /// in a segfault. NoAccess, /// Any attempt to write to or execute the contents of this memory /// will result in a segfault. Reads are permitted. ReadOnly, /// Any attempt to execute the contents of this memory will result /// in a segfault. Reads and writes are permitted. ReadWrite, } /// The type used for storing ref counts. Overflowing this type by /// borrowing too many times will cause a runtime panic. It seems /// implausible that there would be many legitimate use-cases where /// someone needs more than 255 simultaneous borrows of secret data. /// /// TODO: Perhaps this could be moved to an associated type on a trait, /// such that a user who did need a larger value could provide a /// larger replacement. type RefCount = u8; /// NOTE: This implementation is not meant to be exposed directly to /// end-users, and user-facing wrappers must be written with care to /// ensure they statically enforce the required invariants. These /// invariants are asserted with `debug_assert` in order to catch bugs /// at development-time, but these assertions will be compiled out in /// release-mode due to the expectation that they are enforced /// statically. /// /// TODO: document invariants #[derive(Eq)] pub(crate) struct Box<T: Bytes> { /// the non-null pointer to the underlying protected memory ptr: NonNull<T>, /// the number of elements of `T` that can be stored in `ptr` len: usize, /// the pointer's current protection level prot: Cell<Prot>, /// the number of outstanding borrows; mutable borrows are tracked /// here even though there is a max of one, so that asserts can /// ensure invariants are obeyed refs: Cell<RefCount>, } impl<T: Bytes> Box<T> { /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. The callback `F` will be used for initialization and will /// be called with a mutable reference to the unlocked [`Box`]. The /// [`Box`] will be locked before it is returned from this function. pub(crate) fn new<F>(len: usize, init: F) -> Self where F: FnOnce(&mut Self), { let mut boxed = Self::new_unlocked(len); proven!(boxed.ptr != std::ptr::NonNull::dangling()); proven!(boxed.len == len); init(&mut boxed); boxed.lock(); boxed } /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. The callback `F` will be used for initialization and will /// be called with a mutable reference to the unlocked [`Box`]. This /// callback must return a [`Result`] indicating whether or not the /// initialization succeeded (the [`Ok`] value is ignored). The /// [`Box`] will be locked before it is returned from this function. pub(crate) fn try_new<U, E, F>(len: usize, init: F) -> Result<Self, E> where F: FnOnce(&mut Self) -> Result<U, E> { let mut boxed = Self::new_unlocked(len); proven!(boxed.ptr != std::ptr::NonNull::dangling()); proven!(boxed.len == len); let result = init(&mut boxed); boxed.lock(); result.map(|_| boxed) } /// Returns the number of elements in the [`Box`]. #[allow(clippy::missing_const_for_fn)] // not usable on min supported Rust pub(crate) fn len(&self) -> usize { self.len } /// Returns true if the [`Box`] is empty. #[allow(clippy::missing_const_for_fn)] // not usable on min supported Rust pub(crate) fn is_empty(&self) -> bool { self.len == 0 } /// Returns the size in bytes of the data contained in the [`Box`]. /// This does not include incidental metadata used in the /// implementation of [`Box`] itself, only the size of the data /// allocated on behalf of the user. /// /// It is the maximum number of bytes that can be read from the /// internal pointer. pub(crate) fn size(&self) -> usize { self.len * T::size() } /// Allows the contents of the [`Box`] to be read from. Any call to /// this function *must* be balanced with a call to /// [`lock`](Box::lock). Mirroring Rust's borrowing rules, there may /// be any number of outstanding immutable unlocks (technically, /// limited by the max value of [`RefCount`]) *or* one mutable /// unlock. pub(crate) fn unlock(&self) -> &Self { self.retain(Prot::ReadOnly); self } /// Allows the contents of the [`Box`] to be read from and written /// to. Any call to this function *must* be balanced with a call to /// [`lock`](Box::lock). Mirroring Rust's borrowing rules, there may /// be any number of outstanding immutable unlocks (technically, /// limited by the max value of [`RefCount`]) *or* one mutable /// unlock. pub(crate) fn unlock_mut(&mut self) -> &mut Self { self.retain(Prot::ReadWrite); self } /// Disables all access to the underlying memory. Must only be /// called to precisely balance prior calls to [`unlock`](Box::unlock) /// and [`unlock_mut`](Box::unlock_mut). /// /// Calling this method in excess of the number of outstanding /// unlocks will result in a runtime panic. Omitting a call to this /// method and leaving an outstanding unlock will result in a /// runtime panic when this object is dropped. pub(crate) fn lock(&self) { self.release(); } /// Converts the [`Box`]'s contents into a reference. This must only /// happen while it is unlocked, and the reference must go out of /// scope before it is locked. /// /// Panics if `len == 0`, in which case it would be unsafe to /// dereference the internal pointer. pub(crate) fn as_ref(&self) -> &T { // we use never! here to ensure that panics happen in both debug // and release builds since it would be a violation of memory- // safety if a zero-length dereference happens never!(self.is_empty(), "secrets: attempted to dereference a zero-length pointer"); proven!(self.prot.get() != Prot::NoAccess, "secrets: may not call Box::as_ref while locked"); unsafe { self.ptr.as_ref() } } /// Converts the [`Box`]'s contents into a mutable reference. This /// must only happen while it is mutably unlocked, and the slice /// must go out of scope before it is locked. /// /// Panics if `len == 0`, in which case it would be unsafe to /// dereference the internal pointer. pub(crate) fn as_mut(&mut self) -> &mut T { // we use never! here to ensure that panics happen in both debug // and release builds since it would be a violation of memory- // safety if a zero-length dereference happens never!(self.is_empty(), "secrets: attempted to dereference a zero-length pointer"); proven!(self.prot.get() == Prot::ReadWrite, "secrets: may not call Box::as_mut unless mutably unlocked"); unsafe { self.ptr.as_mut() } } /// Converts the [`Box`]'s contents into a slice. This must only /// happen while it is unlocked, and the slice must go out of scope /// before it is locked. pub(crate) fn as_slice(&self) -> &[T] { // NOTE: after some consideration, I've decided that this method // and its as_mut_slice() sister *are* safe. // // Using the retuned ref might cause a SIGSEGV, but this is not // UB (in fact, it's explicitly defined behavior!), cannot cause // a data race, cannot produce an invalid primitive, nor can it // break any other guarantee of "safe Rust". Just a SIGSEGV. // // However, as currently used by wrappers in this crate, these // methods are *never* called on unlocked data. Doing so would // be indicative of a bug, so we want to detect this during // development. If it happens in release mode, it's not // explicitly unsafe so we don't need to enable this check. proven!(self.prot.get() != Prot::NoAccess, "secrets: may not call Box::as_slice while locked"); unsafe { slice::from_raw_parts( self.ptr.as_ptr(), self.len, ) } } /// Converts the [`Box`]'s contents into a mutable slice. This must /// only happen while it is mutably unlocked, and the slice must go /// out of scope before it is locked. pub(crate) fn as_mut_slice(&mut self) -> &mut [T] { proven!(self.prot.get() == Prot::ReadWrite, "secrets: may not call Box::as_mut_slice unless mutably unlocked"); unsafe { slice::from_raw_parts_mut( self.ptr.as_ptr(), self.len, ) } } /// Instantiates a new [`Box`] that can hold `len` elements of type /// `T`. This [`Box`] will be unlocked and *must* be locked before /// it is dropped. /// /// TODO: make `len` a `NonZero` when it's stabilized and remove the /// related panic. fn new_unlocked(len: usize) -> Self { tested!(len == 0); tested!(std::mem::size_of::<T>() == 0); assert!(sodium::init(), "secrets: failed to initialize libsodium"); // `sodium::allocarray` returns a memory location that already // allows r/w access let ptr = NonNull::new(unsafe { sodium::allocarray::<T>(len) }) .expect("secrets: failed to allocate memory"); // NOTE: We technically could save a little extra work here by // initializing the struct with [`Prot::NoAccess`] and a zero // refcount, and manually calling `mprotect` when finished with // initialization. However, the `as_mut()` call performs sanity // checks that ensure it's [`Prot::ReadWrite`] so it's easier to // just send everything through the "normal" code paths. Self { ptr, len, prot: Cell::new(Prot::ReadWrite), refs: Cell::new(1), } } /// Performs the underlying retain half of the retain/release logic /// for monitoring outstanding calls to unlock. fn retain(&self, prot: Prot) { let refs = self.refs.get(); tested!(refs == RefCount::min_value()); tested!(refs == RefCount::max_value()); tested!(prot == Prot::NoAccess); if refs == 0 { // when retaining, we must retain to a protection level with // some access proven!(prot != Prot::NoAccess, "secrets: must retain readably or writably"); // allow access to the pointer and record what level of // access is being permitted // // ordering probably doesn't matter here, but we set our // internal protection flag first so we never run the risk // of believing that memory is protected when it isn't self.prot.set(prot); mprotect(self.ptr.as_ptr(), prot); } else { // if we have a nonzero retain count, there is nothing to // change, but we can assert some invariants: // // * our current protection level *must not* be // [`Prot::NoAccess`] or we have underflowed the ref // counter // * our current protection level *must not* be // [`Prot::ReadWrite`] because that would imply non- // exclusive mutable access // * our target protection level *must* be `ReadOnly` // since otherwise would involve changing the protection // level of a currently-borrowed resource proven!(Prot::NoAccess != self.prot.get(), "secrets: out-of-order retain/release detected"); proven!(Prot::ReadWrite != self.prot.get(), "secrets: cannot unlock mutably more than once"); proven!(Prot::ReadOnly == prot, "secrets: cannot unlock mutably while unlocked immutably"); } // "255 retains ought to be enough for anybody" // // We use `checked_add` to ensure we don't overflow our ref // counter. This is ensured even in production builds because // it's infeasible for consumers of this API to actually enforce // this. That said, it's unlikely that anyone would need to // have more than 255 outstanding retains at one time. // // This also protects us in the event of balanced, out-of-order // retain/release code. If an out-of-order `release` causes the // ref counter to wrap around below zero, the subsequent // `retain` will panic here. match refs.checked_add(1) { Some(v) => self.refs.set(v), None if self.is_locked() => panic!("secrets: out-of-order retain/release detected"), None => panic!("secrets: retained too many times"), }; } /// Removes one outsdanding retain, and changes the memory /// protection level back to [`Prot::NoAccess`] when the number of /// outstanding retains reaches zero. fn release(&self) { // When releasing, we should always have at least one retain // outstanding. This is enforced by all users through // refcounting on allocation and drop. proven!(self.refs.get() != 0, "secrets: releases exceeded retains"); // When releasing, our protection level must allow some kind of // access. If this condition isn't true, it was already // [`Prot::NoAccess`] so at least the memory was protected. proven!(self.prot.get() != Prot::NoAccess, "secrets: releasing memory that's already locked"); // Deciding whether or not to use `checked_sub` or // `wrapping_sub` here has pros and cons. The `proven!`s above // help us catch this kind of accident in development, but if // a released library has a bug that has imbalanced // retains/releases, `wrapping_sub` will cause the refcount to // underflow and wrap. // // `checked_sub` ensures that wrapping won't happen, but will // cause consistency issues in the event of balanced but // *out-of-order* calls to retain/release. In such a scenario, // this will cause the retain count to be nonzero at drop time, // leaving the memory unlocked for an indeterminate period of // time. // // We choose `wrapped_sub` here because, by undeflowing, it will // ensure that a subsequent `retain` will not unlock the memory // and will trigger a `checked_add` runtime panic which we find // preferable for safety purposes. let refs = self.refs.get().wrapping_sub(1); self.refs.set(refs); if refs == 0
} /// Returns true if the protection level is [`NoAccess`]. Ignores /// ref count. fn is_locked(&self) -> bool { self.prot.get() == Prot::NoAccess } } impl<T: Bytes + Randomizable> Box<T> { /// Instantiates a new [`Box`] with crypotgraphically-randomized /// contents. pub(crate) fn random(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().randomize()) } } impl<T: Bytes + Zeroable> Box<T> { /// Instantiates a new [`Box`] whose backing memory is zeroed. pub(crate) fn zero(len: usize) -> Self { Self::new(len, |b| b.as_mut_slice().zero()) } } impl<T: Bytes> Drop for Box<T> { fn drop(&mut self) { // [`Drop::drop`] is called during stack unwinding, so we may be // in a panic already. if !thread::panicking() { // If this value is being dropped, we want to ensure that // every retain has been balanced with a release. If this // is not true in release, the memory will be freed // momentarily so we don't need to worry about it. proven!(self.refs.get() == 0, "secrets: retains exceeded releases"); // Similarly, any dropped value should have previously been // set to deny any access. proven!(self.prot.get() == Prot::NoAccess, "secrets: dropped secret was still accessible"); } unsafe { sodium::free(self.ptr.as_mut()) } } } impl<T: Bytes> Debug for Box<T> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{{ {} bytes redacted }}", self.size()) } } impl<T: Bytes> Clone for Box<T> { fn clone(&self) -> Self { Self::new(self.len, |b| { b.as_mut_slice().copy_from_slice(self.unlock().as_slice()); self.lock(); }) } } impl<T: Bytes + ConstantEq> PartialEq for Box<T> { fn eq(&self, other: &Self) -> bool { if self.len != other.len { return false; } let lhs = self.unlock().as_slice(); let rhs = other.unlock().as_slice(); let ret = lhs.constant_eq(rhs); self.lock(); other.lock(); ret } } impl<T: Bytes + Zeroable> From<&mut T> for Box<T> { fn from(data: &mut T) -> Self { // this is safe since the secret and data can never overlap Self::new(1, |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut()) } }) } } impl<T: Bytes + Zeroable> From<&mut [T]> for Box<T> { fn from(data: &mut [T]) -> Self { // this is safe since the secret and data can never overlap Self::new(data.len(), |b| { let _ = &data; // ensure the entirety of `data` is closed over unsafe { data.transfer(b.as_mut_slice()) } }) } } unsafe impl<T: Bytes + Send> Send for Box<T> {} /// Immediately changes the page protection level on `ptr` to `prot`. fn mprotect<T>(ptr: *mut T, prot: Prot) { if !match prot { Prot::NoAccess => unsafe { sodium::mprotect_noaccess(ptr) }, Prot::ReadOnly => unsafe { sodium::mprotect_readonly(ptr) }, Prot::ReadWrite => unsafe { sodium::mprotect_readwrite(ptr) }, } { panic!("secrets: error setting memory protection to {:?}", prot); } } // LCOV_EXCL_START #[cfg(test)] mod tests { use super::*; #[test] fn it_allows_custom_initialization() { let boxed = Box::<u8>::new(1, |secret| { secret.as_mut_slice().clone_from_slice(b"\x04"); }); assert_eq!(boxed.unlock().as_slice(), [0x04]); boxed.lock(); } #[test] fn it_initializes_with_garbage() { let boxed = Box::<u8>::new(4, |_| {}); let unboxed = boxed.unlock().as_slice(); // sodium changed the value of the garbage byte they used, so we // allocate a byte and see what's inside to probe for the // specific value let garbage = unsafe { let garbage_ptr = sodium::allocarray::<u8>(1); let garbage_byte = *garbage_ptr; sodium::free(garbage_ptr); vec![garbage_byte; unboxed.len()] }; // sanity-check the garbage byte in case we have a bug in how we // probe for it assert_ne!(garbage, vec![0; garbage.len()]); assert_eq!(unboxed, &garbage[..]); boxed.lock(); } #[test] fn it_initializes_with_zero() { let boxed = Box::<u32>::zero(4); assert_eq!(boxed.unlock().as_slice(), [0, 0, 0, 0]); boxed.lock(); } #[test] fn it_initializes_from_values() { let mut value = [4_u64]; let boxed = Box::from(&mut value[..]); assert_eq!(value, [0]); assert_eq!(boxed.unlock().as_slice(), [4]); boxed.lock(); } #[test] fn it_compares_equality() { let boxed_1 = Box::<u8>::random(1); let boxed_2 = boxed_1.clone(); assert_eq!(boxed_1, boxed_2); assert_eq!(boxed_2, boxed_1); } #[test] fn it_compares_inequality() { let boxed_1 = Box::<u128>::random(32); let boxed_2 = Box::<u128>::random(32); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); } #[test] fn it_compares_inequality_using_size() { let boxed_1 = Box::<u8>::from(&mut [0, 0, 0, 0][..]); let boxed_2 = Box::<u8>::from(&mut [0, 0, 0, 0, 0][..]); assert_ne!(boxed_1, boxed_2); assert_ne!(boxed_2, boxed_1); } #[test] fn it_initializes_with_zero_refs() { let boxed = Box::<u8>::zero(10); assert_eq!(0, boxed.refs.get()); } #[test] fn it_tracks_ref_counts_accurately() { let mut boxed = Box::<u8>::random(10); let _ = boxed.unlock(); let _ = boxed.unlock(); let _ = boxed.unlock(); assert_eq!(3, boxed.refs.get()); boxed.lock(); boxed.lock(); boxed.lock(); assert_eq!(0, boxed.refs.get()); let _ = boxed.unlock_mut(); assert_eq!(1, boxed.refs.get()); boxed.lock(); assert_eq!(0, boxed.refs.get()); } #[test] fn it_doesnt_overflow_early() { let boxed = Box::<u64>::zero(4); for _ in 0..u8::max_value() { let _ = boxed.unlock(); } for _ in 0..u8::max_value() { boxed.lock(); } } #[test] fn it_allows_arbitrary_readers() { let boxed = Box::<u8>::zero(1); let mut count = 0_u8; sodium::memrandom(count.as_mut_bytes()); for _ in 0..count { let _ = boxed.unlock(); } for _ in 0..count { boxed.lock() } } #[test] fn it_can_be_sent_between_threads() { use std::sync::mpsc; use std::thread; let (tx, rx) = mpsc::channel(); let child = thread::spawn(move || { let boxed = Box::<u64>::random(1); let value = boxed.unlock().as_slice().to_vec(); // here we send an *unlocked* Box to the rx side; this lets // us make sure that the sent Box isn't dropped when this // thread exits, and that the other thread gets an unlocked // Box that it's responsible for locking tx.send((boxed, value)).expect("failed to send to channel"); }); let (boxed, value) = rx.recv().expect("failed to read from channel"); assert_eq!(Prot::ReadOnly, boxed.prot.get()); assert_eq!(value, boxed.as_slice()); child.join().expect("child terminated"); boxed.lock(); } #[test] #[should_panic(expected = "secrets: retained too many times")] fn it_doesnt_allow_overflowing_readers() { let boxed = Box::<[u64; 8]>::zero(4); for _ in 0..=u8::max_value() { let _ = boxed.unlock(); } // this ensures that we *don't* inadvertently panic if we // somehow made it through the above statement for _ in 0..boxed.refs.get() { boxed.lock() } } #[test] #[should_panic(expected = "secrets: out-of-order retain/release detected")] fn it_detects_out_of_order_retains_and_releases_that_underflow() { let boxed = Box::<u8>::zero(5); // manually set up this condition, since doing it using the // wrappers will cause other panics to happen boxed.refs.set(boxed.refs.get().wrapping_sub(1)); boxed.prot.set(Prot::NoAccess); boxed.retain(Prot::ReadOnly); } #[test] #[should_panic(expected = "secrets: failed to initialize libsodium")] fn it_detects_sodium_init_failure() { sodium::fail(); let _ = Box::<u8>::zero(0); } #[test] #[should_panic(expected = "secrets: error setting memory protection to NoAccess")] fn it_detects_sodium_mprotect_failure() { sodium::fail(); mprotect(std::ptr::null_mut::<u8>(), Prot::NoAccess); } } // There isn't a great way to run these tests on systems that don't have a native `fork()` call, so // we'll just skip them for now. #[cfg(all(test, target_family = "unix"))] mod tests_sigsegv { use super::*; use std::process; fn assert_sigsegv<F>(f: F) where F: FnOnce(), { unsafe { let pid : libc::pid_t = libc::fork(); let mut stat : libc::c_int = 0; match pid { -1 => panic!("`fork(2)` failed"), 0 => { f(); process::exit(0) }, _ => { if libc::waitpid(pid, &mut stat, 0) == -1 { panic!("`waitpid(2)` failed"); }; // assert that the process terminated due to a signal assert!(libc::WIFSIGNALED(stat)); // assert that we received a SIGBUS or SIGSEGV, // either of which can be sent by an attempt to // access protected memory regions assert!( libc::WTERMSIG(stat) == libc::SIGBUS || libc::WTERMSIG(stat) == libc::SIGSEGV ); } } } } #[test] fn it_kills_attempts_to_read_while_locked() { assert_sigsegv(|| { let val = unsafe { Box::<u32>::zero(1).ptr.as_ptr().read() }; // TODO: replace with [`test::black_box`] when stable let _ = sodium::memcmp(val.as_bytes(), val.as_bytes()); }); } #[test] fn it_kills_attempts_to_write_while_locked() { assert_sigsegv(|| { unsafe { Box::<u64>::zero(1).ptr.as_ptr().write(1) }; }); } #[test] fn it_kills_attempts_to_read_after_explicitly_locked() { assert_sigsegv(|| { let boxed = Box::<u32>::random(4); let val = boxed.unlock().as_slice(); let _ = boxed.unlock(); boxed.lock(); boxed.lock(); let _ = sodium::memcmp( val.as_bytes(), val.as_bytes(), ); }); } } #[cfg(all(test, profile = "debug"))] mod tests_proven_statements { use super::*; #[test] #[should_panic(expected = "secrets: attempted to dereference a zero-length pointer")] fn it_doesnt_allow_referencing_zero_length() { let boxed = Box::<u8>::new_unlocked(0); let _ = boxed.as_ref(); } #[test] #[should_panic(expected = "secrets: cannot unlock mutably more than once")] fn it_doesnt_allow_multiple_writers() { let mut boxed = Box::<u64>::zero(1); let _ = boxed.unlock_mut(); let _ = boxed.unlock_mut(); } #[test] #[should_panic(expected = "secrets: releases exceeded retains")] fn it_doesnt_allow_negative_users() { Box::<u64>::zero(10).lock(); } #[test] #[should_panic(expected = "secrets: releases exceeded retains")] fn it_doesnt_allow_unbalanced_locking() { let boxed = Box::<u64>::zero(4); let _ = boxed.unlock(); boxed.lock(); boxed.lock(); } #[test] #[should_panic(expected = "secrets: cannot unlock mutably while unlocked immutably")] fn it_doesnt_allow_different_access_types() { let mut boxed = Box::<[u128; 128]>::zero(5); let _ = boxed.unlock(); let _ = boxed.unlock_mut(); } #[test] #[should_panic(expected = "secrets: retains exceeded releases")] fn it_doesnt_allow_outstanding_readers() { let _ = Box::<u8>::zero(1).unlock(); } #[test] #[should_panic(expected = "secrets: retains exceeded releases")] fn it_doesnt_allow_outstanding_writers() { let _ = Box::<u8>::zero(1).unlock_mut(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_ref while locked")] fn it_doesnt_allow_as_ref_while_locked() { let _ = Box::<u8>::zero(1).as_ref(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut unless mutably unlocked")] fn it_doesnt_allow_as_mut_while_locked() { let _ = Box::<u8>::zero(1).as_mut(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut unless mutably unlocked")] fn it_doesnt_allow_as_mut_while_readonly() { let mut boxed = Box::<u8>::zero(1); let _ = boxed.unlock(); let _ = boxed.as_mut(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_slice while locked")] fn it_doesnt_allow_as_slice_while_locked() { let _ = Box::<u8>::zero(1).as_slice(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut_slice unless mutably unlocked")] fn it_doesnt_allow_as_mut_slice_while_locked() { let _ = Box::<u8>::zero(1).as_mut_slice(); } #[test] #[should_panic(expected = "secrets: may not call Box::as_mut_slice unless mutably unlocked")] fn it_doesnt_allow_as_mut_slice_while_readonly() { let mut boxed = Box::<u8>::zero(1); let _ = boxed.unlock(); let _ = boxed.as_mut_slice(); } } // LCOV_EXCL_STOP
{ mprotect(self.ptr.as_ptr(), Prot::NoAccess); self.prot.set(Prot::NoAccess); }
conditional_block
route.go
// Copyright (c) 2018 Cisco and/or its affiliates. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package descriptor import ( "bytes" "context" "fmt" "net" "strings" "github.com/pkg/errors" "go.ligato.io/cn-infra/v2/logging" "go.ligato.io/cn-infra/v2/utils/addrs" "google.golang.org/protobuf/proto" "go.ligato.io/vpp-agent/v3/pkg/models" kvs "go.ligato.io/vpp-agent/v3/plugins/kvscheduler/api" "go.ligato.io/vpp-agent/v3/plugins/netalloc" netalloc_descr "go.ligato.io/vpp-agent/v3/plugins/netalloc/descriptor" ifdescriptor "go.ligato.io/vpp-agent/v3/plugins/vpp/ifplugin/descriptor" "go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/descriptor/adapter" "go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/vppcalls" netalloc_api "go.ligato.io/vpp-agent/v3/proto/ligato/netalloc" interfaces "go.ligato.io/vpp-agent/v3/proto/ligato/vpp/interfaces" l3 "go.ligato.io/vpp-agent/v3/proto/ligato/vpp/l3" ) const ( // RouteDescriptorName is the name of the descriptor for static routes. RouteDescriptorName = "vpp-route" // dependency labels routeOutInterfaceDep = "interface-exists" vrfTableDep = "vrf-table-exists" viaVrfTableDep = "via-vrf-table-exists" // static route weight by default defaultWeight = 1 ) // RouteDescriptor teaches KVScheduler how to configure VPP routes. type RouteDescriptor struct { log logging.Logger routeHandler vppcalls.RouteVppAPI addrAlloc netalloc.AddressAllocator } // NewRouteDescriptor creates a new instance of the Route descriptor. func NewRouteDescriptor( routeHandler vppcalls.RouteVppAPI, addrAlloc netalloc.AddressAllocator, log logging.PluginLogger) *kvs.KVDescriptor { ctx := &RouteDescriptor{ routeHandler: routeHandler, addrAlloc: addrAlloc, log: log.NewLogger("static-route-descriptor"), } typedDescr := &adapter.RouteDescriptor{ Name: RouteDescriptorName, NBKeyPrefix: l3.ModelRoute.KeyPrefix(), ValueTypeName: l3.ModelRoute.ProtoName(), KeySelector: l3.ModelRoute.IsKeyValid, ValueComparator: ctx.EquivalentRoutes, Validate: ctx.Validate, Create: ctx.Create, Delete: ctx.Delete, Retrieve: ctx.Retrieve, Dependencies: ctx.Dependencies, RetrieveDependencies: []string{ netalloc_descr.IPAllocDescriptorName, ifdescriptor.InterfaceDescriptorName, VrfTableDescriptorName}, } return adapter.NewRouteDescriptor(typedDescr) } // EquivalentRoutes is case-insensitive comparison function for l3.Route. func (d *RouteDescriptor) EquivalentRoutes(key string, oldRoute, newRoute *l3.Route) bool { if oldRoute.GetType() != newRoute.GetType() || oldRoute.GetVrfId() != newRoute.GetVrfId() || oldRoute.GetViaVrfId() != newRoute.GetViaVrfId() || oldRoute.GetOutgoingInterface() != newRoute.GetOutgoingInterface() || getWeight(oldRoute) != getWeight(newRoute) || oldRoute.GetPreference() != newRoute.GetPreference() { return false } // compare dst networks if !equalNetworks(oldRoute.DstNetwork, newRoute.DstNetwork) { return false } // compare gw addresses (next hop) if !equalAddrs(getGwAddr(oldRoute), getGwAddr(newRoute)) { return false } return true } // Validate validates VPP static route configuration. func (d *RouteDescriptor) Validate(key string, route *l3.Route) (err error) { // validate destination network err = d.addrAlloc.ValidateIPAddress(route.DstNetwork, "", "dst_network", netalloc.GWRefAllowed) if err != nil { return err } // validate next hop address (GW) err = d.addrAlloc.ValidateIPAddress(getGwAddr(route), route.OutgoingInterface, "gw_addr", netalloc.GWRefRequired) if err != nil { return err } // validate IP network implied by the IP and prefix length if !strings.HasPrefix(route.DstNetwork, netalloc_api.AllocRefPrefix) { _, ipNet, _ := net.ParseCIDR(route.DstNetwork) if !strings.EqualFold(ipNet.String(), route.DstNetwork) { e := fmt.Errorf("DstNetwork (%s) must represent IP network (%s)", route.DstNetwork, ipNet.String()) return kvs.NewInvalidValueError(e, "dst_network") } } // TODO: validate mix of IP versions? return nil } // Create adds VPP static route. func (d *RouteDescriptor)
(key string, route *l3.Route) (metadata interface{}, err error) { err = d.routeHandler.VppAddRoute(context.TODO(), route) if err != nil { return nil, err } return nil, nil } // Delete removes VPP static route. func (d *RouteDescriptor) Delete(key string, route *l3.Route, metadata interface{}) error { err := d.routeHandler.VppDelRoute(context.TODO(), route) if err != nil { return err } return nil } // Retrieve returns all routes associated with interfaces managed by this agent. func (d *RouteDescriptor) Retrieve(correlate []adapter.RouteKVWithMetadata) ( retrieved []adapter.RouteKVWithMetadata, err error, ) { // prepare expected configuration with de-referenced netalloc links nbCfg := make(map[string]*l3.Route) expCfg := make(map[string]*l3.Route) for _, kv := range correlate { dstNetwork := kv.Value.DstNetwork parsed, err := d.addrAlloc.GetOrParseIPAddress(kv.Value.DstNetwork, "", netalloc_api.IPAddressForm_ADDR_NET) if err == nil { dstNetwork = parsed.String() } nextHop := kv.Value.NextHopAddr parsed, err = d.addrAlloc.GetOrParseIPAddress(getGwAddr(kv.Value), kv.Value.OutgoingInterface, netalloc_api.IPAddressForm_ADDR_ONLY) if err == nil { nextHop = parsed.IP.String() } route := proto.Clone(kv.Value).(*l3.Route) route.DstNetwork = dstNetwork route.NextHopAddr = nextHop key := models.Key(route) expCfg[key] = route nbCfg[key] = kv.Value } // Retrieve VPP route configuration routes, err := d.routeHandler.DumpRoutes() if err != nil { return nil, errors.Errorf("failed to dump VPP routes: %v", err) } for _, route := range routes { key := models.Key(route.Route) value := route.Route origin := kvs.UnknownOrigin // correlate with the expected configuration if expCfg, hasExpCfg := expCfg[key]; hasExpCfg { if d.EquivalentRoutes(key, value, expCfg) { value = nbCfg[key] // recreate the key in case the dest. IP or GW IP were replaced with netalloc link key = models.Key(value) origin = kvs.FromNB } } retrieved = append(retrieved, adapter.RouteKVWithMetadata{ Key: key, Value: value, Origin: origin, }) } return retrieved, nil } // Dependencies lists dependencies for a VPP route. func (d *RouteDescriptor) Dependencies(key string, route *l3.Route) []kvs.Dependency { var dependencies []kvs.Dependency // the outgoing interface must exist and be UP if route.OutgoingInterface != "" { dependencies = append(dependencies, kvs.Dependency{ Label: routeOutInterfaceDep, Key: interfaces.InterfaceKey(route.OutgoingInterface), }) } // non-zero VRFs var protocol l3.VrfTable_Protocol _, isIPv6, _ := addrs.ParseIPWithPrefix(route.DstNetwork) if isIPv6 { protocol = l3.VrfTable_IPV6 } if route.VrfId != 0 { dependencies = append(dependencies, kvs.Dependency{ Label: vrfTableDep, Key: l3.VrfTableKey(route.VrfId, protocol), }) } if route.Type == l3.Route_INTER_VRF && route.ViaVrfId != 0 { dependencies = append(dependencies, kvs.Dependency{ Label: viaVrfTableDep, Key: l3.VrfTableKey(route.ViaVrfId, protocol), }) } // if destination network is netalloc reference, then the address must be allocated first allocDep, hasAllocDep := d.addrAlloc.GetAddressAllocDep(route.DstNetwork, "", "dst_network-") if hasAllocDep { dependencies = append(dependencies, allocDep) } // if GW is netalloc reference, then the address must be allocated first allocDep, hasAllocDep = d.addrAlloc.GetAddressAllocDep(route.NextHopAddr, route.OutgoingInterface, "gw_addr-") if hasAllocDep { dependencies = append(dependencies, allocDep) } // TODO: perhaps check GW routability return dependencies } // equalAddrs compares two IP addresses for equality. func equalAddrs(addr1, addr2 string) bool { if strings.HasPrefix(addr1, netalloc_api.AllocRefPrefix) || strings.HasPrefix(addr2, netalloc_api.AllocRefPrefix) { return addr1 == addr2 } a1 := net.ParseIP(addr1) a2 := net.ParseIP(addr2) if a1 == nil || a2 == nil { // if parsing fails, compare as strings return strings.EqualFold(addr1, addr2) } return a1.Equal(a2) } // getGwAddr returns the GW address chosen in the given route, handling the cases // when it is left undefined. func getGwAddr(route *l3.Route) string { if route.GetNextHopAddr() != "" { return route.GetNextHopAddr() } // return zero address // - with netalloc'd destination network, just assume it is for IPv4 if !strings.HasPrefix(route.GetDstNetwork(), netalloc_api.AllocRefPrefix) { _, dstIPNet, err := net.ParseCIDR(route.GetDstNetwork()) if err != nil { return "" } if dstIPNet.IP.To4() == nil { return net.IPv6zero.String() } } return net.IPv4zero.String() } // getWeight returns static route weight, handling the cases when it is left undefined. func getWeight(route *l3.Route) uint32 { if route.Weight == 0 { return defaultWeight } return route.Weight } // equalNetworks compares two IP networks for equality. func equalNetworks(net1, net2 string) bool { if strings.HasPrefix(net1, netalloc_api.AllocRefPrefix) || strings.HasPrefix(net2, netalloc_api.AllocRefPrefix) { return net1 == net2 } _, n1, err1 := net.ParseCIDR(net1) _, n2, err2 := net.ParseCIDR(net2) if err1 != nil || err2 != nil { // if parsing fails, compare as strings return strings.EqualFold(net1, net2) } return n1.IP.Equal(n2.IP) && bytes.Equal(n1.Mask, n2.Mask) }
Create
identifier_name
route.go
// Copyright (c) 2018 Cisco and/or its affiliates. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package descriptor import ( "bytes" "context" "fmt" "net" "strings" "github.com/pkg/errors" "go.ligato.io/cn-infra/v2/logging" "go.ligato.io/cn-infra/v2/utils/addrs" "google.golang.org/protobuf/proto" "go.ligato.io/vpp-agent/v3/pkg/models" kvs "go.ligato.io/vpp-agent/v3/plugins/kvscheduler/api" "go.ligato.io/vpp-agent/v3/plugins/netalloc" netalloc_descr "go.ligato.io/vpp-agent/v3/plugins/netalloc/descriptor" ifdescriptor "go.ligato.io/vpp-agent/v3/plugins/vpp/ifplugin/descriptor" "go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/descriptor/adapter" "go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/vppcalls" netalloc_api "go.ligato.io/vpp-agent/v3/proto/ligato/netalloc" interfaces "go.ligato.io/vpp-agent/v3/proto/ligato/vpp/interfaces" l3 "go.ligato.io/vpp-agent/v3/proto/ligato/vpp/l3" ) const ( // RouteDescriptorName is the name of the descriptor for static routes. RouteDescriptorName = "vpp-route" // dependency labels routeOutInterfaceDep = "interface-exists" vrfTableDep = "vrf-table-exists" viaVrfTableDep = "via-vrf-table-exists" // static route weight by default defaultWeight = 1 ) // RouteDescriptor teaches KVScheduler how to configure VPP routes. type RouteDescriptor struct { log logging.Logger routeHandler vppcalls.RouteVppAPI addrAlloc netalloc.AddressAllocator } // NewRouteDescriptor creates a new instance of the Route descriptor. func NewRouteDescriptor( routeHandler vppcalls.RouteVppAPI, addrAlloc netalloc.AddressAllocator, log logging.PluginLogger) *kvs.KVDescriptor { ctx := &RouteDescriptor{ routeHandler: routeHandler, addrAlloc: addrAlloc, log: log.NewLogger("static-route-descriptor"), } typedDescr := &adapter.RouteDescriptor{ Name: RouteDescriptorName, NBKeyPrefix: l3.ModelRoute.KeyPrefix(), ValueTypeName: l3.ModelRoute.ProtoName(), KeySelector: l3.ModelRoute.IsKeyValid, ValueComparator: ctx.EquivalentRoutes, Validate: ctx.Validate, Create: ctx.Create, Delete: ctx.Delete, Retrieve: ctx.Retrieve, Dependencies: ctx.Dependencies, RetrieveDependencies: []string{ netalloc_descr.IPAllocDescriptorName, ifdescriptor.InterfaceDescriptorName, VrfTableDescriptorName}, } return adapter.NewRouteDescriptor(typedDescr) } // EquivalentRoutes is case-insensitive comparison function for l3.Route. func (d *RouteDescriptor) EquivalentRoutes(key string, oldRoute, newRoute *l3.Route) bool { if oldRoute.GetType() != newRoute.GetType() || oldRoute.GetVrfId() != newRoute.GetVrfId() || oldRoute.GetViaVrfId() != newRoute.GetViaVrfId() || oldRoute.GetOutgoingInterface() != newRoute.GetOutgoingInterface() || getWeight(oldRoute) != getWeight(newRoute) || oldRoute.GetPreference() != newRoute.GetPreference() { return false } // compare dst networks if !equalNetworks(oldRoute.DstNetwork, newRoute.DstNetwork) { return false } // compare gw addresses (next hop) if !equalAddrs(getGwAddr(oldRoute), getGwAddr(newRoute)) { return false } return true } // Validate validates VPP static route configuration. func (d *RouteDescriptor) Validate(key string, route *l3.Route) (err error) { // validate destination network err = d.addrAlloc.ValidateIPAddress(route.DstNetwork, "", "dst_network", netalloc.GWRefAllowed) if err != nil { return err } // validate next hop address (GW) err = d.addrAlloc.ValidateIPAddress(getGwAddr(route), route.OutgoingInterface, "gw_addr", netalloc.GWRefRequired) if err != nil { return err } // validate IP network implied by the IP and prefix length if !strings.HasPrefix(route.DstNetwork, netalloc_api.AllocRefPrefix) { _, ipNet, _ := net.ParseCIDR(route.DstNetwork) if !strings.EqualFold(ipNet.String(), route.DstNetwork) { e := fmt.Errorf("DstNetwork (%s) must represent IP network (%s)", route.DstNetwork, ipNet.String()) return kvs.NewInvalidValueError(e, "dst_network") } } // TODO: validate mix of IP versions? return nil } // Create adds VPP static route. func (d *RouteDescriptor) Create(key string, route *l3.Route) (metadata interface{}, err error) { err = d.routeHandler.VppAddRoute(context.TODO(), route) if err != nil { return nil, err } return nil, nil } // Delete removes VPP static route. func (d *RouteDescriptor) Delete(key string, route *l3.Route, metadata interface{}) error { err := d.routeHandler.VppDelRoute(context.TODO(), route) if err != nil { return err } return nil } // Retrieve returns all routes associated with interfaces managed by this agent. func (d *RouteDescriptor) Retrieve(correlate []adapter.RouteKVWithMetadata) ( retrieved []adapter.RouteKVWithMetadata, err error, ) { // prepare expected configuration with de-referenced netalloc links nbCfg := make(map[string]*l3.Route) expCfg := make(map[string]*l3.Route) for _, kv := range correlate { dstNetwork := kv.Value.DstNetwork parsed, err := d.addrAlloc.GetOrParseIPAddress(kv.Value.DstNetwork, "", netalloc_api.IPAddressForm_ADDR_NET) if err == nil { dstNetwork = parsed.String() } nextHop := kv.Value.NextHopAddr parsed, err = d.addrAlloc.GetOrParseIPAddress(getGwAddr(kv.Value), kv.Value.OutgoingInterface, netalloc_api.IPAddressForm_ADDR_ONLY) if err == nil { nextHop = parsed.IP.String() } route := proto.Clone(kv.Value).(*l3.Route) route.DstNetwork = dstNetwork route.NextHopAddr = nextHop key := models.Key(route) expCfg[key] = route nbCfg[key] = kv.Value } // Retrieve VPP route configuration routes, err := d.routeHandler.DumpRoutes() if err != nil { return nil, errors.Errorf("failed to dump VPP routes: %v", err) } for _, route := range routes { key := models.Key(route.Route) value := route.Route origin := kvs.UnknownOrigin // correlate with the expected configuration if expCfg, hasExpCfg := expCfg[key]; hasExpCfg { if d.EquivalentRoutes(key, value, expCfg) { value = nbCfg[key] // recreate the key in case the dest. IP or GW IP were replaced with netalloc link key = models.Key(value) origin = kvs.FromNB } } retrieved = append(retrieved, adapter.RouteKVWithMetadata{ Key: key, Value: value, Origin: origin, }) } return retrieved, nil } // Dependencies lists dependencies for a VPP route. func (d *RouteDescriptor) Dependencies(key string, route *l3.Route) []kvs.Dependency { var dependencies []kvs.Dependency // the outgoing interface must exist and be UP if route.OutgoingInterface != "" { dependencies = append(dependencies, kvs.Dependency{ Label: routeOutInterfaceDep, Key: interfaces.InterfaceKey(route.OutgoingInterface), }) } // non-zero VRFs var protocol l3.VrfTable_Protocol _, isIPv6, _ := addrs.ParseIPWithPrefix(route.DstNetwork) if isIPv6 { protocol = l3.VrfTable_IPV6 } if route.VrfId != 0 { dependencies = append(dependencies, kvs.Dependency{ Label: vrfTableDep, Key: l3.VrfTableKey(route.VrfId, protocol),
Key: l3.VrfTableKey(route.ViaVrfId, protocol), }) } // if destination network is netalloc reference, then the address must be allocated first allocDep, hasAllocDep := d.addrAlloc.GetAddressAllocDep(route.DstNetwork, "", "dst_network-") if hasAllocDep { dependencies = append(dependencies, allocDep) } // if GW is netalloc reference, then the address must be allocated first allocDep, hasAllocDep = d.addrAlloc.GetAddressAllocDep(route.NextHopAddr, route.OutgoingInterface, "gw_addr-") if hasAllocDep { dependencies = append(dependencies, allocDep) } // TODO: perhaps check GW routability return dependencies } // equalAddrs compares two IP addresses for equality. func equalAddrs(addr1, addr2 string) bool { if strings.HasPrefix(addr1, netalloc_api.AllocRefPrefix) || strings.HasPrefix(addr2, netalloc_api.AllocRefPrefix) { return addr1 == addr2 } a1 := net.ParseIP(addr1) a2 := net.ParseIP(addr2) if a1 == nil || a2 == nil { // if parsing fails, compare as strings return strings.EqualFold(addr1, addr2) } return a1.Equal(a2) } // getGwAddr returns the GW address chosen in the given route, handling the cases // when it is left undefined. func getGwAddr(route *l3.Route) string { if route.GetNextHopAddr() != "" { return route.GetNextHopAddr() } // return zero address // - with netalloc'd destination network, just assume it is for IPv4 if !strings.HasPrefix(route.GetDstNetwork(), netalloc_api.AllocRefPrefix) { _, dstIPNet, err := net.ParseCIDR(route.GetDstNetwork()) if err != nil { return "" } if dstIPNet.IP.To4() == nil { return net.IPv6zero.String() } } return net.IPv4zero.String() } // getWeight returns static route weight, handling the cases when it is left undefined. func getWeight(route *l3.Route) uint32 { if route.Weight == 0 { return defaultWeight } return route.Weight } // equalNetworks compares two IP networks for equality. func equalNetworks(net1, net2 string) bool { if strings.HasPrefix(net1, netalloc_api.AllocRefPrefix) || strings.HasPrefix(net2, netalloc_api.AllocRefPrefix) { return net1 == net2 } _, n1, err1 := net.ParseCIDR(net1) _, n2, err2 := net.ParseCIDR(net2) if err1 != nil || err2 != nil { // if parsing fails, compare as strings return strings.EqualFold(net1, net2) } return n1.IP.Equal(n2.IP) && bytes.Equal(n1.Mask, n2.Mask) }
}) } if route.Type == l3.Route_INTER_VRF && route.ViaVrfId != 0 { dependencies = append(dependencies, kvs.Dependency{ Label: viaVrfTableDep,
random_line_split
route.go
// Copyright (c) 2018 Cisco and/or its affiliates. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package descriptor import ( "bytes" "context" "fmt" "net" "strings" "github.com/pkg/errors" "go.ligato.io/cn-infra/v2/logging" "go.ligato.io/cn-infra/v2/utils/addrs" "google.golang.org/protobuf/proto" "go.ligato.io/vpp-agent/v3/pkg/models" kvs "go.ligato.io/vpp-agent/v3/plugins/kvscheduler/api" "go.ligato.io/vpp-agent/v3/plugins/netalloc" netalloc_descr "go.ligato.io/vpp-agent/v3/plugins/netalloc/descriptor" ifdescriptor "go.ligato.io/vpp-agent/v3/plugins/vpp/ifplugin/descriptor" "go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/descriptor/adapter" "go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/vppcalls" netalloc_api "go.ligato.io/vpp-agent/v3/proto/ligato/netalloc" interfaces "go.ligato.io/vpp-agent/v3/proto/ligato/vpp/interfaces" l3 "go.ligato.io/vpp-agent/v3/proto/ligato/vpp/l3" ) const ( // RouteDescriptorName is the name of the descriptor for static routes. RouteDescriptorName = "vpp-route" // dependency labels routeOutInterfaceDep = "interface-exists" vrfTableDep = "vrf-table-exists" viaVrfTableDep = "via-vrf-table-exists" // static route weight by default defaultWeight = 1 ) // RouteDescriptor teaches KVScheduler how to configure VPP routes. type RouteDescriptor struct { log logging.Logger routeHandler vppcalls.RouteVppAPI addrAlloc netalloc.AddressAllocator } // NewRouteDescriptor creates a new instance of the Route descriptor. func NewRouteDescriptor( routeHandler vppcalls.RouteVppAPI, addrAlloc netalloc.AddressAllocator, log logging.PluginLogger) *kvs.KVDescriptor { ctx := &RouteDescriptor{ routeHandler: routeHandler, addrAlloc: addrAlloc, log: log.NewLogger("static-route-descriptor"), } typedDescr := &adapter.RouteDescriptor{ Name: RouteDescriptorName, NBKeyPrefix: l3.ModelRoute.KeyPrefix(), ValueTypeName: l3.ModelRoute.ProtoName(), KeySelector: l3.ModelRoute.IsKeyValid, ValueComparator: ctx.EquivalentRoutes, Validate: ctx.Validate, Create: ctx.Create, Delete: ctx.Delete, Retrieve: ctx.Retrieve, Dependencies: ctx.Dependencies, RetrieveDependencies: []string{ netalloc_descr.IPAllocDescriptorName, ifdescriptor.InterfaceDescriptorName, VrfTableDescriptorName}, } return adapter.NewRouteDescriptor(typedDescr) } // EquivalentRoutes is case-insensitive comparison function for l3.Route. func (d *RouteDescriptor) EquivalentRoutes(key string, oldRoute, newRoute *l3.Route) bool { if oldRoute.GetType() != newRoute.GetType() || oldRoute.GetVrfId() != newRoute.GetVrfId() || oldRoute.GetViaVrfId() != newRoute.GetViaVrfId() || oldRoute.GetOutgoingInterface() != newRoute.GetOutgoingInterface() || getWeight(oldRoute) != getWeight(newRoute) || oldRoute.GetPreference() != newRoute.GetPreference() { return false } // compare dst networks if !equalNetworks(oldRoute.DstNetwork, newRoute.DstNetwork) { return false } // compare gw addresses (next hop) if !equalAddrs(getGwAddr(oldRoute), getGwAddr(newRoute)) { return false } return true } // Validate validates VPP static route configuration. func (d *RouteDescriptor) Validate(key string, route *l3.Route) (err error) { // validate destination network err = d.addrAlloc.ValidateIPAddress(route.DstNetwork, "", "dst_network", netalloc.GWRefAllowed) if err != nil { return err } // validate next hop address (GW) err = d.addrAlloc.ValidateIPAddress(getGwAddr(route), route.OutgoingInterface, "gw_addr", netalloc.GWRefRequired) if err != nil { return err } // validate IP network implied by the IP and prefix length if !strings.HasPrefix(route.DstNetwork, netalloc_api.AllocRefPrefix) { _, ipNet, _ := net.ParseCIDR(route.DstNetwork) if !strings.EqualFold(ipNet.String(), route.DstNetwork) { e := fmt.Errorf("DstNetwork (%s) must represent IP network (%s)", route.DstNetwork, ipNet.String()) return kvs.NewInvalidValueError(e, "dst_network") } } // TODO: validate mix of IP versions? return nil } // Create adds VPP static route. func (d *RouteDescriptor) Create(key string, route *l3.Route) (metadata interface{}, err error) { err = d.routeHandler.VppAddRoute(context.TODO(), route) if err != nil { return nil, err } return nil, nil } // Delete removes VPP static route. func (d *RouteDescriptor) Delete(key string, route *l3.Route, metadata interface{}) error { err := d.routeHandler.VppDelRoute(context.TODO(), route) if err != nil { return err } return nil } // Retrieve returns all routes associated with interfaces managed by this agent. func (d *RouteDescriptor) Retrieve(correlate []adapter.RouteKVWithMetadata) ( retrieved []adapter.RouteKVWithMetadata, err error, ) { // prepare expected configuration with de-referenced netalloc links nbCfg := make(map[string]*l3.Route) expCfg := make(map[string]*l3.Route) for _, kv := range correlate { dstNetwork := kv.Value.DstNetwork parsed, err := d.addrAlloc.GetOrParseIPAddress(kv.Value.DstNetwork, "", netalloc_api.IPAddressForm_ADDR_NET) if err == nil { dstNetwork = parsed.String() } nextHop := kv.Value.NextHopAddr parsed, err = d.addrAlloc.GetOrParseIPAddress(getGwAddr(kv.Value), kv.Value.OutgoingInterface, netalloc_api.IPAddressForm_ADDR_ONLY) if err == nil { nextHop = parsed.IP.String() } route := proto.Clone(kv.Value).(*l3.Route) route.DstNetwork = dstNetwork route.NextHopAddr = nextHop key := models.Key(route) expCfg[key] = route nbCfg[key] = kv.Value } // Retrieve VPP route configuration routes, err := d.routeHandler.DumpRoutes() if err != nil { return nil, errors.Errorf("failed to dump VPP routes: %v", err) } for _, route := range routes { key := models.Key(route.Route) value := route.Route origin := kvs.UnknownOrigin // correlate with the expected configuration if expCfg, hasExpCfg := expCfg[key]; hasExpCfg { if d.EquivalentRoutes(key, value, expCfg) { value = nbCfg[key] // recreate the key in case the dest. IP or GW IP were replaced with netalloc link key = models.Key(value) origin = kvs.FromNB } } retrieved = append(retrieved, adapter.RouteKVWithMetadata{ Key: key, Value: value, Origin: origin, }) } return retrieved, nil } // Dependencies lists dependencies for a VPP route. func (d *RouteDescriptor) Dependencies(key string, route *l3.Route) []kvs.Dependency { var dependencies []kvs.Dependency // the outgoing interface must exist and be UP if route.OutgoingInterface != "" { dependencies = append(dependencies, kvs.Dependency{ Label: routeOutInterfaceDep, Key: interfaces.InterfaceKey(route.OutgoingInterface), }) } // non-zero VRFs var protocol l3.VrfTable_Protocol _, isIPv6, _ := addrs.ParseIPWithPrefix(route.DstNetwork) if isIPv6 { protocol = l3.VrfTable_IPV6 } if route.VrfId != 0 { dependencies = append(dependencies, kvs.Dependency{ Label: vrfTableDep, Key: l3.VrfTableKey(route.VrfId, protocol), }) } if route.Type == l3.Route_INTER_VRF && route.ViaVrfId != 0 { dependencies = append(dependencies, kvs.Dependency{ Label: viaVrfTableDep, Key: l3.VrfTableKey(route.ViaVrfId, protocol), }) } // if destination network is netalloc reference, then the address must be allocated first allocDep, hasAllocDep := d.addrAlloc.GetAddressAllocDep(route.DstNetwork, "", "dst_network-") if hasAllocDep { dependencies = append(dependencies, allocDep) } // if GW is netalloc reference, then the address must be allocated first allocDep, hasAllocDep = d.addrAlloc.GetAddressAllocDep(route.NextHopAddr, route.OutgoingInterface, "gw_addr-") if hasAllocDep { dependencies = append(dependencies, allocDep) } // TODO: perhaps check GW routability return dependencies } // equalAddrs compares two IP addresses for equality. func equalAddrs(addr1, addr2 string) bool { if strings.HasPrefix(addr1, netalloc_api.AllocRefPrefix) || strings.HasPrefix(addr2, netalloc_api.AllocRefPrefix)
a1 := net.ParseIP(addr1) a2 := net.ParseIP(addr2) if a1 == nil || a2 == nil { // if parsing fails, compare as strings return strings.EqualFold(addr1, addr2) } return a1.Equal(a2) } // getGwAddr returns the GW address chosen in the given route, handling the cases // when it is left undefined. func getGwAddr(route *l3.Route) string { if route.GetNextHopAddr() != "" { return route.GetNextHopAddr() } // return zero address // - with netalloc'd destination network, just assume it is for IPv4 if !strings.HasPrefix(route.GetDstNetwork(), netalloc_api.AllocRefPrefix) { _, dstIPNet, err := net.ParseCIDR(route.GetDstNetwork()) if err != nil { return "" } if dstIPNet.IP.To4() == nil { return net.IPv6zero.String() } } return net.IPv4zero.String() } // getWeight returns static route weight, handling the cases when it is left undefined. func getWeight(route *l3.Route) uint32 { if route.Weight == 0 { return defaultWeight } return route.Weight } // equalNetworks compares two IP networks for equality. func equalNetworks(net1, net2 string) bool { if strings.HasPrefix(net1, netalloc_api.AllocRefPrefix) || strings.HasPrefix(net2, netalloc_api.AllocRefPrefix) { return net1 == net2 } _, n1, err1 := net.ParseCIDR(net1) _, n2, err2 := net.ParseCIDR(net2) if err1 != nil || err2 != nil { // if parsing fails, compare as strings return strings.EqualFold(net1, net2) } return n1.IP.Equal(n2.IP) && bytes.Equal(n1.Mask, n2.Mask) }
{ return addr1 == addr2 }
conditional_block
route.go
// Copyright (c) 2018 Cisco and/or its affiliates. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package descriptor import ( "bytes" "context" "fmt" "net" "strings" "github.com/pkg/errors" "go.ligato.io/cn-infra/v2/logging" "go.ligato.io/cn-infra/v2/utils/addrs" "google.golang.org/protobuf/proto" "go.ligato.io/vpp-agent/v3/pkg/models" kvs "go.ligato.io/vpp-agent/v3/plugins/kvscheduler/api" "go.ligato.io/vpp-agent/v3/plugins/netalloc" netalloc_descr "go.ligato.io/vpp-agent/v3/plugins/netalloc/descriptor" ifdescriptor "go.ligato.io/vpp-agent/v3/plugins/vpp/ifplugin/descriptor" "go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/descriptor/adapter" "go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/vppcalls" netalloc_api "go.ligato.io/vpp-agent/v3/proto/ligato/netalloc" interfaces "go.ligato.io/vpp-agent/v3/proto/ligato/vpp/interfaces" l3 "go.ligato.io/vpp-agent/v3/proto/ligato/vpp/l3" ) const ( // RouteDescriptorName is the name of the descriptor for static routes. RouteDescriptorName = "vpp-route" // dependency labels routeOutInterfaceDep = "interface-exists" vrfTableDep = "vrf-table-exists" viaVrfTableDep = "via-vrf-table-exists" // static route weight by default defaultWeight = 1 ) // RouteDescriptor teaches KVScheduler how to configure VPP routes. type RouteDescriptor struct { log logging.Logger routeHandler vppcalls.RouteVppAPI addrAlloc netalloc.AddressAllocator } // NewRouteDescriptor creates a new instance of the Route descriptor. func NewRouteDescriptor( routeHandler vppcalls.RouteVppAPI, addrAlloc netalloc.AddressAllocator, log logging.PluginLogger) *kvs.KVDescriptor { ctx := &RouteDescriptor{ routeHandler: routeHandler, addrAlloc: addrAlloc, log: log.NewLogger("static-route-descriptor"), } typedDescr := &adapter.RouteDescriptor{ Name: RouteDescriptorName, NBKeyPrefix: l3.ModelRoute.KeyPrefix(), ValueTypeName: l3.ModelRoute.ProtoName(), KeySelector: l3.ModelRoute.IsKeyValid, ValueComparator: ctx.EquivalentRoutes, Validate: ctx.Validate, Create: ctx.Create, Delete: ctx.Delete, Retrieve: ctx.Retrieve, Dependencies: ctx.Dependencies, RetrieveDependencies: []string{ netalloc_descr.IPAllocDescriptorName, ifdescriptor.InterfaceDescriptorName, VrfTableDescriptorName}, } return adapter.NewRouteDescriptor(typedDescr) } // EquivalentRoutes is case-insensitive comparison function for l3.Route. func (d *RouteDescriptor) EquivalentRoutes(key string, oldRoute, newRoute *l3.Route) bool { if oldRoute.GetType() != newRoute.GetType() || oldRoute.GetVrfId() != newRoute.GetVrfId() || oldRoute.GetViaVrfId() != newRoute.GetViaVrfId() || oldRoute.GetOutgoingInterface() != newRoute.GetOutgoingInterface() || getWeight(oldRoute) != getWeight(newRoute) || oldRoute.GetPreference() != newRoute.GetPreference() { return false } // compare dst networks if !equalNetworks(oldRoute.DstNetwork, newRoute.DstNetwork) { return false } // compare gw addresses (next hop) if !equalAddrs(getGwAddr(oldRoute), getGwAddr(newRoute)) { return false } return true } // Validate validates VPP static route configuration. func (d *RouteDescriptor) Validate(key string, route *l3.Route) (err error) { // validate destination network err = d.addrAlloc.ValidateIPAddress(route.DstNetwork, "", "dst_network", netalloc.GWRefAllowed) if err != nil { return err } // validate next hop address (GW) err = d.addrAlloc.ValidateIPAddress(getGwAddr(route), route.OutgoingInterface, "gw_addr", netalloc.GWRefRequired) if err != nil { return err } // validate IP network implied by the IP and prefix length if !strings.HasPrefix(route.DstNetwork, netalloc_api.AllocRefPrefix) { _, ipNet, _ := net.ParseCIDR(route.DstNetwork) if !strings.EqualFold(ipNet.String(), route.DstNetwork) { e := fmt.Errorf("DstNetwork (%s) must represent IP network (%s)", route.DstNetwork, ipNet.String()) return kvs.NewInvalidValueError(e, "dst_network") } } // TODO: validate mix of IP versions? return nil } // Create adds VPP static route. func (d *RouteDescriptor) Create(key string, route *l3.Route) (metadata interface{}, err error) { err = d.routeHandler.VppAddRoute(context.TODO(), route) if err != nil { return nil, err } return nil, nil } // Delete removes VPP static route. func (d *RouteDescriptor) Delete(key string, route *l3.Route, metadata interface{}) error { err := d.routeHandler.VppDelRoute(context.TODO(), route) if err != nil { return err } return nil } // Retrieve returns all routes associated with interfaces managed by this agent. func (d *RouteDescriptor) Retrieve(correlate []adapter.RouteKVWithMetadata) ( retrieved []adapter.RouteKVWithMetadata, err error, )
// Dependencies lists dependencies for a VPP route. func (d *RouteDescriptor) Dependencies(key string, route *l3.Route) []kvs.Dependency { var dependencies []kvs.Dependency // the outgoing interface must exist and be UP if route.OutgoingInterface != "" { dependencies = append(dependencies, kvs.Dependency{ Label: routeOutInterfaceDep, Key: interfaces.InterfaceKey(route.OutgoingInterface), }) } // non-zero VRFs var protocol l3.VrfTable_Protocol _, isIPv6, _ := addrs.ParseIPWithPrefix(route.DstNetwork) if isIPv6 { protocol = l3.VrfTable_IPV6 } if route.VrfId != 0 { dependencies = append(dependencies, kvs.Dependency{ Label: vrfTableDep, Key: l3.VrfTableKey(route.VrfId, protocol), }) } if route.Type == l3.Route_INTER_VRF && route.ViaVrfId != 0 { dependencies = append(dependencies, kvs.Dependency{ Label: viaVrfTableDep, Key: l3.VrfTableKey(route.ViaVrfId, protocol), }) } // if destination network is netalloc reference, then the address must be allocated first allocDep, hasAllocDep := d.addrAlloc.GetAddressAllocDep(route.DstNetwork, "", "dst_network-") if hasAllocDep { dependencies = append(dependencies, allocDep) } // if GW is netalloc reference, then the address must be allocated first allocDep, hasAllocDep = d.addrAlloc.GetAddressAllocDep(route.NextHopAddr, route.OutgoingInterface, "gw_addr-") if hasAllocDep { dependencies = append(dependencies, allocDep) } // TODO: perhaps check GW routability return dependencies } // equalAddrs compares two IP addresses for equality. func equalAddrs(addr1, addr2 string) bool { if strings.HasPrefix(addr1, netalloc_api.AllocRefPrefix) || strings.HasPrefix(addr2, netalloc_api.AllocRefPrefix) { return addr1 == addr2 } a1 := net.ParseIP(addr1) a2 := net.ParseIP(addr2) if a1 == nil || a2 == nil { // if parsing fails, compare as strings return strings.EqualFold(addr1, addr2) } return a1.Equal(a2) } // getGwAddr returns the GW address chosen in the given route, handling the cases // when it is left undefined. func getGwAddr(route *l3.Route) string { if route.GetNextHopAddr() != "" { return route.GetNextHopAddr() } // return zero address // - with netalloc'd destination network, just assume it is for IPv4 if !strings.HasPrefix(route.GetDstNetwork(), netalloc_api.AllocRefPrefix) { _, dstIPNet, err := net.ParseCIDR(route.GetDstNetwork()) if err != nil { return "" } if dstIPNet.IP.To4() == nil { return net.IPv6zero.String() } } return net.IPv4zero.String() } // getWeight returns static route weight, handling the cases when it is left undefined. func getWeight(route *l3.Route) uint32 { if route.Weight == 0 { return defaultWeight } return route.Weight } // equalNetworks compares two IP networks for equality. func equalNetworks(net1, net2 string) bool { if strings.HasPrefix(net1, netalloc_api.AllocRefPrefix) || strings.HasPrefix(net2, netalloc_api.AllocRefPrefix) { return net1 == net2 } _, n1, err1 := net.ParseCIDR(net1) _, n2, err2 := net.ParseCIDR(net2) if err1 != nil || err2 != nil { // if parsing fails, compare as strings return strings.EqualFold(net1, net2) } return n1.IP.Equal(n2.IP) && bytes.Equal(n1.Mask, n2.Mask) }
{ // prepare expected configuration with de-referenced netalloc links nbCfg := make(map[string]*l3.Route) expCfg := make(map[string]*l3.Route) for _, kv := range correlate { dstNetwork := kv.Value.DstNetwork parsed, err := d.addrAlloc.GetOrParseIPAddress(kv.Value.DstNetwork, "", netalloc_api.IPAddressForm_ADDR_NET) if err == nil { dstNetwork = parsed.String() } nextHop := kv.Value.NextHopAddr parsed, err = d.addrAlloc.GetOrParseIPAddress(getGwAddr(kv.Value), kv.Value.OutgoingInterface, netalloc_api.IPAddressForm_ADDR_ONLY) if err == nil { nextHop = parsed.IP.String() } route := proto.Clone(kv.Value).(*l3.Route) route.DstNetwork = dstNetwork route.NextHopAddr = nextHop key := models.Key(route) expCfg[key] = route nbCfg[key] = kv.Value } // Retrieve VPP route configuration routes, err := d.routeHandler.DumpRoutes() if err != nil { return nil, errors.Errorf("failed to dump VPP routes: %v", err) } for _, route := range routes { key := models.Key(route.Route) value := route.Route origin := kvs.UnknownOrigin // correlate with the expected configuration if expCfg, hasExpCfg := expCfg[key]; hasExpCfg { if d.EquivalentRoutes(key, value, expCfg) { value = nbCfg[key] // recreate the key in case the dest. IP or GW IP were replaced with netalloc link key = models.Key(value) origin = kvs.FromNB } } retrieved = append(retrieved, adapter.RouteKVWithMetadata{ Key: key, Value: value, Origin: origin, }) } return retrieved, nil }
identifier_body
models.py
from datetime import timedelta from django.apps import apps from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.utils import timezone from django.utils.functional import cached_property from .util import random_number_token class DeviceManager(models.Manager): """ The :class:`~django.db.models.Manager` object installed as ``Device.objects``. """ def devices_for_user(self, user, confirmed=None): """ Returns a queryset for all devices of this class that belong to the given user. :param user: The user. :type user: :class:`~django.contrib.auth.models.User` :param confirmed: If ``None``, all matching devices are returned. Otherwise, this can be any true or false value to limit the query to confirmed or unconfirmed devices, respectively. """ devices = self.model.objects.filter(user=user) if confirmed is not None: devices = devices.filter(confirmed=bool(confirmed)) return devices class Device(models.Model): """ Abstract base model for a :term:`device` attached to a user. Plugins must subclass this to define their OTP models. .. _unsaved_device_warning: .. warning:: OTP devices are inherently stateful. For example, verifying a token is logically a mutating operation on the device, which may involve incrementing a counter or otherwise consuming a token. A device must be committed to the database before it can be used in any way. .. attribute:: user *ForeignKey*: Foreign key to your user model, as configured by :setting:`AUTH_USER_MODEL` (:class:`~django.contrib.auth.models.User` by default). .. attribute:: name *CharField*: A human-readable name to help the user identify their devices. .. attribute:: confirmed *BooleanField*: A boolean value that tells us whether this device has been confirmed as valid. It defaults to ``True``, but subclasses or individual deployments can force it to ``False`` if they wish to create a device and then ask the user for confirmation. As a rule, built-in APIs that enumerate devices will only include those that are confirmed. .. attribute:: objects A :class:`~django_otp.models.DeviceManager`. """ user = models.ForeignKey( getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), help_text="The user that this device belongs to.", on_delete=models.CASCADE, ) name = models.CharField( max_length=64, help_text="The human-readable name of this device." ) confirmed = models.BooleanField( default=True, help_text="Is this device ready for use?" ) objects = DeviceManager() class Meta: abstract = True def __str__(self):
@property def persistent_id(self): """ A stable device identifier for forms and APIs. """ return '{0}/{1}'.format(self.model_label(), self.id) @classmethod def model_label(cls): """ Returns an identifier for this Django model class. This is just the standard "<app_label>.<model_name>" form. """ return '{0}.{1}'.format(cls._meta.app_label, cls._meta.model_name) @classmethod def from_persistent_id(cls, persistent_id, for_verify=False): """ Loads a device from its persistent id:: device == Device.from_persistent_id(device.persistent_id) :param bool for_verify: If ``True``, we'll load the device with :meth:`~django.db.models.query.QuerySet.select_for_update` to prevent concurrent verifications from succeeding. In which case, this must be called inside a transaction. """ device = None try: model_label, device_id = persistent_id.rsplit('/', 1) app_label, model_name = model_label.split('.') device_cls = apps.get_model(app_label, model_name) if issubclass(device_cls, Device): device_set = device_cls.objects.filter(id=int(device_id)) if for_verify: device_set = device_set.select_for_update() device = device_set.first() except (ValueError, LookupError): pass return device def is_interactive(self): """ Returns ``True`` if this is an interactive device. The default implementation returns ``True`` if :meth:`~django_otp.models.Device.generate_challenge` has been overridden, but subclasses are welcome to provide smarter implementations. :rtype: bool """ return not hasattr(self.generate_challenge, 'stub') def generate_challenge(self): """ Generates a challenge value that the user will need to produce a token. This method is permitted to have side effects, such as transmitting information to the user through some other channel (email or SMS, perhaps). And, of course, some devices may need to commit the challenge to the database. :returns: A message to the user. This should be a string that fits comfortably in the template ``'OTP Challenge: {0}'``. This may return ``None`` if this device is not interactive. :rtype: string or ``None`` :raises: Any :exc:`~exceptions.Exception` is permitted. Callers should trap ``Exception`` and report it to the user. """ return None generate_challenge.stub = True def verify_is_allowed(self): """ Checks whether it is permissible to call :meth:`verify_token`. If it is allowed, returns ``(True, None)``. Otherwise returns ``(False, data_dict)``, where ``data_dict`` contains extra information, defined by the implementation. This method can be used to implement throttling or locking, for example. Client code should check this method before calling :meth:`verify_token` and report problems to the user. To report specific problems, the data dictionary can return include a ``'reason'`` member with a value from the constants in :class:`VerifyNotAllowed`. Otherwise, an ``'error_message'`` member should be provided with an error message. :meth:`verify_token` should also call this method and return False if verification is not allowed. :rtype: (bool, dict or ``None``) """ return (True, None) def verify_token(self, token): """ Verifies a token. As a rule, the token should no longer be valid if this returns ``True``. :param str token: The OTP token provided by the user. :rtype: bool """ return False class SideChannelDevice(Device): """ Abstract base model for a side-channel :term:`device` attached to a user. This model implements token generation, verification and expiration, so the concrete devices only have to implement delivery. """ token = models.CharField(max_length=16, blank=True, null=True) valid_until = models.DateTimeField( default=timezone.now, help_text="The timestamp of the moment of expiry of the saved token.", ) class Meta: abstract = True def generate_token(self, length=6, valid_secs=300, commit=True): """ Generates a token of the specified length, then sets it on the model and sets the expiration of the token on the model. Pass 'commit=False' to avoid calling self.save(). :param int length: Number of decimal digits in the generated token. :param int valid_secs: Amount of seconds the token should be valid. :param bool commit: Whether to autosave the generated token. """ self.token = random_number_token(length) self.valid_until = timezone.now() + timedelta(seconds=valid_secs) if commit: self.save() def verify_token(self, token): """ Verifies a token by content and expiry. On success, the token is cleared and the device saved. :param str token: The OTP token provided by the user. :rtype: bool """ _now = timezone.now() if ( (self.token is not None) and (token == self.token) and (_now < self.valid_until) ): self.token = None self.valid_until = _now self.save() return True else: return False class VerifyNotAllowed: """ Constants that may be returned in the ``reason`` member of the extra information dictionary returned by :meth:`~django_otp.models.Device.verify_is_allowed` .. data:: N_FAILED_ATTEMPTS Indicates that verification is disallowed because of ``n`` successive failed attempts. The data dictionary should include the value of ``n`` in member ``failure_count`` """ N_FAILED_ATTEMPTS = 'N_FAILED_ATTEMPTS' class ThrottlingMixin(models.Model): """ Mixin class for models that want throttling behaviour. This implements exponential back-off for verifying tokens. Subclasses must implement :meth:`get_throttle_factor`, and must use the :meth:`verify_is_allowed`, :meth:`throttle_reset` and :meth:`throttle_increment` methods from within their verify_token() method. See the implementation of :class:`~django_otp.plugins.otp_email.models.EmailDevice` for an example. """ throttling_failure_timestamp = models.DateTimeField( null=True, blank=True, default=None, help_text="A timestamp of the last failed verification attempt. Null if last attempt succeeded.", ) throttling_failure_count = models.PositiveIntegerField( default=0, help_text="Number of successive failed attempts." ) def verify_is_allowed(self): """ If verification is allowed, returns ``(True, None)``. Otherwise, returns ``(False, data_dict)``. ``data_dict`` contains further information. Currently it can be:: { 'reason': VerifyNotAllowed.N_FAILED_ATTEMPTS, 'failure_count': n } where ``n`` is the number of successive failures. See :class:`~django_otp.models.VerifyNotAllowed`. """ if ( self.throttling_enabled and self.throttling_failure_count > 0 and self.throttling_failure_timestamp is not None ): now = timezone.now() delay = (now - self.throttling_failure_timestamp).total_seconds() # Required delays should be 1, 2, 4, 8 ... delay_required = self.get_throttle_factor() * ( 2 ** (self.throttling_failure_count - 1) ) if delay < delay_required: return ( False, { 'reason': VerifyNotAllowed.N_FAILED_ATTEMPTS, 'failure_count': self.throttling_failure_count, 'locked_until': self.throttling_failure_timestamp + timedelta(seconds=delay_required), }, ) return super().verify_is_allowed() def throttle_reset(self, commit=True): """ Call this method to reset throttling (normally when a verify attempt succeeded). Pass 'commit=False' to avoid calling self.save(). """ self.throttling_failure_timestamp = None self.throttling_failure_count = 0 if commit: self.save() def throttle_increment(self, commit=True): """ Call this method to increase throttling (normally when a verify attempt failed). Pass 'commit=False' to avoid calling self.save(). """ self.throttling_failure_timestamp = timezone.now() self.throttling_failure_count += 1 if commit: self.save() @cached_property def throttling_enabled(self): return self.get_throttle_factor() > 0 def get_throttle_factor(self): # pragma: no cover """ This must be implemented to return the throttle factor. The number of seconds required between verification attempts will be :math:`c2^{n-1}` where `c` is this factor and `n` is the number of previous failures. A factor of 1 translates to delays of 1, 2, 4, 8, etc. seconds. A factor of 0 disables the throttling. Normally this is just a wrapper for a plugin-specific setting like :setting:`OTP_EMAIL_THROTTLE_FACTOR`. """ raise NotImplementedError() class Meta: abstract = True
try: user = self.user except ObjectDoesNotExist: user = None return "{0} ({1})".format(self.name, user)
identifier_body
models.py
from datetime import timedelta from django.apps import apps from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.utils import timezone from django.utils.functional import cached_property from .util import random_number_token class DeviceManager(models.Manager): """ The :class:`~django.db.models.Manager` object installed as ``Device.objects``. """ def devices_for_user(self, user, confirmed=None): """ Returns a queryset for all devices of this class that belong to the given user. :param user: The user. :type user: :class:`~django.contrib.auth.models.User` :param confirmed: If ``None``, all matching devices are returned. Otherwise, this can be any true or false value to limit the query to confirmed or unconfirmed devices, respectively. """ devices = self.model.objects.filter(user=user) if confirmed is not None: devices = devices.filter(confirmed=bool(confirmed)) return devices class Device(models.Model): """ Abstract base model for a :term:`device` attached to a user. Plugins must subclass this to define their OTP models. .. _unsaved_device_warning: .. warning:: OTP devices are inherently stateful. For example, verifying a token is logically a mutating operation on the device, which may involve incrementing a counter or otherwise consuming a token. A device must be committed to the database before it can be used in any way. .. attribute:: user *ForeignKey*: Foreign key to your user model, as configured by :setting:`AUTH_USER_MODEL` (:class:`~django.contrib.auth.models.User` by default). .. attribute:: name *CharField*: A human-readable name to help the user identify their devices. .. attribute:: confirmed *BooleanField*: A boolean value that tells us whether this device has been confirmed as valid. It defaults to ``True``, but subclasses or individual deployments can force it to ``False`` if they wish to create a device and then ask the user for confirmation. As a rule, built-in APIs that enumerate devices will only include those that are confirmed. .. attribute:: objects A :class:`~django_otp.models.DeviceManager`. """ user = models.ForeignKey( getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), help_text="The user that this device belongs to.", on_delete=models.CASCADE, ) name = models.CharField( max_length=64, help_text="The human-readable name of this device." ) confirmed = models.BooleanField( default=True, help_text="Is this device ready for use?" ) objects = DeviceManager() class Meta: abstract = True def __str__(self): try: user = self.user except ObjectDoesNotExist: user = None return "{0} ({1})".format(self.name, user) @property def persistent_id(self): """ A stable device identifier for forms and APIs. """ return '{0}/{1}'.format(self.model_label(), self.id) @classmethod def model_label(cls): """ Returns an identifier for this Django model class. This is just the standard "<app_label>.<model_name>" form. """ return '{0}.{1}'.format(cls._meta.app_label, cls._meta.model_name) @classmethod def from_persistent_id(cls, persistent_id, for_verify=False): """ Loads a device from its persistent id:: device == Device.from_persistent_id(device.persistent_id) :param bool for_verify: If ``True``, we'll load the device with :meth:`~django.db.models.query.QuerySet.select_for_update` to prevent concurrent verifications from succeeding. In which case, this must be called inside a transaction. """ device = None try: model_label, device_id = persistent_id.rsplit('/', 1) app_label, model_name = model_label.split('.') device_cls = apps.get_model(app_label, model_name) if issubclass(device_cls, Device): device_set = device_cls.objects.filter(id=int(device_id)) if for_verify: device_set = device_set.select_for_update() device = device_set.first() except (ValueError, LookupError): pass return device def is_interactive(self): """ Returns ``True`` if this is an interactive device. The default implementation returns ``True`` if :meth:`~django_otp.models.Device.generate_challenge` has been overridden, but subclasses are welcome to provide smarter implementations. :rtype: bool """ return not hasattr(self.generate_challenge, 'stub') def generate_challenge(self): """ Generates a challenge value that the user will need to produce a token. This method is permitted to have side effects, such as transmitting information to the user through some other channel (email or SMS, perhaps). And, of course, some devices may need to commit the challenge to the database. :returns: A message to the user. This should be a string that fits comfortably in the template ``'OTP Challenge: {0}'``. This may return ``None`` if this device is not interactive. :rtype: string or ``None`` :raises: Any :exc:`~exceptions.Exception` is permitted. Callers should trap ``Exception`` and report it to the user. """ return None generate_challenge.stub = True def verify_is_allowed(self): """ Checks whether it is permissible to call :meth:`verify_token`. If it is allowed, returns ``(True, None)``. Otherwise returns ``(False, data_dict)``, where ``data_dict`` contains extra information, defined by the implementation. This method can be used to implement throttling or locking, for example. Client code should check this method before calling :meth:`verify_token` and report problems to the user. To report specific problems, the data dictionary can return include a ``'reason'`` member with a value from the constants in :class:`VerifyNotAllowed`. Otherwise, an ``'error_message'`` member should be provided with an error message. :meth:`verify_token` should also call this method and return False if verification is not allowed. :rtype: (bool, dict or ``None``) """ return (True, None) def verify_token(self, token): """ Verifies a token. As a rule, the token should no longer be valid if this returns ``True``. :param str token: The OTP token provided by the user. :rtype: bool """ return False class SideChannelDevice(Device): """ Abstract base model for a side-channel :term:`device` attached to a user. This model implements token generation, verification and expiration, so the concrete devices only have to implement delivery. """ token = models.CharField(max_length=16, blank=True, null=True) valid_until = models.DateTimeField( default=timezone.now, help_text="The timestamp of the moment of expiry of the saved token.", ) class Meta: abstract = True def generate_token(self, length=6, valid_secs=300, commit=True): """ Generates a token of the specified length, then sets it on the model and sets the expiration of the token on the model. Pass 'commit=False' to avoid calling self.save(). :param int length: Number of decimal digits in the generated token. :param int valid_secs: Amount of seconds the token should be valid. :param bool commit: Whether to autosave the generated token. """ self.token = random_number_token(length) self.valid_until = timezone.now() + timedelta(seconds=valid_secs) if commit: self.save() def verify_token(self, token): """ Verifies a token by content and expiry. On success, the token is cleared and the device saved.
:param str token: The OTP token provided by the user. :rtype: bool """ _now = timezone.now() if ( (self.token is not None) and (token == self.token) and (_now < self.valid_until) ): self.token = None self.valid_until = _now self.save() return True else: return False class VerifyNotAllowed: """ Constants that may be returned in the ``reason`` member of the extra information dictionary returned by :meth:`~django_otp.models.Device.verify_is_allowed` .. data:: N_FAILED_ATTEMPTS Indicates that verification is disallowed because of ``n`` successive failed attempts. The data dictionary should include the value of ``n`` in member ``failure_count`` """ N_FAILED_ATTEMPTS = 'N_FAILED_ATTEMPTS' class ThrottlingMixin(models.Model): """ Mixin class for models that want throttling behaviour. This implements exponential back-off for verifying tokens. Subclasses must implement :meth:`get_throttle_factor`, and must use the :meth:`verify_is_allowed`, :meth:`throttle_reset` and :meth:`throttle_increment` methods from within their verify_token() method. See the implementation of :class:`~django_otp.plugins.otp_email.models.EmailDevice` for an example. """ throttling_failure_timestamp = models.DateTimeField( null=True, blank=True, default=None, help_text="A timestamp of the last failed verification attempt. Null if last attempt succeeded.", ) throttling_failure_count = models.PositiveIntegerField( default=0, help_text="Number of successive failed attempts." ) def verify_is_allowed(self): """ If verification is allowed, returns ``(True, None)``. Otherwise, returns ``(False, data_dict)``. ``data_dict`` contains further information. Currently it can be:: { 'reason': VerifyNotAllowed.N_FAILED_ATTEMPTS, 'failure_count': n } where ``n`` is the number of successive failures. See :class:`~django_otp.models.VerifyNotAllowed`. """ if ( self.throttling_enabled and self.throttling_failure_count > 0 and self.throttling_failure_timestamp is not None ): now = timezone.now() delay = (now - self.throttling_failure_timestamp).total_seconds() # Required delays should be 1, 2, 4, 8 ... delay_required = self.get_throttle_factor() * ( 2 ** (self.throttling_failure_count - 1) ) if delay < delay_required: return ( False, { 'reason': VerifyNotAllowed.N_FAILED_ATTEMPTS, 'failure_count': self.throttling_failure_count, 'locked_until': self.throttling_failure_timestamp + timedelta(seconds=delay_required), }, ) return super().verify_is_allowed() def throttle_reset(self, commit=True): """ Call this method to reset throttling (normally when a verify attempt succeeded). Pass 'commit=False' to avoid calling self.save(). """ self.throttling_failure_timestamp = None self.throttling_failure_count = 0 if commit: self.save() def throttle_increment(self, commit=True): """ Call this method to increase throttling (normally when a verify attempt failed). Pass 'commit=False' to avoid calling self.save(). """ self.throttling_failure_timestamp = timezone.now() self.throttling_failure_count += 1 if commit: self.save() @cached_property def throttling_enabled(self): return self.get_throttle_factor() > 0 def get_throttle_factor(self): # pragma: no cover """ This must be implemented to return the throttle factor. The number of seconds required between verification attempts will be :math:`c2^{n-1}` where `c` is this factor and `n` is the number of previous failures. A factor of 1 translates to delays of 1, 2, 4, 8, etc. seconds. A factor of 0 disables the throttling. Normally this is just a wrapper for a plugin-specific setting like :setting:`OTP_EMAIL_THROTTLE_FACTOR`. """ raise NotImplementedError() class Meta: abstract = True
random_line_split
models.py
from datetime import timedelta from django.apps import apps from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.utils import timezone from django.utils.functional import cached_property from .util import random_number_token class DeviceManager(models.Manager): """ The :class:`~django.db.models.Manager` object installed as ``Device.objects``. """ def devices_for_user(self, user, confirmed=None): """ Returns a queryset for all devices of this class that belong to the given user. :param user: The user. :type user: :class:`~django.contrib.auth.models.User` :param confirmed: If ``None``, all matching devices are returned. Otherwise, this can be any true or false value to limit the query to confirmed or unconfirmed devices, respectively. """ devices = self.model.objects.filter(user=user) if confirmed is not None: devices = devices.filter(confirmed=bool(confirmed)) return devices class
(models.Model): """ Abstract base model for a :term:`device` attached to a user. Plugins must subclass this to define their OTP models. .. _unsaved_device_warning: .. warning:: OTP devices are inherently stateful. For example, verifying a token is logically a mutating operation on the device, which may involve incrementing a counter or otherwise consuming a token. A device must be committed to the database before it can be used in any way. .. attribute:: user *ForeignKey*: Foreign key to your user model, as configured by :setting:`AUTH_USER_MODEL` (:class:`~django.contrib.auth.models.User` by default). .. attribute:: name *CharField*: A human-readable name to help the user identify their devices. .. attribute:: confirmed *BooleanField*: A boolean value that tells us whether this device has been confirmed as valid. It defaults to ``True``, but subclasses or individual deployments can force it to ``False`` if they wish to create a device and then ask the user for confirmation. As a rule, built-in APIs that enumerate devices will only include those that are confirmed. .. attribute:: objects A :class:`~django_otp.models.DeviceManager`. """ user = models.ForeignKey( getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), help_text="The user that this device belongs to.", on_delete=models.CASCADE, ) name = models.CharField( max_length=64, help_text="The human-readable name of this device." ) confirmed = models.BooleanField( default=True, help_text="Is this device ready for use?" ) objects = DeviceManager() class Meta: abstract = True def __str__(self): try: user = self.user except ObjectDoesNotExist: user = None return "{0} ({1})".format(self.name, user) @property def persistent_id(self): """ A stable device identifier for forms and APIs. """ return '{0}/{1}'.format(self.model_label(), self.id) @classmethod def model_label(cls): """ Returns an identifier for this Django model class. This is just the standard "<app_label>.<model_name>" form. """ return '{0}.{1}'.format(cls._meta.app_label, cls._meta.model_name) @classmethod def from_persistent_id(cls, persistent_id, for_verify=False): """ Loads a device from its persistent id:: device == Device.from_persistent_id(device.persistent_id) :param bool for_verify: If ``True``, we'll load the device with :meth:`~django.db.models.query.QuerySet.select_for_update` to prevent concurrent verifications from succeeding. In which case, this must be called inside a transaction. """ device = None try: model_label, device_id = persistent_id.rsplit('/', 1) app_label, model_name = model_label.split('.') device_cls = apps.get_model(app_label, model_name) if issubclass(device_cls, Device): device_set = device_cls.objects.filter(id=int(device_id)) if for_verify: device_set = device_set.select_for_update() device = device_set.first() except (ValueError, LookupError): pass return device def is_interactive(self): """ Returns ``True`` if this is an interactive device. The default implementation returns ``True`` if :meth:`~django_otp.models.Device.generate_challenge` has been overridden, but subclasses are welcome to provide smarter implementations. :rtype: bool """ return not hasattr(self.generate_challenge, 'stub') def generate_challenge(self): """ Generates a challenge value that the user will need to produce a token. This method is permitted to have side effects, such as transmitting information to the user through some other channel (email or SMS, perhaps). And, of course, some devices may need to commit the challenge to the database. :returns: A message to the user. This should be a string that fits comfortably in the template ``'OTP Challenge: {0}'``. This may return ``None`` if this device is not interactive. :rtype: string or ``None`` :raises: Any :exc:`~exceptions.Exception` is permitted. Callers should trap ``Exception`` and report it to the user. """ return None generate_challenge.stub = True def verify_is_allowed(self): """ Checks whether it is permissible to call :meth:`verify_token`. If it is allowed, returns ``(True, None)``. Otherwise returns ``(False, data_dict)``, where ``data_dict`` contains extra information, defined by the implementation. This method can be used to implement throttling or locking, for example. Client code should check this method before calling :meth:`verify_token` and report problems to the user. To report specific problems, the data dictionary can return include a ``'reason'`` member with a value from the constants in :class:`VerifyNotAllowed`. Otherwise, an ``'error_message'`` member should be provided with an error message. :meth:`verify_token` should also call this method and return False if verification is not allowed. :rtype: (bool, dict or ``None``) """ return (True, None) def verify_token(self, token): """ Verifies a token. As a rule, the token should no longer be valid if this returns ``True``. :param str token: The OTP token provided by the user. :rtype: bool """ return False class SideChannelDevice(Device): """ Abstract base model for a side-channel :term:`device` attached to a user. This model implements token generation, verification and expiration, so the concrete devices only have to implement delivery. """ token = models.CharField(max_length=16, blank=True, null=True) valid_until = models.DateTimeField( default=timezone.now, help_text="The timestamp of the moment of expiry of the saved token.", ) class Meta: abstract = True def generate_token(self, length=6, valid_secs=300, commit=True): """ Generates a token of the specified length, then sets it on the model and sets the expiration of the token on the model. Pass 'commit=False' to avoid calling self.save(). :param int length: Number of decimal digits in the generated token. :param int valid_secs: Amount of seconds the token should be valid. :param bool commit: Whether to autosave the generated token. """ self.token = random_number_token(length) self.valid_until = timezone.now() + timedelta(seconds=valid_secs) if commit: self.save() def verify_token(self, token): """ Verifies a token by content and expiry. On success, the token is cleared and the device saved. :param str token: The OTP token provided by the user. :rtype: bool """ _now = timezone.now() if ( (self.token is not None) and (token == self.token) and (_now < self.valid_until) ): self.token = None self.valid_until = _now self.save() return True else: return False class VerifyNotAllowed: """ Constants that may be returned in the ``reason`` member of the extra information dictionary returned by :meth:`~django_otp.models.Device.verify_is_allowed` .. data:: N_FAILED_ATTEMPTS Indicates that verification is disallowed because of ``n`` successive failed attempts. The data dictionary should include the value of ``n`` in member ``failure_count`` """ N_FAILED_ATTEMPTS = 'N_FAILED_ATTEMPTS' class ThrottlingMixin(models.Model): """ Mixin class for models that want throttling behaviour. This implements exponential back-off for verifying tokens. Subclasses must implement :meth:`get_throttle_factor`, and must use the :meth:`verify_is_allowed`, :meth:`throttle_reset` and :meth:`throttle_increment` methods from within their verify_token() method. See the implementation of :class:`~django_otp.plugins.otp_email.models.EmailDevice` for an example. """ throttling_failure_timestamp = models.DateTimeField( null=True, blank=True, default=None, help_text="A timestamp of the last failed verification attempt. Null if last attempt succeeded.", ) throttling_failure_count = models.PositiveIntegerField( default=0, help_text="Number of successive failed attempts." ) def verify_is_allowed(self): """ If verification is allowed, returns ``(True, None)``. Otherwise, returns ``(False, data_dict)``. ``data_dict`` contains further information. Currently it can be:: { 'reason': VerifyNotAllowed.N_FAILED_ATTEMPTS, 'failure_count': n } where ``n`` is the number of successive failures. See :class:`~django_otp.models.VerifyNotAllowed`. """ if ( self.throttling_enabled and self.throttling_failure_count > 0 and self.throttling_failure_timestamp is not None ): now = timezone.now() delay = (now - self.throttling_failure_timestamp).total_seconds() # Required delays should be 1, 2, 4, 8 ... delay_required = self.get_throttle_factor() * ( 2 ** (self.throttling_failure_count - 1) ) if delay < delay_required: return ( False, { 'reason': VerifyNotAllowed.N_FAILED_ATTEMPTS, 'failure_count': self.throttling_failure_count, 'locked_until': self.throttling_failure_timestamp + timedelta(seconds=delay_required), }, ) return super().verify_is_allowed() def throttle_reset(self, commit=True): """ Call this method to reset throttling (normally when a verify attempt succeeded). Pass 'commit=False' to avoid calling self.save(). """ self.throttling_failure_timestamp = None self.throttling_failure_count = 0 if commit: self.save() def throttle_increment(self, commit=True): """ Call this method to increase throttling (normally when a verify attempt failed). Pass 'commit=False' to avoid calling self.save(). """ self.throttling_failure_timestamp = timezone.now() self.throttling_failure_count += 1 if commit: self.save() @cached_property def throttling_enabled(self): return self.get_throttle_factor() > 0 def get_throttle_factor(self): # pragma: no cover """ This must be implemented to return the throttle factor. The number of seconds required between verification attempts will be :math:`c2^{n-1}` where `c` is this factor and `n` is the number of previous failures. A factor of 1 translates to delays of 1, 2, 4, 8, etc. seconds. A factor of 0 disables the throttling. Normally this is just a wrapper for a plugin-specific setting like :setting:`OTP_EMAIL_THROTTLE_FACTOR`. """ raise NotImplementedError() class Meta: abstract = True
Device
identifier_name
models.py
from datetime import timedelta from django.apps import apps from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.utils import timezone from django.utils.functional import cached_property from .util import random_number_token class DeviceManager(models.Manager): """ The :class:`~django.db.models.Manager` object installed as ``Device.objects``. """ def devices_for_user(self, user, confirmed=None): """ Returns a queryset for all devices of this class that belong to the given user. :param user: The user. :type user: :class:`~django.contrib.auth.models.User` :param confirmed: If ``None``, all matching devices are returned. Otherwise, this can be any true or false value to limit the query to confirmed or unconfirmed devices, respectively. """ devices = self.model.objects.filter(user=user) if confirmed is not None: devices = devices.filter(confirmed=bool(confirmed)) return devices class Device(models.Model): """ Abstract base model for a :term:`device` attached to a user. Plugins must subclass this to define their OTP models. .. _unsaved_device_warning: .. warning:: OTP devices are inherently stateful. For example, verifying a token is logically a mutating operation on the device, which may involve incrementing a counter or otherwise consuming a token. A device must be committed to the database before it can be used in any way. .. attribute:: user *ForeignKey*: Foreign key to your user model, as configured by :setting:`AUTH_USER_MODEL` (:class:`~django.contrib.auth.models.User` by default). .. attribute:: name *CharField*: A human-readable name to help the user identify their devices. .. attribute:: confirmed *BooleanField*: A boolean value that tells us whether this device has been confirmed as valid. It defaults to ``True``, but subclasses or individual deployments can force it to ``False`` if they wish to create a device and then ask the user for confirmation. As a rule, built-in APIs that enumerate devices will only include those that are confirmed. .. attribute:: objects A :class:`~django_otp.models.DeviceManager`. """ user = models.ForeignKey( getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), help_text="The user that this device belongs to.", on_delete=models.CASCADE, ) name = models.CharField( max_length=64, help_text="The human-readable name of this device." ) confirmed = models.BooleanField( default=True, help_text="Is this device ready for use?" ) objects = DeviceManager() class Meta: abstract = True def __str__(self): try: user = self.user except ObjectDoesNotExist: user = None return "{0} ({1})".format(self.name, user) @property def persistent_id(self): """ A stable device identifier for forms and APIs. """ return '{0}/{1}'.format(self.model_label(), self.id) @classmethod def model_label(cls): """ Returns an identifier for this Django model class. This is just the standard "<app_label>.<model_name>" form. """ return '{0}.{1}'.format(cls._meta.app_label, cls._meta.model_name) @classmethod def from_persistent_id(cls, persistent_id, for_verify=False): """ Loads a device from its persistent id:: device == Device.from_persistent_id(device.persistent_id) :param bool for_verify: If ``True``, we'll load the device with :meth:`~django.db.models.query.QuerySet.select_for_update` to prevent concurrent verifications from succeeding. In which case, this must be called inside a transaction. """ device = None try: model_label, device_id = persistent_id.rsplit('/', 1) app_label, model_name = model_label.split('.') device_cls = apps.get_model(app_label, model_name) if issubclass(device_cls, Device): device_set = device_cls.objects.filter(id=int(device_id)) if for_verify:
device = device_set.first() except (ValueError, LookupError): pass return device def is_interactive(self): """ Returns ``True`` if this is an interactive device. The default implementation returns ``True`` if :meth:`~django_otp.models.Device.generate_challenge` has been overridden, but subclasses are welcome to provide smarter implementations. :rtype: bool """ return not hasattr(self.generate_challenge, 'stub') def generate_challenge(self): """ Generates a challenge value that the user will need to produce a token. This method is permitted to have side effects, such as transmitting information to the user through some other channel (email or SMS, perhaps). And, of course, some devices may need to commit the challenge to the database. :returns: A message to the user. This should be a string that fits comfortably in the template ``'OTP Challenge: {0}'``. This may return ``None`` if this device is not interactive. :rtype: string or ``None`` :raises: Any :exc:`~exceptions.Exception` is permitted. Callers should trap ``Exception`` and report it to the user. """ return None generate_challenge.stub = True def verify_is_allowed(self): """ Checks whether it is permissible to call :meth:`verify_token`. If it is allowed, returns ``(True, None)``. Otherwise returns ``(False, data_dict)``, where ``data_dict`` contains extra information, defined by the implementation. This method can be used to implement throttling or locking, for example. Client code should check this method before calling :meth:`verify_token` and report problems to the user. To report specific problems, the data dictionary can return include a ``'reason'`` member with a value from the constants in :class:`VerifyNotAllowed`. Otherwise, an ``'error_message'`` member should be provided with an error message. :meth:`verify_token` should also call this method and return False if verification is not allowed. :rtype: (bool, dict or ``None``) """ return (True, None) def verify_token(self, token): """ Verifies a token. As a rule, the token should no longer be valid if this returns ``True``. :param str token: The OTP token provided by the user. :rtype: bool """ return False class SideChannelDevice(Device): """ Abstract base model for a side-channel :term:`device` attached to a user. This model implements token generation, verification and expiration, so the concrete devices only have to implement delivery. """ token = models.CharField(max_length=16, blank=True, null=True) valid_until = models.DateTimeField( default=timezone.now, help_text="The timestamp of the moment of expiry of the saved token.", ) class Meta: abstract = True def generate_token(self, length=6, valid_secs=300, commit=True): """ Generates a token of the specified length, then sets it on the model and sets the expiration of the token on the model. Pass 'commit=False' to avoid calling self.save(). :param int length: Number of decimal digits in the generated token. :param int valid_secs: Amount of seconds the token should be valid. :param bool commit: Whether to autosave the generated token. """ self.token = random_number_token(length) self.valid_until = timezone.now() + timedelta(seconds=valid_secs) if commit: self.save() def verify_token(self, token): """ Verifies a token by content and expiry. On success, the token is cleared and the device saved. :param str token: The OTP token provided by the user. :rtype: bool """ _now = timezone.now() if ( (self.token is not None) and (token == self.token) and (_now < self.valid_until) ): self.token = None self.valid_until = _now self.save() return True else: return False class VerifyNotAllowed: """ Constants that may be returned in the ``reason`` member of the extra information dictionary returned by :meth:`~django_otp.models.Device.verify_is_allowed` .. data:: N_FAILED_ATTEMPTS Indicates that verification is disallowed because of ``n`` successive failed attempts. The data dictionary should include the value of ``n`` in member ``failure_count`` """ N_FAILED_ATTEMPTS = 'N_FAILED_ATTEMPTS' class ThrottlingMixin(models.Model): """ Mixin class for models that want throttling behaviour. This implements exponential back-off for verifying tokens. Subclasses must implement :meth:`get_throttle_factor`, and must use the :meth:`verify_is_allowed`, :meth:`throttle_reset` and :meth:`throttle_increment` methods from within their verify_token() method. See the implementation of :class:`~django_otp.plugins.otp_email.models.EmailDevice` for an example. """ throttling_failure_timestamp = models.DateTimeField( null=True, blank=True, default=None, help_text="A timestamp of the last failed verification attempt. Null if last attempt succeeded.", ) throttling_failure_count = models.PositiveIntegerField( default=0, help_text="Number of successive failed attempts." ) def verify_is_allowed(self): """ If verification is allowed, returns ``(True, None)``. Otherwise, returns ``(False, data_dict)``. ``data_dict`` contains further information. Currently it can be:: { 'reason': VerifyNotAllowed.N_FAILED_ATTEMPTS, 'failure_count': n } where ``n`` is the number of successive failures. See :class:`~django_otp.models.VerifyNotAllowed`. """ if ( self.throttling_enabled and self.throttling_failure_count > 0 and self.throttling_failure_timestamp is not None ): now = timezone.now() delay = (now - self.throttling_failure_timestamp).total_seconds() # Required delays should be 1, 2, 4, 8 ... delay_required = self.get_throttle_factor() * ( 2 ** (self.throttling_failure_count - 1) ) if delay < delay_required: return ( False, { 'reason': VerifyNotAllowed.N_FAILED_ATTEMPTS, 'failure_count': self.throttling_failure_count, 'locked_until': self.throttling_failure_timestamp + timedelta(seconds=delay_required), }, ) return super().verify_is_allowed() def throttle_reset(self, commit=True): """ Call this method to reset throttling (normally when a verify attempt succeeded). Pass 'commit=False' to avoid calling self.save(). """ self.throttling_failure_timestamp = None self.throttling_failure_count = 0 if commit: self.save() def throttle_increment(self, commit=True): """ Call this method to increase throttling (normally when a verify attempt failed). Pass 'commit=False' to avoid calling self.save(). """ self.throttling_failure_timestamp = timezone.now() self.throttling_failure_count += 1 if commit: self.save() @cached_property def throttling_enabled(self): return self.get_throttle_factor() > 0 def get_throttle_factor(self): # pragma: no cover """ This must be implemented to return the throttle factor. The number of seconds required between verification attempts will be :math:`c2^{n-1}` where `c` is this factor and `n` is the number of previous failures. A factor of 1 translates to delays of 1, 2, 4, 8, etc. seconds. A factor of 0 disables the throttling. Normally this is just a wrapper for a plugin-specific setting like :setting:`OTP_EMAIL_THROTTLE_FACTOR`. """ raise NotImplementedError() class Meta: abstract = True
device_set = device_set.select_for_update()
conditional_block
NetHandler.ts
import { Global as G } from "System/global"; import { Macros } from 'System/protocol/Macros' import { Profiler } from "System/utils/Profiler" export enum EnumNetId { base = 1, cross, } enum ConnectStatus { none = 0, // 空闲 connecting = 1, // 正在连接 connected = 2, // 已连接 closed = 3, // 已关闭 error = 4, // 连接错误 disconnected = 5, // 连接断开 } class Socket { onConnect: (id: number, result: boolean, reason: number) => void; onDisConnect: (id: number, reason: number) => void; onReceived: (id: number, data: any, size: number) => void; totalTryTimes: number = 3; private curTryTimes: number = 0; private tcp: Game.TcpClient = null; private host: string; private port: number = 0; private status: ConnectStatus; private id = 0; constructor(id: number) { this.id = id; Game.TcpClient.setHandleTimesInFrame(30); let headsize = 2; if (this.versionCode > 1080) { headsize = 28; } this.tcp = Game.TcpClient.create(800000, 100000, headsize, 200000, 5000, 5000); this.tcp.onConnect = delegate(this, this.onTcpConnect); this.tcp.onDisConnect = delegate(this, this.onTcpDisConnect); this.tcp.onReceived = delegate(this, this.onTcpRecv); } get Id(): number { return this.id; } get Status(): ConnectStatus { return this.status; } connect(host: string, port: number) { this.host = host; this.port = port; this.curTryTimes = 0; this.status = ConnectStatus.connecting; this.doConnect(); } close() { this.tcp.close(); this.status = ConnectStatus.closed; this.host = null; this.port = 0; } send(data: any, size: number) { this.tcp.send(data, size); } private doConnect() { this.curTryTimes++; this.tcp.close(); this.tcp.connect(this.host, this.port, 5000 * 4); // 20 seconds timeout uts.log(uts.format('向{0}:{1}发起连接(第{2}次)...', this.host, this.port, this.curTryTimes)); } private onTcpConnect(isSuccess: boolean, reason: number) { if (null == this.host) { return; } if (isSuccess) { uts.log(uts.format('tcp connect success: {0}:{1}', this.host, this.port)); this.status = ConnectStatus.connected; if (null != this.onConnect) { this.onConnect(this.id, isSuccess, reason); } } else { uts.log(uts.format('tcp connect failed: {0}:{1}, reason is {2}', this.host, this.port, reason)); if (reason != 0 && Game.TcpClient.getError != null) { uts.logWarning(Game.TcpClient.getError()); } if (this.curTryTimes < this.totalTryTimes) { // 继续重试 this.doConnect(); } else { // 超过重试次数 this.status = ConnectStatus.error; if (null != this.onConnect) { this.onConnect(this.id, isSuccess, reason); } } } } private onTcpDisConnect(reason: number) { if (null == this.host) { return; } this.tcp.close(); uts.log(uts.format('tcp disconnected: {0}:{1}, reason is {2}', this.host, this.port, reason)); if (reason != 0 && Game.TcpClient.getError != null) { uts.logWarning(Game.TcpClient.getError()); } this.status = ConnectStatus.disconnected; if (null != this.onDisConnect) { this.onDisConnect(this.id, reason); } } private onTcpRecv(data: any, size: number) { if (null == this.host) { return; } if (null != this.onDisConnect) { this.onReceived(this.id, data, size); } } private get versionCode(): number { let vers = UnityEngine.Application.version.split('.'); if (vers.length < 4) return 100000; return Number(vers[3]); } } export class NetHandler { /**心跳包网络延迟,单位秒。*/ private netDelay = 0; /**心跳包发送时间记录数组。*/ private sendTimeStatArray: number[] = []; private static listeners = {}; private static readonly totalTryTimes: number = 3; private sockets: Socket[] = []; private workSocket: Socket; private ips: string; private hostList: Array<string> = []; private port = 0; private netId: EnumNetId; public head: Protocol.MsgHead = null; /**在收到login response之前锁住消息*/ private isMsgBlocked = true; public onConnectCallback: (isSuccess: boolean) => void; public onDisconnectCallback: () => void; public onExceptionCallback: () => void; get NetDelay(): number { return this.netDelay; } get NetId(): EnumNetId { return this.netId; } connect(ips: string, port: number, netId: EnumNetId) { this.netId = netId; // 同一个socket连接
his.close(); // 多个url用|分开 this.ips = ips; this.hostList = ips.split("|"); //先暂时定为一个 this.port = port; let hostCount: number = this.hostList.length; // 创建ping let curSocketCnt: number = this.sockets.length; for (let i = 0; i < hostCount - curSocketCnt; i++) { let socket = new Socket(curSocketCnt + i); socket.onConnect = delegate(this, this.onConnect); socket.onDisConnect = delegate(this, this.onDisConnect); socket.onReceived = delegate(this, this.onRecv); this.sockets.push(socket); } this.doConnect(); } reConnect() { uts.logWarning('reconnect...'); //不要删除定位crash用 this.close(); this.doConnect(); } doConnect() { this.workSocket = null; // 如果有多个host,则采用ping测试各连接选择最快者 let hostCount: number = this.hostList.length; for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; socket.connect(this.hostList[i], this.port); } } close() { // 关闭连接 this.workSocket = null; let hostCount: number = this.hostList.length; for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; socket.close(); } } send(obj: Protocol.FyMsg) { if (null == this.workSocket) { return; } let msgId: number = obj.m_stMsgHead.m_uiMsgID; let packlen = G.Dr.pack(obj); if (packlen < 0) { uts.bugReport('pack error! err:' + packlen + ', msgid:' + msgId + ', errmsg:' + G.Dr.error()); return; } this.workSocket.send(G.Dr.packBuf(), packlen); // 记录发送时间 if (Macros.MsgID_SyncTime_Request == msgId) { // 将延迟设置为0 this.sendTimeStatArray.push(UnityEngine.Time.realtimeSinceStartup); } } private onConnect(id: number, isSuccess: boolean, reason: number) { if (null != this.workSocket) { return; } this.sendTimeStatArray.length = 0; let hostCount: number = this.hostList.length; if (isSuccess) { for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; if (socket.Id == id) { this.workSocket = socket; } else { socket.close(); } } uts.assert(null != this.workSocket); // 连上socket后即阻塞其它消息 this.isMsgBlocked = true; this.onConnectCallback(true); } else { let errorCnt = 0; for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; if (socket.Status == ConnectStatus.error) { errorCnt++; } } if (errorCnt == hostCount) { this.onConnectCallback(false); } } } private onDisConnect(id: number, reason: number) { if (null != this.workSocket && this.workSocket.Id == id) { if (null != this.onDisconnectCallback) { this.onDisconnectCallback(); } } } private onRecv(id: number, data: any, size: number, busy: boolean) { if (null != this.workSocket && this.workSocket.Id == id) { let msgid = G.Dr.msgid(data, size); if (msgid < 0) { uts.bugReport('get msgid error! err:' + msgid + ", datasize:" + size); return; } if (busy && Macros.MsgID_CastSkill_Notify == msgid) { // 繁忙丢掉技能notify return; } if (Macros.MsgID_LoginServer_Response == msgid) { this.isMsgBlocked = false; } if (this.isMsgBlocked && Macros.MsgID_Account_ListRole_Response != msgid && Macros.MsgID_Account_CreateRole_Response != msgid) { uts.log(uts.format('Ignore message received before login response, msgid={0}', msgid)); return; } let obj: Protocol.FyMsg = G.Dr.getRecvObject(msgid) as Protocol.FyMsg; let rt = G.Dr.unpack(data, size, obj); if (rt < 0) { uts.bugReport('unpack error! err:' + rt + ', msgid:' + msgid + ", datasize:" + size); return; } this.head = obj.m_stMsgHead; // 计算延迟 if (Macros.MsgID_SyncTime_Response == msgid) { let sendTime = this.sendTimeStatArray.shift(); if (sendTime > 0) { this.netDelay = Math.round((UnityEngine.Time.realtimeSinceStartup - sendTime) * 1000); if (this.netDelay > 999) { this.sendTimeStatArray.length = 0; } } } Profiler.push('msgid:' + msgid); this.dispatchData(msgid, obj.m_msgBody); Profiler.pop(); } } static addListener(msgid: number, deleg) { let list = NetHandler.listeners[msgid]; if (list == null) { list = []; NetHandler.listeners[msgid] = list; } list.push(deleg); } static removeListener(msgid: number, deleg) { let list = NetHandler.listeners[msgid]; if (list == null) return; let pos = list.indexOf(deleg); if (pos < 0) return; list.splice(pos, 1); } dispatchData(msgid: number, body) { let list = NetHandler.listeners[msgid]; if (list == null) return; for (let i = 0, n = list.length; i < n; i++) { list[i](body); } } }
,不能list两次role,所以每次都要断开重连 t
identifier_body
NetHandler.ts
import { Global as G } from "System/global"; import { Macros } from 'System/protocol/Macros' import { Profiler } from "System/utils/Profiler" export enum EnumNetId { base = 1, cross, } enum ConnectStatus { none = 0, // 空闲 connecting = 1, // 正在连接 connected = 2, // 已连接 closed = 3, // 已关闭 error = 4, // 连接错误 disconnected = 5, // 连接断开 } class Socket { onConnect: (id: number, result: boolean, reason: number) => void; onDisConnect: (id: number, reason: number) => void; onReceived: (id: number, data: any, size: number) => void; totalTryTimes: number = 3; private curTryTimes: number = 0; private tcp: Game.TcpClient = null; private host: string; private port: number = 0; private status: ConnectStatus; private id = 0; constructor(id: number) { this.id = id; Game.TcpClient.setHandleTimesInFrame(30); let headsize = 2; if (this.versionCode > 1080) { headsize = 28; } this.tcp = Game.TcpClient.create(800000, 100000, headsize, 200000, 5000, 5000); this.tcp.onConnect = delegate(this, this.onTcpConnect); this.tcp.onDisConnect = delegate(this, this.onTcpDisConnect); this.tcp.onReceived = delegate(this, this.onTcpRecv); } get Id(): number { return this.id; } get Status(): ConnectStatus { return this.status; } connect(host: string, port: number) { this.host = host; this.port = port; this.curTryTimes = 0; this.status = ConnectStatus.connecting; this.doConnect(); } close() { this.tcp.close(); this.status = ConnectStatus.closed; this.host = null; this.port = 0; } send(data: any, size: number) { this.tcp.send(data, size); } private doConnect() { this.curTryTimes++; this.tcp.close(); this.tcp.connect(this.host, this.port, 5000 * 4); // 20 seconds timeout uts.log(uts.format('向{0}:{1}发起连接(第{2}次)...', this.host, this.port, this.curTryTimes)); } private onTcpConnect(isSuccess: boolean, reason: number) { if (null == this.host) { return; } if (isSuccess) { uts.log(uts.format('tcp connect success: {0}:{1}', this.host, this.port)); this.status = ConnectStatus.connected; if (null != this.onConnect) { this.onConnect(this.id, isSuccess, reason); } } else { uts.log(uts.format('tcp connect failed: {0}:{1}, reason is {2}', this.host, this.port, reason)); if (reason != 0 && Game.TcpClient.getError != null) { uts.logWarning(Game.TcpClient.getError()); } if (this.curTryTimes < this.totalTryTimes) { // 继续重试 this.doConnect(); } else { // 超过重试次数 this.status = ConnectStatus.error; if (null != this.onConnect) { this.onConnect(this.id, isSuccess, reason); } } } } private onTcpDisConnect(reason: number) { if (null == this.host) { return; } this.tcp.close(); uts.log(uts.format('tcp disconnected: {0}:{1}, reason is {2}', this.host, this.port, reason)); if (reason != 0 && Game.TcpClient.getError != null) { uts.logWarning(Game.TcpClient.getError()); } this.status = ConnectStatus.disconnected; if (null != this.onDisConnect) { this.onDisConnect(this.id, reason); } } private onTcpRecv(data: any, size: number) { if (null == this.host) { return; } if (null != this.onDisConnect) { this.onReceived(this.id, data, size); } } private get versionCode(): number { let vers = UnityEngine.Application.version.split('.'); if (vers.length < 4) return 100000; return Number(vers[3]); } } export class NetHandler { /**心跳包网络延迟,单位秒。*/ private netDelay = 0; /**心跳包发送时间记录数组。*/ private sendTimeStatArray: number[] = []; private static listeners = {}; private static readonly totalTryTimes: number = 3; private sockets: Socket[] = []; private workSocket: Socket; private ips: string; private hostList: Array<string> = []; private port = 0; private netId: EnumNetId; public head: Protocol.MsgHead = null; /**在收到login response之前锁住消息*/ private isMsgBlocked = true; public onConnectCallback: (isSuccess: boolean) => void; public onDisconnectCallback: () => void; public onExceptionCallback: () => void; get NetDelay(): number { return this.netDelay; } get NetId(): EnumNetId { return this.netId; } connect(ips: string, port: number, netId: EnumNetId) { this.netId = netId; // 同一个socket连接,不能list两次role,所以每次都要断开重连 this.close(); // 多个url用|分开 this.ips = ips; this.hostList = ips.split("|"); //先暂时定为一个 this.port = port; let hostCount: number = this.hostList.length; // 创建ping let curSocketCnt: number = this.sockets.length; for (let i = 0; i < hostCount - curSocketCnt; i++) { let socket = new Socket(curSocketCnt + i); socket.onConnect = delegate(this, this.onConnect); socket.onDisConnect = delegate(this, this.onDisConnect); socket.onReceived = delegate(this, this.onRecv); this.sockets.push(socket); } this.doConnect(); } reConnect() { uts.logWarning('reconnect...'); //不要删除定位crash用 this.close(); this.doConnect(); } doConnect() { this.workSocket = null; // 如果有多个host,则采用ping测试各连接选择最快者 let hostCount: number = this.hostList.length; for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; socket.connect(this.hostList[i], this.port); } } close() { // 关闭连接 this.workSocket = null; let hostCount: number = this.hostList.length; for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; socket.close(); } } send(obj: Protocol.FyMsg) { if (null == this.workSocket) { return; } let msgId: number = obj.m_stMsgHead.m_uiMsgID; let packlen = G.Dr.pack(obj); if (packlen < 0) { uts.bugReport('pack error! err:' + packlen + ', msgid:' + msgId + ', errmsg:' + G.Dr.error()); return; } this.workSocket.send(G.Dr.packBuf(), packlen); // 记录发送时间 if (Macros.MsgID_SyncTime_Request == msgId) { // 将延迟设置为0 this.sendTimeStatArray.push(UnityEngine.Time.realtimeSinceStartup); } } private onConnect(id: number, isSuccess: boolean, reason: number) { if (null != this.workSocket) { return; } this.sendTimeStatArray.length = 0; let hostCount: number = this.hostList.length; if (isSuccess) { for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; if (socket.Id == id) { this.workSocket = socket; } else { socket.close(); } } uts.assert(null != this.workSocket); // 连上socket后即阻塞其它消息 this.isMsgBlocked = true; this.onConnectCallback(true); } else { let errorCnt = 0; for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; if (socket.Status == ConnectStatus.error) { errorCnt++; } } if (errorCnt == hostCount) { this.onConnectCallback(false); } } } private onDisConnect(id: number, reason: number) { if (null != this.workSocket && this.workSocket.Id == id) {
this.onDisconnectCallback(); } } } private onRecv(id: number, data: any, size: number, busy: boolean) { if (null != this.workSocket && this.workSocket.Id == id) { let msgid = G.Dr.msgid(data, size); if (msgid < 0) { uts.bugReport('get msgid error! err:' + msgid + ", datasize:" + size); return; } if (busy && Macros.MsgID_CastSkill_Notify == msgid) { // 繁忙丢掉技能notify return; } if (Macros.MsgID_LoginServer_Response == msgid) { this.isMsgBlocked = false; } if (this.isMsgBlocked && Macros.MsgID_Account_ListRole_Response != msgid && Macros.MsgID_Account_CreateRole_Response != msgid) { uts.log(uts.format('Ignore message received before login response, msgid={0}', msgid)); return; } let obj: Protocol.FyMsg = G.Dr.getRecvObject(msgid) as Protocol.FyMsg; let rt = G.Dr.unpack(data, size, obj); if (rt < 0) { uts.bugReport('unpack error! err:' + rt + ', msgid:' + msgid + ", datasize:" + size); return; } this.head = obj.m_stMsgHead; // 计算延迟 if (Macros.MsgID_SyncTime_Response == msgid) { let sendTime = this.sendTimeStatArray.shift(); if (sendTime > 0) { this.netDelay = Math.round((UnityEngine.Time.realtimeSinceStartup - sendTime) * 1000); if (this.netDelay > 999) { this.sendTimeStatArray.length = 0; } } } Profiler.push('msgid:' + msgid); this.dispatchData(msgid, obj.m_msgBody); Profiler.pop(); } } static addListener(msgid: number, deleg) { let list = NetHandler.listeners[msgid]; if (list == null) { list = []; NetHandler.listeners[msgid] = list; } list.push(deleg); } static removeListener(msgid: number, deleg) { let list = NetHandler.listeners[msgid]; if (list == null) return; let pos = list.indexOf(deleg); if (pos < 0) return; list.splice(pos, 1); } dispatchData(msgid: number, body) { let list = NetHandler.listeners[msgid]; if (list == null) return; for (let i = 0, n = list.length; i < n; i++) { list[i](body); } } }
if (null != this.onDisconnectCallback) {
random_line_split
NetHandler.ts
import { Global as G } from "System/global"; import { Macros } from 'System/protocol/Macros' import { Profiler } from "System/utils/Profiler" export enum EnumNetId { base = 1, cross, } enum ConnectStatus { none = 0, // 空闲 connecting = 1, // 正在连接 connected = 2, // 已连接 closed = 3, // 已关闭 error = 4, // 连接错误 disconnected = 5, // 连接断开 } class Socket { onConnect: (id: number, result: boolean, reason: number) => void; onDisConnect: (id: number, reason: number) => void; onReceived: (id: number, data: any, size: number) => void; totalTryTimes: number = 3; private curTryTimes: number = 0; private tcp: Game.TcpClient = null; private host: string; private port: number = 0; private status: ConnectStatus; private id = 0; constructor(id: number) { this.id = id; Game.TcpClient.setHandleTimesInFrame(30); let headsize = 2; if (this.versionCode > 1080) { headsize = 28; } this.tcp = Game.TcpClient.create(800000, 100000, headsize, 200000, 5000, 5000); this.tcp.onConnect = delegate(this, this.onTcpConnect); this.tcp.onDisConnect = delegate(this, this.onTcpDisConnect); this.tcp.onReceived = delegate(this, this.onTcpRecv); } get Id(): number { return this.id; } get Status(): ConnectStatus { return this.status; } connect(host: string, port: number) { this.host = host; this.port = port; this.curTryTimes = 0; this.status = ConnectStatus.connecting; this.doConnect(); } close() { this.tcp.close(); this.status = ConnectStatus.closed; this.host = null; this.port = 0; } send(data: any, size: number) { this.tcp.send(data, size); } private doConnect() { this.curTryTimes++; this.tcp.close(); this.tcp.connect(this.host, this.port, 5000 * 4); // 20 seconds timeout uts.log(uts.format('向{0}:{1}发起连接(第{2}次)...', this.host, this.port, this.curTryTimes)); } private onTcpConnect(isSuccess: boolean, reason: number) { if (null == this.host) { return; } if (isSuccess) { uts.log(uts.format('tcp connect success: {0}:{1}', this.host, this.port)); this.status = ConnectStatus.connected; if (null != this.onConnect) { this.onConnect(this.id, isSuccess, reason); } } else { uts.log(uts.format('tcp connect failed: {0}:{1}, reason is {2}', this.host, this.port, reason)); if (reason != 0 && Game.TcpClient.getError != null) { uts.logWarning(Game.TcpClient.getError()); } if (this.curTryTimes < this.totalTryTimes) { // 继续重试 this.doConnect(); } else { // 超过重试次数 this.status = ConnectStatus.error; if (null != this.onConnect) { this.onConnect(this.id, isSuccess, reason); } } } } private onTcpDisConnect(reason: number) { if (null == this.host) { return; } this.tcp.close(); uts.log(uts.format('tcp disconnected: {0}:{1}, reason is {2}', this.host, this.port, reason)); if (reason != 0 && Game.TcpClient.getError != null) { uts.logWarning(Game.TcpClient.getError()); } this.status = ConnectStatus.disconnected; if (null != this.onDisConnect) { this.onDisConnect(this.id, reason); } } private onTcpRecv(data: any, size: number) { if (null == this.host) { return; } if (null != this.onDisConnect) { this.onReceived(this.id, data, size); } } private get versionCode(): number { let vers = UnityEngine.Application.version.split('.'); if (vers.length < 4) return 100000; return Number(vers[3]); } } export class NetHandler { /**心跳包网络延迟,单位秒。*/ private netDelay = 0; /**心跳包发送时间记录数组。*/ private sendTimeStatArray: number[] = []; private static listeners = {}; private static readonly totalTryTimes: number = 3; private sockets: Socket[] = []; private workSocket: Socket; private ips: string; private hostList: Array<string> = []; private port = 0; private netId: EnumNetId; public head: Protocol.MsgHead = null; /**在收到login response之前锁住消息*/ private isMsgBlocked = true; public onConnectCallback: (isSuccess: boolean) => void; public onDisconnectCallback: () => void; public onExceptionCallback: () => void; get NetDelay(): number { return this.netDelay; } get NetId(): EnumNetId { return this.netId; } connect(ips: string, port: number, netId: EnumNetId) { this.netId = netId; // 同一个socket连接,不能list两次role,所以每次都要断开重连 this.close(); // 多个url用|分开 this.ips = ips; this.hostList = ips.split("|"); //先暂时定为一个 this.port = port; let hostCount: number = this.hostList.length; // 创建ping let curSocketCnt: number = this.sockets.length; for (let i = 0; i < hostCount - curSocketCnt; i++) { let socket = new Socket(curSocketCnt + i); socket.onConnect = delegate(this, this.onConnect); socket.onDisConnect = delegate(this, this.onDisConnect); socket.onReceived = delegate(this, this.onRecv); this.sockets.push(socket); } this.doConnect(); } reConnect() { uts.logWarning('reconnect...'); //不要删除定位crash用 this.close(); this.doConnect(); } doConnect() { this.workSocket = null; // 如果有多个host,则采用ping测试各连接选择最快者 let hostCount: number = this.hostList.length; for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; socket.connect(this.hostList[i], this.port); } } close() { // 关闭连接 this.workSocket = null; let hostCount: number = this.hostList.length; for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; socket.close(); } } send(obj: Protocol.FyMsg) { if (null == this.workSocket) { return; } let msgId: number = obj.m_stMsgHead.m_uiMsgID; let packlen = G.Dr.pack(obj); if (packlen < 0) { uts.bugReport('pack error! err:' + packlen + ', msgid:' + msgId + ', errmsg:' + G.Dr.error()); retu
Socket.send(G.Dr.packBuf(), packlen); // 记录发送时间 if (Macros.MsgID_SyncTime_Request == msgId) { // 将延迟设置为0 this.sendTimeStatArray.push(UnityEngine.Time.realtimeSinceStartup); } } private onConnect(id: number, isSuccess: boolean, reason: number) { if (null != this.workSocket) { return; } this.sendTimeStatArray.length = 0; let hostCount: number = this.hostList.length; if (isSuccess) { for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; if (socket.Id == id) { this.workSocket = socket; } else { socket.close(); } } uts.assert(null != this.workSocket); // 连上socket后即阻塞其它消息 this.isMsgBlocked = true; this.onConnectCallback(true); } else { let errorCnt = 0; for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; if (socket.Status == ConnectStatus.error) { errorCnt++; } } if (errorCnt == hostCount) { this.onConnectCallback(false); } } } private onDisConnect(id: number, reason: number) { if (null != this.workSocket && this.workSocket.Id == id) { if (null != this.onDisconnectCallback) { this.onDisconnectCallback(); } } } private onRecv(id: number, data: any, size: number, busy: boolean) { if (null != this.workSocket && this.workSocket.Id == id) { let msgid = G.Dr.msgid(data, size); if (msgid < 0) { uts.bugReport('get msgid error! err:' + msgid + ", datasize:" + size); return; } if (busy && Macros.MsgID_CastSkill_Notify == msgid) { // 繁忙丢掉技能notify return; } if (Macros.MsgID_LoginServer_Response == msgid) { this.isMsgBlocked = false; } if (this.isMsgBlocked && Macros.MsgID_Account_ListRole_Response != msgid && Macros.MsgID_Account_CreateRole_Response != msgid) { uts.log(uts.format('Ignore message received before login response, msgid={0}', msgid)); return; } let obj: Protocol.FyMsg = G.Dr.getRecvObject(msgid) as Protocol.FyMsg; let rt = G.Dr.unpack(data, size, obj); if (rt < 0) { uts.bugReport('unpack error! err:' + rt + ', msgid:' + msgid + ", datasize:" + size); return; } this.head = obj.m_stMsgHead; // 计算延迟 if (Macros.MsgID_SyncTime_Response == msgid) { let sendTime = this.sendTimeStatArray.shift(); if (sendTime > 0) { this.netDelay = Math.round((UnityEngine.Time.realtimeSinceStartup - sendTime) * 1000); if (this.netDelay > 999) { this.sendTimeStatArray.length = 0; } } } Profiler.push('msgid:' + msgid); this.dispatchData(msgid, obj.m_msgBody); Profiler.pop(); } } static addListener(msgid: number, deleg) { let list = NetHandler.listeners[msgid]; if (list == null) { list = []; NetHandler.listeners[msgid] = list; } list.push(deleg); } static removeListener(msgid: number, deleg) { let list = NetHandler.listeners[msgid]; if (list == null) return; let pos = list.indexOf(deleg); if (pos < 0) return; list.splice(pos, 1); } dispatchData(msgid: number, body) { let list = NetHandler.listeners[msgid]; if (list == null) return; for (let i = 0, n = list.length; i < n; i++) { list[i](body); } } }
rn; } this.work
conditional_block
NetHandler.ts
import { Global as G } from "System/global"; import { Macros } from 'System/protocol/Macros' import { Profiler } from "System/utils/Profiler" export enum EnumNetId { base = 1, cross, } enum ConnectStatus { none = 0, // 空闲 connecting = 1, // 正在连接 connected = 2, // 已连接 closed = 3, // 已关闭 error = 4, // 连接错误 disconnected = 5, // 连接断开 } class Socket { onConnect: (id: number, result: boolean, reason: number) => void; onDisConnect: (id: number, reason: number) => void; onReceived: (id: number, data: any, size: number) => void; totalTryTimes: number = 3; private curTryTimes: number = 0; private tcp: Game.TcpClient = null; private host: string; private port: number = 0; private status: ConnectStatus; private id = 0; constructor(id: number) { this.id = id; Game.TcpClient.setHandleTimesInFrame(30); let headsize = 2; if (this.versionCode > 1080) { headsize = 28; } this.tcp = Game.TcpClient.create(800000, 100000, headsize, 200000, 5000, 5000); this.tcp.onConnect = delegate(this, this.onTcpConnect); this.tcp.onDisConnect = delegate(this, this.onTcpDisConnect); this.tcp.onReceived = delegate(this, this.onTcpRecv); } get Id(): number { return this.id; } get Status(): ConnectStatus { return this.status; } connect(host: string, port: number) { this.host = host; this.port = port; this.curTryTimes = 0; this.status = ConnectStatus.connecting; this.doConnect(); } close() { this.tcp.close();
s.status = ConnectStatus.closed; this.host = null; this.port = 0; } send(data: any, size: number) { this.tcp.send(data, size); } private doConnect() { this.curTryTimes++; this.tcp.close(); this.tcp.connect(this.host, this.port, 5000 * 4); // 20 seconds timeout uts.log(uts.format('向{0}:{1}发起连接(第{2}次)...', this.host, this.port, this.curTryTimes)); } private onTcpConnect(isSuccess: boolean, reason: number) { if (null == this.host) { return; } if (isSuccess) { uts.log(uts.format('tcp connect success: {0}:{1}', this.host, this.port)); this.status = ConnectStatus.connected; if (null != this.onConnect) { this.onConnect(this.id, isSuccess, reason); } } else { uts.log(uts.format('tcp connect failed: {0}:{1}, reason is {2}', this.host, this.port, reason)); if (reason != 0 && Game.TcpClient.getError != null) { uts.logWarning(Game.TcpClient.getError()); } if (this.curTryTimes < this.totalTryTimes) { // 继续重试 this.doConnect(); } else { // 超过重试次数 this.status = ConnectStatus.error; if (null != this.onConnect) { this.onConnect(this.id, isSuccess, reason); } } } } private onTcpDisConnect(reason: number) { if (null == this.host) { return; } this.tcp.close(); uts.log(uts.format('tcp disconnected: {0}:{1}, reason is {2}', this.host, this.port, reason)); if (reason != 0 && Game.TcpClient.getError != null) { uts.logWarning(Game.TcpClient.getError()); } this.status = ConnectStatus.disconnected; if (null != this.onDisConnect) { this.onDisConnect(this.id, reason); } } private onTcpRecv(data: any, size: number) { if (null == this.host) { return; } if (null != this.onDisConnect) { this.onReceived(this.id, data, size); } } private get versionCode(): number { let vers = UnityEngine.Application.version.split('.'); if (vers.length < 4) return 100000; return Number(vers[3]); } } export class NetHandler { /**心跳包网络延迟,单位秒。*/ private netDelay = 0; /**心跳包发送时间记录数组。*/ private sendTimeStatArray: number[] = []; private static listeners = {}; private static readonly totalTryTimes: number = 3; private sockets: Socket[] = []; private workSocket: Socket; private ips: string; private hostList: Array<string> = []; private port = 0; private netId: EnumNetId; public head: Protocol.MsgHead = null; /**在收到login response之前锁住消息*/ private isMsgBlocked = true; public onConnectCallback: (isSuccess: boolean) => void; public onDisconnectCallback: () => void; public onExceptionCallback: () => void; get NetDelay(): number { return this.netDelay; } get NetId(): EnumNetId { return this.netId; } connect(ips: string, port: number, netId: EnumNetId) { this.netId = netId; // 同一个socket连接,不能list两次role,所以每次都要断开重连 this.close(); // 多个url用|分开 this.ips = ips; this.hostList = ips.split("|"); //先暂时定为一个 this.port = port; let hostCount: number = this.hostList.length; // 创建ping let curSocketCnt: number = this.sockets.length; for (let i = 0; i < hostCount - curSocketCnt; i++) { let socket = new Socket(curSocketCnt + i); socket.onConnect = delegate(this, this.onConnect); socket.onDisConnect = delegate(this, this.onDisConnect); socket.onReceived = delegate(this, this.onRecv); this.sockets.push(socket); } this.doConnect(); } reConnect() { uts.logWarning('reconnect...'); //不要删除定位crash用 this.close(); this.doConnect(); } doConnect() { this.workSocket = null; // 如果有多个host,则采用ping测试各连接选择最快者 let hostCount: number = this.hostList.length; for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; socket.connect(this.hostList[i], this.port); } } close() { // 关闭连接 this.workSocket = null; let hostCount: number = this.hostList.length; for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; socket.close(); } } send(obj: Protocol.FyMsg) { if (null == this.workSocket) { return; } let msgId: number = obj.m_stMsgHead.m_uiMsgID; let packlen = G.Dr.pack(obj); if (packlen < 0) { uts.bugReport('pack error! err:' + packlen + ', msgid:' + msgId + ', errmsg:' + G.Dr.error()); return; } this.workSocket.send(G.Dr.packBuf(), packlen); // 记录发送时间 if (Macros.MsgID_SyncTime_Request == msgId) { // 将延迟设置为0 this.sendTimeStatArray.push(UnityEngine.Time.realtimeSinceStartup); } } private onConnect(id: number, isSuccess: boolean, reason: number) { if (null != this.workSocket) { return; } this.sendTimeStatArray.length = 0; let hostCount: number = this.hostList.length; if (isSuccess) { for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; if (socket.Id == id) { this.workSocket = socket; } else { socket.close(); } } uts.assert(null != this.workSocket); // 连上socket后即阻塞其它消息 this.isMsgBlocked = true; this.onConnectCallback(true); } else { let errorCnt = 0; for (let i = 0; i < hostCount; i++) { let socket = this.sockets[i]; if (socket.Status == ConnectStatus.error) { errorCnt++; } } if (errorCnt == hostCount) { this.onConnectCallback(false); } } } private onDisConnect(id: number, reason: number) { if (null != this.workSocket && this.workSocket.Id == id) { if (null != this.onDisconnectCallback) { this.onDisconnectCallback(); } } } private onRecv(id: number, data: any, size: number, busy: boolean) { if (null != this.workSocket && this.workSocket.Id == id) { let msgid = G.Dr.msgid(data, size); if (msgid < 0) { uts.bugReport('get msgid error! err:' + msgid + ", datasize:" + size); return; } if (busy && Macros.MsgID_CastSkill_Notify == msgid) { // 繁忙丢掉技能notify return; } if (Macros.MsgID_LoginServer_Response == msgid) { this.isMsgBlocked = false; } if (this.isMsgBlocked && Macros.MsgID_Account_ListRole_Response != msgid && Macros.MsgID_Account_CreateRole_Response != msgid) { uts.log(uts.format('Ignore message received before login response, msgid={0}', msgid)); return; } let obj: Protocol.FyMsg = G.Dr.getRecvObject(msgid) as Protocol.FyMsg; let rt = G.Dr.unpack(data, size, obj); if (rt < 0) { uts.bugReport('unpack error! err:' + rt + ', msgid:' + msgid + ", datasize:" + size); return; } this.head = obj.m_stMsgHead; // 计算延迟 if (Macros.MsgID_SyncTime_Response == msgid) { let sendTime = this.sendTimeStatArray.shift(); if (sendTime > 0) { this.netDelay = Math.round((UnityEngine.Time.realtimeSinceStartup - sendTime) * 1000); if (this.netDelay > 999) { this.sendTimeStatArray.length = 0; } } } Profiler.push('msgid:' + msgid); this.dispatchData(msgid, obj.m_msgBody); Profiler.pop(); } } static addListener(msgid: number, deleg) { let list = NetHandler.listeners[msgid]; if (list == null) { list = []; NetHandler.listeners[msgid] = list; } list.push(deleg); } static removeListener(msgid: number, deleg) { let list = NetHandler.listeners[msgid]; if (list == null) return; let pos = list.indexOf(deleg); if (pos < 0) return; list.splice(pos, 1); } dispatchData(msgid: number, body) { let list = NetHandler.listeners[msgid]; if (list == null) return; for (let i = 0, n = list.length; i < n; i++) { list[i](body); } } }
thi
identifier_name
zsy_3pandas.py
from pandas import Series, DataFrame import pandas as pd import numpy as np import matplotlib.pyplot as plt # 带有索引的numpy1 # obj = Series([4, 7, -5, 3]) # print(obj) # print(obj.values) # print(obj.index) # 2 # obj2 = Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c']) # print(obj2) # print(obj2.index) # print(obj2['a']) # obj2['d'] = 6 # print(obj2.values) # print(obj2[obj2 > 0]) # print(obj2 * 2) # print(np.exp(obj2)) # print('b' in obj2) # print('e' in obj2) # 3 # sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000} # obj3 = Series(sdata) # # print(obj3) # states = ['Califorina', 'Ohio', 'Oregon', 'Texas'] # obj4 = Series(sdata, index=states) # print(obj4) # print(pd.isnull(obj4)) # print(pd.notnull(obj4)) # print(obj4.isnull()) # print(obj3+obj4) # obj4.name = 'population' # obj4.index.name = 'state' # # print(obj4) # obj.index = ['bob', 'steve', 'jeff', 'ryan'] # print(obj) # 4 data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], 'year': [2000, 2001, 2002, 2001, 2002], 'pop': [1.5, 1.7, 3.6, 2.4, 2.9]} frame = DataFrame(data) # print(frame) # print(DataFrame(data, columns=['year', 'state', 'pop'])) frame2 = DataFrame(data, columns=['year', 'state', 'pop', 'debt'], index=['one', 'two', 'three', 'four', 'five']) # print(frame2) # print(frame2.columns) # print(frame2['state']) # print(frame2.year) # print(frame2.ix['three']) # frame2['debt'] = 16.5 # print(frame2) # frame2['debt'] = np.arange(5.) # print(frame2) val = Series([-1.2, -1.5, -1.7], index=['two', 'four', 'five']) frame2['debt'] = val # print(frame2) frame2['eastern'] = frame2.state == 'Ohio' # print(frame2) # del frame2['eastern'] # print(frame2.columns) pop = {'Nevada': {2001: 2.4, 2002: 2.9}, 'Ohio': {2000: 1.5, 2001: 1.7, 2002: 3.6}} frame3 = DataFrame(pop) # print(frame3) # print(frame3.T) # print(DataFrame(pop, index=[2001, 2002, 2003])) pdata = {'Ohio': frame3['Ohio'][:-1], 'Nevada': frame3['Nevada'][:2]} # print(DataFrame(pdata)) frame3.index.name = 'year'; frame3.columns.name = 'state' # print(frame3) # print(frame3.values) # print(frame2.values) # 5 obj = Series(range(3), index=['a', 'b', 'c']) index = obj.index # print(index) # print(index[1:]) # print(frame3) # print('Ohio' in frame3.columns) # print(2002 in frame3.index) # 6 obj = Series([4.5, 7.2, -5.3, 3.6], index=['d', 'b', 'a', 'c']) # print(obj) obj2 = obj.reindex(['a', 'b', 'c', 'd', 'e']) # print(obj2) obj3 = obj.reindex(['a', 'b', 'c', 'd', 'e'], fill_value=0) # print(obj3) obj4 = Series(['blue', 'purple', 'yellow'], index=[0, 2, 4]) # print(obj4.reindex(range(6), method='ffill')) frame = DataFrame(np.arange(9).reshape((3, 3)), index=['a', 'c', 'd'], columns=['Ohio', 'Texas', 'California']) # print(frame) frame2 =frame.reindex(['a', 'b', 'c', 'd']) # print(frame2) states = ['California', 'Texas', 'Utah'] # print(frame.reindex(columns=states)) # print(frame.reindex(index=['a', 'b', 'c', 'd'], method='ffill')) # print(frame.ix[['a', 'b', 'c', 'd']]) # 7 obj = Series(np.arange(5.), index=['a', 'b', 'c', 'd', 'e']) new_obj = obj.drop('c') # print(obj) # print(new_obj) # print(obj.drop(['d', 'c'])) data = DataFrame(np.arange(16).reshape((4, 4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four']) # print(data) # print(data.drop(['Colorado', 'Ohio'])) # print(data.drop('two', axis=1)) # print(data.drop(['two', 'four'], axis=1)) # 8 obj = Series(np.arange(4.), index=['a', 'b', 'c', 'd']) # print(obj) # print(obj['b']) # print(obj[1]) # print(obj[2:4]) # print(obj[['b', 'a', 'd']]) # print(obj[[1, 3]]) # print(obj[obj < 2]) # print(obj['b':'c']) obj['b':'c'] = 5 # print(obj) # 9 data = DataFrame(np.arange(16).reshape((4, 4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four']) # print(data) # print(data['two']) # print(data[['three', 'one']]) # print(data[:2]) # print(data[data['three'] > 5]) # print(data < 5) # data[data < 5] = 0 # print(data) # print(data.ix['Colorado', ['two', 'three']]) # print(data.ix[['Colorado', 'Utah'], [3, 0, 1]]) # print(data.ix[2]) # print(data.ix[:'Utah', 'two']) # print(data.ix[data.three > 5, :3]) # 10 s1 = Series([7.3, -2.5, 3.4, 1.5], index=['a', 'c', 'd', 'e']) s2 = Series([-2.1, 3.6, -1.5, 4, 3.1], index=['a', 'c', 'e', 'f', 'g']) # print(s1) # print(s2) # print(s1+s2) df1 = DataFrame(np.arange(9.).reshape((3, 3)), columns=list('bcd'), index=['ohio', 'texas', 'colorado']) df2 = DataFrame(np.arange(12.).reshape((4, 3)), columns=list('bde'), index=['utah', 'ohio', 'texas', 'oregon']) # print(df1) # print(df2) # print(df1+df2) df1 = DataFrame(np.arange(12.).reshape((3, 4)), columns=list('abcd')) df2 = DataFrame(np.arange(20.).reshape((4, 5)), columns=list('abcde')) # print(df1) # print(df2) # print(df1+df2) # print(df1.add(df2, fill_value=0)) # print(df1.reindex(columns=df2.columns, fill_value=0)) # 11 arr = np.arange(12.).reshape((3, 4)) # print(arr) # print(arr[0]) # print(arr-arr[0]) frame = DataFrame(np.arange(12.).reshape((4, 3)), columns=list('bde'), index=['utah', 'ohio', 'texas', 'oregon']) series = frame.ix[0] # print(frame) # print(series) # print(frame-series) series2 = Series(range(3), index=['b', 'e', 'f']) # print(series2) # print(frame+series2) series3 = frame['d'] # print(series3) # print(frame.sub(series3, axis=0)) # 12 frame = DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['utah', 'ohio', 'texas', 'oregon']) # print(frame) # print(np.abs(frame)) # f = lambda x: x.max() - x.min() # print(frame.apply(f)) # print(frame.apply(f, axis=1)) def f(x):
eturn Series([x.min(), x.max()], index=['min', 'max']) # print(frame.apply(f)) format = lambda x: '%.2f' % x # print(frame.applymap(format)) # print(frame['e'].map(format)) # 13 obj = Series(range(4), index=['d', 'a', 'b', 'c']) # print(obj) # print(obj.sort_index()) frame = DataFrame(np.arange(8).reshape((2, 4)), index=['three', 'one'], columns=['d', 'a', 'b', 'c']) # print(frame) # print(frame.sort_index()) # print(frame.sort_index(axis=1)) # print(frame.sort_index(axis=1, ascending=False)) obj = Series([4, np.nan, 7, np.nan, -3, 2]) # print(obj.sort_values()) frame = DataFrame({'b': [4, 7, -3, 2], 'a': [0, 1, 0, 1]}) # print(frame) # print(frame.sort_index(by='b')) # print(frame.sort_index(by=['a', 'b'])) # 14排名 obj = Series([7, -5, 7, 4, 2, 0, 4]) # print(obj) # print(obj.rank()) # print(obj.rank(method='first')) # print(obj.rank(ascending=False, method='max')) frame = DataFrame({'b': [4.3, 7, -3, 2], 'a': [0, 1, 0, 1], 'c': [-2, 5, 8, -2.5]}) # print(frame) # print(frame.rank(axis=1)) # 15带有重复值的轴索引 obj = Series(range(5), index=['a', 'a', 'b', 'b', 'c']) # print(obj) # print(obj.index.is_unique) # print(obj['a']) # print(obj['b']) # print(obj['c']) df = DataFrame(np.random.randn(4, 3), index=['a', 'a', 'b', 'b']) # print(df) # print(df.ix['b']) # 16汇总和计算描述统计(约简型) df = DataFrame([[1.4, np.nan], [7.1, -4.5], [np.nan, np.nan], [0.75, -1.3]], index=['a', 'b', 'c', 'd'], columns=['one', 'two']) # print(df) # print(df.sum()) # print(df.sum(axis=1)) # print(df.mean(axis=1, skipna=False)) # print(df.idxmax()) # print(df.idxmin()) # print(df.cumsum()) # print(df.describe()) obj = Series(['a', 'a', 'b', 'c'] * 4) # print(obj) # print(obj.describe()) # 17 obj = Series(['c', 'a', 'd', 'a', 'a', 'b', 'b', 'c', 'c']) uniques = obj.unique() # print(uniques) # print(obj.value_counts()) # print(pd.value_counts(obj.values, sort=False)) mask = obj.isin(['b', 'c']) # print(mask) # print(obj[mask]) data = DataFrame({'Qu1': [1, 3, 4, 3, 4], 'Qu2': [2, 3, 1, 2, 3], 'Qu3': [1, 5, 2, 4, 4]}) # print(data) # result = data.apply(pd.value_counts).fillna(0) # print(result) # 18处理缺失数据 string_data = Series(['aardvark', 'artichoke', np.nan, 'avocado']) # print(string_data) # print(string_data.isnull()) string_data[0] = None # print(string_data) # print(string_data.isnull()) # 19 过滤缺失数据 from numpy import nan as NA data = Series([1, NA, 3.5, NA, 7]) # print(data) # print(data.dropna()) # print(data[data.notnull()]) data = DataFrame([[1., 6.5, 3.], [1., NA, NA], [NA, NA, NA], [NA, 6.5, 3.]]) cleaned = data.dropna() # print(data) # print(cleaned) # print(data.dropna(how='all')) data[4] = NA # print(data) # print(data.dropna(axis=1, how='all')) df = DataFrame(np.random.randn(7, 3)) # print(df) df.ix[:4, 1] = NA df.ix[:2, 2] = NA # print(df) # print(df.dropna(thresh=1)) # print(df.dropna(thresh=2)) # print(df.dropna(thresh=3)) # 20 填充缺失数据 # print(df.fillna(0)) # print(df.fillna({1: 0.5, 2: -1})) # 总是返回被填充对象的引用 # _ = df.fillna(0, inplace=True) # print(df) df = DataFrame(np.random.randn(6, 3)) df.ix[:2, 1] = NA df.ix[:4, 2] = NA # print(df) data = Series([1., NA, 3.5, NA, 7]) # print(data.fillna(data.mean())) # 21 层次化索引 data = Series(np.random.randn(10), index=[['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd'], [1, 2, 3, 1, 2, 3, 1, 2, 2, 3]]) # print(data) # print(data.index) # print(data['b']) # print(data['b':'c']) # print(data.ix[['b', 'd']]) # print(data[:, 2]) # print(data.unstack()) # print(data.unstack().stack()) frame = DataFrame(np.arange(12).reshape((4, 3)), index=[['a', 'a', 'b', 'b'], [1, 2, 1, 2]], columns=[['ohio', 'ohio', 'colorrado'], ['green', 'red', 'green']]) # print(frame) frame.index.names = ['key1', 'key2'] frame.columns.names = ['state', 'color'] # print(frame) # print(frame['ohio']) # print(frame.swaplevel('key1', 'key2')) # print(frame.sort_index(level=1)) # print(frame.swaplevel(0, 1).sort_index(level=1)) # print(frame.sum(level='key2')) # print(frame.sum(level='color', axis=1)) # 22 frame = DataFrame({'a': range(7), 'b': range(7, 0, -1), 'c': ['one', 'one', 'one', 'two', 'two', 'two', 'two'], 'd': [0, 1, 2, 0, 1, 2, 3]}) # print(frame) frame2 = frame.set_index(['c', 'd']) # print(frame2) # print(frame.set_index(['c', 'd'], drop=False)) # print(frame2.reset_index()) # 23整数索引 ser3 = Series(range(3), index=[-5, 1, 3]) frame = DataFrame(np.arange(6).reshape(3, 2), index=[2, 0, 1]) print(frame) # 23面板数据
r
identifier_name
zsy_3pandas.py
from pandas import Series, DataFrame import pandas as pd import numpy as np import matplotlib.pyplot as plt # 带有索引的numpy1 # obj = Series([4, 7, -5, 3]) # print(obj) # print(obj.values) # print(obj.index) # 2 # obj2 = Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c']) # print(obj2) # print(obj2.index) # print(obj2['a']) # obj2['d'] = 6 # print(obj2.values) # print(obj2[obj2 > 0]) # print(obj2 * 2) # print(np.exp(obj2)) # print('b' in obj2) # print('e' in obj2) # 3 # sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000} # obj3 = Series(sdata) # # print(obj3) # states = ['Califorina', 'Ohio', 'Oregon', 'Texas'] # obj4 = Series(sdata, index=states) # print(obj4) # print(pd.isnull(obj4)) # print(pd.notnull(obj4)) # print(obj4.isnull()) # print(obj3+obj4) # obj4.name = 'population' # obj4.index.name = 'state' # # print(obj4) # obj.index = ['bob', 'steve', 'jeff', 'ryan'] # print(obj) # 4 data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], 'year': [2000, 2001, 2002, 2001, 2002], 'pop': [1.5, 1.7, 3.6, 2.4, 2.9]} frame = DataFrame(data) # print(frame) # print(DataFrame(data, columns=['year', 'state', 'pop'])) frame2 = DataFrame(data, columns=['year', 'state', 'pop', 'debt'], index=['one', 'two', 'three', 'four', 'five']) # print(frame2) # print(frame2.columns) # print(frame2['state']) # print(frame2.year) # print(frame2.ix['three']) # frame2['debt'] = 16.5 # print(frame2) # frame2['debt'] = np.arange(5.) # print(frame2) val = Series([-1.2, -1.5, -1.7], index=['two', 'four', 'five']) frame2['debt'] = val # print(frame2) frame2['eastern'] = frame2.state == 'Ohio' # print(frame2) # del frame2['eastern'] # print(frame2.columns) pop = {'Nevada': {2001: 2.4, 2002: 2.9}, 'Ohio': {2000: 1.5, 2001: 1.7, 2002: 3.6}} frame3 = DataFrame(pop) # print(frame3) # print(frame3.T) # print(DataFrame(pop, index=[2001, 2002, 2003])) pdata = {'Ohio': frame3['Ohio'][:-1], 'Nevada': frame3['Nevada'][:2]} # print(DataFrame(pdata)) frame3.index.name = 'year'; frame3.columns.name = 'state' # print(frame3) # print(frame3.values) # print(frame2.values) # 5 obj = Series(range(3), index=['a', 'b', 'c']) index = obj.index # print(index) # print(index[1:]) # print(frame3) # print('Ohio' in frame3.columns) # print(2002 in frame3.index) # 6 obj = Series([4.5, 7.2, -5.3, 3.6], index=['d', 'b', 'a', 'c']) # print(obj) obj2 = obj.reindex(['a', 'b', 'c', 'd', 'e']) # print(obj2) obj3 = obj.reindex(['a', 'b', 'c', 'd', 'e'], fill_value=0) # print(obj3) obj4 = Series(['blue', 'purple', 'yellow'], index=[0, 2, 4]) # print(obj4.reindex(range(6), method='ffill')) frame = DataFrame(np.arange(9).reshape((3, 3)), index=['a', 'c', 'd'], columns=['Ohio', 'Texas', 'California']) # print(frame) frame2 =frame.reindex(['a', 'b', 'c', 'd']) # print(frame2) states = ['California', 'Texas', 'Utah'] # print(frame.reindex(columns=states)) # print(frame.reindex(index=['a', 'b', 'c', 'd'], method='ffill')) # print(frame.ix[['a', 'b', 'c', 'd']]) # 7 obj = Series(np.arange(5.), index=['a', 'b', 'c', 'd', 'e']) new_obj = obj.drop('c') # print(obj) # print(new_obj) # print(obj.drop(['d', 'c'])) data = DataFrame(np.arange(16).reshape((4, 4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four']) # print(data) # print(data.drop(['Colorado', 'Ohio'])) # print(data.drop('two', axis=1)) # print(data.drop(['two', 'four'], axis=1)) # 8 obj = Series(np.arange(4.), index=['a', 'b', 'c', 'd']) # print(obj) # print(obj['b']) # print(obj[1]) # print(obj[2:4]) # print(obj[['b', 'a', 'd']]) # print(obj[[1, 3]]) # print(obj[obj < 2]) # print(obj['b':'c']) obj['b':'c'] = 5 # print(obj) # 9 data = DataFrame(np.arange(16).reshape((4, 4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four']) # print(data) # print(data['two']) # print(data[['three', 'one']]) # print(data[:2]) # print(data[data['three'] > 5]) # print(data < 5) # data[data < 5] = 0 # print(data) # print(data.ix['Colorado', ['two', 'three']]) # print(data.ix[['Colorado', 'Utah'], [3, 0, 1]]) # print(data.ix[2]) # print(data.ix[:'Utah', 'two']) # print(data.ix[data.three > 5, :3]) # 10 s1 = Series([7.3, -2.5, 3.4, 1.5], index=['a', 'c', 'd', 'e']) s2 = Series([-2.1, 3.6, -1.5, 4, 3.1], index=['a', 'c', 'e', 'f', 'g']) # print(s1) # print(s2) # print(s1+s2) df1 = DataFrame(np.arange(9.).reshape((3, 3)), columns=list('bcd'), index=['ohio', 'texas', 'colorado']) df2 = DataFrame(np.arange(12.).reshape((4, 3)), columns=list('bde'), index=['utah', 'ohio', 'texas', 'oregon']) # print(df1) # print(df2) # print(df1+df2) df1 = DataFrame(np.arange(12.).reshape((3, 4)), columns=list('abcd')) df2 = DataFrame(np.arange(20.).reshape((4, 5)), columns=list('abcde')) # print(df1) # print(df2) # print(df1+df2) # print(df1.add(df2, fill_value=0)) # print(df1.reindex(columns=df2.columns, fill_value=0)) # 11 arr = np.arange(12.).reshape((3, 4)) # print(arr) # print(arr[0]) # print(arr-arr[0]) frame = DataFrame(np.arange(12.).reshape((4, 3)), columns=list('bde'), index=['utah', 'ohio', 'texas', 'oregon']) series = frame.ix[0] # print(frame) # print(series) # print(frame-series) series2 = Series(range(3), index=['b', 'e', 'f']) # print(series2) # print(frame+series2) series3 = frame['d'] # print(series3) # print(frame.sub(series3, axis=0)) # 12 frame = DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['utah', 'ohio', 'texas', 'oregon']) # print(frame) # print(np.abs(frame)) # f = lambda x: x.max() - x.min() # print(frame.apply(f)) # print(frame.apply(f, axis=1)) def f(x): return Ser
rame.apply(f)) format = lambda x: '%.2f' % x # print(frame.applymap(format)) # print(frame['e'].map(format)) # 13 obj = Series(range(4), index=['d', 'a', 'b', 'c']) # print(obj) # print(obj.sort_index()) frame = DataFrame(np.arange(8).reshape((2, 4)), index=['three', 'one'], columns=['d', 'a', 'b', 'c']) # print(frame) # print(frame.sort_index()) # print(frame.sort_index(axis=1)) # print(frame.sort_index(axis=1, ascending=False)) obj = Series([4, np.nan, 7, np.nan, -3, 2]) # print(obj.sort_values()) frame = DataFrame({'b': [4, 7, -3, 2], 'a': [0, 1, 0, 1]}) # print(frame) # print(frame.sort_index(by='b')) # print(frame.sort_index(by=['a', 'b'])) # 14排名 obj = Series([7, -5, 7, 4, 2, 0, 4]) # print(obj) # print(obj.rank()) # print(obj.rank(method='first')) # print(obj.rank(ascending=False, method='max')) frame = DataFrame({'b': [4.3, 7, -3, 2], 'a': [0, 1, 0, 1], 'c': [-2, 5, 8, -2.5]}) # print(frame) # print(frame.rank(axis=1)) # 15带有重复值的轴索引 obj = Series(range(5), index=['a', 'a', 'b', 'b', 'c']) # print(obj) # print(obj.index.is_unique) # print(obj['a']) # print(obj['b']) # print(obj['c']) df = DataFrame(np.random.randn(4, 3), index=['a', 'a', 'b', 'b']) # print(df) # print(df.ix['b']) # 16汇总和计算描述统计(约简型) df = DataFrame([[1.4, np.nan], [7.1, -4.5], [np.nan, np.nan], [0.75, -1.3]], index=['a', 'b', 'c', 'd'], columns=['one', 'two']) # print(df) # print(df.sum()) # print(df.sum(axis=1)) # print(df.mean(axis=1, skipna=False)) # print(df.idxmax()) # print(df.idxmin()) # print(df.cumsum()) # print(df.describe()) obj = Series(['a', 'a', 'b', 'c'] * 4) # print(obj) # print(obj.describe()) # 17 obj = Series(['c', 'a', 'd', 'a', 'a', 'b', 'b', 'c', 'c']) uniques = obj.unique() # print(uniques) # print(obj.value_counts()) # print(pd.value_counts(obj.values, sort=False)) mask = obj.isin(['b', 'c']) # print(mask) # print(obj[mask]) data = DataFrame({'Qu1': [1, 3, 4, 3, 4], 'Qu2': [2, 3, 1, 2, 3], 'Qu3': [1, 5, 2, 4, 4]}) # print(data) # result = data.apply(pd.value_counts).fillna(0) # print(result) # 18处理缺失数据 string_data = Series(['aardvark', 'artichoke', np.nan, 'avocado']) # print(string_data) # print(string_data.isnull()) string_data[0] = None # print(string_data) # print(string_data.isnull()) # 19 过滤缺失数据 from numpy import nan as NA data = Series([1, NA, 3.5, NA, 7]) # print(data) # print(data.dropna()) # print(data[data.notnull()]) data = DataFrame([[1., 6.5, 3.], [1., NA, NA], [NA, NA, NA], [NA, 6.5, 3.]]) cleaned = data.dropna() # print(data) # print(cleaned) # print(data.dropna(how='all')) data[4] = NA # print(data) # print(data.dropna(axis=1, how='all')) df = DataFrame(np.random.randn(7, 3)) # print(df) df.ix[:4, 1] = NA df.ix[:2, 2] = NA # print(df) # print(df.dropna(thresh=1)) # print(df.dropna(thresh=2)) # print(df.dropna(thresh=3)) # 20 填充缺失数据 # print(df.fillna(0)) # print(df.fillna({1: 0.5, 2: -1})) # 总是返回被填充对象的引用 # _ = df.fillna(0, inplace=True) # print(df) df = DataFrame(np.random.randn(6, 3)) df.ix[:2, 1] = NA df.ix[:4, 2] = NA # print(df) data = Series([1., NA, 3.5, NA, 7]) # print(data.fillna(data.mean())) # 21 层次化索引 data = Series(np.random.randn(10), index=[['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd'], [1, 2, 3, 1, 2, 3, 1, 2, 2, 3]]) # print(data) # print(data.index) # print(data['b']) # print(data['b':'c']) # print(data.ix[['b', 'd']]) # print(data[:, 2]) # print(data.unstack()) # print(data.unstack().stack()) frame = DataFrame(np.arange(12).reshape((4, 3)), index=[['a', 'a', 'b', 'b'], [1, 2, 1, 2]], columns=[['ohio', 'ohio', 'colorrado'], ['green', 'red', 'green']]) # print(frame) frame.index.names = ['key1', 'key2'] frame.columns.names = ['state', 'color'] # print(frame) # print(frame['ohio']) # print(frame.swaplevel('key1', 'key2')) # print(frame.sort_index(level=1)) # print(frame.swaplevel(0, 1).sort_index(level=1)) # print(frame.sum(level='key2')) # print(frame.sum(level='color', axis=1)) # 22 frame = DataFrame({'a': range(7), 'b': range(7, 0, -1), 'c': ['one', 'one', 'one', 'two', 'two', 'two', 'two'], 'd': [0, 1, 2, 0, 1, 2, 3]}) # print(frame) frame2 = frame.set_index(['c', 'd']) # print(frame2) # print(frame.set_index(['c', 'd'], drop=False)) # print(frame2.reset_index()) # 23整数索引 ser3 = Series(range(3), index=[-5, 1, 3]) frame = DataFrame(np.arange(6).reshape(3, 2), index=[2, 0, 1]) print(frame) # 23面板数据
ies([x.min(), x.max()], index=['min', 'max']) # print(f
identifier_body
zsy_3pandas.py
from pandas import Series, DataFrame import pandas as pd import numpy as np import matplotlib.pyplot as plt # 带有索引的numpy1 # obj = Series([4, 7, -5, 3]) # print(obj) # print(obj.values) # print(obj.index) # 2 # obj2 = Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c']) # print(obj2) # print(obj2.index) # print(obj2['a']) # obj2['d'] = 6 # print(obj2.values) # print(obj2[obj2 > 0]) # print(obj2 * 2) # print(np.exp(obj2)) # print('b' in obj2) # print('e' in obj2) # 3 # sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000} # obj3 = Series(sdata) # # print(obj3) # states = ['Califorina', 'Ohio', 'Oregon', 'Texas'] # obj4 = Series(sdata, index=states) # print(obj4) # print(pd.isnull(obj4)) # print(pd.notnull(obj4)) # print(obj4.isnull()) # print(obj3+obj4) # obj4.name = 'population' # obj4.index.name = 'state' # # print(obj4) # obj.index = ['bob', 'steve', 'jeff', 'ryan'] # print(obj) # 4 data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], 'year': [2000, 2001, 2002, 2001, 2002], 'pop': [1.5, 1.7, 3.6, 2.4, 2.9]} frame = DataFrame(data) # print(frame) # print(DataFrame(data, columns=['year', 'state', 'pop'])) frame2 = DataFrame(data, columns=['year', 'state', 'pop', 'debt'], index=['one', 'two', 'three', 'four', 'five']) # print(frame2) # print(frame2.columns) # print(frame2['state']) # print(frame2.year) # print(frame2.ix['three']) # frame2['debt'] = 16.5 # print(frame2) # frame2['debt'] = np.arange(5.) # print(frame2) val = Series([-1.2, -1.5, -1.7], index=['two', 'four', 'five']) frame2['debt'] = val # print(frame2) frame2['eastern'] = frame2.state == 'Ohio' # print(frame2) # del frame2['eastern'] # print(frame2.columns) pop = {'Nevada': {2001: 2.4, 2002: 2.9}, 'Ohio': {2000: 1.5, 2001: 1.7, 2002: 3.6}} frame3 = DataFrame(pop) # print(frame3) # print(frame3.T) # print(DataFrame(pop, index=[2001, 2002, 2003])) pdata = {'Ohio': frame3['Ohio'][:-1], 'Nevada': frame3['Nevada'][:2]} # print(DataFrame(pdata)) frame3.index.name = 'year'; frame3.columns.name = 'state' # print(frame3) # print(frame3.values) # print(frame2.values) # 5 obj = Series(range(3), index=['a', 'b', 'c']) index = obj.index # print(index) # print(index[1:]) # print(frame3) # print('Ohio' in frame3.columns) # print(2002 in frame3.index) # 6 obj = Series([4.5, 7.2, -5.3, 3.6], index=['d', 'b', 'a', 'c']) # print(obj) obj2 = obj.reindex(['a', 'b', 'c', 'd', 'e']) # print(obj2) obj3 = obj.reindex(['a', 'b', 'c', 'd', 'e'], fill_value=0) # print(obj3) obj4 = Series(['blue', 'purple', 'yellow'], index=[0, 2, 4]) # print(obj4.reindex(range(6), method='ffill')) frame = DataFrame(np.arange(9).reshape((3, 3)), index=['a', 'c', 'd'], columns=['Ohio', 'Texas', 'California']) # print(frame) frame2 =frame.reindex(['a', 'b', 'c', 'd']) # print(frame2) states = ['California', 'Texas', 'Utah'] # print(frame.reindex(columns=states)) # print(frame.reindex(index=['a', 'b', 'c', 'd'], method='ffill')) # print(frame.ix[['a', 'b', 'c', 'd']]) # 7 obj = Series(np.arange(5.), index=['a', 'b', 'c', 'd', 'e']) new_obj = obj.drop('c') # print(obj) # print(new_obj) # print(obj.drop(['d', 'c'])) data = DataFrame(np.arange(16).reshape((4, 4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four']) # print(data) # print(data.drop(['Colorado', 'Ohio'])) # print(data.drop('two', axis=1)) # print(data.drop(['two', 'four'], axis=1)) # 8 obj = Series(np.arange(4.), index=['a', 'b', 'c', 'd']) # print(obj) # print(obj['b']) # print(obj[1]) # print(obj[2:4]) # print(obj[['b', 'a', 'd']]) # print(obj[[1, 3]]) # print(obj[obj < 2]) # print(obj['b':'c']) obj['b':'c'] = 5 # print(obj) # 9 data = DataFrame(np.arange(16).reshape((4, 4)), index=['Ohio', 'Colorado', 'Utah', 'New York'], columns=['one', 'two', 'three', 'four']) # print(data) # print(data['two']) # print(data[['three', 'one']]) # print(data[:2]) # print(data[data['three'] > 5]) # print(data < 5) # data[data < 5] = 0 # print(data) # print(data.ix['Colorado', ['two', 'three']]) # print(data.ix[['Colorado', 'Utah'], [3, 0, 1]]) # print(data.ix[2]) # print(data.ix[:'Utah', 'two']) # print(data.ix[data.three > 5, :3]) # 10 s1 = Series([7.3, -2.5, 3.4, 1.5], index=['a', 'c', 'd', 'e']) s2 = Series([-2.1, 3.6, -1.5, 4, 3.1], index=['a', 'c', 'e', 'f', 'g']) # print(s1) # print(s2) # print(s1+s2) df1 = DataFrame(np.arange(9.).reshape((3, 3)), columns=list('bcd'), index=['ohio', 'texas', 'colorado']) df2 = DataFrame(np.arange(12.).reshape((4, 3)), columns=list('bde'), index=['utah', 'ohio', 'texas', 'oregon']) # print(df1) # print(df2) # print(df1+df2) df1 = DataFrame(np.arange(12.).reshape((3, 4)), columns=list('abcd')) df2 = DataFrame(np.arange(20.).reshape((4, 5)), columns=list('abcde')) # print(df1) # print(df2) # print(df1+df2) # print(df1.add(df2, fill_value=0)) # print(df1.reindex(columns=df2.columns, fill_value=0)) # 11 arr = np.arange(12.).reshape((3, 4)) # print(arr) # print(arr[0]) # print(arr-arr[0]) frame = DataFrame(np.arange(12.).reshape((4, 3)), columns=list('bde'), index=['utah', 'ohio', 'texas', 'oregon']) series = frame.ix[0] # print(frame) # print(series) # print(frame-series) series2 = Series(range(3), index=['b', 'e', 'f']) # print(series2) # print(frame+series2) series3 = frame['d'] # print(series3) # print(frame.sub(series3, axis=0)) # 12 frame = DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['utah', 'ohio', 'texas', 'oregon']) # print(frame) # print(np.abs(frame)) # f = lambda x: x.max() - x.min() # print(frame.apply(f)) # print(frame.apply(f, axis=1)) def f(x): return Series([x.min(), x.max()], index=['min', 'max']) # print(frame.apply(f)) format = lambda x: '%.2f' % x # print(frame.applymap(format)) # print(frame['e'].map(format)) # 13 obj = Series(range(4), index=['d', 'a', 'b', 'c']) # print(obj) # print(obj.sort_index()) frame = DataFrame(np.arange(8).reshape((2, 4)), index=['three', 'one'], columns=['d', 'a', 'b', 'c']) # print(frame) # print(frame.sort_index()) # print(frame.sort_index(axis=1)) # print(frame.sort_index(axis=1, ascending=False)) obj = Series([4, np.nan, 7, np.nan, -3, 2]) # print(obj.sort_values()) frame = DataFrame({'b': [4, 7, -3, 2], 'a': [0, 1, 0, 1]}) # print(frame) # print(frame.sort_index(by='b')) # print(frame.sort_index(by=['a', 'b'])) # 14排名 obj = Series([7, -5, 7, 4, 2, 0, 4]) # print(obj) # print(obj.rank()) # print(obj.rank(method='first')) # print(obj.rank(ascending=False, method='max')) frame = DataFrame({'b': [4.3, 7, -3, 2], 'a': [0, 1, 0, 1], 'c': [-2, 5, 8, -2.5]}) # print(frame) # print(frame.rank(axis=1)) # 15带有重复值的轴索引 obj = Series(range(5), index=['a', 'a', 'b', 'b', 'c']) # print(obj) # print(obj.index.is_unique) # print(obj['a']) # print(obj['b']) # print(obj['c']) df = DataFrame(np.random.randn(4, 3), index=['a', 'a', 'b', 'b']) # print(df) # print(df.ix['b']) # 16汇总和计算描述统计(约简型) df = DataFrame([[1.4, np.nan], [7.1, -4.5], [np.nan, np.nan], [0.75, -1.3]], index=['a', 'b', 'c', 'd'], columns=['one', 'two']) # print(df) # print(df.sum()) # print(df.sum(axis=1)) # print(df.mean(axis=1, skipna=False)) # print(df.idxmax()) # print(df.idxmin()) # print(df.cumsum()) # print(df.describe()) obj = Series(['a', 'a', 'b', 'c'] * 4) # print(obj) # print(obj.describe()) # 17 obj = Series(['c', 'a', 'd', 'a', 'a', 'b', 'b', 'c', 'c']) uniques = obj.unique() # print(uniques) # print(obj.value_counts()) # print(pd.value_counts(obj.values, sort=False)) mask = obj.isin(['b', 'c']) # print(mask) # print(obj[mask]) data = DataFrame({'Qu1': [1, 3, 4, 3, 4], 'Qu2': [2, 3, 1, 2, 3], 'Qu3': [1, 5, 2, 4, 4]}) # print(data) # result = data.apply(pd.value_counts).fillna(0) # print(result) # 18处理缺失数据 string_data = Series(['aardvark', 'artichoke', np.nan, 'avocado']) # print(string_data) # print(string_data.isnull()) string_data[0] = None # print(string_data) # print(string_data.isnull()) # 19 过滤缺失数据 from numpy import nan as NA data = Series([1, NA, 3.5, NA, 7]) # print(data) # print(data.dropna()) # print(data[data.notnull()]) data = DataFrame([[1., 6.5, 3.], [1., NA, NA], [NA, NA, NA], [NA, 6.5, 3.]]) cleaned = data.dropna() # print(data) # print(cleaned) # print(data.dropna(how='all')) data[4] = NA # print(data) # print(data.dropna(axis=1, how='all')) df = DataFrame(np.random.randn(7, 3)) # print(df) df.ix[:4, 1] = NA df.ix[:2, 2] = NA # print(df) # print(df.dropna(thresh=1)) # print(df.dropna(thresh=2)) # print(df.dropna(thresh=3)) # 20 填充缺失数据 # print(df.fillna(0)) # print(df.fillna({1: 0.5, 2: -1})) # 总是返回被填充对象的引用 # _ = df.fillna(0, inplace=True) # print(df) df = DataFrame(np.random.randn(6, 3)) df.ix[:2, 1] = NA df.ix[:4, 2] = NA # print(df) data = Series([1., NA, 3.5, NA, 7]) # print(data.fillna(data.mean())) # 21 层次化索引 data = Series(np.random.randn(10), index=[['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd'], [1, 2, 3, 1, 2, 3, 1, 2, 2, 3]]) # print(data) # print(data.index) # print(data['b']) # print(data['b':'c']) # print(data.ix[['b', 'd']]) # print(data[:, 2]) # print(data.unstack()) # print(data.unstack().stack()) frame = DataFrame(np.arange(12).reshape((4, 3)), index=[['a', 'a', 'b', 'b'], [1, 2, 1, 2]], columns=[['ohio', 'ohio', 'colorrado'], ['green', 'red', 'green']]) # print(frame) frame.index.names = ['key1', 'key2'] frame.columns.names = ['state', 'color'] # print(frame) # print(frame['ohio']) # print(frame.swaplevel('key1', 'key2')) # print(frame.sort_index(level=1)) # print(frame.swaplevel(0, 1).sort_index(level=1)) # print(frame.sum(level='key2')) # print(frame.sum(level='color', axis=1))
# 22 frame = DataFrame({'a': range(7), 'b': range(7, 0, -1), 'c': ['one', 'one', 'one', 'two', 'two', 'two', 'two'], 'd': [0, 1, 2, 0, 1, 2, 3]}) # print(frame) frame2 = frame.set_index(['c', 'd']) # print(frame2) # print(frame.set_index(['c', 'd'], drop=False)) # print(frame2.reset_index()) # 23整数索引 ser3 = Series(range(3), index=[-5, 1, 3]) frame = DataFrame(np.arange(6).reshape(3, 2), index=[2, 0, 1]) print(frame) # 23面板数据
random_line_split
movement.py
#Libraries import time from adafruit_servokit import ServoKit import curses import adafruit_bno055 from adafruit_extended_bus import ExtendedI2C as I2C import busio import board import pynmea2 import serial from math import sin, cos, sqrt, atan2, radians, degrees import numpy as np import csv import inspect import pyrealsense2.pyrealsense2 as rs import cv2 #Constants PCAServo=16 #Total of 16 Channels MIN_PWM=1100 #Minimum PWM Signal Sent MAX_PWM=1900 #Max PWM Signal Sent #Parameters Brake = 70 #Stop Servos from Moving Max_Speed = 100 #Max Speed Servos can turn #Motor Channels LeftMotor = 2 RightMotor = 1 Blower = 0 #Motor Driver Objects pca = ServoKit(channels=16) stdscr = curses.initscr() #GPS Objects ser = serial.Serial(port = '/dev/ttyACM0', baudrate = 9600, timeout = 1.0) #er2 = serial.Serial(port = '/dev/ttyACM0', baudrate = 9600, timeout = 1.0) #IMU Objects i2c = busio.I2C(board.SCL_1, board.SDA_1) # Device is /dev/i2c-1 sensor = adafruit_bno055.BNO055_I2C(i2c) #Camera pipeline = rs.pipeline() config = rs.config() config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30) #function init def init(): print("initializing...\r\n") #Motor Initializiation for i in range(PCAServo): pca.servo[i].set_pulse_width_range(MIN_PWM, MAX_PWM) pca.servo[i].angle = Brake #function main def main(): auto() # print("What mode do you want to run?\r\n") # print("'auto' for autonomous movement or 'manual' for manual control\r\n") # print("in auto, the rover will move according to predefined path\r\n") # print("in manual, the rover will move according to your controls and will record the path\r\n") # input1 = input() # if input1 == "auto": # print("starting auto\r\n") # auto() # elif input1 == "manual": # print("starting manual\r\n") # Thread(target = manual).start() # Thread(target = gpswrite).start() # else: # print("did you enter the wrong command?\r\n") # print("try again\r\n") ######################NAVIGATION CODE##################################################################### #poll for current GPS Coordinates def gps(): while True: msg = ser.readline().decode('utf-8', 'ignore') if msg.startswith('$'): if "GGA" in msg: gpsCoord = pynmea2.parse(msg) current_lat = gpsCoord.latitude current_lon = gpsCoord.longitude return current_lat, current_lon #poll for current GPS Coordinates def gps2(): while True: msg = ser2.readline().decode('utf-8', 'ignore') if msg.startswith('$'): if "GGA" in msg: gpsCoord = pynmea2.parse(msg) current_lat = gpsCoord.latitude current_lon = gpsCoord.longitude return current_lat, current_lon #Store GPS data from RTK GPS (C099-F9P) def gpswrite(): filename = 'GPSData.csv' gpsData = open(filename, 'w') fieldnames = ['latitude','longitude'] gps = csv.DictWriter(gpsData, fieldnames=fieldnames, delimiter = ' ') gps.writeheader() while True: msg = ser.readline().decode('utf-8', 'ignore') #Exclude Non-GPS Related Values if msg.startswith('$'): #Acquire $GPGGA Data for Lat Lon Coord if "GGA" in msg: gpsCoord = pynmea2.parse(msg) latitude = gpsCoord.latitude longitude = gpsCoord.longitude #Frequency of Data Acquisition time.sleep(0.1) gps.writerow({'latitude' : latitude, 'longitude' : longitude}) #get GPS Data stored in GPSData.csv def gpsread(count): filename = 'GPSData.csv' #Create Empty Set to store GPS Data from .csv file lat = [] lon = [] with open(filename) as gps: gpsreader = csv.DictReader(gps, delimiter = ' ') for row in gpsreader: #Convert str into float latitude = float(row['latitude']) longitude = float(row['longitude']) #Put Data in .csv file into an array lat.append(latitude) lon.append(longitude) desired_lat = lat[count] desired_lon = lon[count] return desired_lat, desired_lon def csvlen(): filename = 'GPSData.csv' num_row = 0 with open(filename) as gps: gpsreader = csv.DictReader(gps) for row in gpsreader: num_row += 1 return num_row #determine bearing to know what angle the rover needs to turn to def navigate(current_lat, current_lon, desired_lat, desired_lon): #convert lat and lon angles to radians lat1 = radians(current_lat) lon1 = radians(current_lon) lat2 = radians(desired_lat) lon2 = radians(desired_lon) #get change in lat and lon values dlon = lon2 - lon1 dlat = lat2 - lat1 print("calculating bearing\r\n") #math for calculating bearing x = cos(lat2) * sin(dlon) y = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon) bearing = np.arctan2(x,y) bearing = np.degrees(bearing) return bearing #################################OBJECT AVOIDANCE CODE################################## #function camera depth def camera(): #start streaming # pipeline.start(config) pipeline.start(config) frames = pipeline.wait_for_frames() for frame in frames: if frame.is_depth_frame():
pipeline.stop() return ##############EXTEDNDED KALMAN FILTER CODE######################################### # A matrix # 3x3 matrix -> number of states x number of states matrix # Expresses how the state of the system [x,y,yaw] changes # from k-1 to k when no control command is executed. # Typically a robot on wheels only drives when the wheels are told to turn. # For this case, A is the identity matrix. # A is sometimes F in the literature. A_k_minus_1 = np.array([[1.0, 0, 0], [ 0,1.0, 0], [ 0, 0, 1.0]]) # Noise applied to the forward kinematics (calculation # of the estimated state at time k from the state # transition model of the mobile robot). This is a vector # with the number of elements equal to the number of states process_noise_v_k_minus_1 = np.array([0.01,0.01,0.003]) # State model noise covariance matrix Q_k # When Q is large, the Kalman Filter tracks large changes in # the sensor measurements more closely than for smaller Q. # Q is a square matrix that has the same number of rows as states. Q_k = np.array([[1.0, 0, 0], [ 0, 1.0, 0], [ 0, 0, 1.0]]) # Measurement matrix H_k # Used to convert the predicted state estimate at time k # into predicted sensor measurements at time k. # In this case, H will be the identity matrix since the # estimated state maps directly to state measurements from the # odometry data [x, y, yaw] # H has the same number of rows as sensor measurements # and same number of columns as states. H_k = np.array([[1.0, 0, 0], [ 0,1.0, 0], [ 0, 0, 1.0]]) # Sensor measurement noise covariance matrix R_k # Has the same number of rows and columns as sensor measurements. # If we are sure about the measurements, R will be near zero. R_k = np.array([[1.0, 0, 0], [ 0, 1.0, 0], [ 0, 0, 1.0]]) # Sensor noise. This is a vector with the # number of elements equal to the number of sensor measurements. sensor_noise_w_k = np.array([0.07,0.07,0.04]) def getB(yaw, deltak): """ Calculates and returns the B matrix 3x2 matix -> number of states x number of control inputs The control inputs are the forward speed and the rotation rate around the z axis from the x-axis in the counterclockwise direction. [v,yaw_rate] Expresses how the state of the system [x,y,yaw] changes from k-1 to k due to the control commands (i.e. control input). :param yaw: The yaw angle (rotation angle around the z axis) in rad :param deltak: The change in time from time step k-1 to k in sec """ B = np.array([ [np.cos(yaw)*deltak, 0], [np.sin(yaw)*deltak, 0], [0, deltak]]) return B def ekf(z_k_observation_vector, state_estimate_k_minus_1, control_vector_k_minus_1, P_k_minus_1, dk): """ Extended Kalman Filter. Fuses noisy sensor measurement to create an optimal estimate of the state of the robotic system. INPUT :param z_k_observation_vector The observation from the Odometry 3x1 NumPy Array [x,y,yaw] in the global reference frame in [meters,meters,radians]. :param state_estimate_k_minus_1 The state estimate at time k-1 3x1 NumPy Array [x,y,yaw] in the global reference frame in [meters,meters,radians]. :param control_vector_k_minus_1 The control vector applied at time k-1 3x1 NumPy Array [v,v,yaw rate] in the global reference frame in [meters per second,meters per second,radians per second]. :param P_k_minus_1 The state covariance matrix estimate at time k-1 3x3 NumPy Array :param dk Time interval in seconds OUTPUT :return state_estimate_k near-optimal state estimate at time k 3x1 NumPy Array ---> [meters,meters,radians] :return P_k state covariance_estimate for time k 3x3 NumPy Array """ ######################### Predict ############################# # Predict the state estimate at time k based on the state # estimate at time k-1 and the control input applied at time k-1. state_estimate_k = A_k_minus_1 @ (state_estimate_k_minus_1) + (getB(state_estimate_k_minus_1[2],dk)) @ (control_vector_k_minus_1) + (process_noise_v_k_minus_1) print(f'State Estimate Before EKF={state_estimate_k}\r\n') # Predict the state covariance estimate based on the previous # covariance and some noise P_k = A_k_minus_1 @ P_k_minus_1 @ A_k_minus_1.T + (Q_k) ################### Update (Correct) ########################## # Calculate the difference between the actual sensor measurements # at time k minus what the measurement model predicted # the sensor measurements would be for the current timestep k. measurement_residual_y_k = z_k_observation_vector - ( (H_k @ state_estimate_k) + ( sensor_noise_w_k)) print(f'Observation={z_k_observation_vector}\r\n') # Calculate the measurement residual covariance S_k = H_k @ P_k @ H_k.T + R_k # Calculate the near-optimal Kalman gain # We use pseudoinverse since some of the matrices might be # non-square or singular. K_k = P_k @ H_k.T @ np.linalg.pinv(S_k) # Calculate an updated state estimate for time k state_estimate_k = state_estimate_k + (K_k @ measurement_residual_y_k) # Update the state covariance estimate for time k P_k = P_k - (K_k @ H_k @ P_k) # Print the best (near-optimal) estimate of the current state of the robot print(f'State Estimate After EKF={state_estimate_k}\r\n') # Return the updated state and covariance estimates return state_estimate_k, P_k ############################################################################################ #function auto def auto(): print("starting autonomous movement.\r\n") #Count for Number of WPs assigned count = 0 #Timestep for IMU EKF k = 1 #compass bearing will be the offset for the rover to calculate the relative angle compass_bearing_arr = [] bearing_arr=[] z_k = [] num_row = csvlen() sensor.mode = adafruit_bno055.COMPASS_MODE time.sleep(5) #initialize compass bearing for offset for i in range(100): compass_bearing_arr.append(sensor.euler[0]) compass_bearing_std = np.std(compass_bearing_arr) #if compass standard deviation above 0.5 degrees reinitialize offset if compass_bearing_std > 0.5: print("bearing not accurate, reinitializing\r\n") auto() else: print("compass calibrated\r\n") compass_bearing = np.average(compass_bearing_arr) sensor.mode = adafruit_bno055.NDOF_MODE print("count: {}, num row: {}\r\n".format(str(count), str(num_row))) print("initializing\r\n") try: #keeps running if did not reach final location while count != num_row: print("moving autonmously \r\n") #Get initial lat and lon from GPS Coord current_lat, current_lon = gps() #Get relative angle from IMU current_bearing = sensor.euler[0] + compass_bearing #creates a list of sensor observations at successive time steps #each list within z_k is an observation vector yaw = radians(sensor.euler[0]) pitch = sensor.euler[1] roll = sensor.euler[2] bearing_arr = pitch, roll, yaw #bearing_arr = np.transpose(bearing_arr, axes=None) z_k.append(bearing_arr) # z_k = np.array([[4.721,0.143,0.006], # k=1 # [9.353,0.284,0.007], # k=2 # [14.773,0.422,0.009],# k=3 # [18.246,0.555,0.011], # k=4 # [22.609,0.715,0.012]])# k=5 #print('Sensor Observation', z_k, '\r\n') dk = 1 # The estimated state vector at time k-1 in the global reference frame. # [x_k_minus_1, y_k_minus_1, yaw_k_minus_1] # [meters, meters, radians] state_estimate_k_minus_1 = np.array([0.0,0.0,0.0]) # The control input vector at time k-1 in the global reference frame. # [v, yaw_rate] # [meters/second, radians/second] # In the literature, this is commonly u. # Because there is no angular velocity and the robot begins at the # origin with a 0 radians yaw angle, this robot is traveling along # the positive x-axis in the global reference frame. control_vector_k_minus_1 = np.array([4.5,0.0]) # State covariance matrix P_k_minus_1 # This matrix has the same number of rows (and columns) as the # number of states (i.e. 3x3 matrix). P is sometimes referred # to as Sigma in the literature. It represents an estimate of # the accuracy of the state estimate at time k made using the # state transition matrix. We start off with guessed values. P_k_minus_1 = np.array([[0.1, 0, 0], [ 0,0.1, 0], [ 0, 0, 0.1]]) # Run the Extended Kalman Filter and store the # near-optimal state and covariance estimates for k, z_k in enumerate(z_k, start = 1): print(f'Timestep k = {k}\r\n') optimal_state_estimate_k, covariance_estimate_k = ekf( z_k, # Most recent sensor measurement state_estimate_k_minus_1, # Our most recent estimate of the state control_vector_k_minus_1, # Our most recent control input P_k_minus_1, # Our most recent state covariance matrix dk) # Time interval current_bearing = degrees(optimal_state_estimate[2]) + compass_bearing print(current_bearing) break # Get ready for the next timestep by updating the variable values state_estimate_k_minus_1 = optimal_state_estimate_k P_k_minus_1 = covariance_estimate_k #get and calculate the bearing the rover should be heading desired_lat, desired_lon = gpsread(count) desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) #Check for Objects in the way camera() if current_bearing < 0: current_bearing = 360 + current_bearing if current_bearing > 360: current_bearing = current_bearing - 360 #Due to the calculation for the desired bearing, we need to ensure that the values align with the current #bearing to allow for accurate results if desired_bearing < 0: desired_bearing = 360 + desired_bearing #calculate the shortest angle to turn left or right left_close = current_bearing - desired_bearing right_close = desired_bearing - current_bearing if left_close < 0: left_close = left_close + 360 if right_close < 0: right_close = right_close + 360 print("current bearing: {}, desired bearing: {}\r\n".format(str(current_bearing), str(desired_bearing))) #Need to ensure that the rover does not read past the last point of the data to ensure no indexing errors if count >= num_row: count = num_row break #only move forward if bearing is reached to allow the rover to reach the desired point. if abs(desired_bearing - current_bearing) <= 2: forward() # time.sleep(0.3) current_bearing = sensor.euler[0] #only increment to the next waypoint if waypoint is reached. if abs(desired_lat - current_lat) < 0.000001 and abs(desired_lon - current_lon) < 0.000001: print("wp reached\r\n") brake() current_lat, current_lon = gps() desired_lat, desired_lon = gpsread(count) desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) count += 1 elif right_close <= left_close: right() # time.sleep(0.3) current_bearing = sensor.euler[0] #allow the robot to reach closer to the desired bearing before determining whether bearing was truly #reached to account for fluctiations if abs(desired_bearing - current_bearing) <= 2: print("bearing reached \r\n") brake() current_lat, current_lon = gps() desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) elif left_close <= right_close: left() # time.sleep(0.3) current_bearing = sensor.euler[0] if abs(desired_bearing - current_bearing) <= 2: print("bearing reached\r\n") brake() current_lat, current_lon = gps() desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) elif abs(desired_lat - current_lat) < 0.000001 and abs(desired_lon - current_lon) < 0.000001: brake() current_lat, current_lon = gps() desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) except KeyboardInterrupt: hard_brake() print("exiting\r\n") #function Manual #Move Snobot with Keyboard only def Manual(): print("starting manual movement\n") print("press wasd to control the movement\n") try: while True: key = stdscr.getch() #Forward if key == ord('w'): forward() #Move Left elif key == ord('a'): left() #Move Right elif key == ord('d'): right() #Reverse elif key == ord('s'): reverse() else: brake() curses.endwin() #Stop all motors you stop program except KeyboardInterrupt: print("end\n") hard_brake() curses.endwin() def forward(): print("forward\r\n") pca.servo[LeftMotor].angle = 97 #forward above 80 reverse below 15 pca.servo[RightMotor].angle = 50 #forward below 50 reverse above 50 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def left(): print("left\r\n") pca.servo[LeftMotor].angle = 50 pca.servo[RightMotor].angle = 50 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def right(): print("right\r\n") pca.servo[LeftMotor].angle = 95 pca.servo[RightMotor].angle = 95 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def reverse(): print("reverse\r\n") pca.servo[LeftMotor].angle = 50 pca.servo[RightMotor].angle = 97 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def brake(): print("brake\r\n") pca.servo[LeftMotor].angle = Brake pca.servo[RightMotor].angle = Brake pca.servo[Blower].angle = 120 time.sleep(0.05) def hard_brake(): print("STOP\r\n") pca.servo[LeftMotor].angle = Brake pca.servo[RightMotor].angle = Brake pca.servo[Blower].angle = Brake if __name__ == '__main__': init() main()
depth = frames.get_depth_frame() for y in range(0,480,40): for x in range(0,600,40): dist = depth.get_distance(x,y) if y == 480: pipeline.stop() return if dist > 0.1 and dist < 1: if x > 200 and x < 400: #center of camera, what to do? hard_brake() print("object in the way...\r\n") pipeline.stop() camera() elif x < 200: #left of camera, what to do? print("object on left\r\n") right() time.sleep(0.3) hard_brake() pipeline.stop() camera() elif x > 400: #right of camera, what to do? print("object on right\r\n") left() time.sleep(0.3) hard_brake() pipeline.stop() camera()
conditional_block
movement.py
#Libraries import time from adafruit_servokit import ServoKit import curses import adafruit_bno055 from adafruit_extended_bus import ExtendedI2C as I2C import busio import board import pynmea2 import serial from math import sin, cos, sqrt, atan2, radians, degrees import numpy as np import csv import inspect import pyrealsense2.pyrealsense2 as rs import cv2 #Constants PCAServo=16 #Total of 16 Channels MIN_PWM=1100 #Minimum PWM Signal Sent MAX_PWM=1900 #Max PWM Signal Sent #Parameters Brake = 70 #Stop Servos from Moving Max_Speed = 100 #Max Speed Servos can turn #Motor Channels LeftMotor = 2 RightMotor = 1 Blower = 0 #Motor Driver Objects pca = ServoKit(channels=16) stdscr = curses.initscr() #GPS Objects ser = serial.Serial(port = '/dev/ttyACM0', baudrate = 9600, timeout = 1.0) #er2 = serial.Serial(port = '/dev/ttyACM0', baudrate = 9600, timeout = 1.0) #IMU Objects i2c = busio.I2C(board.SCL_1, board.SDA_1) # Device is /dev/i2c-1 sensor = adafruit_bno055.BNO055_I2C(i2c) #Camera pipeline = rs.pipeline() config = rs.config() config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30) #function init def init(): print("initializing...\r\n") #Motor Initializiation for i in range(PCAServo): pca.servo[i].set_pulse_width_range(MIN_PWM, MAX_PWM) pca.servo[i].angle = Brake #function main def main(): auto() # print("What mode do you want to run?\r\n") # print("'auto' for autonomous movement or 'manual' for manual control\r\n") # print("in auto, the rover will move according to predefined path\r\n") # print("in manual, the rover will move according to your controls and will record the path\r\n") # input1 = input() # if input1 == "auto": # print("starting auto\r\n") # auto() # elif input1 == "manual": # print("starting manual\r\n") # Thread(target = manual).start() # Thread(target = gpswrite).start() # else: # print("did you enter the wrong command?\r\n") # print("try again\r\n") ######################NAVIGATION CODE##################################################################### #poll for current GPS Coordinates def gps(): while True: msg = ser.readline().decode('utf-8', 'ignore') if msg.startswith('$'): if "GGA" in msg: gpsCoord = pynmea2.parse(msg) current_lat = gpsCoord.latitude current_lon = gpsCoord.longitude return current_lat, current_lon #poll for current GPS Coordinates def gps2(): while True: msg = ser2.readline().decode('utf-8', 'ignore') if msg.startswith('$'): if "GGA" in msg: gpsCoord = pynmea2.parse(msg) current_lat = gpsCoord.latitude current_lon = gpsCoord.longitude return current_lat, current_lon #Store GPS data from RTK GPS (C099-F9P) def gpswrite(): filename = 'GPSData.csv' gpsData = open(filename, 'w') fieldnames = ['latitude','longitude'] gps = csv.DictWriter(gpsData, fieldnames=fieldnames, delimiter = ' ') gps.writeheader() while True: msg = ser.readline().decode('utf-8', 'ignore') #Exclude Non-GPS Related Values if msg.startswith('$'): #Acquire $GPGGA Data for Lat Lon Coord if "GGA" in msg: gpsCoord = pynmea2.parse(msg) latitude = gpsCoord.latitude longitude = gpsCoord.longitude #Frequency of Data Acquisition time.sleep(0.1) gps.writerow({'latitude' : latitude, 'longitude' : longitude}) #get GPS Data stored in GPSData.csv def gpsread(count): filename = 'GPSData.csv' #Create Empty Set to store GPS Data from .csv file lat = [] lon = [] with open(filename) as gps: gpsreader = csv.DictReader(gps, delimiter = ' ') for row in gpsreader: #Convert str into float latitude = float(row['latitude']) longitude = float(row['longitude']) #Put Data in .csv file into an array lat.append(latitude) lon.append(longitude) desired_lat = lat[count] desired_lon = lon[count] return desired_lat, desired_lon def csvlen(): filename = 'GPSData.csv' num_row = 0 with open(filename) as gps: gpsreader = csv.DictReader(gps) for row in gpsreader: num_row += 1 return num_row #determine bearing to know what angle the rover needs to turn to def navigate(current_lat, current_lon, desired_lat, desired_lon): #convert lat and lon angles to radians lat1 = radians(current_lat) lon1 = radians(current_lon) lat2 = radians(desired_lat) lon2 = radians(desired_lon) #get change in lat and lon values dlon = lon2 - lon1 dlat = lat2 - lat1 print("calculating bearing\r\n") #math for calculating bearing x = cos(lat2) * sin(dlon) y = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon) bearing = np.arctan2(x,y) bearing = np.degrees(bearing) return bearing #################################OBJECT AVOIDANCE CODE################################## #function camera depth def camera(): #start streaming # pipeline.start(config) pipeline.start(config) frames = pipeline.wait_for_frames() for frame in frames: if frame.is_depth_frame(): depth = frames.get_depth_frame() for y in range(0,480,40): for x in range(0,600,40): dist = depth.get_distance(x,y) if y == 480: pipeline.stop() return if dist > 0.1 and dist < 1: if x > 200 and x < 400: #center of camera, what to do? hard_brake() print("object in the way...\r\n") pipeline.stop() camera() elif x < 200: #left of camera, what to do? print("object on left\r\n") right() time.sleep(0.3) hard_brake() pipeline.stop() camera() elif x > 400: #right of camera, what to do? print("object on right\r\n") left() time.sleep(0.3) hard_brake() pipeline.stop() camera() pipeline.stop() return ##############EXTEDNDED KALMAN FILTER CODE######################################### # A matrix # 3x3 matrix -> number of states x number of states matrix # Expresses how the state of the system [x,y,yaw] changes # from k-1 to k when no control command is executed. # Typically a robot on wheels only drives when the wheels are told to turn. # For this case, A is the identity matrix. # A is sometimes F in the literature. A_k_minus_1 = np.array([[1.0, 0, 0], [ 0,1.0, 0], [ 0, 0, 1.0]]) # Noise applied to the forward kinematics (calculation # of the estimated state at time k from the state # transition model of the mobile robot). This is a vector # with the number of elements equal to the number of states process_noise_v_k_minus_1 = np.array([0.01,0.01,0.003]) # State model noise covariance matrix Q_k # When Q is large, the Kalman Filter tracks large changes in # the sensor measurements more closely than for smaller Q. # Q is a square matrix that has the same number of rows as states. Q_k = np.array([[1.0, 0, 0], [ 0, 1.0, 0], [ 0, 0, 1.0]]) # Measurement matrix H_k # Used to convert the predicted state estimate at time k # into predicted sensor measurements at time k. # In this case, H will be the identity matrix since the # estimated state maps directly to state measurements from the # odometry data [x, y, yaw] # H has the same number of rows as sensor measurements # and same number of columns as states. H_k = np.array([[1.0, 0, 0], [ 0,1.0, 0], [ 0, 0, 1.0]]) # Sensor measurement noise covariance matrix R_k # Has the same number of rows and columns as sensor measurements. # If we are sure about the measurements, R will be near zero. R_k = np.array([[1.0, 0, 0], [ 0, 1.0, 0], [ 0, 0, 1.0]]) # Sensor noise. This is a vector with the # number of elements equal to the number of sensor measurements. sensor_noise_w_k = np.array([0.07,0.07,0.04]) def getB(yaw, deltak): """ Calculates and returns the B matrix 3x2 matix -> number of states x number of control inputs The control inputs are the forward speed and the rotation rate around the z axis from the x-axis in the counterclockwise direction. [v,yaw_rate] Expresses how the state of the system [x,y,yaw] changes from k-1 to k due to the control commands (i.e. control input). :param yaw: The yaw angle (rotation angle around the z axis) in rad :param deltak: The change in time from time step k-1 to k in sec """ B = np.array([ [np.cos(yaw)*deltak, 0], [np.sin(yaw)*deltak, 0], [0, deltak]]) return B def ekf(z_k_observation_vector, state_estimate_k_minus_1, control_vector_k_minus_1, P_k_minus_1, dk): """ Extended Kalman Filter. Fuses noisy sensor measurement to create an optimal estimate of the state of the robotic system. INPUT :param z_k_observation_vector The observation from the Odometry 3x1 NumPy Array [x,y,yaw] in the global reference frame in [meters,meters,radians]. :param state_estimate_k_minus_1 The state estimate at time k-1 3x1 NumPy Array [x,y,yaw] in the global reference frame in [meters,meters,radians]. :param control_vector_k_minus_1 The control vector applied at time k-1 3x1 NumPy Array [v,v,yaw rate] in the global reference frame in [meters per second,meters per second,radians per second]. :param P_k_minus_1 The state covariance matrix estimate at time k-1 3x3 NumPy Array :param dk Time interval in seconds OUTPUT :return state_estimate_k near-optimal state estimate at time k 3x1 NumPy Array ---> [meters,meters,radians] :return P_k state covariance_estimate for time k 3x3 NumPy Array """ ######################### Predict ############################# # Predict the state estimate at time k based on the state # estimate at time k-1 and the control input applied at time k-1. state_estimate_k = A_k_minus_1 @ (state_estimate_k_minus_1) + (getB(state_estimate_k_minus_1[2],dk)) @ (control_vector_k_minus_1) + (process_noise_v_k_minus_1) print(f'State Estimate Before EKF={state_estimate_k}\r\n') # Predict the state covariance estimate based on the previous # covariance and some noise P_k = A_k_minus_1 @ P_k_minus_1 @ A_k_minus_1.T + (Q_k) ################### Update (Correct) ########################## # Calculate the difference between the actual sensor measurements # at time k minus what the measurement model predicted # the sensor measurements would be for the current timestep k. measurement_residual_y_k = z_k_observation_vector - ( (H_k @ state_estimate_k) + ( sensor_noise_w_k)) print(f'Observation={z_k_observation_vector}\r\n') # Calculate the measurement residual covariance S_k = H_k @ P_k @ H_k.T + R_k # Calculate the near-optimal Kalman gain # We use pseudoinverse since some of the matrices might be # non-square or singular. K_k = P_k @ H_k.T @ np.linalg.pinv(S_k) # Calculate an updated state estimate for time k state_estimate_k = state_estimate_k + (K_k @ measurement_residual_y_k) # Update the state covariance estimate for time k P_k = P_k - (K_k @ H_k @ P_k) # Print the best (near-optimal) estimate of the current state of the robot print(f'State Estimate After EKF={state_estimate_k}\r\n') # Return the updated state and covariance estimates return state_estimate_k, P_k ############################################################################################ #function auto def auto(): print("starting autonomous movement.\r\n") #Count for Number of WPs assigned count = 0 #Timestep for IMU EKF k = 1 #compass bearing will be the offset for the rover to calculate the relative angle compass_bearing_arr = [] bearing_arr=[] z_k = [] num_row = csvlen() sensor.mode = adafruit_bno055.COMPASS_MODE time.sleep(5) #initialize compass bearing for offset for i in range(100): compass_bearing_arr.append(sensor.euler[0]) compass_bearing_std = np.std(compass_bearing_arr) #if compass standard deviation above 0.5 degrees reinitialize offset if compass_bearing_std > 0.5: print("bearing not accurate, reinitializing\r\n") auto() else: print("compass calibrated\r\n") compass_bearing = np.average(compass_bearing_arr) sensor.mode = adafruit_bno055.NDOF_MODE print("count: {}, num row: {}\r\n".format(str(count), str(num_row))) print("initializing\r\n") try: #keeps running if did not reach final location while count != num_row: print("moving autonmously \r\n") #Get initial lat and lon from GPS Coord current_lat, current_lon = gps() #Get relative angle from IMU current_bearing = sensor.euler[0] + compass_bearing #creates a list of sensor observations at successive time steps #each list within z_k is an observation vector yaw = radians(sensor.euler[0]) pitch = sensor.euler[1] roll = sensor.euler[2] bearing_arr = pitch, roll, yaw #bearing_arr = np.transpose(bearing_arr, axes=None) z_k.append(bearing_arr) # z_k = np.array([[4.721,0.143,0.006], # k=1 # [9.353,0.284,0.007], # k=2 # [14.773,0.422,0.009],# k=3 # [18.246,0.555,0.011], # k=4 # [22.609,0.715,0.012]])# k=5 #print('Sensor Observation', z_k, '\r\n') dk = 1 # The estimated state vector at time k-1 in the global reference frame. # [x_k_minus_1, y_k_minus_1, yaw_k_minus_1] # [meters, meters, radians] state_estimate_k_minus_1 = np.array([0.0,0.0,0.0]) # The control input vector at time k-1 in the global reference frame. # [v, yaw_rate] # [meters/second, radians/second] # In the literature, this is commonly u. # Because there is no angular velocity and the robot begins at the # origin with a 0 radians yaw angle, this robot is traveling along # the positive x-axis in the global reference frame. control_vector_k_minus_1 = np.array([4.5,0.0]) # State covariance matrix P_k_minus_1 # This matrix has the same number of rows (and columns) as the # number of states (i.e. 3x3 matrix). P is sometimes referred # to as Sigma in the literature. It represents an estimate of # the accuracy of the state estimate at time k made using the # state transition matrix. We start off with guessed values. P_k_minus_1 = np.array([[0.1, 0, 0], [ 0,0.1, 0], [ 0, 0, 0.1]]) # Run the Extended Kalman Filter and store the # near-optimal state and covariance estimates for k, z_k in enumerate(z_k, start = 1): print(f'Timestep k = {k}\r\n') optimal_state_estimate_k, covariance_estimate_k = ekf( z_k, # Most recent sensor measurement state_estimate_k_minus_1, # Our most recent estimate of the state control_vector_k_minus_1, # Our most recent control input P_k_minus_1, # Our most recent state covariance matrix dk) # Time interval current_bearing = degrees(optimal_state_estimate[2]) + compass_bearing print(current_bearing) break
# Get ready for the next timestep by updating the variable values state_estimate_k_minus_1 = optimal_state_estimate_k P_k_minus_1 = covariance_estimate_k #get and calculate the bearing the rover should be heading desired_lat, desired_lon = gpsread(count) desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) #Check for Objects in the way camera() if current_bearing < 0: current_bearing = 360 + current_bearing if current_bearing > 360: current_bearing = current_bearing - 360 #Due to the calculation for the desired bearing, we need to ensure that the values align with the current #bearing to allow for accurate results if desired_bearing < 0: desired_bearing = 360 + desired_bearing #calculate the shortest angle to turn left or right left_close = current_bearing - desired_bearing right_close = desired_bearing - current_bearing if left_close < 0: left_close = left_close + 360 if right_close < 0: right_close = right_close + 360 print("current bearing: {}, desired bearing: {}\r\n".format(str(current_bearing), str(desired_bearing))) #Need to ensure that the rover does not read past the last point of the data to ensure no indexing errors if count >= num_row: count = num_row break #only move forward if bearing is reached to allow the rover to reach the desired point. if abs(desired_bearing - current_bearing) <= 2: forward() # time.sleep(0.3) current_bearing = sensor.euler[0] #only increment to the next waypoint if waypoint is reached. if abs(desired_lat - current_lat) < 0.000001 and abs(desired_lon - current_lon) < 0.000001: print("wp reached\r\n") brake() current_lat, current_lon = gps() desired_lat, desired_lon = gpsread(count) desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) count += 1 elif right_close <= left_close: right() # time.sleep(0.3) current_bearing = sensor.euler[0] #allow the robot to reach closer to the desired bearing before determining whether bearing was truly #reached to account for fluctiations if abs(desired_bearing - current_bearing) <= 2: print("bearing reached \r\n") brake() current_lat, current_lon = gps() desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) elif left_close <= right_close: left() # time.sleep(0.3) current_bearing = sensor.euler[0] if abs(desired_bearing - current_bearing) <= 2: print("bearing reached\r\n") brake() current_lat, current_lon = gps() desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) elif abs(desired_lat - current_lat) < 0.000001 and abs(desired_lon - current_lon) < 0.000001: brake() current_lat, current_lon = gps() desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) except KeyboardInterrupt: hard_brake() print("exiting\r\n") #function Manual #Move Snobot with Keyboard only def Manual(): print("starting manual movement\n") print("press wasd to control the movement\n") try: while True: key = stdscr.getch() #Forward if key == ord('w'): forward() #Move Left elif key == ord('a'): left() #Move Right elif key == ord('d'): right() #Reverse elif key == ord('s'): reverse() else: brake() curses.endwin() #Stop all motors you stop program except KeyboardInterrupt: print("end\n") hard_brake() curses.endwin() def forward(): print("forward\r\n") pca.servo[LeftMotor].angle = 97 #forward above 80 reverse below 15 pca.servo[RightMotor].angle = 50 #forward below 50 reverse above 50 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def left(): print("left\r\n") pca.servo[LeftMotor].angle = 50 pca.servo[RightMotor].angle = 50 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def right(): print("right\r\n") pca.servo[LeftMotor].angle = 95 pca.servo[RightMotor].angle = 95 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def reverse(): print("reverse\r\n") pca.servo[LeftMotor].angle = 50 pca.servo[RightMotor].angle = 97 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def brake(): print("brake\r\n") pca.servo[LeftMotor].angle = Brake pca.servo[RightMotor].angle = Brake pca.servo[Blower].angle = 120 time.sleep(0.05) def hard_brake(): print("STOP\r\n") pca.servo[LeftMotor].angle = Brake pca.servo[RightMotor].angle = Brake pca.servo[Blower].angle = Brake if __name__ == '__main__': init() main()
random_line_split
movement.py
#Libraries import time from adafruit_servokit import ServoKit import curses import adafruit_bno055 from adafruit_extended_bus import ExtendedI2C as I2C import busio import board import pynmea2 import serial from math import sin, cos, sqrt, atan2, radians, degrees import numpy as np import csv import inspect import pyrealsense2.pyrealsense2 as rs import cv2 #Constants PCAServo=16 #Total of 16 Channels MIN_PWM=1100 #Minimum PWM Signal Sent MAX_PWM=1900 #Max PWM Signal Sent #Parameters Brake = 70 #Stop Servos from Moving Max_Speed = 100 #Max Speed Servos can turn #Motor Channels LeftMotor = 2 RightMotor = 1 Blower = 0 #Motor Driver Objects pca = ServoKit(channels=16) stdscr = curses.initscr() #GPS Objects ser = serial.Serial(port = '/dev/ttyACM0', baudrate = 9600, timeout = 1.0) #er2 = serial.Serial(port = '/dev/ttyACM0', baudrate = 9600, timeout = 1.0) #IMU Objects i2c = busio.I2C(board.SCL_1, board.SDA_1) # Device is /dev/i2c-1 sensor = adafruit_bno055.BNO055_I2C(i2c) #Camera pipeline = rs.pipeline() config = rs.config() config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30) #function init def init(): print("initializing...\r\n") #Motor Initializiation for i in range(PCAServo): pca.servo[i].set_pulse_width_range(MIN_PWM, MAX_PWM) pca.servo[i].angle = Brake #function main def main(): auto() # print("What mode do you want to run?\r\n") # print("'auto' for autonomous movement or 'manual' for manual control\r\n") # print("in auto, the rover will move according to predefined path\r\n") # print("in manual, the rover will move according to your controls and will record the path\r\n") # input1 = input() # if input1 == "auto": # print("starting auto\r\n") # auto() # elif input1 == "manual": # print("starting manual\r\n") # Thread(target = manual).start() # Thread(target = gpswrite).start() # else: # print("did you enter the wrong command?\r\n") # print("try again\r\n") ######################NAVIGATION CODE##################################################################### #poll for current GPS Coordinates def gps(): while True: msg = ser.readline().decode('utf-8', 'ignore') if msg.startswith('$'): if "GGA" in msg: gpsCoord = pynmea2.parse(msg) current_lat = gpsCoord.latitude current_lon = gpsCoord.longitude return current_lat, current_lon #poll for current GPS Coordinates def gps2(): while True: msg = ser2.readline().decode('utf-8', 'ignore') if msg.startswith('$'): if "GGA" in msg: gpsCoord = pynmea2.parse(msg) current_lat = gpsCoord.latitude current_lon = gpsCoord.longitude return current_lat, current_lon #Store GPS data from RTK GPS (C099-F9P) def gpswrite(): filename = 'GPSData.csv' gpsData = open(filename, 'w') fieldnames = ['latitude','longitude'] gps = csv.DictWriter(gpsData, fieldnames=fieldnames, delimiter = ' ') gps.writeheader() while True: msg = ser.readline().decode('utf-8', 'ignore') #Exclude Non-GPS Related Values if msg.startswith('$'): #Acquire $GPGGA Data for Lat Lon Coord if "GGA" in msg: gpsCoord = pynmea2.parse(msg) latitude = gpsCoord.latitude longitude = gpsCoord.longitude #Frequency of Data Acquisition time.sleep(0.1) gps.writerow({'latitude' : latitude, 'longitude' : longitude}) #get GPS Data stored in GPSData.csv def gpsread(count): filename = 'GPSData.csv' #Create Empty Set to store GPS Data from .csv file lat = [] lon = [] with open(filename) as gps: gpsreader = csv.DictReader(gps, delimiter = ' ') for row in gpsreader: #Convert str into float latitude = float(row['latitude']) longitude = float(row['longitude']) #Put Data in .csv file into an array lat.append(latitude) lon.append(longitude) desired_lat = lat[count] desired_lon = lon[count] return desired_lat, desired_lon def csvlen(): filename = 'GPSData.csv' num_row = 0 with open(filename) as gps: gpsreader = csv.DictReader(gps) for row in gpsreader: num_row += 1 return num_row #determine bearing to know what angle the rover needs to turn to def navigate(current_lat, current_lon, desired_lat, desired_lon): #convert lat and lon angles to radians lat1 = radians(current_lat) lon1 = radians(current_lon) lat2 = radians(desired_lat) lon2 = radians(desired_lon) #get change in lat and lon values dlon = lon2 - lon1 dlat = lat2 - lat1 print("calculating bearing\r\n") #math for calculating bearing x = cos(lat2) * sin(dlon) y = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon) bearing = np.arctan2(x,y) bearing = np.degrees(bearing) return bearing #################################OBJECT AVOIDANCE CODE################################## #function camera depth def camera(): #start streaming # pipeline.start(config) pipeline.start(config) frames = pipeline.wait_for_frames() for frame in frames: if frame.is_depth_frame(): depth = frames.get_depth_frame() for y in range(0,480,40): for x in range(0,600,40): dist = depth.get_distance(x,y) if y == 480: pipeline.stop() return if dist > 0.1 and dist < 1: if x > 200 and x < 400: #center of camera, what to do? hard_brake() print("object in the way...\r\n") pipeline.stop() camera() elif x < 200: #left of camera, what to do? print("object on left\r\n") right() time.sleep(0.3) hard_brake() pipeline.stop() camera() elif x > 400: #right of camera, what to do? print("object on right\r\n") left() time.sleep(0.3) hard_brake() pipeline.stop() camera() pipeline.stop() return ##############EXTEDNDED KALMAN FILTER CODE######################################### # A matrix # 3x3 matrix -> number of states x number of states matrix # Expresses how the state of the system [x,y,yaw] changes # from k-1 to k when no control command is executed. # Typically a robot on wheels only drives when the wheels are told to turn. # For this case, A is the identity matrix. # A is sometimes F in the literature. A_k_minus_1 = np.array([[1.0, 0, 0], [ 0,1.0, 0], [ 0, 0, 1.0]]) # Noise applied to the forward kinematics (calculation # of the estimated state at time k from the state # transition model of the mobile robot). This is a vector # with the number of elements equal to the number of states process_noise_v_k_minus_1 = np.array([0.01,0.01,0.003]) # State model noise covariance matrix Q_k # When Q is large, the Kalman Filter tracks large changes in # the sensor measurements more closely than for smaller Q. # Q is a square matrix that has the same number of rows as states. Q_k = np.array([[1.0, 0, 0], [ 0, 1.0, 0], [ 0, 0, 1.0]]) # Measurement matrix H_k # Used to convert the predicted state estimate at time k # into predicted sensor measurements at time k. # In this case, H will be the identity matrix since the # estimated state maps directly to state measurements from the # odometry data [x, y, yaw] # H has the same number of rows as sensor measurements # and same number of columns as states. H_k = np.array([[1.0, 0, 0], [ 0,1.0, 0], [ 0, 0, 1.0]]) # Sensor measurement noise covariance matrix R_k # Has the same number of rows and columns as sensor measurements. # If we are sure about the measurements, R will be near zero. R_k = np.array([[1.0, 0, 0], [ 0, 1.0, 0], [ 0, 0, 1.0]]) # Sensor noise. This is a vector with the # number of elements equal to the number of sensor measurements. sensor_noise_w_k = np.array([0.07,0.07,0.04]) def getB(yaw, deltak): """ Calculates and returns the B matrix 3x2 matix -> number of states x number of control inputs The control inputs are the forward speed and the rotation rate around the z axis from the x-axis in the counterclockwise direction. [v,yaw_rate] Expresses how the state of the system [x,y,yaw] changes from k-1 to k due to the control commands (i.e. control input). :param yaw: The yaw angle (rotation angle around the z axis) in rad :param deltak: The change in time from time step k-1 to k in sec """ B = np.array([ [np.cos(yaw)*deltak, 0], [np.sin(yaw)*deltak, 0], [0, deltak]]) return B def ekf(z_k_observation_vector, state_estimate_k_minus_1, control_vector_k_minus_1, P_k_minus_1, dk): """ Extended Kalman Filter. Fuses noisy sensor measurement to create an optimal estimate of the state of the robotic system. INPUT :param z_k_observation_vector The observation from the Odometry 3x1 NumPy Array [x,y,yaw] in the global reference frame in [meters,meters,radians]. :param state_estimate_k_minus_1 The state estimate at time k-1 3x1 NumPy Array [x,y,yaw] in the global reference frame in [meters,meters,radians]. :param control_vector_k_minus_1 The control vector applied at time k-1 3x1 NumPy Array [v,v,yaw rate] in the global reference frame in [meters per second,meters per second,radians per second]. :param P_k_minus_1 The state covariance matrix estimate at time k-1 3x3 NumPy Array :param dk Time interval in seconds OUTPUT :return state_estimate_k near-optimal state estimate at time k 3x1 NumPy Array ---> [meters,meters,radians] :return P_k state covariance_estimate for time k 3x3 NumPy Array """ ######################### Predict ############################# # Predict the state estimate at time k based on the state # estimate at time k-1 and the control input applied at time k-1. state_estimate_k = A_k_minus_1 @ (state_estimate_k_minus_1) + (getB(state_estimate_k_minus_1[2],dk)) @ (control_vector_k_minus_1) + (process_noise_v_k_minus_1) print(f'State Estimate Before EKF={state_estimate_k}\r\n') # Predict the state covariance estimate based on the previous # covariance and some noise P_k = A_k_minus_1 @ P_k_minus_1 @ A_k_minus_1.T + (Q_k) ################### Update (Correct) ########################## # Calculate the difference between the actual sensor measurements # at time k minus what the measurement model predicted # the sensor measurements would be for the current timestep k. measurement_residual_y_k = z_k_observation_vector - ( (H_k @ state_estimate_k) + ( sensor_noise_w_k)) print(f'Observation={z_k_observation_vector}\r\n') # Calculate the measurement residual covariance S_k = H_k @ P_k @ H_k.T + R_k # Calculate the near-optimal Kalman gain # We use pseudoinverse since some of the matrices might be # non-square or singular. K_k = P_k @ H_k.T @ np.linalg.pinv(S_k) # Calculate an updated state estimate for time k state_estimate_k = state_estimate_k + (K_k @ measurement_residual_y_k) # Update the state covariance estimate for time k P_k = P_k - (K_k @ H_k @ P_k) # Print the best (near-optimal) estimate of the current state of the robot print(f'State Estimate After EKF={state_estimate_k}\r\n') # Return the updated state and covariance estimates return state_estimate_k, P_k ############################################################################################ #function auto def auto(): print("starting autonomous movement.\r\n") #Count for Number of WPs assigned count = 0 #Timestep for IMU EKF k = 1 #compass bearing will be the offset for the rover to calculate the relative angle compass_bearing_arr = [] bearing_arr=[] z_k = [] num_row = csvlen() sensor.mode = adafruit_bno055.COMPASS_MODE time.sleep(5) #initialize compass bearing for offset for i in range(100): compass_bearing_arr.append(sensor.euler[0]) compass_bearing_std = np.std(compass_bearing_arr) #if compass standard deviation above 0.5 degrees reinitialize offset if compass_bearing_std > 0.5: print("bearing not accurate, reinitializing\r\n") auto() else: print("compass calibrated\r\n") compass_bearing = np.average(compass_bearing_arr) sensor.mode = adafruit_bno055.NDOF_MODE print("count: {}, num row: {}\r\n".format(str(count), str(num_row))) print("initializing\r\n") try: #keeps running if did not reach final location while count != num_row: print("moving autonmously \r\n") #Get initial lat and lon from GPS Coord current_lat, current_lon = gps() #Get relative angle from IMU current_bearing = sensor.euler[0] + compass_bearing #creates a list of sensor observations at successive time steps #each list within z_k is an observation vector yaw = radians(sensor.euler[0]) pitch = sensor.euler[1] roll = sensor.euler[2] bearing_arr = pitch, roll, yaw #bearing_arr = np.transpose(bearing_arr, axes=None) z_k.append(bearing_arr) # z_k = np.array([[4.721,0.143,0.006], # k=1 # [9.353,0.284,0.007], # k=2 # [14.773,0.422,0.009],# k=3 # [18.246,0.555,0.011], # k=4 # [22.609,0.715,0.012]])# k=5 #print('Sensor Observation', z_k, '\r\n') dk = 1 # The estimated state vector at time k-1 in the global reference frame. # [x_k_minus_1, y_k_minus_1, yaw_k_minus_1] # [meters, meters, radians] state_estimate_k_minus_1 = np.array([0.0,0.0,0.0]) # The control input vector at time k-1 in the global reference frame. # [v, yaw_rate] # [meters/second, radians/second] # In the literature, this is commonly u. # Because there is no angular velocity and the robot begins at the # origin with a 0 radians yaw angle, this robot is traveling along # the positive x-axis in the global reference frame. control_vector_k_minus_1 = np.array([4.5,0.0]) # State covariance matrix P_k_minus_1 # This matrix has the same number of rows (and columns) as the # number of states (i.e. 3x3 matrix). P is sometimes referred # to as Sigma in the literature. It represents an estimate of # the accuracy of the state estimate at time k made using the # state transition matrix. We start off with guessed values. P_k_minus_1 = np.array([[0.1, 0, 0], [ 0,0.1, 0], [ 0, 0, 0.1]]) # Run the Extended Kalman Filter and store the # near-optimal state and covariance estimates for k, z_k in enumerate(z_k, start = 1): print(f'Timestep k = {k}\r\n') optimal_state_estimate_k, covariance_estimate_k = ekf( z_k, # Most recent sensor measurement state_estimate_k_minus_1, # Our most recent estimate of the state control_vector_k_minus_1, # Our most recent control input P_k_minus_1, # Our most recent state covariance matrix dk) # Time interval current_bearing = degrees(optimal_state_estimate[2]) + compass_bearing print(current_bearing) break # Get ready for the next timestep by updating the variable values state_estimate_k_minus_1 = optimal_state_estimate_k P_k_minus_1 = covariance_estimate_k #get and calculate the bearing the rover should be heading desired_lat, desired_lon = gpsread(count) desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) #Check for Objects in the way camera() if current_bearing < 0: current_bearing = 360 + current_bearing if current_bearing > 360: current_bearing = current_bearing - 360 #Due to the calculation for the desired bearing, we need to ensure that the values align with the current #bearing to allow for accurate results if desired_bearing < 0: desired_bearing = 360 + desired_bearing #calculate the shortest angle to turn left or right left_close = current_bearing - desired_bearing right_close = desired_bearing - current_bearing if left_close < 0: left_close = left_close + 360 if right_close < 0: right_close = right_close + 360 print("current bearing: {}, desired bearing: {}\r\n".format(str(current_bearing), str(desired_bearing))) #Need to ensure that the rover does not read past the last point of the data to ensure no indexing errors if count >= num_row: count = num_row break #only move forward if bearing is reached to allow the rover to reach the desired point. if abs(desired_bearing - current_bearing) <= 2: forward() # time.sleep(0.3) current_bearing = sensor.euler[0] #only increment to the next waypoint if waypoint is reached. if abs(desired_lat - current_lat) < 0.000001 and abs(desired_lon - current_lon) < 0.000001: print("wp reached\r\n") brake() current_lat, current_lon = gps() desired_lat, desired_lon = gpsread(count) desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) count += 1 elif right_close <= left_close: right() # time.sleep(0.3) current_bearing = sensor.euler[0] #allow the robot to reach closer to the desired bearing before determining whether bearing was truly #reached to account for fluctiations if abs(desired_bearing - current_bearing) <= 2: print("bearing reached \r\n") brake() current_lat, current_lon = gps() desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) elif left_close <= right_close: left() # time.sleep(0.3) current_bearing = sensor.euler[0] if abs(desired_bearing - current_bearing) <= 2: print("bearing reached\r\n") brake() current_lat, current_lon = gps() desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) elif abs(desired_lat - current_lat) < 0.000001 and abs(desired_lon - current_lon) < 0.000001: brake() current_lat, current_lon = gps() desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) except KeyboardInterrupt: hard_brake() print("exiting\r\n") #function Manual #Move Snobot with Keyboard only def Manual():
def forward(): print("forward\r\n") pca.servo[LeftMotor].angle = 97 #forward above 80 reverse below 15 pca.servo[RightMotor].angle = 50 #forward below 50 reverse above 50 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def left(): print("left\r\n") pca.servo[LeftMotor].angle = 50 pca.servo[RightMotor].angle = 50 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def right(): print("right\r\n") pca.servo[LeftMotor].angle = 95 pca.servo[RightMotor].angle = 95 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def reverse(): print("reverse\r\n") pca.servo[LeftMotor].angle = 50 pca.servo[RightMotor].angle = 97 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def brake(): print("brake\r\n") pca.servo[LeftMotor].angle = Brake pca.servo[RightMotor].angle = Brake pca.servo[Blower].angle = 120 time.sleep(0.05) def hard_brake(): print("STOP\r\n") pca.servo[LeftMotor].angle = Brake pca.servo[RightMotor].angle = Brake pca.servo[Blower].angle = Brake if __name__ == '__main__': init() main()
print("starting manual movement\n") print("press wasd to control the movement\n") try: while True: key = stdscr.getch() #Forward if key == ord('w'): forward() #Move Left elif key == ord('a'): left() #Move Right elif key == ord('d'): right() #Reverse elif key == ord('s'): reverse() else: brake() curses.endwin() #Stop all motors you stop program except KeyboardInterrupt: print("end\n") hard_brake() curses.endwin()
identifier_body
movement.py
#Libraries import time from adafruit_servokit import ServoKit import curses import adafruit_bno055 from adafruit_extended_bus import ExtendedI2C as I2C import busio import board import pynmea2 import serial from math import sin, cos, sqrt, atan2, radians, degrees import numpy as np import csv import inspect import pyrealsense2.pyrealsense2 as rs import cv2 #Constants PCAServo=16 #Total of 16 Channels MIN_PWM=1100 #Minimum PWM Signal Sent MAX_PWM=1900 #Max PWM Signal Sent #Parameters Brake = 70 #Stop Servos from Moving Max_Speed = 100 #Max Speed Servos can turn #Motor Channels LeftMotor = 2 RightMotor = 1 Blower = 0 #Motor Driver Objects pca = ServoKit(channels=16) stdscr = curses.initscr() #GPS Objects ser = serial.Serial(port = '/dev/ttyACM0', baudrate = 9600, timeout = 1.0) #er2 = serial.Serial(port = '/dev/ttyACM0', baudrate = 9600, timeout = 1.0) #IMU Objects i2c = busio.I2C(board.SCL_1, board.SDA_1) # Device is /dev/i2c-1 sensor = adafruit_bno055.BNO055_I2C(i2c) #Camera pipeline = rs.pipeline() config = rs.config() config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30) #function init def init(): print("initializing...\r\n") #Motor Initializiation for i in range(PCAServo): pca.servo[i].set_pulse_width_range(MIN_PWM, MAX_PWM) pca.servo[i].angle = Brake #function main def main(): auto() # print("What mode do you want to run?\r\n") # print("'auto' for autonomous movement or 'manual' for manual control\r\n") # print("in auto, the rover will move according to predefined path\r\n") # print("in manual, the rover will move according to your controls and will record the path\r\n") # input1 = input() # if input1 == "auto": # print("starting auto\r\n") # auto() # elif input1 == "manual": # print("starting manual\r\n") # Thread(target = manual).start() # Thread(target = gpswrite).start() # else: # print("did you enter the wrong command?\r\n") # print("try again\r\n") ######################NAVIGATION CODE##################################################################### #poll for current GPS Coordinates def gps(): while True: msg = ser.readline().decode('utf-8', 'ignore') if msg.startswith('$'): if "GGA" in msg: gpsCoord = pynmea2.parse(msg) current_lat = gpsCoord.latitude current_lon = gpsCoord.longitude return current_lat, current_lon #poll for current GPS Coordinates def gps2(): while True: msg = ser2.readline().decode('utf-8', 'ignore') if msg.startswith('$'): if "GGA" in msg: gpsCoord = pynmea2.parse(msg) current_lat = gpsCoord.latitude current_lon = gpsCoord.longitude return current_lat, current_lon #Store GPS data from RTK GPS (C099-F9P) def gpswrite(): filename = 'GPSData.csv' gpsData = open(filename, 'w') fieldnames = ['latitude','longitude'] gps = csv.DictWriter(gpsData, fieldnames=fieldnames, delimiter = ' ') gps.writeheader() while True: msg = ser.readline().decode('utf-8', 'ignore') #Exclude Non-GPS Related Values if msg.startswith('$'): #Acquire $GPGGA Data for Lat Lon Coord if "GGA" in msg: gpsCoord = pynmea2.parse(msg) latitude = gpsCoord.latitude longitude = gpsCoord.longitude #Frequency of Data Acquisition time.sleep(0.1) gps.writerow({'latitude' : latitude, 'longitude' : longitude}) #get GPS Data stored in GPSData.csv def gpsread(count): filename = 'GPSData.csv' #Create Empty Set to store GPS Data from .csv file lat = [] lon = [] with open(filename) as gps: gpsreader = csv.DictReader(gps, delimiter = ' ') for row in gpsreader: #Convert str into float latitude = float(row['latitude']) longitude = float(row['longitude']) #Put Data in .csv file into an array lat.append(latitude) lon.append(longitude) desired_lat = lat[count] desired_lon = lon[count] return desired_lat, desired_lon def csvlen(): filename = 'GPSData.csv' num_row = 0 with open(filename) as gps: gpsreader = csv.DictReader(gps) for row in gpsreader: num_row += 1 return num_row #determine bearing to know what angle the rover needs to turn to def navigate(current_lat, current_lon, desired_lat, desired_lon): #convert lat and lon angles to radians lat1 = radians(current_lat) lon1 = radians(current_lon) lat2 = radians(desired_lat) lon2 = radians(desired_lon) #get change in lat and lon values dlon = lon2 - lon1 dlat = lat2 - lat1 print("calculating bearing\r\n") #math for calculating bearing x = cos(lat2) * sin(dlon) y = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon) bearing = np.arctan2(x,y) bearing = np.degrees(bearing) return bearing #################################OBJECT AVOIDANCE CODE################################## #function camera depth def camera(): #start streaming # pipeline.start(config) pipeline.start(config) frames = pipeline.wait_for_frames() for frame in frames: if frame.is_depth_frame(): depth = frames.get_depth_frame() for y in range(0,480,40): for x in range(0,600,40): dist = depth.get_distance(x,y) if y == 480: pipeline.stop() return if dist > 0.1 and dist < 1: if x > 200 and x < 400: #center of camera, what to do? hard_brake() print("object in the way...\r\n") pipeline.stop() camera() elif x < 200: #left of camera, what to do? print("object on left\r\n") right() time.sleep(0.3) hard_brake() pipeline.stop() camera() elif x > 400: #right of camera, what to do? print("object on right\r\n") left() time.sleep(0.3) hard_brake() pipeline.stop() camera() pipeline.stop() return ##############EXTEDNDED KALMAN FILTER CODE######################################### # A matrix # 3x3 matrix -> number of states x number of states matrix # Expresses how the state of the system [x,y,yaw] changes # from k-1 to k when no control command is executed. # Typically a robot on wheels only drives when the wheels are told to turn. # For this case, A is the identity matrix. # A is sometimes F in the literature. A_k_minus_1 = np.array([[1.0, 0, 0], [ 0,1.0, 0], [ 0, 0, 1.0]]) # Noise applied to the forward kinematics (calculation # of the estimated state at time k from the state # transition model of the mobile robot). This is a vector # with the number of elements equal to the number of states process_noise_v_k_minus_1 = np.array([0.01,0.01,0.003]) # State model noise covariance matrix Q_k # When Q is large, the Kalman Filter tracks large changes in # the sensor measurements more closely than for smaller Q. # Q is a square matrix that has the same number of rows as states. Q_k = np.array([[1.0, 0, 0], [ 0, 1.0, 0], [ 0, 0, 1.0]]) # Measurement matrix H_k # Used to convert the predicted state estimate at time k # into predicted sensor measurements at time k. # In this case, H will be the identity matrix since the # estimated state maps directly to state measurements from the # odometry data [x, y, yaw] # H has the same number of rows as sensor measurements # and same number of columns as states. H_k = np.array([[1.0, 0, 0], [ 0,1.0, 0], [ 0, 0, 1.0]]) # Sensor measurement noise covariance matrix R_k # Has the same number of rows and columns as sensor measurements. # If we are sure about the measurements, R will be near zero. R_k = np.array([[1.0, 0, 0], [ 0, 1.0, 0], [ 0, 0, 1.0]]) # Sensor noise. This is a vector with the # number of elements equal to the number of sensor measurements. sensor_noise_w_k = np.array([0.07,0.07,0.04]) def getB(yaw, deltak): """ Calculates and returns the B matrix 3x2 matix -> number of states x number of control inputs The control inputs are the forward speed and the rotation rate around the z axis from the x-axis in the counterclockwise direction. [v,yaw_rate] Expresses how the state of the system [x,y,yaw] changes from k-1 to k due to the control commands (i.e. control input). :param yaw: The yaw angle (rotation angle around the z axis) in rad :param deltak: The change in time from time step k-1 to k in sec """ B = np.array([ [np.cos(yaw)*deltak, 0], [np.sin(yaw)*deltak, 0], [0, deltak]]) return B def ekf(z_k_observation_vector, state_estimate_k_minus_1, control_vector_k_minus_1, P_k_minus_1, dk): """ Extended Kalman Filter. Fuses noisy sensor measurement to create an optimal estimate of the state of the robotic system. INPUT :param z_k_observation_vector The observation from the Odometry 3x1 NumPy Array [x,y,yaw] in the global reference frame in [meters,meters,radians]. :param state_estimate_k_minus_1 The state estimate at time k-1 3x1 NumPy Array [x,y,yaw] in the global reference frame in [meters,meters,radians]. :param control_vector_k_minus_1 The control vector applied at time k-1 3x1 NumPy Array [v,v,yaw rate] in the global reference frame in [meters per second,meters per second,radians per second]. :param P_k_minus_1 The state covariance matrix estimate at time k-1 3x3 NumPy Array :param dk Time interval in seconds OUTPUT :return state_estimate_k near-optimal state estimate at time k 3x1 NumPy Array ---> [meters,meters,radians] :return P_k state covariance_estimate for time k 3x3 NumPy Array """ ######################### Predict ############################# # Predict the state estimate at time k based on the state # estimate at time k-1 and the control input applied at time k-1. state_estimate_k = A_k_minus_1 @ (state_estimate_k_minus_1) + (getB(state_estimate_k_minus_1[2],dk)) @ (control_vector_k_minus_1) + (process_noise_v_k_minus_1) print(f'State Estimate Before EKF={state_estimate_k}\r\n') # Predict the state covariance estimate based on the previous # covariance and some noise P_k = A_k_minus_1 @ P_k_minus_1 @ A_k_minus_1.T + (Q_k) ################### Update (Correct) ########################## # Calculate the difference between the actual sensor measurements # at time k minus what the measurement model predicted # the sensor measurements would be for the current timestep k. measurement_residual_y_k = z_k_observation_vector - ( (H_k @ state_estimate_k) + ( sensor_noise_w_k)) print(f'Observation={z_k_observation_vector}\r\n') # Calculate the measurement residual covariance S_k = H_k @ P_k @ H_k.T + R_k # Calculate the near-optimal Kalman gain # We use pseudoinverse since some of the matrices might be # non-square or singular. K_k = P_k @ H_k.T @ np.linalg.pinv(S_k) # Calculate an updated state estimate for time k state_estimate_k = state_estimate_k + (K_k @ measurement_residual_y_k) # Update the state covariance estimate for time k P_k = P_k - (K_k @ H_k @ P_k) # Print the best (near-optimal) estimate of the current state of the robot print(f'State Estimate After EKF={state_estimate_k}\r\n') # Return the updated state and covariance estimates return state_estimate_k, P_k ############################################################################################ #function auto def auto(): print("starting autonomous movement.\r\n") #Count for Number of WPs assigned count = 0 #Timestep for IMU EKF k = 1 #compass bearing will be the offset for the rover to calculate the relative angle compass_bearing_arr = [] bearing_arr=[] z_k = [] num_row = csvlen() sensor.mode = adafruit_bno055.COMPASS_MODE time.sleep(5) #initialize compass bearing for offset for i in range(100): compass_bearing_arr.append(sensor.euler[0]) compass_bearing_std = np.std(compass_bearing_arr) #if compass standard deviation above 0.5 degrees reinitialize offset if compass_bearing_std > 0.5: print("bearing not accurate, reinitializing\r\n") auto() else: print("compass calibrated\r\n") compass_bearing = np.average(compass_bearing_arr) sensor.mode = adafruit_bno055.NDOF_MODE print("count: {}, num row: {}\r\n".format(str(count), str(num_row))) print("initializing\r\n") try: #keeps running if did not reach final location while count != num_row: print("moving autonmously \r\n") #Get initial lat and lon from GPS Coord current_lat, current_lon = gps() #Get relative angle from IMU current_bearing = sensor.euler[0] + compass_bearing #creates a list of sensor observations at successive time steps #each list within z_k is an observation vector yaw = radians(sensor.euler[0]) pitch = sensor.euler[1] roll = sensor.euler[2] bearing_arr = pitch, roll, yaw #bearing_arr = np.transpose(bearing_arr, axes=None) z_k.append(bearing_arr) # z_k = np.array([[4.721,0.143,0.006], # k=1 # [9.353,0.284,0.007], # k=2 # [14.773,0.422,0.009],# k=3 # [18.246,0.555,0.011], # k=4 # [22.609,0.715,0.012]])# k=5 #print('Sensor Observation', z_k, '\r\n') dk = 1 # The estimated state vector at time k-1 in the global reference frame. # [x_k_minus_1, y_k_minus_1, yaw_k_minus_1] # [meters, meters, radians] state_estimate_k_minus_1 = np.array([0.0,0.0,0.0]) # The control input vector at time k-1 in the global reference frame. # [v, yaw_rate] # [meters/second, radians/second] # In the literature, this is commonly u. # Because there is no angular velocity and the robot begins at the # origin with a 0 radians yaw angle, this robot is traveling along # the positive x-axis in the global reference frame. control_vector_k_minus_1 = np.array([4.5,0.0]) # State covariance matrix P_k_minus_1 # This matrix has the same number of rows (and columns) as the # number of states (i.e. 3x3 matrix). P is sometimes referred # to as Sigma in the literature. It represents an estimate of # the accuracy of the state estimate at time k made using the # state transition matrix. We start off with guessed values. P_k_minus_1 = np.array([[0.1, 0, 0], [ 0,0.1, 0], [ 0, 0, 0.1]]) # Run the Extended Kalman Filter and store the # near-optimal state and covariance estimates for k, z_k in enumerate(z_k, start = 1): print(f'Timestep k = {k}\r\n') optimal_state_estimate_k, covariance_estimate_k = ekf( z_k, # Most recent sensor measurement state_estimate_k_minus_1, # Our most recent estimate of the state control_vector_k_minus_1, # Our most recent control input P_k_minus_1, # Our most recent state covariance matrix dk) # Time interval current_bearing = degrees(optimal_state_estimate[2]) + compass_bearing print(current_bearing) break # Get ready for the next timestep by updating the variable values state_estimate_k_minus_1 = optimal_state_estimate_k P_k_minus_1 = covariance_estimate_k #get and calculate the bearing the rover should be heading desired_lat, desired_lon = gpsread(count) desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) #Check for Objects in the way camera() if current_bearing < 0: current_bearing = 360 + current_bearing if current_bearing > 360: current_bearing = current_bearing - 360 #Due to the calculation for the desired bearing, we need to ensure that the values align with the current #bearing to allow for accurate results if desired_bearing < 0: desired_bearing = 360 + desired_bearing #calculate the shortest angle to turn left or right left_close = current_bearing - desired_bearing right_close = desired_bearing - current_bearing if left_close < 0: left_close = left_close + 360 if right_close < 0: right_close = right_close + 360 print("current bearing: {}, desired bearing: {}\r\n".format(str(current_bearing), str(desired_bearing))) #Need to ensure that the rover does not read past the last point of the data to ensure no indexing errors if count >= num_row: count = num_row break #only move forward if bearing is reached to allow the rover to reach the desired point. if abs(desired_bearing - current_bearing) <= 2: forward() # time.sleep(0.3) current_bearing = sensor.euler[0] #only increment to the next waypoint if waypoint is reached. if abs(desired_lat - current_lat) < 0.000001 and abs(desired_lon - current_lon) < 0.000001: print("wp reached\r\n") brake() current_lat, current_lon = gps() desired_lat, desired_lon = gpsread(count) desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) count += 1 elif right_close <= left_close: right() # time.sleep(0.3) current_bearing = sensor.euler[0] #allow the robot to reach closer to the desired bearing before determining whether bearing was truly #reached to account for fluctiations if abs(desired_bearing - current_bearing) <= 2: print("bearing reached \r\n") brake() current_lat, current_lon = gps() desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) elif left_close <= right_close: left() # time.sleep(0.3) current_bearing = sensor.euler[0] if abs(desired_bearing - current_bearing) <= 2: print("bearing reached\r\n") brake() current_lat, current_lon = gps() desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) elif abs(desired_lat - current_lat) < 0.000001 and abs(desired_lon - current_lon) < 0.000001: brake() current_lat, current_lon = gps() desired_bearing = navigate(current_lat, current_lon, desired_lat, desired_lon) except KeyboardInterrupt: hard_brake() print("exiting\r\n") #function Manual #Move Snobot with Keyboard only def Manual(): print("starting manual movement\n") print("press wasd to control the movement\n") try: while True: key = stdscr.getch() #Forward if key == ord('w'): forward() #Move Left elif key == ord('a'): left() #Move Right elif key == ord('d'): right() #Reverse elif key == ord('s'): reverse() else: brake() curses.endwin() #Stop all motors you stop program except KeyboardInterrupt: print("end\n") hard_brake() curses.endwin() def forward(): print("forward\r\n") pca.servo[LeftMotor].angle = 97 #forward above 80 reverse below 15 pca.servo[RightMotor].angle = 50 #forward below 50 reverse above 50 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def left(): print("left\r\n") pca.servo[LeftMotor].angle = 50 pca.servo[RightMotor].angle = 50 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def
(): print("right\r\n") pca.servo[LeftMotor].angle = 95 pca.servo[RightMotor].angle = 95 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def reverse(): print("reverse\r\n") pca.servo[LeftMotor].angle = 50 pca.servo[RightMotor].angle = 97 pca.servo[Blower].angle = Max_Speed time.sleep(0.05) def brake(): print("brake\r\n") pca.servo[LeftMotor].angle = Brake pca.servo[RightMotor].angle = Brake pca.servo[Blower].angle = 120 time.sleep(0.05) def hard_brake(): print("STOP\r\n") pca.servo[LeftMotor].angle = Brake pca.servo[RightMotor].angle = Brake pca.servo[Blower].angle = Brake if __name__ == '__main__': init() main()
right
identifier_name
model.py
from sklearn import preprocessing from random import shuffle import numpy as np import collections import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from tensorflow.keras.layers import Dense, Dropout, Activation, Conv1D, GlobalMaxPooling1D from tensorflow.keras.models import Sequential, model_from_json from tensorflow.keras import backend as K from gensim.models.keyedvectors import KeyedVectors from nltk.tokenize import TreebankWordTokenizer import re import pickle import os import yaml import pandas from typing import List from tensorflow.keras.utils import to_categorical from tensorflow.keras import losses, optimizers from early_stopping import EarlyStoppingAtMaxMacroF1 import json import hashlib SEED = 7 def read_csv_json(file_name) -> pandas.DataFrame: if file_name.endswith('json') or file_name.endswith('jsonl'): df = pandas.read_json(file_name, lines=True) elif file_name.endswith('csv'): df = pandas.read_csv(file_name) else: raise NotImplementedError return df def use_only_alphanumeric(input): pattern = re.compile('[\W^\'\"]+') output = pattern.sub(' ', input).strip() return output def tokenize_and_vectorize(tokenizer, embedding_vector, dataset, embedding_dims): vectorized_data = [] # probably could be optimized further ds1 = [use_only_alphanumeric(samp.lower()) for samp in dataset] token_list = [tokenizer.tokenize(sample) for sample in ds1] for tokens in token_list: vecs = [] for token in tokens: try: vecs.append(embedding_vector[token].tolist()) except KeyError: # print('token not found: (%s) in sentence: %s' % (token, ' '.join(tokens))) np.random.seed(int(hashlib.sha1(token.encode()).hexdigest(), 16) % (10 ** 6)) unk_vec = np.random.rand(embedding_dims) vecs.append(unk_vec.tolist()) continue vectorized_data.append(vecs) return vectorized_data def pad_trunc(data, maxlen): """ For a given dataset pad with zero vectors or truncate to maxlen """ new_data = [] # Create a vector of 0s the length of our word vectors zero_vector = [] for _ in range(len(data[0][0])): zero_vector.append(0.0) for sample in data: if len(sample) > maxlen: temp = sample[:maxlen] elif len(sample) < maxlen: temp = list(sample) # Append the appropriate number 0 vectors to the list additional_elems = maxlen - len(sample) for _ in range(additional_elems): temp.append(zero_vector) else: temp = sample new_data.append(temp) return new_data def save(model, le, path, history): ''' save model based on model, encoder ''' if not os.path.exists(path): os.makedirs(path, exist_ok=True) print(f'saving model to {path}') structure_file = os.path.join(path, 'structure.json') weight_file = os.path.join(path, 'weight.h5') labels_file = os.path.join(path, 'classes') with open(structure_file, "w") as json_file: json_file.write(model.to_json()) model.save_weights(weight_file) np.save(labels_file, le.categories_[0]) with open(os.path.join(path, "log.json"), 'w') as f: json.dump(history.history, f) def load(path): print(f'loading model from {path}') structure_file = os.path.join(path, 'structure.json') weight_file = os.path.join(path, 'weight.h5') labels_file = os.path.join(path, 'classes.npy') with open(structure_file, "r") as json_file: json_string = json_file.read() model = model_from_json(json_string) model.load_weights(weight_file) model._make_predict_function() #le = preprocessing.LabelEncoder() categories = np.load(labels_file) le = preprocessing.OneHotEncoder(handle_unknown='ignore', sparse=False) le.fit([[c] for c in categories]) json_file.close() return model, le def predict(session, graph, model, vectorized_input, num_classes): if session is None: raise ("Session is not initialized") if graph is None: raise ("Graph is not initialized") if model is None: raise ("Model is not initialized") with session.as_default(): with graph.as_default(): probs = model.predict_proba(vectorized_input) preds = model.predict_classes(vectorized_input) preds = to_categorical(preds, num_classes=num_classes) return (probs, preds) class Model: def __init__(self, word2vec_pkl_path, config_path, label_smoothing=0): with open(config_path, 'r') as f: self.model_cfg = yaml.safe_load(f)['model'] self.tokenizer = TreebankWordTokenizer() with open(word2vec_pkl_path, 'rb') as f: self.vectors = pickle.load(f) self.model = None self.session = None self.graph = None self.le_encoder = None self.label_smoothing = label_smoothing def train(self, tr_set_path: str, save_path: str, va_split: float=0.1, stratified_split: bool=False, early_stopping: bool=True): """ Train a model for a given dataset Dataset should be a list of tuples consisting of training sentence and the class label Args: tr_set_path: path to training data save_path: path to save model weights and labels va_split: fraction of training data to be used for validation in early stopping. Only effective when stratified_split is set to False. Will be overridden if stratified_split is True. stratified_split: whether to split training data stratified by class. If True, validation will be done on a fixed val set from a stratified split out of the training set with the fraction of va_split. early_stopping: whether to do early stopping Returns: history of training including average loss for each training epoch """ df_tr = read_csv_json(tr_set_path) if stratified_split: df_va = df_tr.groupby('intent').apply(lambda g: g.sample(frac=va_split, random_state=SEED)) df_tr = df_tr[~df_tr.index.isin(df_va.index.get_level_values(1))] va_messages, va_labels = list(df_va.text), list(df_va.intent) va_dataset = [{'data': va_messages[i], 'label': va_labels[i]} for i in range(len(df_va))] tr_messages, tr_labels = list(df_tr.text), list(df_tr.intent) tr_dataset = [{'data': tr_messages[i], 'label': tr_labels[i]} for i in range(len(df_tr))] (x_train, y_train, le_encoder) = self.__preprocess(tr_dataset) (x_va, y_va, _) = self.__preprocess(va_dataset, le_encoder) else: tr_messages, tr_labels = list(df_tr.text), list(df_tr.intent) tr_dataset = [{'data': tr_messages[i], 'label': tr_labels[i]} for i in range(len(df_tr))] (x_train, y_train, le_encoder) = self.__preprocess(tr_dataset) K.clear_session() graph = tf.Graph() with graph.as_default(): session = tf.Session() with session.as_default(): session.run(tf.global_variables_initializer()) model = self.__build_model(num_classes=len(le_encoder.categories_[0])) model.compile( loss=losses.CategoricalCrossentropy(label_smoothing=self.label_smoothing), #metrics=['categorical_accuracy'], optimizer=self.model_cfg.get('optimizer', 'adam') #default lr at 0.001 #optimizer=optimizers.Adam(learning_rate=5e-4) ) # early stopping callback using validation loss callback = tf.keras.callbacks.EarlyStopping( monitor="val_loss", min_delta=0, patience=5, verbose=0, mode="auto", baseline=None, restore_best_weights=True, ) #callback = EarlyStoppingAtMaxMacroF1( # patience=100, # record all epochs # validation=(x_va, y_va) #) print('start training') history = model.fit(x_train, y_train, batch_size=self.model_cfg['batch_size'], epochs=100, validation_split=va_split if not stratified_split else 0, validation_data=(x_va, y_va) if stratified_split else None, callbacks=[callback] if early_stopping else None) history.history['train_data'] = tr_set_path print(f'finished training in {len(history.history["loss"])} epochs') save(model, le_encoder, save_path, history) self.model = model self.session = session self.graph = graph self.le_encoder = le_encoder # return training history return history.history def __preprocess(self, dataset, le_encoder=None): ''' Preprocess the dataset, transform the categorical labels into numbers.
Get word embeddings for the training data. ''' shuffle(dataset) data = [s['data'] for s in dataset] #labels = [s['label'] for s in dataset] labels = [[s['label']] for s in dataset] #le_encoder = preprocessing.LabelEncoder() if le_encoder is None: le_encoder = preprocessing.OneHotEncoder(handle_unknown='ignore', sparse=False) le_encoder.fit(labels) encoded_labels = le_encoder.transform(labels) print('%s intents with %s samples' % (len(le_encoder.get_feature_names()), len(data))) #print('train %s intents with %s samples' % (len(set(labels)), len(data))) #print(collections.Counter(labels)) print(le_encoder.categories_[0]) vectorized_data = tokenize_and_vectorize(self.tokenizer, self.vectors, data, self.model_cfg['embedding_dims']) # split_point = int(len(vectorized_data) * .9) x_train = vectorized_data # vectorized_data[:split_point] y_train = encoded_labels # encoded_labels[:split_point] x_train = pad_trunc(x_train, self.model_cfg['maxlen']) x_train = np.reshape(x_train, (len(x_train), self.model_cfg['maxlen'], self.model_cfg['embedding_dims'])) y_train = np.array(y_train) return x_train, y_train, le_encoder def __build_model(self, num_classes=2, type='keras'): print('Build model') model = Sequential() layers = self.model_cfg.get('layers', 1) for l in range(layers): self.__addLayers(model, self.model_cfg) model.add(Dense(num_classes)) model.add(Activation('softmax')) return model def __addLayers(self, model, model_cfg): maxlen = model_cfg.get('maxlen', 400) strides = model_cfg.get('strides', 1) embedding_dims = model_cfg.get('embedding_dims', 300) filters = model_cfg.get('filters', 250) activation_type = model_cfg.get('activation', 'relu') kernel_size = model_cfg.get('kernel_size', 3) hidden_dims = model_cfg.get('hidden_dims', 200) model.add(Conv1D( filters, kernel_size, padding='valid', activation=activation_type, strides=strides, input_shape=(maxlen, embedding_dims))) model.add(GlobalMaxPooling1D()) model.add(Dense(hidden_dims)) model.add(Activation(activation_type)) def load(self, path): K.clear_session() graph = tf.Graph() with graph.as_default(): session = tf.Session() with session.as_default(): self.session = session self.graph = graph (model, le) = load(path) self.model = model self.le_encoder = le def predict(self, input: List[str]): vectorized_data = tokenize_and_vectorize(self.tokenizer, self.vectors, input, self.model_cfg['embedding_dims']) x_train = pad_trunc(vectorized_data, self.model_cfg['maxlen']) vectorized_input = np.reshape(x_train, (len(x_train), self.model_cfg['maxlen'], self.model_cfg['embedding_dims'])) (probs, preds) = predict(self.session, self.graph, self.model, vectorized_input, len(self.le_encoder.categories_[0])) probs = probs.tolist() results = self.le_encoder.inverse_transform(preds) output = [{'input': input[i], 'embeddings': x_train[i], #'label': r, 'label': r.item(), 'highestProb': max(probs[i]), #'prob': dict(zip(self.le_encoder.classes_, probs[i])) 'prob': dict(zip(self.le_encoder.categories_[0], probs[i])) } for i, r in enumerate(results)] return output
random_line_split
model.py
from sklearn import preprocessing from random import shuffle import numpy as np import collections import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from tensorflow.keras.layers import Dense, Dropout, Activation, Conv1D, GlobalMaxPooling1D from tensorflow.keras.models import Sequential, model_from_json from tensorflow.keras import backend as K from gensim.models.keyedvectors import KeyedVectors from nltk.tokenize import TreebankWordTokenizer import re import pickle import os import yaml import pandas from typing import List from tensorflow.keras.utils import to_categorical from tensorflow.keras import losses, optimizers from early_stopping import EarlyStoppingAtMaxMacroF1 import json import hashlib SEED = 7 def read_csv_json(file_name) -> pandas.DataFrame: if file_name.endswith('json') or file_name.endswith('jsonl'): df = pandas.read_json(file_name, lines=True) elif file_name.endswith('csv'): df = pandas.read_csv(file_name) else: raise NotImplementedError return df def use_only_alphanumeric(input): pattern = re.compile('[\W^\'\"]+') output = pattern.sub(' ', input).strip() return output def tokenize_and_vectorize(tokenizer, embedding_vector, dataset, embedding_dims): vectorized_data = [] # probably could be optimized further ds1 = [use_only_alphanumeric(samp.lower()) for samp in dataset] token_list = [tokenizer.tokenize(sample) for sample in ds1] for tokens in token_list: vecs = [] for token in tokens: try: vecs.append(embedding_vector[token].tolist()) except KeyError: # print('token not found: (%s) in sentence: %s' % (token, ' '.join(tokens))) np.random.seed(int(hashlib.sha1(token.encode()).hexdigest(), 16) % (10 ** 6)) unk_vec = np.random.rand(embedding_dims) vecs.append(unk_vec.tolist()) continue vectorized_data.append(vecs) return vectorized_data def pad_trunc(data, maxlen): """ For a given dataset pad with zero vectors or truncate to maxlen """ new_data = [] # Create a vector of 0s the length of our word vectors zero_vector = [] for _ in range(len(data[0][0])): zero_vector.append(0.0) for sample in data: if len(sample) > maxlen: temp = sample[:maxlen] elif len(sample) < maxlen: temp = list(sample) # Append the appropriate number 0 vectors to the list additional_elems = maxlen - len(sample) for _ in range(additional_elems): temp.append(zero_vector) else: temp = sample new_data.append(temp) return new_data def save(model, le, path, history):
def load(path): print(f'loading model from {path}') structure_file = os.path.join(path, 'structure.json') weight_file = os.path.join(path, 'weight.h5') labels_file = os.path.join(path, 'classes.npy') with open(structure_file, "r") as json_file: json_string = json_file.read() model = model_from_json(json_string) model.load_weights(weight_file) model._make_predict_function() #le = preprocessing.LabelEncoder() categories = np.load(labels_file) le = preprocessing.OneHotEncoder(handle_unknown='ignore', sparse=False) le.fit([[c] for c in categories]) json_file.close() return model, le def predict(session, graph, model, vectorized_input, num_classes): if session is None: raise ("Session is not initialized") if graph is None: raise ("Graph is not initialized") if model is None: raise ("Model is not initialized") with session.as_default(): with graph.as_default(): probs = model.predict_proba(vectorized_input) preds = model.predict_classes(vectorized_input) preds = to_categorical(preds, num_classes=num_classes) return (probs, preds) class Model: def __init__(self, word2vec_pkl_path, config_path, label_smoothing=0): with open(config_path, 'r') as f: self.model_cfg = yaml.safe_load(f)['model'] self.tokenizer = TreebankWordTokenizer() with open(word2vec_pkl_path, 'rb') as f: self.vectors = pickle.load(f) self.model = None self.session = None self.graph = None self.le_encoder = None self.label_smoothing = label_smoothing def train(self, tr_set_path: str, save_path: str, va_split: float=0.1, stratified_split: bool=False, early_stopping: bool=True): """ Train a model for a given dataset Dataset should be a list of tuples consisting of training sentence and the class label Args: tr_set_path: path to training data save_path: path to save model weights and labels va_split: fraction of training data to be used for validation in early stopping. Only effective when stratified_split is set to False. Will be overridden if stratified_split is True. stratified_split: whether to split training data stratified by class. If True, validation will be done on a fixed val set from a stratified split out of the training set with the fraction of va_split. early_stopping: whether to do early stopping Returns: history of training including average loss for each training epoch """ df_tr = read_csv_json(tr_set_path) if stratified_split: df_va = df_tr.groupby('intent').apply(lambda g: g.sample(frac=va_split, random_state=SEED)) df_tr = df_tr[~df_tr.index.isin(df_va.index.get_level_values(1))] va_messages, va_labels = list(df_va.text), list(df_va.intent) va_dataset = [{'data': va_messages[i], 'label': va_labels[i]} for i in range(len(df_va))] tr_messages, tr_labels = list(df_tr.text), list(df_tr.intent) tr_dataset = [{'data': tr_messages[i], 'label': tr_labels[i]} for i in range(len(df_tr))] (x_train, y_train, le_encoder) = self.__preprocess(tr_dataset) (x_va, y_va, _) = self.__preprocess(va_dataset, le_encoder) else: tr_messages, tr_labels = list(df_tr.text), list(df_tr.intent) tr_dataset = [{'data': tr_messages[i], 'label': tr_labels[i]} for i in range(len(df_tr))] (x_train, y_train, le_encoder) = self.__preprocess(tr_dataset) K.clear_session() graph = tf.Graph() with graph.as_default(): session = tf.Session() with session.as_default(): session.run(tf.global_variables_initializer()) model = self.__build_model(num_classes=len(le_encoder.categories_[0])) model.compile( loss=losses.CategoricalCrossentropy(label_smoothing=self.label_smoothing), #metrics=['categorical_accuracy'], optimizer=self.model_cfg.get('optimizer', 'adam') #default lr at 0.001 #optimizer=optimizers.Adam(learning_rate=5e-4) ) # early stopping callback using validation loss callback = tf.keras.callbacks.EarlyStopping( monitor="val_loss", min_delta=0, patience=5, verbose=0, mode="auto", baseline=None, restore_best_weights=True, ) #callback = EarlyStoppingAtMaxMacroF1( # patience=100, # record all epochs # validation=(x_va, y_va) #) print('start training') history = model.fit(x_train, y_train, batch_size=self.model_cfg['batch_size'], epochs=100, validation_split=va_split if not stratified_split else 0, validation_data=(x_va, y_va) if stratified_split else None, callbacks=[callback] if early_stopping else None) history.history['train_data'] = tr_set_path print(f'finished training in {len(history.history["loss"])} epochs') save(model, le_encoder, save_path, history) self.model = model self.session = session self.graph = graph self.le_encoder = le_encoder # return training history return history.history def __preprocess(self, dataset, le_encoder=None): ''' Preprocess the dataset, transform the categorical labels into numbers. Get word embeddings for the training data. ''' shuffle(dataset) data = [s['data'] for s in dataset] #labels = [s['label'] for s in dataset] labels = [[s['label']] for s in dataset] #le_encoder = preprocessing.LabelEncoder() if le_encoder is None: le_encoder = preprocessing.OneHotEncoder(handle_unknown='ignore', sparse=False) le_encoder.fit(labels) encoded_labels = le_encoder.transform(labels) print('%s intents with %s samples' % (len(le_encoder.get_feature_names()), len(data))) #print('train %s intents with %s samples' % (len(set(labels)), len(data))) #print(collections.Counter(labels)) print(le_encoder.categories_[0]) vectorized_data = tokenize_and_vectorize(self.tokenizer, self.vectors, data, self.model_cfg['embedding_dims']) # split_point = int(len(vectorized_data) * .9) x_train = vectorized_data # vectorized_data[:split_point] y_train = encoded_labels # encoded_labels[:split_point] x_train = pad_trunc(x_train, self.model_cfg['maxlen']) x_train = np.reshape(x_train, (len(x_train), self.model_cfg['maxlen'], self.model_cfg['embedding_dims'])) y_train = np.array(y_train) return x_train, y_train, le_encoder def __build_model(self, num_classes=2, type='keras'): print('Build model') model = Sequential() layers = self.model_cfg.get('layers', 1) for l in range(layers): self.__addLayers(model, self.model_cfg) model.add(Dense(num_classes)) model.add(Activation('softmax')) return model def __addLayers(self, model, model_cfg): maxlen = model_cfg.get('maxlen', 400) strides = model_cfg.get('strides', 1) embedding_dims = model_cfg.get('embedding_dims', 300) filters = model_cfg.get('filters', 250) activation_type = model_cfg.get('activation', 'relu') kernel_size = model_cfg.get('kernel_size', 3) hidden_dims = model_cfg.get('hidden_dims', 200) model.add(Conv1D( filters, kernel_size, padding='valid', activation=activation_type, strides=strides, input_shape=(maxlen, embedding_dims))) model.add(GlobalMaxPooling1D()) model.add(Dense(hidden_dims)) model.add(Activation(activation_type)) def load(self, path): K.clear_session() graph = tf.Graph() with graph.as_default(): session = tf.Session() with session.as_default(): self.session = session self.graph = graph (model, le) = load(path) self.model = model self.le_encoder = le def predict(self, input: List[str]): vectorized_data = tokenize_and_vectorize(self.tokenizer, self.vectors, input, self.model_cfg['embedding_dims']) x_train = pad_trunc(vectorized_data, self.model_cfg['maxlen']) vectorized_input = np.reshape(x_train, (len(x_train), self.model_cfg['maxlen'], self.model_cfg['embedding_dims'])) (probs, preds) = predict(self.session, self.graph, self.model, vectorized_input, len(self.le_encoder.categories_[0])) probs = probs.tolist() results = self.le_encoder.inverse_transform(preds) output = [{'input': input[i], 'embeddings': x_train[i], #'label': r, 'label': r.item(), 'highestProb': max(probs[i]), #'prob': dict(zip(self.le_encoder.classes_, probs[i])) 'prob': dict(zip(self.le_encoder.categories_[0], probs[i])) } for i, r in enumerate(results)] return output
''' save model based on model, encoder ''' if not os.path.exists(path): os.makedirs(path, exist_ok=True) print(f'saving model to {path}') structure_file = os.path.join(path, 'structure.json') weight_file = os.path.join(path, 'weight.h5') labels_file = os.path.join(path, 'classes') with open(structure_file, "w") as json_file: json_file.write(model.to_json()) model.save_weights(weight_file) np.save(labels_file, le.categories_[0]) with open(os.path.join(path, "log.json"), 'w') as f: json.dump(history.history, f)
identifier_body
model.py
from sklearn import preprocessing from random import shuffle import numpy as np import collections import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from tensorflow.keras.layers import Dense, Dropout, Activation, Conv1D, GlobalMaxPooling1D from tensorflow.keras.models import Sequential, model_from_json from tensorflow.keras import backend as K from gensim.models.keyedvectors import KeyedVectors from nltk.tokenize import TreebankWordTokenizer import re import pickle import os import yaml import pandas from typing import List from tensorflow.keras.utils import to_categorical from tensorflow.keras import losses, optimizers from early_stopping import EarlyStoppingAtMaxMacroF1 import json import hashlib SEED = 7 def read_csv_json(file_name) -> pandas.DataFrame: if file_name.endswith('json') or file_name.endswith('jsonl'): df = pandas.read_json(file_name, lines=True) elif file_name.endswith('csv'): df = pandas.read_csv(file_name) else: raise NotImplementedError return df def use_only_alphanumeric(input): pattern = re.compile('[\W^\'\"]+') output = pattern.sub(' ', input).strip() return output def tokenize_and_vectorize(tokenizer, embedding_vector, dataset, embedding_dims): vectorized_data = [] # probably could be optimized further ds1 = [use_only_alphanumeric(samp.lower()) for samp in dataset] token_list = [tokenizer.tokenize(sample) for sample in ds1] for tokens in token_list: vecs = [] for token in tokens: try: vecs.append(embedding_vector[token].tolist()) except KeyError: # print('token not found: (%s) in sentence: %s' % (token, ' '.join(tokens))) np.random.seed(int(hashlib.sha1(token.encode()).hexdigest(), 16) % (10 ** 6)) unk_vec = np.random.rand(embedding_dims) vecs.append(unk_vec.tolist()) continue vectorized_data.append(vecs) return vectorized_data def pad_trunc(data, maxlen): """ For a given dataset pad with zero vectors or truncate to maxlen """ new_data = [] # Create a vector of 0s the length of our word vectors zero_vector = [] for _ in range(len(data[0][0])): zero_vector.append(0.0) for sample in data: if len(sample) > maxlen: temp = sample[:maxlen] elif len(sample) < maxlen: temp = list(sample) # Append the appropriate number 0 vectors to the list additional_elems = maxlen - len(sample) for _ in range(additional_elems): temp.append(zero_vector) else: temp = sample new_data.append(temp) return new_data def save(model, le, path, history): ''' save model based on model, encoder ''' if not os.path.exists(path): os.makedirs(path, exist_ok=True) print(f'saving model to {path}') structure_file = os.path.join(path, 'structure.json') weight_file = os.path.join(path, 'weight.h5') labels_file = os.path.join(path, 'classes') with open(structure_file, "w") as json_file: json_file.write(model.to_json()) model.save_weights(weight_file) np.save(labels_file, le.categories_[0]) with open(os.path.join(path, "log.json"), 'w') as f: json.dump(history.history, f) def load(path): print(f'loading model from {path}') structure_file = os.path.join(path, 'structure.json') weight_file = os.path.join(path, 'weight.h5') labels_file = os.path.join(path, 'classes.npy') with open(structure_file, "r") as json_file: json_string = json_file.read() model = model_from_json(json_string) model.load_weights(weight_file) model._make_predict_function() #le = preprocessing.LabelEncoder() categories = np.load(labels_file) le = preprocessing.OneHotEncoder(handle_unknown='ignore', sparse=False) le.fit([[c] for c in categories]) json_file.close() return model, le def predict(session, graph, model, vectorized_input, num_classes): if session is None: raise ("Session is not initialized") if graph is None: raise ("Graph is not initialized") if model is None: raise ("Model is not initialized") with session.as_default(): with graph.as_default(): probs = model.predict_proba(vectorized_input) preds = model.predict_classes(vectorized_input) preds = to_categorical(preds, num_classes=num_classes) return (probs, preds) class Model: def __init__(self, word2vec_pkl_path, config_path, label_smoothing=0): with open(config_path, 'r') as f: self.model_cfg = yaml.safe_load(f)['model'] self.tokenizer = TreebankWordTokenizer() with open(word2vec_pkl_path, 'rb') as f: self.vectors = pickle.load(f) self.model = None self.session = None self.graph = None self.le_encoder = None self.label_smoothing = label_smoothing def train(self, tr_set_path: str, save_path: str, va_split: float=0.1, stratified_split: bool=False, early_stopping: bool=True): """ Train a model for a given dataset Dataset should be a list of tuples consisting of training sentence and the class label Args: tr_set_path: path to training data save_path: path to save model weights and labels va_split: fraction of training data to be used for validation in early stopping. Only effective when stratified_split is set to False. Will be overridden if stratified_split is True. stratified_split: whether to split training data stratified by class. If True, validation will be done on a fixed val set from a stratified split out of the training set with the fraction of va_split. early_stopping: whether to do early stopping Returns: history of training including average loss for each training epoch """ df_tr = read_csv_json(tr_set_path) if stratified_split: df_va = df_tr.groupby('intent').apply(lambda g: g.sample(frac=va_split, random_state=SEED)) df_tr = df_tr[~df_tr.index.isin(df_va.index.get_level_values(1))] va_messages, va_labels = list(df_va.text), list(df_va.intent) va_dataset = [{'data': va_messages[i], 'label': va_labels[i]} for i in range(len(df_va))] tr_messages, tr_labels = list(df_tr.text), list(df_tr.intent) tr_dataset = [{'data': tr_messages[i], 'label': tr_labels[i]} for i in range(len(df_tr))] (x_train, y_train, le_encoder) = self.__preprocess(tr_dataset) (x_va, y_va, _) = self.__preprocess(va_dataset, le_encoder) else: tr_messages, tr_labels = list(df_tr.text), list(df_tr.intent) tr_dataset = [{'data': tr_messages[i], 'label': tr_labels[i]} for i in range(len(df_tr))] (x_train, y_train, le_encoder) = self.__preprocess(tr_dataset) K.clear_session() graph = tf.Graph() with graph.as_default(): session = tf.Session() with session.as_default(): session.run(tf.global_variables_initializer()) model = self.__build_model(num_classes=len(le_encoder.categories_[0])) model.compile( loss=losses.CategoricalCrossentropy(label_smoothing=self.label_smoothing), #metrics=['categorical_accuracy'], optimizer=self.model_cfg.get('optimizer', 'adam') #default lr at 0.001 #optimizer=optimizers.Adam(learning_rate=5e-4) ) # early stopping callback using validation loss callback = tf.keras.callbacks.EarlyStopping( monitor="val_loss", min_delta=0, patience=5, verbose=0, mode="auto", baseline=None, restore_best_weights=True, ) #callback = EarlyStoppingAtMaxMacroF1( # patience=100, # record all epochs # validation=(x_va, y_va) #) print('start training') history = model.fit(x_train, y_train, batch_size=self.model_cfg['batch_size'], epochs=100, validation_split=va_split if not stratified_split else 0, validation_data=(x_va, y_va) if stratified_split else None, callbacks=[callback] if early_stopping else None) history.history['train_data'] = tr_set_path print(f'finished training in {len(history.history["loss"])} epochs') save(model, le_encoder, save_path, history) self.model = model self.session = session self.graph = graph self.le_encoder = le_encoder # return training history return history.history def
(self, dataset, le_encoder=None): ''' Preprocess the dataset, transform the categorical labels into numbers. Get word embeddings for the training data. ''' shuffle(dataset) data = [s['data'] for s in dataset] #labels = [s['label'] for s in dataset] labels = [[s['label']] for s in dataset] #le_encoder = preprocessing.LabelEncoder() if le_encoder is None: le_encoder = preprocessing.OneHotEncoder(handle_unknown='ignore', sparse=False) le_encoder.fit(labels) encoded_labels = le_encoder.transform(labels) print('%s intents with %s samples' % (len(le_encoder.get_feature_names()), len(data))) #print('train %s intents with %s samples' % (len(set(labels)), len(data))) #print(collections.Counter(labels)) print(le_encoder.categories_[0]) vectorized_data = tokenize_and_vectorize(self.tokenizer, self.vectors, data, self.model_cfg['embedding_dims']) # split_point = int(len(vectorized_data) * .9) x_train = vectorized_data # vectorized_data[:split_point] y_train = encoded_labels # encoded_labels[:split_point] x_train = pad_trunc(x_train, self.model_cfg['maxlen']) x_train = np.reshape(x_train, (len(x_train), self.model_cfg['maxlen'], self.model_cfg['embedding_dims'])) y_train = np.array(y_train) return x_train, y_train, le_encoder def __build_model(self, num_classes=2, type='keras'): print('Build model') model = Sequential() layers = self.model_cfg.get('layers', 1) for l in range(layers): self.__addLayers(model, self.model_cfg) model.add(Dense(num_classes)) model.add(Activation('softmax')) return model def __addLayers(self, model, model_cfg): maxlen = model_cfg.get('maxlen', 400) strides = model_cfg.get('strides', 1) embedding_dims = model_cfg.get('embedding_dims', 300) filters = model_cfg.get('filters', 250) activation_type = model_cfg.get('activation', 'relu') kernel_size = model_cfg.get('kernel_size', 3) hidden_dims = model_cfg.get('hidden_dims', 200) model.add(Conv1D( filters, kernel_size, padding='valid', activation=activation_type, strides=strides, input_shape=(maxlen, embedding_dims))) model.add(GlobalMaxPooling1D()) model.add(Dense(hidden_dims)) model.add(Activation(activation_type)) def load(self, path): K.clear_session() graph = tf.Graph() with graph.as_default(): session = tf.Session() with session.as_default(): self.session = session self.graph = graph (model, le) = load(path) self.model = model self.le_encoder = le def predict(self, input: List[str]): vectorized_data = tokenize_and_vectorize(self.tokenizer, self.vectors, input, self.model_cfg['embedding_dims']) x_train = pad_trunc(vectorized_data, self.model_cfg['maxlen']) vectorized_input = np.reshape(x_train, (len(x_train), self.model_cfg['maxlen'], self.model_cfg['embedding_dims'])) (probs, preds) = predict(self.session, self.graph, self.model, vectorized_input, len(self.le_encoder.categories_[0])) probs = probs.tolist() results = self.le_encoder.inverse_transform(preds) output = [{'input': input[i], 'embeddings': x_train[i], #'label': r, 'label': r.item(), 'highestProb': max(probs[i]), #'prob': dict(zip(self.le_encoder.classes_, probs[i])) 'prob': dict(zip(self.le_encoder.categories_[0], probs[i])) } for i, r in enumerate(results)] return output
__preprocess
identifier_name
model.py
from sklearn import preprocessing from random import shuffle import numpy as np import collections import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from tensorflow.keras.layers import Dense, Dropout, Activation, Conv1D, GlobalMaxPooling1D from tensorflow.keras.models import Sequential, model_from_json from tensorflow.keras import backend as K from gensim.models.keyedvectors import KeyedVectors from nltk.tokenize import TreebankWordTokenizer import re import pickle import os import yaml import pandas from typing import List from tensorflow.keras.utils import to_categorical from tensorflow.keras import losses, optimizers from early_stopping import EarlyStoppingAtMaxMacroF1 import json import hashlib SEED = 7 def read_csv_json(file_name) -> pandas.DataFrame: if file_name.endswith('json') or file_name.endswith('jsonl'): df = pandas.read_json(file_name, lines=True) elif file_name.endswith('csv'): df = pandas.read_csv(file_name) else: raise NotImplementedError return df def use_only_alphanumeric(input): pattern = re.compile('[\W^\'\"]+') output = pattern.sub(' ', input).strip() return output def tokenize_and_vectorize(tokenizer, embedding_vector, dataset, embedding_dims): vectorized_data = [] # probably could be optimized further ds1 = [use_only_alphanumeric(samp.lower()) for samp in dataset] token_list = [tokenizer.tokenize(sample) for sample in ds1] for tokens in token_list: vecs = [] for token in tokens: try: vecs.append(embedding_vector[token].tolist()) except KeyError: # print('token not found: (%s) in sentence: %s' % (token, ' '.join(tokens))) np.random.seed(int(hashlib.sha1(token.encode()).hexdigest(), 16) % (10 ** 6)) unk_vec = np.random.rand(embedding_dims) vecs.append(unk_vec.tolist()) continue vectorized_data.append(vecs) return vectorized_data def pad_trunc(data, maxlen): """ For a given dataset pad with zero vectors or truncate to maxlen """ new_data = [] # Create a vector of 0s the length of our word vectors zero_vector = [] for _ in range(len(data[0][0])): zero_vector.append(0.0) for sample in data: if len(sample) > maxlen: temp = sample[:maxlen] elif len(sample) < maxlen: temp = list(sample) # Append the appropriate number 0 vectors to the list additional_elems = maxlen - len(sample) for _ in range(additional_elems): temp.append(zero_vector) else:
new_data.append(temp) return new_data def save(model, le, path, history): ''' save model based on model, encoder ''' if not os.path.exists(path): os.makedirs(path, exist_ok=True) print(f'saving model to {path}') structure_file = os.path.join(path, 'structure.json') weight_file = os.path.join(path, 'weight.h5') labels_file = os.path.join(path, 'classes') with open(structure_file, "w") as json_file: json_file.write(model.to_json()) model.save_weights(weight_file) np.save(labels_file, le.categories_[0]) with open(os.path.join(path, "log.json"), 'w') as f: json.dump(history.history, f) def load(path): print(f'loading model from {path}') structure_file = os.path.join(path, 'structure.json') weight_file = os.path.join(path, 'weight.h5') labels_file = os.path.join(path, 'classes.npy') with open(structure_file, "r") as json_file: json_string = json_file.read() model = model_from_json(json_string) model.load_weights(weight_file) model._make_predict_function() #le = preprocessing.LabelEncoder() categories = np.load(labels_file) le = preprocessing.OneHotEncoder(handle_unknown='ignore', sparse=False) le.fit([[c] for c in categories]) json_file.close() return model, le def predict(session, graph, model, vectorized_input, num_classes): if session is None: raise ("Session is not initialized") if graph is None: raise ("Graph is not initialized") if model is None: raise ("Model is not initialized") with session.as_default(): with graph.as_default(): probs = model.predict_proba(vectorized_input) preds = model.predict_classes(vectorized_input) preds = to_categorical(preds, num_classes=num_classes) return (probs, preds) class Model: def __init__(self, word2vec_pkl_path, config_path, label_smoothing=0): with open(config_path, 'r') as f: self.model_cfg = yaml.safe_load(f)['model'] self.tokenizer = TreebankWordTokenizer() with open(word2vec_pkl_path, 'rb') as f: self.vectors = pickle.load(f) self.model = None self.session = None self.graph = None self.le_encoder = None self.label_smoothing = label_smoothing def train(self, tr_set_path: str, save_path: str, va_split: float=0.1, stratified_split: bool=False, early_stopping: bool=True): """ Train a model for a given dataset Dataset should be a list of tuples consisting of training sentence and the class label Args: tr_set_path: path to training data save_path: path to save model weights and labels va_split: fraction of training data to be used for validation in early stopping. Only effective when stratified_split is set to False. Will be overridden if stratified_split is True. stratified_split: whether to split training data stratified by class. If True, validation will be done on a fixed val set from a stratified split out of the training set with the fraction of va_split. early_stopping: whether to do early stopping Returns: history of training including average loss for each training epoch """ df_tr = read_csv_json(tr_set_path) if stratified_split: df_va = df_tr.groupby('intent').apply(lambda g: g.sample(frac=va_split, random_state=SEED)) df_tr = df_tr[~df_tr.index.isin(df_va.index.get_level_values(1))] va_messages, va_labels = list(df_va.text), list(df_va.intent) va_dataset = [{'data': va_messages[i], 'label': va_labels[i]} for i in range(len(df_va))] tr_messages, tr_labels = list(df_tr.text), list(df_tr.intent) tr_dataset = [{'data': tr_messages[i], 'label': tr_labels[i]} for i in range(len(df_tr))] (x_train, y_train, le_encoder) = self.__preprocess(tr_dataset) (x_va, y_va, _) = self.__preprocess(va_dataset, le_encoder) else: tr_messages, tr_labels = list(df_tr.text), list(df_tr.intent) tr_dataset = [{'data': tr_messages[i], 'label': tr_labels[i]} for i in range(len(df_tr))] (x_train, y_train, le_encoder) = self.__preprocess(tr_dataset) K.clear_session() graph = tf.Graph() with graph.as_default(): session = tf.Session() with session.as_default(): session.run(tf.global_variables_initializer()) model = self.__build_model(num_classes=len(le_encoder.categories_[0])) model.compile( loss=losses.CategoricalCrossentropy(label_smoothing=self.label_smoothing), #metrics=['categorical_accuracy'], optimizer=self.model_cfg.get('optimizer', 'adam') #default lr at 0.001 #optimizer=optimizers.Adam(learning_rate=5e-4) ) # early stopping callback using validation loss callback = tf.keras.callbacks.EarlyStopping( monitor="val_loss", min_delta=0, patience=5, verbose=0, mode="auto", baseline=None, restore_best_weights=True, ) #callback = EarlyStoppingAtMaxMacroF1( # patience=100, # record all epochs # validation=(x_va, y_va) #) print('start training') history = model.fit(x_train, y_train, batch_size=self.model_cfg['batch_size'], epochs=100, validation_split=va_split if not stratified_split else 0, validation_data=(x_va, y_va) if stratified_split else None, callbacks=[callback] if early_stopping else None) history.history['train_data'] = tr_set_path print(f'finished training in {len(history.history["loss"])} epochs') save(model, le_encoder, save_path, history) self.model = model self.session = session self.graph = graph self.le_encoder = le_encoder # return training history return history.history def __preprocess(self, dataset, le_encoder=None): ''' Preprocess the dataset, transform the categorical labels into numbers. Get word embeddings for the training data. ''' shuffle(dataset) data = [s['data'] for s in dataset] #labels = [s['label'] for s in dataset] labels = [[s['label']] for s in dataset] #le_encoder = preprocessing.LabelEncoder() if le_encoder is None: le_encoder = preprocessing.OneHotEncoder(handle_unknown='ignore', sparse=False) le_encoder.fit(labels) encoded_labels = le_encoder.transform(labels) print('%s intents with %s samples' % (len(le_encoder.get_feature_names()), len(data))) #print('train %s intents with %s samples' % (len(set(labels)), len(data))) #print(collections.Counter(labels)) print(le_encoder.categories_[0]) vectorized_data = tokenize_and_vectorize(self.tokenizer, self.vectors, data, self.model_cfg['embedding_dims']) # split_point = int(len(vectorized_data) * .9) x_train = vectorized_data # vectorized_data[:split_point] y_train = encoded_labels # encoded_labels[:split_point] x_train = pad_trunc(x_train, self.model_cfg['maxlen']) x_train = np.reshape(x_train, (len(x_train), self.model_cfg['maxlen'], self.model_cfg['embedding_dims'])) y_train = np.array(y_train) return x_train, y_train, le_encoder def __build_model(self, num_classes=2, type='keras'): print('Build model') model = Sequential() layers = self.model_cfg.get('layers', 1) for l in range(layers): self.__addLayers(model, self.model_cfg) model.add(Dense(num_classes)) model.add(Activation('softmax')) return model def __addLayers(self, model, model_cfg): maxlen = model_cfg.get('maxlen', 400) strides = model_cfg.get('strides', 1) embedding_dims = model_cfg.get('embedding_dims', 300) filters = model_cfg.get('filters', 250) activation_type = model_cfg.get('activation', 'relu') kernel_size = model_cfg.get('kernel_size', 3) hidden_dims = model_cfg.get('hidden_dims', 200) model.add(Conv1D( filters, kernel_size, padding='valid', activation=activation_type, strides=strides, input_shape=(maxlen, embedding_dims))) model.add(GlobalMaxPooling1D()) model.add(Dense(hidden_dims)) model.add(Activation(activation_type)) def load(self, path): K.clear_session() graph = tf.Graph() with graph.as_default(): session = tf.Session() with session.as_default(): self.session = session self.graph = graph (model, le) = load(path) self.model = model self.le_encoder = le def predict(self, input: List[str]): vectorized_data = tokenize_and_vectorize(self.tokenizer, self.vectors, input, self.model_cfg['embedding_dims']) x_train = pad_trunc(vectorized_data, self.model_cfg['maxlen']) vectorized_input = np.reshape(x_train, (len(x_train), self.model_cfg['maxlen'], self.model_cfg['embedding_dims'])) (probs, preds) = predict(self.session, self.graph, self.model, vectorized_input, len(self.le_encoder.categories_[0])) probs = probs.tolist() results = self.le_encoder.inverse_transform(preds) output = [{'input': input[i], 'embeddings': x_train[i], #'label': r, 'label': r.item(), 'highestProb': max(probs[i]), #'prob': dict(zip(self.le_encoder.classes_, probs[i])) 'prob': dict(zip(self.le_encoder.categories_[0], probs[i])) } for i, r in enumerate(results)] return output
temp = sample
conditional_block
mod.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use crate::{ command_utils::get_worker_api_direct, get_layer_two_nonce, trusted_command_utils::{ decode_balance, get_identifiers, get_keystore_path, get_pair_from_str, }, trusted_commands::TrustedArgs, trusted_operation::{get_json_request, get_state, perform_trusted_operation, wait_until}, Cli, }; use codec::Decode; use hdrhistogram::Histogram; use ita_stf::{Getter, Index, KeyPair, TrustedCall, TrustedGetter, TrustedOperation}; use itc_rpc_client::direct_client::{DirectApi, DirectClient}; use itp_types::{ Balance, ShardIdentifier, TrustedOperationStatus, TrustedOperationStatus::{InSidechainBlock, Submitted}, }; use log::*; use rand::Rng; use rayon::prelude::*; use sgx_crypto_helper::rsa3072::Rsa3072PubKey; use sp_application_crypto::sr25519; use sp_core::{sr25519 as sr25519_core, Pair}; use std::{ string::ToString, sync::mpsc::{channel, Receiver}, thread, time, time::Instant, vec::Vec, }; use substrate_client_keystore::{KeystoreExt, LocalKeystore}; // Needs to be above the existential deposit minimum, otherwise an account will not // be created and the state is not increased. const EXISTENTIAL_DEPOSIT: Balance = 1000; #[derive(Parser)] pub struct BenchmarkCommands { /// The number of clients (=threads) to be used in the benchmark #[clap(default_value_t = 10)] number_clients: u32, /// The number of iterations to execute for each client #[clap(default_value_t = 30)] number_iterations: u32, /// Adds a random wait before each transaction. This is the lower bound for the interval in ms. #[clap(default_value_t = 0)] random_wait_before_transaction_min_ms: u32, /// Adds a random wait before each transaction. This is the upper bound for the interval in ms. #[clap(default_value_t = 0)] random_wait_before_transaction_max_ms: u32, /// Whether to wait for "InSidechainBlock" confirmation for each transaction #[clap(short, long)] wait_for_confirmation: bool, /// Account to be used for initial funding of generated accounts used in benchmark #[clap(default_value_t = String::from("//Alice"))] funding_account: String, } struct BenchmarkClient { account: sr25519_core::Pair, current_balance: u128, client_api: DirectClient, receiver: Receiver<String>, } impl BenchmarkClient { fn new( account: sr25519_core::Pair, initial_balance: u128, initial_request: String, cli: &Cli, ) -> Self { debug!("get direct api"); let client_api = get_worker_api_direct(cli); debug!("setup sender and receiver"); let (sender, receiver) = channel(); client_api.watch(initial_request, sender); BenchmarkClient { account, current_balance: initial_balance, client_api, receiver } } } /// Stores timing information about a specific transaction struct BenchmarkTransaction { started: Instant, submitted: Instant, confirmed: Option<Instant>, } impl BenchmarkCommands { pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedArgs) { let random_wait_before_transaction_ms: (u32, u32) = ( self.random_wait_before_transaction_min_ms, self.random_wait_before_transaction_max_ms, ); let store = LocalKeystore::open(get_keystore_path(trusted_args), None).unwrap(); let funding_account_keys = get_pair_from_str(trusted_args, &self.funding_account); let (mrenclave, shard) = get_identifiers(trusted_args); // Get shielding pubkey. let worker_api_direct = get_worker_api_direct(cli); let shielding_pubkey: Rsa3072PubKey = match worker_api_direct.get_rsa_pubkey() { Ok(key) => key, Err(err_msg) => panic!("{}", err_msg.to_string()), }; let nonce_start = get_layer_two_nonce!(funding_account_keys, cli, trusted_args); println!("Nonce for account {}: {}", self.funding_account, nonce_start); let mut accounts = Vec::new(); // Setup new accounts and initialize them with money from Alice. for i in 0..self.number_clients { let nonce = i + nonce_start; println!("Initializing account {}", i); // Create new account to use. let a: sr25519::AppPair = store.generate().unwrap(); let account = get_pair_from_str(trusted_args, a.public().to_string().as_str()); let initial_balance = 10000000; // Transfer amount from Alice to new account. let top: TrustedOperation = TrustedCall::balance_transfer( funding_account_keys.public().into(), account.public().into(), initial_balance, ) .sign(&KeyPair::Sr25519(funding_account_keys.clone()), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); // For the last account we wait for confirmation in order to ensure all accounts were setup correctly let wait_for_confirmation = i == self.number_clients - 1; let account_funding_request = get_json_request(shard, &top, shielding_pubkey); let client = BenchmarkClient::new(account, initial_balance, account_funding_request, cli); let _result = wait_for_top_confirmation(wait_for_confirmation, &client); accounts.push(client); } rayon::ThreadPoolBuilder::new() .num_threads(self.number_clients as usize) .build_global() .unwrap(); let overall_start = Instant::now(); // Run actual benchmark logic, in parallel, for each account initialized above. let outputs: Vec<Vec<BenchmarkTransaction>> = accounts .into_par_iter() .map(move |mut client| { let mut output: Vec<BenchmarkTransaction> = Vec::new(); for i in 0..self.number_iterations { println!("Iteration: {}", i); if random_wait_before_transaction_ms.1 > 0 { random_wait(random_wait_before_transaction_ms); } // Create new account. let account_keys: sr25519::AppPair = store.generate().unwrap(); let new_account = get_pair_from_str(trusted_args, account_keys.public().to_string().as_str()); println!(" Transfer amount: {}", EXISTENTIAL_DEPOSIT); println!(" From: {:?}", client.account.public()); println!(" To: {:?}", new_account.public()); // Get nonce of account. let nonce = get_nonce(client.account.clone(), shard, &client.client_api); // Transfer money from client account to new account. let top: TrustedOperation = TrustedCall::balance_transfer( client.account.public().into(), new_account.public().into(), EXISTENTIAL_DEPOSIT, ) .sign(&KeyPair::Sr25519(client.account.clone()), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); let last_iteration = i == self.number_iterations - 1; let jsonrpc_call = get_json_request(shard, &top, shielding_pubkey); client.client_api.send(&jsonrpc_call).unwrap(); let result = wait_for_top_confirmation( self.wait_for_confirmation || last_iteration, &client, ); client.current_balance -= EXISTENTIAL_DEPOSIT; let balance = get_balance(client.account.clone(), shard, &client.client_api); println!("Balance: {}", balance.unwrap_or_default()); assert_eq!(client.current_balance, balance.unwrap()); output.push(result); // FIXME: We probably should re-fund the account in this case. if client.current_balance <= EXISTENTIAL_DEPOSIT { error!("Account {:?} does not have enough balance anymore. Finishing benchmark early", client.account.public()); break; } } client.client_api.close().unwrap(); output }) .collect(); println!( "Finished benchmark with {} clients and {} transactions in {} ms", self.number_clients, self.number_iterations, overall_start.elapsed().as_millis() ); print_benchmark_statistic(outputs, self.wait_for_confirmation) } } fn get_balance( account: sr25519::Pair, shard: ShardIdentifier, direct_client: &DirectClient, ) -> Option<u128> { let getter = Getter::trusted( TrustedGetter::free_balance(account.public().into()) .sign(&KeyPair::Sr25519(account.clone())), ); let getter_start_timer = Instant::now(); let getter_result = get_state(direct_client, shard, &getter); let getter_execution_time = getter_start_timer.elapsed().as_millis(); let balance = decode_balance(getter_result); info!("Balance getter execution took {} ms", getter_execution_time,); debug!("Retrieved {:?} Balance for {:?}", balance.unwrap_or_default(), account.public()); balance } fn
( account: sr25519::Pair, shard: ShardIdentifier, direct_client: &DirectClient, ) -> Index { let getter = Getter::trusted( TrustedGetter::nonce(account.public().into()).sign(&KeyPair::Sr25519(account.clone())), ); let getter_start_timer = Instant::now(); let getter_result = get_state(direct_client, shard, &getter); let getter_execution_time = getter_start_timer.elapsed().as_millis(); let nonce = match getter_result { Some(encoded_nonce) => Index::decode(&mut encoded_nonce.as_slice()).unwrap(), None => Default::default(), }; info!("Nonce getter execution took {} ms", getter_execution_time,); debug!("Retrieved {:?} nonce for {:?}", nonce, account.public()); nonce } fn print_benchmark_statistic(outputs: Vec<Vec<BenchmarkTransaction>>, wait_for_confirmation: bool) { let mut hist = Histogram::<u64>::new(1).unwrap(); for output in outputs { for t in output { let benchmarked_timestamp = if wait_for_confirmation { t.confirmed } else { Some(t.submitted) }; if let Some(confirmed) = benchmarked_timestamp { hist += confirmed.duration_since(t.started).as_millis() as u64; } else { println!("Missing measurement data"); } } } for i in (5..=100).step_by(5) { let text = format!( "{} percent are done within {} ms", i, hist.value_at_quantile(i as f64 / 100.0) ); println!("{}", text); } } fn random_wait(random_wait_before_transaction_ms: (u32, u32)) { let mut rng = rand::thread_rng(); let sleep_time = time::Duration::from_millis( rng.gen_range(random_wait_before_transaction_ms.0..=random_wait_before_transaction_ms.1) .into(), ); println!("Sleep for: {}ms", sleep_time.as_millis()); thread::sleep(sleep_time); } fn wait_for_top_confirmation( wait_for_sidechain_block: bool, client: &BenchmarkClient, ) -> BenchmarkTransaction { let started = Instant::now(); let submitted = wait_until(&client.receiver, is_submitted); let confirmed = if wait_for_sidechain_block { // We wait for the transaction hash that actually matches the submitted hash loop { let transaction_information = wait_until(&client.receiver, is_sidechain_block); if let Some((hash, _)) = transaction_information { if hash == submitted.unwrap().0 { break transaction_information } } } } else { None }; if let (Some(s), Some(c)) = (submitted, confirmed) { // Assert the two hashes are identical assert_eq!(s.0, c.0); } BenchmarkTransaction { started, submitted: submitted.unwrap().1, confirmed: confirmed.map(|v| v.1), } } fn is_submitted(s: TrustedOperationStatus) -> bool { matches!(s, Submitted) } fn is_sidechain_block(s: TrustedOperationStatus) -> bool { matches!(s, InSidechainBlock(_)) }
get_nonce
identifier_name
mod.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use crate::{ command_utils::get_worker_api_direct, get_layer_two_nonce, trusted_command_utils::{ decode_balance, get_identifiers, get_keystore_path, get_pair_from_str, }, trusted_commands::TrustedArgs, trusted_operation::{get_json_request, get_state, perform_trusted_operation, wait_until}, Cli, }; use codec::Decode; use hdrhistogram::Histogram; use ita_stf::{Getter, Index, KeyPair, TrustedCall, TrustedGetter, TrustedOperation}; use itc_rpc_client::direct_client::{DirectApi, DirectClient}; use itp_types::{ Balance, ShardIdentifier, TrustedOperationStatus, TrustedOperationStatus::{InSidechainBlock, Submitted}, }; use log::*; use rand::Rng; use rayon::prelude::*; use sgx_crypto_helper::rsa3072::Rsa3072PubKey; use sp_application_crypto::sr25519; use sp_core::{sr25519 as sr25519_core, Pair}; use std::{ string::ToString, sync::mpsc::{channel, Receiver}, thread, time, time::Instant, vec::Vec, }; use substrate_client_keystore::{KeystoreExt, LocalKeystore}; // Needs to be above the existential deposit minimum, otherwise an account will not // be created and the state is not increased. const EXISTENTIAL_DEPOSIT: Balance = 1000; #[derive(Parser)] pub struct BenchmarkCommands { /// The number of clients (=threads) to be used in the benchmark #[clap(default_value_t = 10)] number_clients: u32, /// The number of iterations to execute for each client #[clap(default_value_t = 30)] number_iterations: u32, /// Adds a random wait before each transaction. This is the lower bound for the interval in ms. #[clap(default_value_t = 0)] random_wait_before_transaction_min_ms: u32, /// Adds a random wait before each transaction. This is the upper bound for the interval in ms. #[clap(default_value_t = 0)] random_wait_before_transaction_max_ms: u32, /// Whether to wait for "InSidechainBlock" confirmation for each transaction #[clap(short, long)] wait_for_confirmation: bool, /// Account to be used for initial funding of generated accounts used in benchmark #[clap(default_value_t = String::from("//Alice"))] funding_account: String, } struct BenchmarkClient { account: sr25519_core::Pair, current_balance: u128, client_api: DirectClient, receiver: Receiver<String>, } impl BenchmarkClient { fn new( account: sr25519_core::Pair, initial_balance: u128, initial_request: String, cli: &Cli, ) -> Self { debug!("get direct api"); let client_api = get_worker_api_direct(cli); debug!("setup sender and receiver"); let (sender, receiver) = channel(); client_api.watch(initial_request, sender); BenchmarkClient { account, current_balance: initial_balance, client_api, receiver } } } /// Stores timing information about a specific transaction struct BenchmarkTransaction { started: Instant, submitted: Instant, confirmed: Option<Instant>, } impl BenchmarkCommands { pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedArgs) { let random_wait_before_transaction_ms: (u32, u32) = ( self.random_wait_before_transaction_min_ms, self.random_wait_before_transaction_max_ms, ); let store = LocalKeystore::open(get_keystore_path(trusted_args), None).unwrap(); let funding_account_keys = get_pair_from_str(trusted_args, &self.funding_account); let (mrenclave, shard) = get_identifiers(trusted_args); // Get shielding pubkey. let worker_api_direct = get_worker_api_direct(cli); let shielding_pubkey: Rsa3072PubKey = match worker_api_direct.get_rsa_pubkey() { Ok(key) => key, Err(err_msg) => panic!("{}", err_msg.to_string()), }; let nonce_start = get_layer_two_nonce!(funding_account_keys, cli, trusted_args); println!("Nonce for account {}: {}", self.funding_account, nonce_start); let mut accounts = Vec::new(); // Setup new accounts and initialize them with money from Alice. for i in 0..self.number_clients { let nonce = i + nonce_start; println!("Initializing account {}", i); // Create new account to use. let a: sr25519::AppPair = store.generate().unwrap(); let account = get_pair_from_str(trusted_args, a.public().to_string().as_str()); let initial_balance = 10000000; // Transfer amount from Alice to new account. let top: TrustedOperation = TrustedCall::balance_transfer( funding_account_keys.public().into(), account.public().into(), initial_balance, ) .sign(&KeyPair::Sr25519(funding_account_keys.clone()), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); // For the last account we wait for confirmation in order to ensure all accounts were setup correctly let wait_for_confirmation = i == self.number_clients - 1; let account_funding_request = get_json_request(shard, &top, shielding_pubkey); let client = BenchmarkClient::new(account, initial_balance, account_funding_request, cli); let _result = wait_for_top_confirmation(wait_for_confirmation, &client); accounts.push(client); } rayon::ThreadPoolBuilder::new() .num_threads(self.number_clients as usize) .build_global() .unwrap(); let overall_start = Instant::now(); // Run actual benchmark logic, in parallel, for each account initialized above. let outputs: Vec<Vec<BenchmarkTransaction>> = accounts .into_par_iter() .map(move |mut client| { let mut output: Vec<BenchmarkTransaction> = Vec::new(); for i in 0..self.number_iterations { println!("Iteration: {}", i); if random_wait_before_transaction_ms.1 > 0
// Create new account. let account_keys: sr25519::AppPair = store.generate().unwrap(); let new_account = get_pair_from_str(trusted_args, account_keys.public().to_string().as_str()); println!(" Transfer amount: {}", EXISTENTIAL_DEPOSIT); println!(" From: {:?}", client.account.public()); println!(" To: {:?}", new_account.public()); // Get nonce of account. let nonce = get_nonce(client.account.clone(), shard, &client.client_api); // Transfer money from client account to new account. let top: TrustedOperation = TrustedCall::balance_transfer( client.account.public().into(), new_account.public().into(), EXISTENTIAL_DEPOSIT, ) .sign(&KeyPair::Sr25519(client.account.clone()), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); let last_iteration = i == self.number_iterations - 1; let jsonrpc_call = get_json_request(shard, &top, shielding_pubkey); client.client_api.send(&jsonrpc_call).unwrap(); let result = wait_for_top_confirmation( self.wait_for_confirmation || last_iteration, &client, ); client.current_balance -= EXISTENTIAL_DEPOSIT; let balance = get_balance(client.account.clone(), shard, &client.client_api); println!("Balance: {}", balance.unwrap_or_default()); assert_eq!(client.current_balance, balance.unwrap()); output.push(result); // FIXME: We probably should re-fund the account in this case. if client.current_balance <= EXISTENTIAL_DEPOSIT { error!("Account {:?} does not have enough balance anymore. Finishing benchmark early", client.account.public()); break; } } client.client_api.close().unwrap(); output }) .collect(); println!( "Finished benchmark with {} clients and {} transactions in {} ms", self.number_clients, self.number_iterations, overall_start.elapsed().as_millis() ); print_benchmark_statistic(outputs, self.wait_for_confirmation) } } fn get_balance( account: sr25519::Pair, shard: ShardIdentifier, direct_client: &DirectClient, ) -> Option<u128> { let getter = Getter::trusted( TrustedGetter::free_balance(account.public().into()) .sign(&KeyPair::Sr25519(account.clone())), ); let getter_start_timer = Instant::now(); let getter_result = get_state(direct_client, shard, &getter); let getter_execution_time = getter_start_timer.elapsed().as_millis(); let balance = decode_balance(getter_result); info!("Balance getter execution took {} ms", getter_execution_time,); debug!("Retrieved {:?} Balance for {:?}", balance.unwrap_or_default(), account.public()); balance } fn get_nonce( account: sr25519::Pair, shard: ShardIdentifier, direct_client: &DirectClient, ) -> Index { let getter = Getter::trusted( TrustedGetter::nonce(account.public().into()).sign(&KeyPair::Sr25519(account.clone())), ); let getter_start_timer = Instant::now(); let getter_result = get_state(direct_client, shard, &getter); let getter_execution_time = getter_start_timer.elapsed().as_millis(); let nonce = match getter_result { Some(encoded_nonce) => Index::decode(&mut encoded_nonce.as_slice()).unwrap(), None => Default::default(), }; info!("Nonce getter execution took {} ms", getter_execution_time,); debug!("Retrieved {:?} nonce for {:?}", nonce, account.public()); nonce } fn print_benchmark_statistic(outputs: Vec<Vec<BenchmarkTransaction>>, wait_for_confirmation: bool) { let mut hist = Histogram::<u64>::new(1).unwrap(); for output in outputs { for t in output { let benchmarked_timestamp = if wait_for_confirmation { t.confirmed } else { Some(t.submitted) }; if let Some(confirmed) = benchmarked_timestamp { hist += confirmed.duration_since(t.started).as_millis() as u64; } else { println!("Missing measurement data"); } } } for i in (5..=100).step_by(5) { let text = format!( "{} percent are done within {} ms", i, hist.value_at_quantile(i as f64 / 100.0) ); println!("{}", text); } } fn random_wait(random_wait_before_transaction_ms: (u32, u32)) { let mut rng = rand::thread_rng(); let sleep_time = time::Duration::from_millis( rng.gen_range(random_wait_before_transaction_ms.0..=random_wait_before_transaction_ms.1) .into(), ); println!("Sleep for: {}ms", sleep_time.as_millis()); thread::sleep(sleep_time); } fn wait_for_top_confirmation( wait_for_sidechain_block: bool, client: &BenchmarkClient, ) -> BenchmarkTransaction { let started = Instant::now(); let submitted = wait_until(&client.receiver, is_submitted); let confirmed = if wait_for_sidechain_block { // We wait for the transaction hash that actually matches the submitted hash loop { let transaction_information = wait_until(&client.receiver, is_sidechain_block); if let Some((hash, _)) = transaction_information { if hash == submitted.unwrap().0 { break transaction_information } } } } else { None }; if let (Some(s), Some(c)) = (submitted, confirmed) { // Assert the two hashes are identical assert_eq!(s.0, c.0); } BenchmarkTransaction { started, submitted: submitted.unwrap().1, confirmed: confirmed.map(|v| v.1), } } fn is_submitted(s: TrustedOperationStatus) -> bool { matches!(s, Submitted) } fn is_sidechain_block(s: TrustedOperationStatus) -> bool { matches!(s, InSidechainBlock(_)) }
{ random_wait(random_wait_before_transaction_ms); }
conditional_block
mod.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use crate::{ command_utils::get_worker_api_direct, get_layer_two_nonce, trusted_command_utils::{ decode_balance, get_identifiers, get_keystore_path, get_pair_from_str, }, trusted_commands::TrustedArgs, trusted_operation::{get_json_request, get_state, perform_trusted_operation, wait_until}, Cli, }; use codec::Decode; use hdrhistogram::Histogram; use ita_stf::{Getter, Index, KeyPair, TrustedCall, TrustedGetter, TrustedOperation}; use itc_rpc_client::direct_client::{DirectApi, DirectClient}; use itp_types::{ Balance, ShardIdentifier, TrustedOperationStatus, TrustedOperationStatus::{InSidechainBlock, Submitted}, }; use log::*; use rand::Rng; use rayon::prelude::*; use sgx_crypto_helper::rsa3072::Rsa3072PubKey; use sp_application_crypto::sr25519; use sp_core::{sr25519 as sr25519_core, Pair}; use std::{ string::ToString, sync::mpsc::{channel, Receiver}, thread, time, time::Instant, vec::Vec, }; use substrate_client_keystore::{KeystoreExt, LocalKeystore}; // Needs to be above the existential deposit minimum, otherwise an account will not // be created and the state is not increased. const EXISTENTIAL_DEPOSIT: Balance = 1000; #[derive(Parser)] pub struct BenchmarkCommands { /// The number of clients (=threads) to be used in the benchmark #[clap(default_value_t = 10)] number_clients: u32, /// The number of iterations to execute for each client #[clap(default_value_t = 30)] number_iterations: u32, /// Adds a random wait before each transaction. This is the lower bound for the interval in ms. #[clap(default_value_t = 0)] random_wait_before_transaction_min_ms: u32, /// Adds a random wait before each transaction. This is the upper bound for the interval in ms. #[clap(default_value_t = 0)] random_wait_before_transaction_max_ms: u32, /// Whether to wait for "InSidechainBlock" confirmation for each transaction #[clap(short, long)] wait_for_confirmation: bool, /// Account to be used for initial funding of generated accounts used in benchmark #[clap(default_value_t = String::from("//Alice"))] funding_account: String, } struct BenchmarkClient { account: sr25519_core::Pair, current_balance: u128, client_api: DirectClient, receiver: Receiver<String>, } impl BenchmarkClient { fn new( account: sr25519_core::Pair, initial_balance: u128, initial_request: String, cli: &Cli, ) -> Self { debug!("get direct api"); let client_api = get_worker_api_direct(cli); debug!("setup sender and receiver"); let (sender, receiver) = channel(); client_api.watch(initial_request, sender); BenchmarkClient { account, current_balance: initial_balance, client_api, receiver } } } /// Stores timing information about a specific transaction struct BenchmarkTransaction { started: Instant, submitted: Instant, confirmed: Option<Instant>, } impl BenchmarkCommands { pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedArgs) { let random_wait_before_transaction_ms: (u32, u32) = ( self.random_wait_before_transaction_min_ms, self.random_wait_before_transaction_max_ms, ); let store = LocalKeystore::open(get_keystore_path(trusted_args), None).unwrap(); let funding_account_keys = get_pair_from_str(trusted_args, &self.funding_account); let (mrenclave, shard) = get_identifiers(trusted_args); // Get shielding pubkey. let worker_api_direct = get_worker_api_direct(cli); let shielding_pubkey: Rsa3072PubKey = match worker_api_direct.get_rsa_pubkey() { Ok(key) => key, Err(err_msg) => panic!("{}", err_msg.to_string()), }; let nonce_start = get_layer_two_nonce!(funding_account_keys, cli, trusted_args); println!("Nonce for account {}: {}", self.funding_account, nonce_start); let mut accounts = Vec::new(); // Setup new accounts and initialize them with money from Alice. for i in 0..self.number_clients { let nonce = i + nonce_start; println!("Initializing account {}", i); // Create new account to use. let a: sr25519::AppPair = store.generate().unwrap(); let account = get_pair_from_str(trusted_args, a.public().to_string().as_str()); let initial_balance = 10000000; // Transfer amount from Alice to new account. let top: TrustedOperation = TrustedCall::balance_transfer( funding_account_keys.public().into(), account.public().into(), initial_balance, ) .sign(&KeyPair::Sr25519(funding_account_keys.clone()), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); // For the last account we wait for confirmation in order to ensure all accounts were setup correctly let wait_for_confirmation = i == self.number_clients - 1; let account_funding_request = get_json_request(shard, &top, shielding_pubkey); let client = BenchmarkClient::new(account, initial_balance, account_funding_request, cli); let _result = wait_for_top_confirmation(wait_for_confirmation, &client); accounts.push(client); } rayon::ThreadPoolBuilder::new() .num_threads(self.number_clients as usize) .build_global() .unwrap(); let overall_start = Instant::now(); // Run actual benchmark logic, in parallel, for each account initialized above. let outputs: Vec<Vec<BenchmarkTransaction>> = accounts .into_par_iter() .map(move |mut client| { let mut output: Vec<BenchmarkTransaction> = Vec::new(); for i in 0..self.number_iterations { println!("Iteration: {}", i); if random_wait_before_transaction_ms.1 > 0 { random_wait(random_wait_before_transaction_ms); } // Create new account. let account_keys: sr25519::AppPair = store.generate().unwrap(); let new_account = get_pair_from_str(trusted_args, account_keys.public().to_string().as_str()); println!(" Transfer amount: {}", EXISTENTIAL_DEPOSIT); println!(" From: {:?}", client.account.public()); println!(" To: {:?}", new_account.public()); // Get nonce of account. let nonce = get_nonce(client.account.clone(), shard, &client.client_api); // Transfer money from client account to new account. let top: TrustedOperation = TrustedCall::balance_transfer( client.account.public().into(), new_account.public().into(), EXISTENTIAL_DEPOSIT, ) .sign(&KeyPair::Sr25519(client.account.clone()), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); let last_iteration = i == self.number_iterations - 1; let jsonrpc_call = get_json_request(shard, &top, shielding_pubkey); client.client_api.send(&jsonrpc_call).unwrap(); let result = wait_for_top_confirmation( self.wait_for_confirmation || last_iteration, &client, ); client.current_balance -= EXISTENTIAL_DEPOSIT; let balance = get_balance(client.account.clone(), shard, &client.client_api); println!("Balance: {}", balance.unwrap_or_default()); assert_eq!(client.current_balance, balance.unwrap()); output.push(result); // FIXME: We probably should re-fund the account in this case. if client.current_balance <= EXISTENTIAL_DEPOSIT { error!("Account {:?} does not have enough balance anymore. Finishing benchmark early", client.account.public());
output }) .collect(); println!( "Finished benchmark with {} clients and {} transactions in {} ms", self.number_clients, self.number_iterations, overall_start.elapsed().as_millis() ); print_benchmark_statistic(outputs, self.wait_for_confirmation) } } fn get_balance( account: sr25519::Pair, shard: ShardIdentifier, direct_client: &DirectClient, ) -> Option<u128> { let getter = Getter::trusted( TrustedGetter::free_balance(account.public().into()) .sign(&KeyPair::Sr25519(account.clone())), ); let getter_start_timer = Instant::now(); let getter_result = get_state(direct_client, shard, &getter); let getter_execution_time = getter_start_timer.elapsed().as_millis(); let balance = decode_balance(getter_result); info!("Balance getter execution took {} ms", getter_execution_time,); debug!("Retrieved {:?} Balance for {:?}", balance.unwrap_or_default(), account.public()); balance } fn get_nonce( account: sr25519::Pair, shard: ShardIdentifier, direct_client: &DirectClient, ) -> Index { let getter = Getter::trusted( TrustedGetter::nonce(account.public().into()).sign(&KeyPair::Sr25519(account.clone())), ); let getter_start_timer = Instant::now(); let getter_result = get_state(direct_client, shard, &getter); let getter_execution_time = getter_start_timer.elapsed().as_millis(); let nonce = match getter_result { Some(encoded_nonce) => Index::decode(&mut encoded_nonce.as_slice()).unwrap(), None => Default::default(), }; info!("Nonce getter execution took {} ms", getter_execution_time,); debug!("Retrieved {:?} nonce for {:?}", nonce, account.public()); nonce } fn print_benchmark_statistic(outputs: Vec<Vec<BenchmarkTransaction>>, wait_for_confirmation: bool) { let mut hist = Histogram::<u64>::new(1).unwrap(); for output in outputs { for t in output { let benchmarked_timestamp = if wait_for_confirmation { t.confirmed } else { Some(t.submitted) }; if let Some(confirmed) = benchmarked_timestamp { hist += confirmed.duration_since(t.started).as_millis() as u64; } else { println!("Missing measurement data"); } } } for i in (5..=100).step_by(5) { let text = format!( "{} percent are done within {} ms", i, hist.value_at_quantile(i as f64 / 100.0) ); println!("{}", text); } } fn random_wait(random_wait_before_transaction_ms: (u32, u32)) { let mut rng = rand::thread_rng(); let sleep_time = time::Duration::from_millis( rng.gen_range(random_wait_before_transaction_ms.0..=random_wait_before_transaction_ms.1) .into(), ); println!("Sleep for: {}ms", sleep_time.as_millis()); thread::sleep(sleep_time); } fn wait_for_top_confirmation( wait_for_sidechain_block: bool, client: &BenchmarkClient, ) -> BenchmarkTransaction { let started = Instant::now(); let submitted = wait_until(&client.receiver, is_submitted); let confirmed = if wait_for_sidechain_block { // We wait for the transaction hash that actually matches the submitted hash loop { let transaction_information = wait_until(&client.receiver, is_sidechain_block); if let Some((hash, _)) = transaction_information { if hash == submitted.unwrap().0 { break transaction_information } } } } else { None }; if let (Some(s), Some(c)) = (submitted, confirmed) { // Assert the two hashes are identical assert_eq!(s.0, c.0); } BenchmarkTransaction { started, submitted: submitted.unwrap().1, confirmed: confirmed.map(|v| v.1), } } fn is_submitted(s: TrustedOperationStatus) -> bool { matches!(s, Submitted) } fn is_sidechain_block(s: TrustedOperationStatus) -> bool { matches!(s, InSidechainBlock(_)) }
break; } } client.client_api.close().unwrap();
random_line_split
app.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import math from scipy.misc import comb from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler,LabelEncoder from sklearn.model_selection import cross_val_score from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline from sklearn.metrics import accuracy_score from MajorityVowteClassifier import MajoritVoteClassifier # 获取数据并且将y值量化 iris = datasets.load_iris() X,y = iris.data[50:,[1,2]],iris.target[50:] le = LabelEncoder() y = le.fit_transform(y) # 划分数据集 X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.5,random_state=1,stratify=y) def ensemble_error(n_classifier,error): ''' 集成分类器误差率计算 :param n_classifier: 分类器个数 :param error: 单个分类器的误差率 :return: 集成分类器误差率 ''' k_start = int(math.ceil(n_classifier/2.)) probs = [comb(n_classifier,k)*(error**k)*(1-error)**(n_classifier-k) for k in range(k_start,n_classifier+1)] return sum(probs) # 绘制集成分类器和单个分类器随着单个分类器的误差率变化而变化的曲线 def function1(): error_range = np.arange(0.0,1.01,0.1) ens_errors = [ensemble_error(n_classifier=11,error=error) for error in error_range] plt.plot(error_range,error_range,linestyle='--',label='base error',lw='2') plt.plot(error_range,ens_errors,label='ensemble error',lw='2') plt.xlabel("base error") plt.ylabel("base/ensemble error") plt.legend(loc='upper left') plt.grid(alpha=0.5) plt.show() #################集成分类器---简单投票分类器################################## # 使用k-折交叉验证评估各评估器的性能 def function2(): clf1 = LogisticRegression(penalty='l2',C=0.001,random_state=1) clf2 = DecisionTreeClassifier(max_depth=1,criterion='entropy',random_state=0) clf3 = KNeighborsClassifier(n_neighbors=1,p=2,metric='minkowski') pipe1 = Pipeline([['sc',StandardScaler()],['clf',clf1]]) pipe3 = Pipeline([['sc',StandardScaler()],['clf',clf3]]) mv_clf = MajoritVoteClassifier(classifiers=[pipe1,clf2,pipe3]) clf_labels = ['logistic regression','decision tree','KNN','majority voting'] all_clf = [pipe1,clf2,pipe3,mv_clf] print("10-fold cross validation:\n") for clf,label in zip(all_clf,clf_labels): scores = cross_val_score(estimator=clf,X=X_train,y=y_train, cv=10,scoring='roc_auc') print("roc auc: %0.2f (+/- %0.2f) [%s]"%(scores.mean(),scores.std(),label)) # 由打印的结果可以看出,集成分类器的性能相对于单个的分类器有质的提升 # 绘制评估器的roc曲线,评估模型性能 from sklearn.metrics import roc_curve from sklearn.metrics import auc colors = ['black','orange','blue','green'] linestyle = [':','--','-.','-'] for clf, label,clr,ls in zip(all_clf,clf_labels,colors,linestyle): y_pred = clf.fit(X_train,y_train).predict_proba(X_test)[:,1] # 假定正分类为1 fpr,tpr,thresholds = roc_curve(y_true=y_test,y_score=y_pred) roc_auc = auc(x=fpr,y=tpr) plt.plot(fpr,tpr,color=clr,linestyle=ls,label='%s (auc=%.2f)' % (label,roc_auc)) plt.legend(loc='lower right') plt.plot([0,1],[0,1],linestyle='--',color='gray',lw=2) # 随机猜测roc曲线 plt.xlim([-0.1,1.1]) plt.ylim([-0.1,1.1]) plt.grid(alpha=0.5) plt.xlabel('false positive rate (fpr)') plt.ylabel('true positive rate (tpr)') plt.show() # 绘制各个评估器的决策边界 sc = StandardScaler() X_train_std = sc.fit_transform(X_train) from itertools import product x1_min = X_train_std[:,0].min()-1 x1_max = X_train_std[:,0].max()+1 x2_min = X_train_std[:,1].min()-1 x2_max = X_train_std[:,1].max()+1 xx1,xx2 = np.meshgrid(np.arange(x1_min,x1_max,0.1), np.arange(x2_min,x2_max,0.1)) f,axarr = plt.subplots(nrows=2,ncols=2, sharex='col',sharey='row', figsize=(7,5)) for idx,clf,tt in zip(product([0,1],[0,1]),all_clf,clf_labels): clf.fit(X_train_std,y_train) Z = clf.predict(np.c_[xx1.ravel(),xx2.ravel()]) Z = Z.reshape(xx1.shape) axarr[idx[0],idx[1]].contourf(xx1,xx2,Z,alpha=0.3) axarr[idx[0],idx[1]].scatter(X_train_std[y_train==0,0], X_train_std[y_train==0,1], c='blue',marker='^',s=50) axarr[idx[0], idx[1]].scatter(X_train_std[y_train == 1, 0], X_train_std[y_train == 1, 1], c='green', marker='o', s=50) axarr[idx[0],idx[1]].set_title(tt) plt.text(-3.5,-4.5,s='sepal width [standardized]',ha='center',va='center',fontsize=12) plt.text(-12.5,4.5,s='sepal length [standardized]',ha='center',va='center',fontsize=12,rotation=90) plt.show() # 集成分类的成员分类器调优 def function3(): clf1 = LogisticRegression(penalty='l2', C=0.001, random_state=1) clf2 = DecisionTreeClassifier(max_depth=1, criterion='entropy', random_state=0) clf3 = KNeighborsClassifier(n_neighbors=1, p=2, metric='minkowski') pipe1 = Pipeline([['sc', StandardScaler()], ['clf', clf1]]) pipe3 = Pipeline([['sc', StandardScaler()], ['clf', clf3]]) mv_clf = MajoritVoteClassifier(classifiers=[pipe1, clf2, pipe3]) # 打印出参数构成 print(mv_clf.get_params()) # 使用网格搜索对决策树深度,逻辑斯谛回归的正则参数进行调优 from sklearn.model_selection import GridSearchCV params = { 'decisiontreeclassifier__max_depth':[1,2], 'pipeline-1__clf__C':[0.001,0.1,100.0] } grid = GridSearchCV(estimator=mv_clf,param_grid=params,cv=10,scoring='roc_auc') grid.fit(X_train,y_train) print("best parameters:%s" % grid.best_params_) print("accuracy : %.2f" % grid.best_score_) #################集成分类器---bagging分类器################################## def function4(): from sklearn.ensemble import BaggingClassifier df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/' 'machine-learning-databases/wine/wine.data', header=None) df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline'] # drop 1 class df_wine = df_wine[df_wine['Class label'] != 1] y = df_wine['Class label'].values X = df_wine[['Alcohol', 'OD280/OD315 of diluted wines']].values le = LabelEncoder() y = le.fit_transform(y) X_train, X_test, y_train, y_test = \ train_test_split(X, y, test_size = 0.2, random_state = 1, stratify = y) tree = DecisionTreeClassifier(criterion='entropy', random_state=1, max_depth=None) bag = BaggingClassifier(base_estimator=tree, n_estimators=500, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, n_jobs=-1, random_state=1) # 使用单颗决策树 tree = tree.fit(X_train,y_train) y_train_pred = tree.predict(X_train) y_test_pred = tree.predict(X_test) tree_train = accuracy_score(y_train, y_train_pred) tree_test = accuracy_score(y_test, y_test_pred) print('Decision tree train/test accuracies %.3f/%.3f'% (tree_train, tree_test)) # 使用bagging集成分类器 bag = bag.fit(X_train, y_train) y_train_pred = bag.predict(X_train) y_test_pred = bag.predict(X_test) bag_train = accuracy_score(y_train, y_train_pred) bag_test = accuracy_score(y_test, y_test_pred) print('Bagging train/test accuracies %.3f/%.3f'% (bag_train, bag_test)) # 绘制两个模型的决策区域 x1_min = X_train[:,0].min()-1 x1_max = X_train[:,0].max()+1 x2_min = X_train[:,1].min()-1 x2_max = X_train[:,1].max()+1 xx1,xx2 = np.meshgrid(np.arange(x1_min,x1_max,0.1),np.arange(x2_min,x2_max)) f,axarr = plt.subplots(nrows=1,ncols=2,sharex='col',sharey='row',figsize=(8,3)) for idx,clf,tt in zip([0,1],[tree,bag],['decision tree','bagging']): clf.fit(X_train,y_train) Z = clf.predict(np.c_[xx1.ravel(),xx2.ravel()]) Z = Z.reshape(xx1.shape) axarr[idx].contourf(xx1,xx2,Z,alpha=0.3) axarr[idx].scatter(X_train[y_train==0,0],X_train[y_train==0,1], c='blue',marker='^') axarr[idx].scatter(X_train[y_train==1,0],X_train[y_train==1,1], c='green',marker='o') axarr[idx].set_title(tt) axarr[0].set_ylabel('alcohol',fontsize=12) plt.text(10.2,-1.2,s='OD280/OD
, 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline'] # drop 1 class df_wine = df_wine[df_wine['Class label'] != 1] y = df_wine['Class label'].values X = df_wine[['Alcohol', 'OD280/OD315 of diluted wines']].values le = LabelEncoder() y = le.fit_transform(y) X_train, X_test, y_train, y_test = \ train_test_split(X, y, test_size=0.2, random_state=1, stratify=y) tree = DecisionTreeClassifier(criterion='entropy', random_state=1, max_depth=1) ada = AdaBoostClassifier(base_estimator=tree, n_estimators=500, learning_rate=0.1, random_state=1) # 单颗决策树(弱学习机) tree = tree.fit(X_train,y_train) y_train_pred = tree.predict(X_train) y_test_pred = tree.predict(X_test) tree_train = accuracy_score(y_train, y_train_pred) tree_test = accuracy_score(y_test, y_test_pred) print('Decision tree train/test accuracies %.3f/%.3f' % (tree_train, tree_test)) # AdaBoost算法 ada = ada.fit(X_train, y_train) y_train_pred = ada.predict(X_train) y_test_pred = ada.predict(X_test) tree_train = accuracy_score(y_train, y_train_pred) tree_test = accuracy_score(y_test, y_test_pred) print('AdaBoost train/test accuracies %.3f/%.3f' % (tree_train, tree_test)) # 绘制两个模型的决策区域 x1_min = X_train[:, 0].min() - 1 x1_max = X_train[:, 0].max() + 1 x2_min = X_train[:, 1].min() - 1 x2_max = X_train[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, 0.1), np.arange(x2_min, x2_max)) f, axarr = plt.subplots(nrows=1, ncols=2, sharex='col', sharey='row', figsize=(8, 3)) for idx, clf, tt in zip([0, 1], [tree, ada], ['decision tree', 'bagging']): clf.fit(X_train, y_train) Z = clf.predict(np.c_[xx1.ravel(), xx2.ravel()]) Z = Z.reshape(xx1.shape) axarr[idx].contourf(xx1, xx2, Z, alpha=0.3) axarr[idx].scatter(X_train[y_train == 0, 0], X_train[y_train == 0, 1], c='blue', marker='^') axarr[idx].scatter(X_train[y_train == 1, 0], X_train[y_train == 1, 1], c='green', marker='o') axarr[idx].set_title(tt) axarr[0].set_ylabel('alcohol', fontsize=12) plt.text(10.2, -1.2, s='OD280/OD315 of diluted wines', ha='center', va='center', fontsize=12) plt.show() if __name__ == "__main__": # function1() # function2() # function3() # function4() function5()
315 of diluted wines', ha='center',va='center',fontsize=12) plt.show() ############################AdaBoost算法############################### # def function5(): from sklearn.ensemble import AdaBoostClassifier df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/' 'machine-learning-databases/wine/wine.data', header=None) df_wine.columns = ['Class label'
conditional_block
app.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import math from scipy.misc import comb from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler,LabelEncoder from sklearn.model_selection import cross_val_score from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline from sklearn.metrics import accuracy_score from MajorityVowteClassifier import MajoritVoteClassifier # 获取数据并且将y值量化 iris = datasets.load_iris() X,y = iris.data[50:,[1,2]],iris.target[50:] le = LabelEncoder() y = le.fit_transform(y) # 划分数据集 X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.5,random_state=1,stratify=y) def ensemble_error(n_classifier,error): ''' 集成分类器误差率计算 :param n_classifier: 分类器个数 :param error: 单个分类器的误差率 :return: 集成分类器误差率 ''' k_start = int(math.ceil(n_classifier/2.)) probs = [comb(n_classifier,k)*(error**k)*(1-error)**(n_classifier-k) for k in range(k_start,n_classifier+1)] return sum(probs) # 绘制集成分类器和单个分类器随着单个分类器的误差率变化而变化的曲线 def function1(): error_range = np.arange(0.0,1.01,0.1) ens_errors = [ensemble_error(n_classifier=11,error=error) for error in error_range] plt.plot(error_range,error_range,linestyle='--',label='base error',lw='2') plt.plot(error_range,ens_errors,label='ensemble error',lw='2') plt.xlabel("base error") plt.ylabel("base/ensemble error") plt.legend(loc='upper left') plt.grid(alpha=0.5) plt.show() #################集成分类器---简单投票分类器################################## # 使用k-折交叉验证评估各评估器的性能 def function2(): clf1 = LogisticRegression(penalty='l2',C=0.001,random_state=1) clf2 = DecisionTreeClassifier(max_depth=1,criterion='entropy',random_state=0) clf3 = KNeighborsClassifier(n_neighbors=1,p=2,metric='minkowski') pipe1 = Pipeline([['sc',StandardScaler()],['clf',clf1]]) pipe3 = Pipeline([['sc',StandardScaler()],['clf',clf3]]) mv_clf = MajoritVoteClassifier(classifiers=[pipe1,clf2,pipe3]) clf_labels = ['logistic regression','decision tree','KNN','majority voting'] all_clf = [pipe1,clf2,pipe3,mv_clf] print("10-fold cross validation:\n") for clf,label in zip(all_clf,clf_labels): scores = cross_val_score(estimator=clf,X=X_train,y=y_train, cv=10,scoring='roc_auc') print("roc auc: %0.2f (+/- %0.2f) [%s]"%(scores.mean(),scores.std(),label)) # 由打印的结果可以看出,集成分类器的性能相对于单个的分类器有质的提升 # 绘制评估器的roc曲线,评估模型性能 from sklearn.metrics import roc_curve from sklearn.metrics import auc colors = ['black','orange','blue','green'] linestyle = [':','--','-.','-'] for clf, label,clr,ls in zip(all_clf,clf_labels,colors,linestyle): y_pred = clf.fit(X_train,y_train).predict_proba(X_test)[:,1] # 假定正分类为1 fpr,tpr,thresholds = roc_curve(y_true=y_test,y_score=y_pred) roc_auc = auc(x=fpr,y=tpr) plt.plot(fpr,tpr,color=clr,linestyle=ls,label='%s (auc=%.2f)' % (label,roc_auc)) plt.legend(loc='lower right') plt.plot([0,1],[0,1],linestyle='--',color='gray',lw=2) # 随机猜测roc曲线 plt.xlim([-0.1,1.1]) plt.ylim([-0.1,1.1]) plt.grid(alpha=0.5) plt.xlabel('false positive rate (fpr)') plt.ylabel('true positive rate (tpr)') plt.show() # 绘制各个评估器的决策边界 sc = StandardScaler() X_train_std = sc.fit_transform(X_train) from itertools import product x1_min = X_train_std[:,0].min()-1 x1_max = X_train_std[:,0].max()+1 x2_min = X_train_std[:,1].min()-1 x2_max = X_train_std[:,1].max()+1 xx1,xx2 = np.meshgrid(np.arange(x1_min,x1_max,0.1), np.arange(x2_min,x2_max,0.1)) f,axarr = plt.subplots(nrows=2,ncols=2, sharex='col',sharey='row', figsize=(7,5)) for idx,clf,tt in zip(product([0,1],[0,1]),all_clf,clf_labels): clf.fit(X_train_std,y_train) Z = clf.predict(np.c_[xx1.ravel(),xx2.ravel()]) Z = Z.reshape(xx1.shape) axarr[idx[0],idx[1]].contourf(xx1,xx2,Z,alpha=0.3) axarr[idx[0],idx[1]].scatter(X_train_std[y_train==0,0], X_train_std[y_train==0,1], c='blue',marker='^',s=50) axarr[idx[0], idx[1]].scatter(X_train_std[y_train == 1, 0], X_train_std[y_train == 1, 1], c='green', marker='o', s=50) axarr[idx[0],idx[1]].set_title(tt) plt.text(-3.5,-4.5,s='sepal width [standardized]',ha='center',va='center',fontsize=12) plt.text(-12.5,4.5,s='sepal length [standardized]',ha='center',va='center',fontsize=12,rotation=90) plt.show() # 集成分类的成员分类器调优 def function3(): clf1 = LogisticRegression(penalty='l2', C=0.001, random_state=1) clf2 = DecisionTreeClassifier(max_depth=1, criterion='entropy', random_state=0) clf3 = KNeighborsClassifier(n_neighbors=1, p=2, metric='minkowski') pipe1 = Pipeline([['sc', StandardScaler()], ['clf', clf1]]) pipe3 = Pipeline([['sc', StandardScaler()], ['clf', clf3]]) mv_clf = MajoritVoteClassifier(classifiers=[pipe1, clf2, pipe3]) # 打印出参数构成 print(mv_clf.get_params()) # 使用网格搜索对决策树深度,逻辑斯谛回归的正则参数进行调优 from sklearn.model_selection import GridSearchCV params = { 'decisiontreeclassifier__max_depth':[1,2], 'pipeline-1__clf__C':[0.001,0.1,100.0] } grid = GridSearchCV(estimator=mv_clf,param_grid=params,cv=10,scoring='roc_auc') grid.fit(X_train,y_train) print("best parameters:%s" % grid.best_params_) print("accuracy : %.2f" % grid.best_score_) #################集成分类器---bagging分类器################################## def function4(): from sklearn.ensemble import BaggingClassifier df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/' 'machine-learning-databases/wine/wine.data', header=None) df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline'] # drop 1 class df_wine = df_wine[df_wine['Class label'] != 1] y = df_wine['Class label'].values X = df_wine[['Alcohol', 'OD280/OD315 of diluted wines']].values le = LabelEncoder() y = le.fit_transform(y) X_train, X_test, y_train, y_test = \ train_test_split(X, y, test_size = 0.2, random_state = 1, stratify = y) tree = DecisionTreeClassifier(criterion='entropy', random_state=1, max_depth=None) bag = BaggingClassifier(base_estimator=tree, n_estimators=500, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, n_jobs=-1, random_state=1) # 使用单颗决策树 tree = tree.fit(X_train,y_train) y_train_pred = tree.predict(X_train) y_test_pred = tree.predict(X_test) tree_train = accuracy_score(y_train, y_train_pred) tree_test = accuracy_score(y_test, y_test_pred) print('Decision tree train/test accuracies %.3f/%.3f'% (tree_train, tree_test)) # 使用bagging集成分类器 bag = bag.fit(X_train, y_train) y_train_pred = bag.predict(X_train) y_test_pred = bag.predict(X_test) bag_train = accuracy_score(y_train, y_train_pred) bag_test = accuracy_score(y_test, y_test_pred) print('Bagging train/test accuracies %.3f/%.3f'% (bag_train, bag_test)) # 绘制两个模型的决策区域 x1_min = X_train[:,0].min()-1 x1_max = X_train[:,0].max()+1 x2_min = X_train[:,1].min()-1 x2_max = X_train[:,1].max()+1 xx1,xx2 = np.meshgrid(np.arange(x1_min,x1_max,0.1),np.arange(x2_min,x2_max)) f,axarr = plt.subplots(nrows=1,ncols=2,sharex='col',sharey='row',figsize=(8,3)) for idx,clf,tt in zip([0,1],[tree,bag],['decision tree','bagging']): clf.fit(X_train,y_train) Z = clf.predict(np.c_[xx1.ravel(),xx2.ravel()]) Z = Z.reshape(xx1.shape) axarr[idx].contourf(xx1,xx2,Z,alpha=0.3) axarr[idx].scatter(X_train[y_train==0,0],X_train[y_train==0,1], c='blue',marker='^') axarr[idx].scatter(X_train[y_train==1,0],X_train[y_train==1,1], c='green',marker='o') axarr[idx].set_title(tt) axarr[0].set_ylabel('alcohol',fontsize=12) plt.text(10.2,-1.2,s='OD280/OD315 of diluted wines', ha='center',va='center',fontsize=12) plt.show() ############################AdaBoost算法############################### # def function5(): from sklearn.ensemble import AdaBoostClassifier df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/' 'machine-learning-databases/wine/wine.data', header=None) df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline'] # drop 1 class df_wine = df_wine[df_wine['Class label'] != 1] y = df_wine['Class label'].values X = df_wine[['Alcohol', 'OD280/OD315 of diluted wines']].values le = LabelEncoder() y = le.fit_transform(y) X_train, X_test, y_train, y_test = \ train_test_split(X, y, test_size=0.2, random_state=1, stratify=y) tree = DecisionTreeClassifier(criterion='entropy', random_state=1, max_depth=1) ada = AdaBoostClassifier(base_estimator=tree,
# 单颗决策树(弱学习机) tree = tree.fit(X_train,y_train) y_train_pred = tree.predict(X_train) y_test_pred = tree.predict(X_test) tree_train = accuracy_score(y_train, y_train_pred) tree_test = accuracy_score(y_test, y_test_pred) print('Decision tree train/test accuracies %.3f/%.3f' % (tree_train, tree_test)) # AdaBoost算法 ada = ada.fit(X_train, y_train) y_train_pred = ada.predict(X_train) y_test_pred = ada.predict(X_test) tree_train = accuracy_score(y_train, y_train_pred) tree_test = accuracy_score(y_test, y_test_pred) print('AdaBoost train/test accuracies %.3f/%.3f' % (tree_train, tree_test)) # 绘制两个模型的决策区域 x1_min = X_train[:, 0].min() - 1 x1_max = X_train[:, 0].max() + 1 x2_min = X_train[:, 1].min() - 1 x2_max = X_train[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, 0.1), np.arange(x2_min, x2_max)) f, axarr = plt.subplots(nrows=1, ncols=2, sharex='col', sharey='row', figsize=(8, 3)) for idx, clf, tt in zip([0, 1], [tree, ada], ['decision tree', 'bagging']): clf.fit(X_train, y_train) Z = clf.predict(np.c_[xx1.ravel(), xx2.ravel()]) Z = Z.reshape(xx1.shape) axarr[idx].contourf(xx1, xx2, Z, alpha=0.3) axarr[idx].scatter(X_train[y_train == 0, 0], X_train[y_train == 0, 1], c='blue', marker='^') axarr[idx].scatter(X_train[y_train == 1, 0], X_train[y_train == 1, 1], c='green', marker='o') axarr[idx].set_title(tt) axarr[0].set_ylabel('alcohol', fontsize=12) plt.text(10.2, -1.2, s='OD280/OD315 of diluted wines', ha='center', va='center', fontsize=12) plt.show() if __name__ == "__main__": # function1() # function2() # function3() # function4() function5()
n_estimators=500, learning_rate=0.1, random_state=1)
random_line_split
app.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import math from scipy.misc import comb from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler,LabelEncoder from sklearn.model_selection import cross_val_score from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline from sklearn.metrics import accuracy_score from MajorityVowteClassifier import MajoritVoteClassifier # 获取数据并且将y值量化 iris = datasets.load_iris() X,y = iris.data[50:,[1,2]],iris.target[50:] le = LabelEncoder() y = le.fit_transform(y) # 划分数据集 X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.5,random_state=1,stratify=y) def ensemble_error(n_classifier,error): ''' 集成分类器误差率计算 :param n_classifier: 分类器个数 :param error: 单个分类器的误差率 :return: 集成分类器误差率 ''' k_start = int(math.ceil(n_classifier/2.)) probs = [comb(n_classifier,k)*(error**k)*(1-error)**(n_classifier-k) for k in range(k_start,n_classifier+1)] return sum(probs) # 绘制集成分类器和单个分类器随着单个分类器的误差率变化而变化的曲线 def function1(): error_range = np.arange(0.0,1.01,0.1) ens_errors = [ensemble_error(n_classifier=11,error=error) for error in error_range] plt.plot(error_range,error_range,linestyle='--',label='base error',lw='2') plt.plot(error_range,ens_errors,label='ensemble error',lw='2') plt.xlabel("base error") plt.ylabel("base/ensemble error") plt.legend(loc='upper left') plt.grid(alpha=0.5) plt.show() #################集成分类器---简单投票分类器################################## # 使用k-折交叉验证评估各评估器的性能 def function2(): clf1 = LogisticRegression(penalty='l2',C=0.001,random_state=1) clf2 = DecisionTreeClassifier(max_depth=1,criterion='entropy',random_state=0) clf3 = KNeighborsClassifier(n_neighbors=1,p=2,metric='minkowski') pipe1 = Pipeline([['sc',StandardScaler()],['clf',clf1]]) pipe3 = Pipeline([['sc',StandardScaler()],['clf',clf3]]) mv_clf = MajoritVoteClassifier(classifiers=[pipe1,clf2,pipe3]) clf_labels = ['logistic regression','decision tree','KNN','majority voting'] all_clf = [pipe1,clf2,pipe3,mv_clf] print("10-fold cross validation:\n") for clf,label in zip(all_clf,clf_labels): scores = cross_val_score(estimator=clf,X=X_train,y=y_train, cv=10,scoring='roc_auc') print("roc auc: %0.2f (+/- %0.2f) [%s]"%(scores.mean(),scores.std(),label)) # 由打印的结果可以看出,集成分类器的性能相对于单个的分类器有质的提升 # 绘制评估器的roc曲线,评估模型性能 from sklearn.metrics import roc_curve from sklearn.metrics import auc colors = ['black','orange','blue','green'] linestyle = [':','--','-.','-'] for clf, label,clr,ls in zip(all_clf,clf_labels,colors,linestyle): y_pred = clf.fit(X_train,y_train).predict_proba(X_test)[:,1] # 假定正分类为1 fpr,tpr,thresholds = roc_curve(y_true=y_test,y_score=y_pred) roc_auc = auc(x=fpr,y=tpr) plt.plot(fpr,tpr,color=clr,linestyle=ls,label='%s (auc=%.2f)' % (label,roc_auc)) plt.legend(loc='lower right') plt.plot([0,1],[0,1],linestyle='--',color='gray',lw=2) # 随机猜测roc曲线 plt.xlim([-0.1,1.1]) plt.ylim([-0.1,1.1]) plt.grid(alpha=0.5) plt.xlabel('false positive rate (fpr)') plt.ylabel('true positive rate (tpr)') plt.show() # 绘制各个评估器的决策边界 sc = StandardScaler() X_train_std = sc.fit_transform(X_train) from itertools import product x1_min = X_train_std[:,0].min()-1 x1_max = X_train_std[:,0].max()+1 x2_min = X_train_std[:,1].min()-1 x2_max = X_train_std[:,1].max()+1 xx1,xx2 = np.meshgrid(np.arange(x1_min,x1_max,0.1), np.arange(x2_min,x2_max,0.1)) f,axarr = plt.subplots(nrows=2,ncols=2, sharex='col',sharey='row', figsize=(7,5)) for idx,clf,tt in zip(product([0,1],[0,1]),all_clf,clf_labels): clf.fit(X_train_std,y_train) Z = clf.predict(np.c_[xx1.ravel(),xx2.ravel()]) Z = Z.reshape(xx1.shape) axarr[idx[0],idx[1]].contourf(xx1,xx2,Z,alpha=0.3) axarr[idx[0],idx[1]].scatter(X_train_std[y_train==0,0], X_train_std[y_train==0,1], c='blue',marker='^',s=50) axarr[idx[0], idx[1]].scatter(X_train_std[y_train == 1, 0], X_train_std[y_train == 1, 1], c='green', marker='o', s=50) axarr[idx[0],idx[1]].set_title(tt) plt.text(-3.5,-4.5,s='sepal width [standardized]',ha='center',va='center',fontsize=12) plt.text(-12.5,4.5,s='sepal length [standardized]',ha='center',va='center',fontsize=12,rotation=90) plt.show() # 集成分类的成员分类器调优 def function3(): clf1 = LogisticRegression(penalty='l2', C=0.001, random_state=1) clf2 = DecisionTreeClassifier(max_depth=1, criterion='entropy', random_state=0) clf3 = KNeighborsClassifier(n_neighbors=1, p=2, metric='minkowski') pipe1 = Pipeline([['sc', StandardScaler()], ['clf', clf1]]) pipe3 = Pipeline([['sc', StandardScaler()], ['clf', clf3]]) mv_clf = MajoritVoteClassifier(classifiers=[pipe1, clf2, pipe3]) # 打印出参数构成 print(mv_clf.get_params()) # 使用网格搜索对决策树深度,逻辑斯谛回归的正则参数进行调优 from sklearn.model_selection import GridSearchCV params = { 'decisiontreeclassifier__max_depth':[1,2], 'pipeline-1__clf__C':[0.001,0.1,100.0] } grid = GridSearchCV(estimator=mv_clf,param_grid=params,cv=10,scoring='roc_auc') grid.fit(X_train,y_train) print("best parameters:%s" % grid.best_params_) print("accuracy : %.2f" % grid.best_score_) #################集成分类器---bagging分类器################################## def function4(): from sklearn.ensemble import BaggingClassifier df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/' 'machine-learning-databases/wine/wine.data', header=None) df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', 'Nonfla
enols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline'] # drop 1 class df_wine = df_wine[df_wine['Class label'] != 1] y = df_wine['Class label'].values X = df_wine[['Alcohol', 'OD280/OD315 of diluted wines']].values le = LabelEncoder() y = le.fit_transform(y) X_train, X_test, y_train, y_test = \ train_test_split(X, y, test_size = 0.2, random_state = 1, stratify = y) tree = DecisionTreeClassifier(criterion='entropy', random_state=1, max_depth=None) bag = BaggingClassifier(base_estimator=tree, n_estimators=500, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, n_jobs=-1, random_state=1) # 使用单颗决策树 tree = tree.fit(X_train,y_train) y_train_pred = tree.predict(X_train) y_test_pred = tree.predict(X_test) tree_train = accuracy_score(y_train, y_train_pred) tree_test = accuracy_score(y_test, y_test_pred) print('Decision tree train/test accuracies %.3f/%.3f'% (tree_train, tree_test)) # 使用bagging集成分类器 bag = bag.fit(X_train, y_train) y_train_pred = bag.predict(X_train) y_test_pred = bag.predict(X_test) bag_train = accuracy_score(y_train, y_train_pred) bag_test = accuracy_score(y_test, y_test_pred) print('Bagging train/test accuracies %.3f/%.3f'% (bag_train, bag_test)) # 绘制两个模型的决策区域 x1_min = X_train[:,0].min()-1 x1_max = X_train[:,0].max()+1 x2_min = X_train[:,1].min()-1 x2_max = X_train[:,1].max()+1 xx1,xx2 = np.meshgrid(np.arange(x1_min,x1_max,0.1),np.arange(x2_min,x2_max)) f,axarr = plt.subplots(nrows=1,ncols=2,sharex='col',sharey='row',figsize=(8,3)) for idx,clf,tt in zip([0,1],[tree,bag],['decision tree','bagging']): clf.fit(X_train,y_train) Z = clf.predict(np.c_[xx1.ravel(),xx2.ravel()]) Z = Z.reshape(xx1.shape) axarr[idx].contourf(xx1,xx2,Z,alpha=0.3) axarr[idx].scatter(X_train[y_train==0,0],X_train[y_train==0,1], c='blue',marker='^') axarr[idx].scatter(X_train[y_train==1,0],X_train[y_train==1,1], c='green',marker='o') axarr[idx].set_title(tt) axarr[0].set_ylabel('alcohol',fontsize=12) plt.text(10.2,-1.2,s='OD280/OD315 of diluted wines', ha='center',va='center',fontsize=12) plt.show() ############################AdaBoost算法############################### # def function5(): from sklearn.ensemble import AdaBoostClassifier df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/' 'machine-learning-databases/wine/wine.data', header=None) df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline'] # drop 1 class df_wine = df_wine[df_wine['Class label'] != 1] y = df_wine['Class label'].values X = df_wine[['Alcohol', 'OD280/OD315 of diluted wines']].values le = LabelEncoder() y = le.fit_transform(y) X_train, X_test, y_train, y_test = \ train_test_split(X, y, test_size=0.2, random_state=1, stratify=y) tree = DecisionTreeClassifier(criterion='entropy', random_state=1, max_depth=1) ada = AdaBoostClassifier(base_estimator=tree, n_estimators=500, learning_rate=0.1, random_state=1) # 单颗决策树(弱学习机) tree = tree.fit(X_train,y_train) y_train_pred = tree.predict(X_train) y_test_pred = tree.predict(X_test) tree_train = accuracy_score(y_train, y_train_pred) tree_test = accuracy_score(y_test, y_test_pred) print('Decision tree train/test accuracies %.3f/%.3f' % (tree_train, tree_test)) # AdaBoost算法 ada = ada.fit(X_train, y_train) y_train_pred = ada.predict(X_train) y_test_pred = ada.predict(X_test) tree_train = accuracy_score(y_train, y_train_pred) tree_test = accuracy_score(y_test, y_test_pred) print('AdaBoost train/test accuracies %.3f/%.3f' % (tree_train, tree_test)) # 绘制两个模型的决策区域 x1_min = X_train[:, 0].min() - 1 x1_max = X_train[:, 0].max() + 1 x2_min = X_train[:, 1].min() - 1 x2_max = X_train[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, 0.1), np.arange(x2_min, x2_max)) f, axarr = plt.subplots(nrows=1, ncols=2, sharex='col', sharey='row', figsize=(8, 3)) for idx, clf, tt in zip([0, 1], [tree, ada], ['decision tree', 'bagging']): clf.fit(X_train, y_train) Z = clf.predict(np.c_[xx1.ravel(), xx2.ravel()]) Z = Z.reshape(xx1.shape) axarr[idx].contourf(xx1, xx2, Z, alpha=0.3) axarr[idx].scatter(X_train[y_train == 0, 0], X_train[y_train == 0, 1], c='blue', marker='^') axarr[idx].scatter(X_train[y_train == 1, 0], X_train[y_train == 1, 1], c='green', marker='o') axarr[idx].set_title(tt) axarr[0].set_ylabel('alcohol', fontsize=12) plt.text(10.2, -1.2, s='OD280/OD315 of diluted wines', ha='center', va='center', fontsize=12) plt.show() if __name__ == "__main__": # function1() # function2() # function3() # function4() function5()
vanoid ph
identifier_name
app.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import math from scipy.misc import comb from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler,LabelEncoder from sklearn.model_selection import cross_val_score from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline from sklearn.metrics import accuracy_score from MajorityVowteClassifier import MajoritVoteClassifier # 获取数据并且将y值量化 iris = datasets.load_iris() X,y = iris.data[50:,[1,2]],iris.target[50:] le = LabelEncoder() y = le.fit_transform(y) # 划分数据集 X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.5,random_state=1,stratify=y) def ensemble_error(n_classifier,error): ''' 集成分类器误差率计算 :param n_classifier: 分类器个数 :param error: 单个分类器的误差率 :return: 集成分类器误差率 ''' k_start = int(math.ceil(n_classifier/2.)) probs = [comb(n_classifier,k)*(error**k)*(1-error)**(n_classifier-k) for k in range(k_start,n_classifier+1)] return sum(probs) # 绘制集成分类器和单个分类器随着单个分类器的误差率变化而变化的曲线 def function1(): error_range = np.arange(0.0,1.01,0.1) ens_errors = [ensemble_error(n_classifier=11,error=error) for error in error_range] plt.plot(error_range,error_
random_state=1) clf2 = DecisionTreeClassifier(max_depth=1,criterion='entropy',random_state=0) clf3 = KNeighborsClassifier(n_neighbors=1,p=2,metric='minkowski') pipe1 = Pipeline([['sc',StandardScaler()],['clf',clf1]]) pipe3 = Pipeline([['sc',StandardScaler()],['clf',clf3]]) mv_clf = MajoritVoteClassifier(classifiers=[pipe1,clf2,pipe3]) clf_labels = ['logistic regression','decision tree','KNN','majority voting'] all_clf = [pipe1,clf2,pipe3,mv_clf] print("10-fold cross validation:\n") for clf,label in zip(all_clf,clf_labels): scores = cross_val_score(estimator=clf,X=X_train,y=y_train, cv=10,scoring='roc_auc') print("roc auc: %0.2f (+/- %0.2f) [%s]"%(scores.mean(),scores.std(),label)) # 由打印的结果可以看出,集成分类器的性能相对于单个的分类器有质的提升 # 绘制评估器的roc曲线,评估模型性能 from sklearn.metrics import roc_curve from sklearn.metrics import auc colors = ['black','orange','blue','green'] linestyle = [':','--','-.','-'] for clf, label,clr,ls in zip(all_clf,clf_labels,colors,linestyle): y_pred = clf.fit(X_train,y_train).predict_proba(X_test)[:,1] # 假定正分类为1 fpr,tpr,thresholds = roc_curve(y_true=y_test,y_score=y_pred) roc_auc = auc(x=fpr,y=tpr) plt.plot(fpr,tpr,color=clr,linestyle=ls,label='%s (auc=%.2f)' % (label,roc_auc)) plt.legend(loc='lower right') plt.plot([0,1],[0,1],linestyle='--',color='gray',lw=2) # 随机猜测roc曲线 plt.xlim([-0.1,1.1]) plt.ylim([-0.1,1.1]) plt.grid(alpha=0.5) plt.xlabel('false positive rate (fpr)') plt.ylabel('true positive rate (tpr)') plt.show() # 绘制各个评估器的决策边界 sc = StandardScaler() X_train_std = sc.fit_transform(X_train) from itertools import product x1_min = X_train_std[:,0].min()-1 x1_max = X_train_std[:,0].max()+1 x2_min = X_train_std[:,1].min()-1 x2_max = X_train_std[:,1].max()+1 xx1,xx2 = np.meshgrid(np.arange(x1_min,x1_max,0.1), np.arange(x2_min,x2_max,0.1)) f,axarr = plt.subplots(nrows=2,ncols=2, sharex='col',sharey='row', figsize=(7,5)) for idx,clf,tt in zip(product([0,1],[0,1]),all_clf,clf_labels): clf.fit(X_train_std,y_train) Z = clf.predict(np.c_[xx1.ravel(),xx2.ravel()]) Z = Z.reshape(xx1.shape) axarr[idx[0],idx[1]].contourf(xx1,xx2,Z,alpha=0.3) axarr[idx[0],idx[1]].scatter(X_train_std[y_train==0,0], X_train_std[y_train==0,1], c='blue',marker='^',s=50) axarr[idx[0], idx[1]].scatter(X_train_std[y_train == 1, 0], X_train_std[y_train == 1, 1], c='green', marker='o', s=50) axarr[idx[0],idx[1]].set_title(tt) plt.text(-3.5,-4.5,s='sepal width [standardized]',ha='center',va='center',fontsize=12) plt.text(-12.5,4.5,s='sepal length [standardized]',ha='center',va='center',fontsize=12,rotation=90) plt.show() # 集成分类的成员分类器调优 def function3(): clf1 = LogisticRegression(penalty='l2', C=0.001, random_state=1) clf2 = DecisionTreeClassifier(max_depth=1, criterion='entropy', random_state=0) clf3 = KNeighborsClassifier(n_neighbors=1, p=2, metric='minkowski') pipe1 = Pipeline([['sc', StandardScaler()], ['clf', clf1]]) pipe3 = Pipeline([['sc', StandardScaler()], ['clf', clf3]]) mv_clf = MajoritVoteClassifier(classifiers=[pipe1, clf2, pipe3]) # 打印出参数构成 print(mv_clf.get_params()) # 使用网格搜索对决策树深度,逻辑斯谛回归的正则参数进行调优 from sklearn.model_selection import GridSearchCV params = { 'decisiontreeclassifier__max_depth':[1,2], 'pipeline-1__clf__C':[0.001,0.1,100.0] } grid = GridSearchCV(estimator=mv_clf,param_grid=params,cv=10,scoring='roc_auc') grid.fit(X_train,y_train) print("best parameters:%s" % grid.best_params_) print("accuracy : %.2f" % grid.best_score_) #################集成分类器---bagging分类器################################## def function4(): from sklearn.ensemble import BaggingClassifier df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/' 'machine-learning-databases/wine/wine.data', header=None) df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline'] # drop 1 class df_wine = df_wine[df_wine['Class label'] != 1] y = df_wine['Class label'].values X = df_wine[['Alcohol', 'OD280/OD315 of diluted wines']].values le = LabelEncoder() y = le.fit_transform(y) X_train, X_test, y_train, y_test = \ train_test_split(X, y, test_size = 0.2, random_state = 1, stratify = y) tree = DecisionTreeClassifier(criterion='entropy', random_state=1, max_depth=None) bag = BaggingClassifier(base_estimator=tree, n_estimators=500, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, n_jobs=-1, random_state=1) # 使用单颗决策树 tree = tree.fit(X_train,y_train) y_train_pred = tree.predict(X_train) y_test_pred = tree.predict(X_test) tree_train = accuracy_score(y_train, y_train_pred) tree_test = accuracy_score(y_test, y_test_pred) print('Decision tree train/test accuracies %.3f/%.3f'% (tree_train, tree_test)) # 使用bagging集成分类器 bag = bag.fit(X_train, y_train) y_train_pred = bag.predict(X_train) y_test_pred = bag.predict(X_test) bag_train = accuracy_score(y_train, y_train_pred) bag_test = accuracy_score(y_test, y_test_pred) print('Bagging train/test accuracies %.3f/%.3f'% (bag_train, bag_test)) # 绘制两个模型的决策区域 x1_min = X_train[:,0].min()-1 x1_max = X_train[:,0].max()+1 x2_min = X_train[:,1].min()-1 x2_max = X_train[:,1].max()+1 xx1,xx2 = np.meshgrid(np.arange(x1_min,x1_max,0.1),np.arange(x2_min,x2_max)) f,axarr = plt.subplots(nrows=1,ncols=2,sharex='col',sharey='row',figsize=(8,3)) for idx,clf,tt in zip([0,1],[tree,bag],['decision tree','bagging']): clf.fit(X_train,y_train) Z = clf.predict(np.c_[xx1.ravel(),xx2.ravel()]) Z = Z.reshape(xx1.shape) axarr[idx].contourf(xx1,xx2,Z,alpha=0.3) axarr[idx].scatter(X_train[y_train==0,0],X_train[y_train==0,1], c='blue',marker='^') axarr[idx].scatter(X_train[y_train==1,0],X_train[y_train==1,1], c='green',marker='o') axarr[idx].set_title(tt) axarr[0].set_ylabel('alcohol',fontsize=12) plt.text(10.2,-1.2,s='OD280/OD315 of diluted wines', ha='center',va='center',fontsize=12) plt.show() ############################AdaBoost算法############################### # def function5(): from sklearn.ensemble import AdaBoostClassifier df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/' 'machine-learning-databases/wine/wine.data', header=None) df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline'] # drop 1 class df_wine = df_wine[df_wine['Class label'] != 1] y = df_wine['Class label'].values X = df_wine[['Alcohol', 'OD280/OD315 of diluted wines']].values le = LabelEncoder() y = le.fit_transform(y) X_train, X_test, y_train, y_test = \ train_test_split(X, y, test_size=0.2, random_state=1, stratify=y) tree = DecisionTreeClassifier(criterion='entropy', random_state=1, max_depth=1) ada = AdaBoostClassifier(base_estimator=tree, n_estimators=500, learning_rate=0.1, random_state=1) # 单颗决策树(弱学习机) tree = tree.fit(X_train,y_train) y_train_pred = tree.predict(X_train) y_test_pred = tree.predict(X_test) tree_train = accuracy_score(y_train, y_train_pred) tree_test = accuracy_score(y_test, y_test_pred) print('Decision tree train/test accuracies %.3f/%.3f' % (tree_train, tree_test)) # AdaBoost算法 ada = ada.fit(X_train, y_train) y_train_pred = ada.predict(X_train) y_test_pred = ada.predict(X_test) tree_train = accuracy_score(y_train, y_train_pred) tree_test = accuracy_score(y_test, y_test_pred) print('AdaBoost train/test accuracies %.3f/%.3f' % (tree_train, tree_test)) # 绘制两个模型的决策区域 x1_min = X_train[:, 0].min() - 1 x1_max = X_train[:, 0].max() + 1 x2_min = X_train[:, 1].min() - 1 x2_max = X_train[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, 0.1), np.arange(x2_min, x2_max)) f, axarr = plt.subplots(nrows=1, ncols=2, sharex='col', sharey='row', figsize=(8, 3)) for idx, clf, tt in zip([0, 1], [tree, ada], ['decision tree', 'bagging']): clf.fit(X_train, y_train) Z = clf.predict(np.c_[xx1.ravel(), xx2.ravel()]) Z = Z.reshape(xx1.shape) axarr[idx].contourf(xx1, xx2, Z, alpha=0.3) axarr[idx].scatter(X_train[y_train == 0, 0], X_train[y_train == 0, 1], c='blue', marker='^') axarr[idx].scatter(X_train[y_train == 1, 0], X_train[y_train == 1, 1], c='green', marker='o') axarr[idx].set_title(tt) axarr[0].set_ylabel('alcohol', fontsize=12) plt.text(10.2, -1.2, s='OD280/OD315 of diluted wines', ha='center', va='center', fontsize=12) plt.show() if __name__ == "__main__": # function1() # function2() # function3() # function4() function5()
range,linestyle='--',label='base error',lw='2') plt.plot(error_range,ens_errors,label='ensemble error',lw='2') plt.xlabel("base error") plt.ylabel("base/ensemble error") plt.legend(loc='upper left') plt.grid(alpha=0.5) plt.show() #################集成分类器---简单投票分类器################################## # 使用k-折交叉验证评估各评估器的性能 def function2(): clf1 = LogisticRegression(penalty='l2',C=0.001,
identifier_body
nargs.go
package nargs import ( "fmt" "go/ast" "go/build" "go/token" "log" "sort" "strconv" "strings" ) func init() { build.Default.UseAllFiles = true } // Flags contains configuration specific to nargs // * IncludeTests - include test files in analysis // * SetExitStatus - set exit status to 1 if any issues are found // * IncludeNamedReturns - include unused named returns // * IncludeReceivers - include unused receivers type Flags struct { IncludeTests bool SetExitStatus bool IncludeNamedReturns bool IncludeReceivers bool } type unusedVisitor struct { fileSet *token.FileSet resultsSet map[string]struct{} includeNamedReturns bool includeReceivers bool errsFound bool } // CheckForUnusedFunctionArgs will parse the files/packages contained in args // and walk the AST searching for unused function parameters. func CheckForUnusedFunctionArgs(args []string, flags Flags) (results []string, exitWithStatus bool, _ error) { fset := token.NewFileSet() files, err := parseInput(args, fset, flags.IncludeTests) if err != nil { return nil, false, fmt.Errorf("could not parse input, %v", err) } retVis := &unusedVisitor{ fileSet: fset, includeNamedReturns: flags.IncludeNamedReturns, includeReceivers: flags.IncludeReceivers, resultsSet: make(map[string]struct{}), } // visitorResult contains the results for a specific visitor and is cleared on each // iteration var visitorResult []string for _, f := range files { if f == nil { continue } ast.Walk(retVis, f) for result, _ := range retVis.resultsSet { visitorResult = append(visitorResult, result) } // Due to our analysis, of the ast.File, we may end up getting our results out of order. Sort by line number to keep // the results in a consistent format. sort.Sort(byLineNumber(visitorResult)) results = append(results, visitorResult...) visitorResult = nil retVis.resultsSet = make(map[string]struct{}) } return results, retVis.errsFound && flags.SetExitStatus, nil } // ugly, but not sure if there's another option.. type byLineNumber []string func (a byLineNumber) Len() int { return len(a) } func (a byLineNumber) Less(i, j int) bool { iLine := strings.Split(a[i], ":") num := strings.Split(iLine[1], " ") iNum, _ := strconv.Atoi(num[0]) jLine := strings.Split(a[j], ":") num = strings.Split(jLine[1], " ") jNum, _ := strconv.Atoi(num[0]) return iNum < jNum } func (a byLineNumber) Swap(i, j int) { a[i], a[j] = a[j], a[i] } // Visit implements the ast.Visitor Visit method. func (v *unusedVisitor) Visit(node ast.Node) ast.Visitor { var stmtList []ast.Stmt var file *token.File paramMap := make(map[string]bool) var funcDecl *ast.FuncDecl switch topLevelType := node.(type) { case *ast.FuncDecl: funcDecl = topLevelType if funcDecl.Body == nil { // This means funcDecl is an external (non-Go) function, these // should not be included in the analysis return v } stmtList = v.handleFuncDecl(paramMap, funcDecl, stmtList) file = v.fileSet.File(funcDecl.Pos()) case *ast.File: file = v.fileSet.File(topLevelType.Pos()) if topLevelType.Decls != nil { stmtList = v.handleDecls(paramMap, topLevelType.Decls, stmtList) } default: return v } // We cannot exit if len(paramMap) == 0, we may have a function closure with // unused variables // Analyze body of function v.handleStmts(paramMap, stmtList) for funcName, used := range paramMap { if !used { if file != nil { if funcDecl != nil && funcDecl.Name != nil { //TODO print parameter vs parameter(s)? //TODO differentiation of used parameter vs. receiver? resStr := fmt.Sprintf("%v:%v %v contains unused parameter %v\n", file.Name(), file.Position(funcDecl.Pos()).Line, funcDecl.Name.Name, funcName) v.resultsSet[resStr] = struct{}{} v.errsFound = true } } } } return v } func (v *unusedVisitor) handleStmts(paramMap map[string]bool, stmtList []ast.Stmt) { for len(stmtList) != 0 { stmt := stmtList[0] switch s := stmt.(type) { case *ast.IfStmt: stmtList = append(stmtList, s.Init, s.Body, s.Else) stmtList = v.handleExprs(paramMap, []ast.Expr{s.Cond}, stmtList) case *ast.AssignStmt: assigned := false for index, right := range s.Rhs { funcLit, ok := right.(*ast.FuncLit) if !ok { continue } funcName, ok := s.Lhs[index].(*ast.Ident) if !ok { //TODO - understand this case a little more // log.Printf("@@@@@@@@@@@@@@@@@@@@@@@@@2 wat") continue } v.handleFuncLit(paramMap, funcLit, funcName) assigned = true } if !assigned { stmtList = v.handleExprs(paramMap, s.Lhs, stmtList) stmtList = v.handleExprs(paramMap, s.Rhs, stmtList) } case *ast.BlockStmt: stmtList = append(stmtList, s.List...) case *ast.ReturnStmt: stmtList = v.handleExprs(paramMap, s.Results, stmtList) case *ast.DeclStmt: stmtList = v.handleDecls(paramMap, []ast.Decl{s.Decl}, stmtList) case *ast.ExprStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList) case *ast.RangeStmt: stmtList = append(stmtList, s.Body) stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList) case *ast.ForStmt: stmtList = append(stmtList, s.Init) stmtList = append(stmtList, s.Body) stmtList = v.handleExprs(paramMap, []ast.Expr{s.Cond}, stmtList) stmtList = append(stmtList, s.Post) case *ast.TypeSwitchStmt: stmtList = append(stmtList, s.Body, s.Assign, s.Init) case *ast.CaseClause: stmtList = v.handleExprs(paramMap, s.List, stmtList) stmtList = append(stmtList, s.Body...) case *ast.SendStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.Chan, s.Value}, stmtList) case *ast.GoStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.Call}, stmtList) case *ast.DeferStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.Call}, stmtList) case *ast.SelectStmt: stmtList = append(stmtList, s.Body) case *ast.CommClause: stmtList = append(stmtList, s.Body...) stmtList = append(stmtList, s.Comm) case *ast.BranchStmt: handleIdent(paramMap, s.Label) case *ast.SwitchStmt: stmtList = append(stmtList, s.Body, s.Init) stmtList = v.handleExprs(paramMap, []ast.Expr{s.Tag}, stmtList) case *ast.LabeledStmt: handleIdent(paramMap, s.Label) stmtList = append(stmtList, s.Stmt) case *ast.IncDecStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList) case nil, *ast.EmptyStmt: //no-op default: log.Printf("ERROR: unknown stmt type %T\n", s) } stmtList = stmtList[1:] } } func handleIdents(paramMap map[string]bool, identList []*ast.Ident) { for _, ident := range identList { handleIdent(paramMap, ident) } } func handleIdent(paramMap map[string]bool, ident *ast.Ident) { if ident == nil { return } if ident.Obj != nil && ident.Obj.Kind == ast.Var { if _, ok := paramMap[ident.Obj.Name]; ok { paramMap[ident.Obj.Name] = true } /*else { if ident.Obj.Name != "_" { paramMap[ident.Obj.Name] = false } }*/ } //TODO - ensure this truly isn't needed - can we rely on the // ident object name? // if _, ok := paramMap[ident.Name]; ok { // paramMap[ident.Name] = true // } } func (v *unusedVisitor) handleExprs(paramMap map[string]bool, exprList []ast.Expr, stmtList []ast.Stmt) []ast.Stmt { for len(exprList) != 0 { expr := exprList[0] switch e := expr.(type) { case *ast.Ident: handleIdent(paramMap, e) case *ast.BinaryExpr: exprList = append(exprList, e.X) //TODO, do we need to then worry about x.left being used? exprList = append(exprList, e.Y) //TODO, do we need to then worry about x.left being used? case *ast.CallExpr: exprList = append(exprList, e.Args...) exprList = append(exprList, e.Fun) case *ast.IndexExpr: exprList = append(exprList, e.X) exprList = append(exprList, e.Index) case *ast.KeyValueExpr: exprList = append(exprList, e.Key, e.Value) case *ast.ParenExpr: exprList = append(exprList, e.X) case *ast.SelectorExpr: exprList = append(exprList, e.X) handleIdent(paramMap, e.Sel) case *ast.SliceExpr: exprList = append(exprList, e.Low, e.High, e.Max, e.X) case *ast.StarExpr: // need to dig deeper to see if this is a derefenced type exprList = append(exprList, e.X) case *ast.TypeAssertExpr: exprList = append(exprList, e.X, e.Type) case *ast.UnaryExpr: exprList = append(exprList, e.X) case *ast.BasicLit: // nothing to do here, no variable name case *ast.FuncLit: exprList = append(exprList, e.Type) stmtList = append(stmtList, e.Body) case *ast.CompositeLit: exprList = append(exprList, e.Elts...) case *ast.ArrayType: exprList = append(exprList, e.Elt, e.Len) case *ast.ChanType: exprList = append(exprList, e.Value) case *ast.FuncType: exprList, stmtList = handleFieldList(paramMap, e.Params, exprList, stmtList) exprList, stmtList = handleFieldList(paramMap, e.Results, exprList, stmtList) case *ast.InterfaceType: exprList, stmtList = handleFieldList(paramMap, e.Methods, exprList, stmtList) case *ast.MapType: exprList = append(exprList, e.Key, e.Value) case *ast.StructType: //TODO: no-op, unless it contains funcs I guess? revisit this // exprList, stmtList = handleFieldList(paramMap, e.Fields, exprList, stmtList) case *ast.Ellipsis: exprList = append(exprList, e.Elt) case nil: // no op default: log.Printf("ERROR: unknown expr type %T\n", e) } exprList = exprList[1:] } return stmtList } func
(paramMap map[string]bool, fieldList *ast.FieldList, exprList []ast.Expr, stmtList []ast.Stmt) ([]ast.Expr, []ast.Stmt) { if fieldList == nil { return exprList, stmtList } for _, field := range fieldList.List { exprList = append(exprList, field.Type) handleIdents(paramMap, field.Names) } return exprList, stmtList } func (v *unusedVisitor) handleDecls(paramMap map[string]bool, decls []ast.Decl, initialStmts []ast.Stmt) []ast.Stmt { for _, decl := range decls { switch d := decl.(type) { case *ast.GenDecl: for _, spec := range d.Specs { switch specType := spec.(type) { case *ast.ValueSpec: //TODO - I think the only specs we care about here are when we have a function declaration handleIdents(paramMap, specType.Names) initialStmts = v.handleExprs(paramMap, []ast.Expr{specType.Type}, initialStmts) initialStmts = v.handleExprs(paramMap, specType.Values, initialStmts) for index, value := range specType.Values { funcLit, ok := value.(*ast.FuncLit) if !ok { continue } funcName := specType.Names[index] // get arguments of function, this is a candidate // with potentially unused arguments v.handleFuncLit(paramMap, funcLit, funcName) } case *ast.TypeSpec: handleIdent(paramMap, specType.Name) initialStmts = v.handleExprs(paramMap, []ast.Expr{specType.Type}, initialStmts) case *ast.ImportSpec: // no-op, ImportSpecs do not contain functions default: log.Printf("ERROR: unknown spec type %T\n", specType) } } case *ast.FuncDecl: initialStmts = v.handleFuncDecl(paramMap, d, initialStmts) default: log.Printf("ERROR: unknown decl type %T\n", d) } } return initialStmts } // paramMap is passed in for cases where we have an outer function with a parameter // that is captured by closure by the function literal func (v *unusedVisitor) handleFuncLit(paramMap map[string]bool, funcLit *ast.FuncLit, funcName *ast.Ident) { if funcLit.Type != nil && funcLit.Type.Params != nil && len(funcLit.Type.Params.List) > 0 { // declare a separate parameter map for handling funcParamMap := make(map[string]bool) for _, param := range funcLit.Type.Params.List { for _, paramName := range param.Names { if paramName.Name != "_" { funcParamMap[paramName.Name] = false } } } // generate potential statements v.handleStmts(funcParamMap, []ast.Stmt{funcLit.Body}) v.handleStmts(paramMap, []ast.Stmt{funcLit.Body}) for paramName, used := range funcParamMap { if !used && paramName != "_" { //TODO: this append currently causes things to appear out of order (2) file := v.fileSet.File(funcLit.Pos()) resStr := fmt.Sprintf("%v:%v %v contains unused parameter %v\n", file.Name(), file.Position(funcLit.Pos()).Line, funcName.Name, paramName) v.resultsSet[resStr] = struct{}{} } } } } func (v *unusedVisitor) handleFuncDecl(paramMap map[string]bool, funcDecl *ast.FuncDecl, initialStmts []ast.Stmt) []ast.Stmt { if funcDecl.Body != nil { initialStmts = append(initialStmts, funcDecl.Body.List...) } if funcDecl.Type != nil { if funcDecl.Type.Params != nil { for _, paramList := range funcDecl.Type.Params.List { for _, name := range paramList.Names { if name.Name == "_" { continue } paramMap[name.Name] = false } } } if v.includeNamedReturns && funcDecl.Type.Results != nil { for _, paramList := range funcDecl.Type.Results.List { for _, name := range paramList.Names { if name.Name == "_" { continue } paramMap[name.Name] = false } } } } if v.includeReceivers && funcDecl.Recv != nil { for _, field := range funcDecl.Recv.List { for _, name := range field.Names { if name.Name == "_" { continue } paramMap[name.Name] = false } } } return initialStmts }
handleFieldList
identifier_name
nargs.go
package nargs import ( "fmt" "go/ast" "go/build" "go/token" "log" "sort" "strconv" "strings" ) func init() { build.Default.UseAllFiles = true } // Flags contains configuration specific to nargs // * IncludeTests - include test files in analysis // * SetExitStatus - set exit status to 1 if any issues are found // * IncludeNamedReturns - include unused named returns // * IncludeReceivers - include unused receivers type Flags struct { IncludeTests bool SetExitStatus bool IncludeNamedReturns bool IncludeReceivers bool } type unusedVisitor struct { fileSet *token.FileSet resultsSet map[string]struct{} includeNamedReturns bool includeReceivers bool errsFound bool } // CheckForUnusedFunctionArgs will parse the files/packages contained in args // and walk the AST searching for unused function parameters. func CheckForUnusedFunctionArgs(args []string, flags Flags) (results []string, exitWithStatus bool, _ error) { fset := token.NewFileSet() files, err := parseInput(args, fset, flags.IncludeTests) if err != nil { return nil, false, fmt.Errorf("could not parse input, %v", err) } retVis := &unusedVisitor{ fileSet: fset, includeNamedReturns: flags.IncludeNamedReturns, includeReceivers: flags.IncludeReceivers, resultsSet: make(map[string]struct{}), } // visitorResult contains the results for a specific visitor and is cleared on each // iteration var visitorResult []string for _, f := range files { if f == nil { continue } ast.Walk(retVis, f) for result, _ := range retVis.resultsSet { visitorResult = append(visitorResult, result) } // Due to our analysis, of the ast.File, we may end up getting our results out of order. Sort by line number to keep // the results in a consistent format. sort.Sort(byLineNumber(visitorResult)) results = append(results, visitorResult...) visitorResult = nil retVis.resultsSet = make(map[string]struct{}) } return results, retVis.errsFound && flags.SetExitStatus, nil } // ugly, but not sure if there's another option.. type byLineNumber []string func (a byLineNumber) Len() int { return len(a) } func (a byLineNumber) Less(i, j int) bool { iLine := strings.Split(a[i], ":") num := strings.Split(iLine[1], " ") iNum, _ := strconv.Atoi(num[0]) jLine := strings.Split(a[j], ":") num = strings.Split(jLine[1], " ") jNum, _ := strconv.Atoi(num[0]) return iNum < jNum } func (a byLineNumber) Swap(i, j int) { a[i], a[j] = a[j], a[i] } // Visit implements the ast.Visitor Visit method. func (v *unusedVisitor) Visit(node ast.Node) ast.Visitor { var stmtList []ast.Stmt var file *token.File paramMap := make(map[string]bool) var funcDecl *ast.FuncDecl switch topLevelType := node.(type) { case *ast.FuncDecl: funcDecl = topLevelType if funcDecl.Body == nil { // This means funcDecl is an external (non-Go) function, these // should not be included in the analysis return v } stmtList = v.handleFuncDecl(paramMap, funcDecl, stmtList) file = v.fileSet.File(funcDecl.Pos()) case *ast.File: file = v.fileSet.File(topLevelType.Pos()) if topLevelType.Decls != nil { stmtList = v.handleDecls(paramMap, topLevelType.Decls, stmtList) } default: return v } // We cannot exit if len(paramMap) == 0, we may have a function closure with // unused variables // Analyze body of function v.handleStmts(paramMap, stmtList) for funcName, used := range paramMap { if !used { if file != nil { if funcDecl != nil && funcDecl.Name != nil { //TODO print parameter vs parameter(s)? //TODO differentiation of used parameter vs. receiver? resStr := fmt.Sprintf("%v:%v %v contains unused parameter %v\n", file.Name(), file.Position(funcDecl.Pos()).Line, funcDecl.Name.Name, funcName) v.resultsSet[resStr] = struct{}{} v.errsFound = true } } } } return v } func (v *unusedVisitor) handleStmts(paramMap map[string]bool, stmtList []ast.Stmt) { for len(stmtList) != 0 { stmt := stmtList[0] switch s := stmt.(type) { case *ast.IfStmt: stmtList = append(stmtList, s.Init, s.Body, s.Else) stmtList = v.handleExprs(paramMap, []ast.Expr{s.Cond}, stmtList) case *ast.AssignStmt: assigned := false for index, right := range s.Rhs { funcLit, ok := right.(*ast.FuncLit) if !ok { continue } funcName, ok := s.Lhs[index].(*ast.Ident) if !ok { //TODO - understand this case a little more // log.Printf("@@@@@@@@@@@@@@@@@@@@@@@@@2 wat") continue } v.handleFuncLit(paramMap, funcLit, funcName) assigned = true } if !assigned { stmtList = v.handleExprs(paramMap, s.Lhs, stmtList) stmtList = v.handleExprs(paramMap, s.Rhs, stmtList) } case *ast.BlockStmt: stmtList = append(stmtList, s.List...) case *ast.ReturnStmt: stmtList = v.handleExprs(paramMap, s.Results, stmtList) case *ast.DeclStmt: stmtList = v.handleDecls(paramMap, []ast.Decl{s.Decl}, stmtList) case *ast.ExprStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList) case *ast.RangeStmt: stmtList = append(stmtList, s.Body) stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList) case *ast.ForStmt: stmtList = append(stmtList, s.Init) stmtList = append(stmtList, s.Body) stmtList = v.handleExprs(paramMap, []ast.Expr{s.Cond}, stmtList) stmtList = append(stmtList, s.Post) case *ast.TypeSwitchStmt: stmtList = append(stmtList, s.Body, s.Assign, s.Init) case *ast.CaseClause: stmtList = v.handleExprs(paramMap, s.List, stmtList) stmtList = append(stmtList, s.Body...) case *ast.SendStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.Chan, s.Value}, stmtList) case *ast.GoStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.Call}, stmtList) case *ast.DeferStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.Call}, stmtList) case *ast.SelectStmt: stmtList = append(stmtList, s.Body) case *ast.CommClause: stmtList = append(stmtList, s.Body...) stmtList = append(stmtList, s.Comm) case *ast.BranchStmt: handleIdent(paramMap, s.Label) case *ast.SwitchStmt: stmtList = append(stmtList, s.Body, s.Init) stmtList = v.handleExprs(paramMap, []ast.Expr{s.Tag}, stmtList) case *ast.LabeledStmt: handleIdent(paramMap, s.Label) stmtList = append(stmtList, s.Stmt) case *ast.IncDecStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList) case nil, *ast.EmptyStmt: //no-op default: log.Printf("ERROR: unknown stmt type %T\n", s) } stmtList = stmtList[1:] } } func handleIdents(paramMap map[string]bool, identList []*ast.Ident) { for _, ident := range identList { handleIdent(paramMap, ident) } } func handleIdent(paramMap map[string]bool, ident *ast.Ident) { if ident == nil { return } if ident.Obj != nil && ident.Obj.Kind == ast.Var { if _, ok := paramMap[ident.Obj.Name]; ok { paramMap[ident.Obj.Name] = true } /*else { if ident.Obj.Name != "_" { paramMap[ident.Obj.Name] = false } }*/ } //TODO - ensure this truly isn't needed - can we rely on the // ident object name? // if _, ok := paramMap[ident.Name]; ok { // paramMap[ident.Name] = true // } } func (v *unusedVisitor) handleExprs(paramMap map[string]bool, exprList []ast.Expr, stmtList []ast.Stmt) []ast.Stmt { for len(exprList) != 0 { expr := exprList[0] switch e := expr.(type) { case *ast.Ident: handleIdent(paramMap, e) case *ast.BinaryExpr: exprList = append(exprList, e.X) //TODO, do we need to then worry about x.left being used? exprList = append(exprList, e.Y) //TODO, do we need to then worry about x.left being used? case *ast.CallExpr: exprList = append(exprList, e.Args...) exprList = append(exprList, e.Fun) case *ast.IndexExpr: exprList = append(exprList, e.X) exprList = append(exprList, e.Index) case *ast.KeyValueExpr: exprList = append(exprList, e.Key, e.Value) case *ast.ParenExpr: exprList = append(exprList, e.X) case *ast.SelectorExpr: exprList = append(exprList, e.X) handleIdent(paramMap, e.Sel) case *ast.SliceExpr: exprList = append(exprList, e.Low, e.High, e.Max, e.X) case *ast.StarExpr: // need to dig deeper to see if this is a derefenced type exprList = append(exprList, e.X) case *ast.TypeAssertExpr: exprList = append(exprList, e.X, e.Type) case *ast.UnaryExpr: exprList = append(exprList, e.X) case *ast.BasicLit: // nothing to do here, no variable name case *ast.FuncLit: exprList = append(exprList, e.Type) stmtList = append(stmtList, e.Body) case *ast.CompositeLit: exprList = append(exprList, e.Elts...) case *ast.ArrayType: exprList = append(exprList, e.Elt, e.Len) case *ast.ChanType: exprList = append(exprList, e.Value) case *ast.FuncType: exprList, stmtList = handleFieldList(paramMap, e.Params, exprList, stmtList) exprList, stmtList = handleFieldList(paramMap, e.Results, exprList, stmtList) case *ast.InterfaceType: exprList, stmtList = handleFieldList(paramMap, e.Methods, exprList, stmtList) case *ast.MapType: exprList = append(exprList, e.Key, e.Value) case *ast.StructType: //TODO: no-op, unless it contains funcs I guess? revisit this // exprList, stmtList = handleFieldList(paramMap, e.Fields, exprList, stmtList) case *ast.Ellipsis: exprList = append(exprList, e.Elt) case nil: // no op default: log.Printf("ERROR: unknown expr type %T\n", e) } exprList = exprList[1:] } return stmtList } func handleFieldList(paramMap map[string]bool, fieldList *ast.FieldList, exprList []ast.Expr, stmtList []ast.Stmt) ([]ast.Expr, []ast.Stmt) { if fieldList == nil { return exprList, stmtList } for _, field := range fieldList.List { exprList = append(exprList, field.Type) handleIdents(paramMap, field.Names) } return exprList, stmtList } func (v *unusedVisitor) handleDecls(paramMap map[string]bool, decls []ast.Decl, initialStmts []ast.Stmt) []ast.Stmt { for _, decl := range decls { switch d := decl.(type) { case *ast.GenDecl: for _, spec := range d.Specs { switch specType := spec.(type) { case *ast.ValueSpec: //TODO - I think the only specs we care about here are when we have a function declaration handleIdents(paramMap, specType.Names) initialStmts = v.handleExprs(paramMap, []ast.Expr{specType.Type}, initialStmts) initialStmts = v.handleExprs(paramMap, specType.Values, initialStmts) for index, value := range specType.Values { funcLit, ok := value.(*ast.FuncLit) if !ok { continue } funcName := specType.Names[index] // get arguments of function, this is a candidate // with potentially unused arguments v.handleFuncLit(paramMap, funcLit, funcName) } case *ast.TypeSpec: handleIdent(paramMap, specType.Name) initialStmts = v.handleExprs(paramMap, []ast.Expr{specType.Type}, initialStmts) case *ast.ImportSpec: // no-op, ImportSpecs do not contain functions default: log.Printf("ERROR: unknown spec type %T\n", specType) } } case *ast.FuncDecl: initialStmts = v.handleFuncDecl(paramMap, d, initialStmts) default: log.Printf("ERROR: unknown decl type %T\n", d) } } return initialStmts } // paramMap is passed in for cases where we have an outer function with a parameter // that is captured by closure by the function literal func (v *unusedVisitor) handleFuncLit(paramMap map[string]bool, funcLit *ast.FuncLit, funcName *ast.Ident) { if funcLit.Type != nil && funcLit.Type.Params != nil && len(funcLit.Type.Params.List) > 0 { // declare a separate parameter map for handling funcParamMap := make(map[string]bool) for _, param := range funcLit.Type.Params.List { for _, paramName := range param.Names { if paramName.Name != "_" { funcParamMap[paramName.Name] = false } } } // generate potential statements v.handleStmts(funcParamMap, []ast.Stmt{funcLit.Body}) v.handleStmts(paramMap, []ast.Stmt{funcLit.Body}) for paramName, used := range funcParamMap { if !used && paramName != "_" { //TODO: this append currently causes things to appear out of order (2) file := v.fileSet.File(funcLit.Pos()) resStr := fmt.Sprintf("%v:%v %v contains unused parameter %v\n", file.Name(), file.Position(funcLit.Pos()).Line, funcName.Name, paramName) v.resultsSet[resStr] = struct{}{} } } } } func (v *unusedVisitor) handleFuncDecl(paramMap map[string]bool, funcDecl *ast.FuncDecl, initialStmts []ast.Stmt) []ast.Stmt { if funcDecl.Body != nil { initialStmts = append(initialStmts, funcDecl.Body.List...) } if funcDecl.Type != nil { if funcDecl.Type.Params != nil
if v.includeNamedReturns && funcDecl.Type.Results != nil { for _, paramList := range funcDecl.Type.Results.List { for _, name := range paramList.Names { if name.Name == "_" { continue } paramMap[name.Name] = false } } } } if v.includeReceivers && funcDecl.Recv != nil { for _, field := range funcDecl.Recv.List { for _, name := range field.Names { if name.Name == "_" { continue } paramMap[name.Name] = false } } } return initialStmts }
{ for _, paramList := range funcDecl.Type.Params.List { for _, name := range paramList.Names { if name.Name == "_" { continue } paramMap[name.Name] = false } } }
conditional_block
nargs.go
package nargs import ( "fmt" "go/ast" "go/build" "go/token" "log" "sort" "strconv" "strings" ) func init() { build.Default.UseAllFiles = true } // Flags contains configuration specific to nargs // * IncludeTests - include test files in analysis // * SetExitStatus - set exit status to 1 if any issues are found // * IncludeNamedReturns - include unused named returns // * IncludeReceivers - include unused receivers type Flags struct { IncludeTests bool SetExitStatus bool IncludeNamedReturns bool IncludeReceivers bool } type unusedVisitor struct { fileSet *token.FileSet resultsSet map[string]struct{} includeNamedReturns bool includeReceivers bool errsFound bool } // CheckForUnusedFunctionArgs will parse the files/packages contained in args // and walk the AST searching for unused function parameters. func CheckForUnusedFunctionArgs(args []string, flags Flags) (results []string, exitWithStatus bool, _ error) { fset := token.NewFileSet() files, err := parseInput(args, fset, flags.IncludeTests) if err != nil { return nil, false, fmt.Errorf("could not parse input, %v", err) } retVis := &unusedVisitor{ fileSet: fset, includeNamedReturns: flags.IncludeNamedReturns, includeReceivers: flags.IncludeReceivers, resultsSet: make(map[string]struct{}), } // visitorResult contains the results for a specific visitor and is cleared on each // iteration var visitorResult []string for _, f := range files { if f == nil { continue } ast.Walk(retVis, f) for result, _ := range retVis.resultsSet { visitorResult = append(visitorResult, result) } // Due to our analysis, of the ast.File, we may end up getting our results out of order. Sort by line number to keep // the results in a consistent format. sort.Sort(byLineNumber(visitorResult)) results = append(results, visitorResult...) visitorResult = nil retVis.resultsSet = make(map[string]struct{}) } return results, retVis.errsFound && flags.SetExitStatus, nil } // ugly, but not sure if there's another option.. type byLineNumber []string func (a byLineNumber) Len() int { return len(a) } func (a byLineNumber) Less(i, j int) bool { iLine := strings.Split(a[i], ":") num := strings.Split(iLine[1], " ") iNum, _ := strconv.Atoi(num[0]) jLine := strings.Split(a[j], ":") num = strings.Split(jLine[1], " ") jNum, _ := strconv.Atoi(num[0]) return iNum < jNum } func (a byLineNumber) Swap(i, j int)
// Visit implements the ast.Visitor Visit method. func (v *unusedVisitor) Visit(node ast.Node) ast.Visitor { var stmtList []ast.Stmt var file *token.File paramMap := make(map[string]bool) var funcDecl *ast.FuncDecl switch topLevelType := node.(type) { case *ast.FuncDecl: funcDecl = topLevelType if funcDecl.Body == nil { // This means funcDecl is an external (non-Go) function, these // should not be included in the analysis return v } stmtList = v.handleFuncDecl(paramMap, funcDecl, stmtList) file = v.fileSet.File(funcDecl.Pos()) case *ast.File: file = v.fileSet.File(topLevelType.Pos()) if topLevelType.Decls != nil { stmtList = v.handleDecls(paramMap, topLevelType.Decls, stmtList) } default: return v } // We cannot exit if len(paramMap) == 0, we may have a function closure with // unused variables // Analyze body of function v.handleStmts(paramMap, stmtList) for funcName, used := range paramMap { if !used { if file != nil { if funcDecl != nil && funcDecl.Name != nil { //TODO print parameter vs parameter(s)? //TODO differentiation of used parameter vs. receiver? resStr := fmt.Sprintf("%v:%v %v contains unused parameter %v\n", file.Name(), file.Position(funcDecl.Pos()).Line, funcDecl.Name.Name, funcName) v.resultsSet[resStr] = struct{}{} v.errsFound = true } } } } return v } func (v *unusedVisitor) handleStmts(paramMap map[string]bool, stmtList []ast.Stmt) { for len(stmtList) != 0 { stmt := stmtList[0] switch s := stmt.(type) { case *ast.IfStmt: stmtList = append(stmtList, s.Init, s.Body, s.Else) stmtList = v.handleExprs(paramMap, []ast.Expr{s.Cond}, stmtList) case *ast.AssignStmt: assigned := false for index, right := range s.Rhs { funcLit, ok := right.(*ast.FuncLit) if !ok { continue } funcName, ok := s.Lhs[index].(*ast.Ident) if !ok { //TODO - understand this case a little more // log.Printf("@@@@@@@@@@@@@@@@@@@@@@@@@2 wat") continue } v.handleFuncLit(paramMap, funcLit, funcName) assigned = true } if !assigned { stmtList = v.handleExprs(paramMap, s.Lhs, stmtList) stmtList = v.handleExprs(paramMap, s.Rhs, stmtList) } case *ast.BlockStmt: stmtList = append(stmtList, s.List...) case *ast.ReturnStmt: stmtList = v.handleExprs(paramMap, s.Results, stmtList) case *ast.DeclStmt: stmtList = v.handleDecls(paramMap, []ast.Decl{s.Decl}, stmtList) case *ast.ExprStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList) case *ast.RangeStmt: stmtList = append(stmtList, s.Body) stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList) case *ast.ForStmt: stmtList = append(stmtList, s.Init) stmtList = append(stmtList, s.Body) stmtList = v.handleExprs(paramMap, []ast.Expr{s.Cond}, stmtList) stmtList = append(stmtList, s.Post) case *ast.TypeSwitchStmt: stmtList = append(stmtList, s.Body, s.Assign, s.Init) case *ast.CaseClause: stmtList = v.handleExprs(paramMap, s.List, stmtList) stmtList = append(stmtList, s.Body...) case *ast.SendStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.Chan, s.Value}, stmtList) case *ast.GoStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.Call}, stmtList) case *ast.DeferStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.Call}, stmtList) case *ast.SelectStmt: stmtList = append(stmtList, s.Body) case *ast.CommClause: stmtList = append(stmtList, s.Body...) stmtList = append(stmtList, s.Comm) case *ast.BranchStmt: handleIdent(paramMap, s.Label) case *ast.SwitchStmt: stmtList = append(stmtList, s.Body, s.Init) stmtList = v.handleExprs(paramMap, []ast.Expr{s.Tag}, stmtList) case *ast.LabeledStmt: handleIdent(paramMap, s.Label) stmtList = append(stmtList, s.Stmt) case *ast.IncDecStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList) case nil, *ast.EmptyStmt: //no-op default: log.Printf("ERROR: unknown stmt type %T\n", s) } stmtList = stmtList[1:] } } func handleIdents(paramMap map[string]bool, identList []*ast.Ident) { for _, ident := range identList { handleIdent(paramMap, ident) } } func handleIdent(paramMap map[string]bool, ident *ast.Ident) { if ident == nil { return } if ident.Obj != nil && ident.Obj.Kind == ast.Var { if _, ok := paramMap[ident.Obj.Name]; ok { paramMap[ident.Obj.Name] = true } /*else { if ident.Obj.Name != "_" { paramMap[ident.Obj.Name] = false } }*/ } //TODO - ensure this truly isn't needed - can we rely on the // ident object name? // if _, ok := paramMap[ident.Name]; ok { // paramMap[ident.Name] = true // } } func (v *unusedVisitor) handleExprs(paramMap map[string]bool, exprList []ast.Expr, stmtList []ast.Stmt) []ast.Stmt { for len(exprList) != 0 { expr := exprList[0] switch e := expr.(type) { case *ast.Ident: handleIdent(paramMap, e) case *ast.BinaryExpr: exprList = append(exprList, e.X) //TODO, do we need to then worry about x.left being used? exprList = append(exprList, e.Y) //TODO, do we need to then worry about x.left being used? case *ast.CallExpr: exprList = append(exprList, e.Args...) exprList = append(exprList, e.Fun) case *ast.IndexExpr: exprList = append(exprList, e.X) exprList = append(exprList, e.Index) case *ast.KeyValueExpr: exprList = append(exprList, e.Key, e.Value) case *ast.ParenExpr: exprList = append(exprList, e.X) case *ast.SelectorExpr: exprList = append(exprList, e.X) handleIdent(paramMap, e.Sel) case *ast.SliceExpr: exprList = append(exprList, e.Low, e.High, e.Max, e.X) case *ast.StarExpr: // need to dig deeper to see if this is a derefenced type exprList = append(exprList, e.X) case *ast.TypeAssertExpr: exprList = append(exprList, e.X, e.Type) case *ast.UnaryExpr: exprList = append(exprList, e.X) case *ast.BasicLit: // nothing to do here, no variable name case *ast.FuncLit: exprList = append(exprList, e.Type) stmtList = append(stmtList, e.Body) case *ast.CompositeLit: exprList = append(exprList, e.Elts...) case *ast.ArrayType: exprList = append(exprList, e.Elt, e.Len) case *ast.ChanType: exprList = append(exprList, e.Value) case *ast.FuncType: exprList, stmtList = handleFieldList(paramMap, e.Params, exprList, stmtList) exprList, stmtList = handleFieldList(paramMap, e.Results, exprList, stmtList) case *ast.InterfaceType: exprList, stmtList = handleFieldList(paramMap, e.Methods, exprList, stmtList) case *ast.MapType: exprList = append(exprList, e.Key, e.Value) case *ast.StructType: //TODO: no-op, unless it contains funcs I guess? revisit this // exprList, stmtList = handleFieldList(paramMap, e.Fields, exprList, stmtList) case *ast.Ellipsis: exprList = append(exprList, e.Elt) case nil: // no op default: log.Printf("ERROR: unknown expr type %T\n", e) } exprList = exprList[1:] } return stmtList } func handleFieldList(paramMap map[string]bool, fieldList *ast.FieldList, exprList []ast.Expr, stmtList []ast.Stmt) ([]ast.Expr, []ast.Stmt) { if fieldList == nil { return exprList, stmtList } for _, field := range fieldList.List { exprList = append(exprList, field.Type) handleIdents(paramMap, field.Names) } return exprList, stmtList } func (v *unusedVisitor) handleDecls(paramMap map[string]bool, decls []ast.Decl, initialStmts []ast.Stmt) []ast.Stmt { for _, decl := range decls { switch d := decl.(type) { case *ast.GenDecl: for _, spec := range d.Specs { switch specType := spec.(type) { case *ast.ValueSpec: //TODO - I think the only specs we care about here are when we have a function declaration handleIdents(paramMap, specType.Names) initialStmts = v.handleExprs(paramMap, []ast.Expr{specType.Type}, initialStmts) initialStmts = v.handleExprs(paramMap, specType.Values, initialStmts) for index, value := range specType.Values { funcLit, ok := value.(*ast.FuncLit) if !ok { continue } funcName := specType.Names[index] // get arguments of function, this is a candidate // with potentially unused arguments v.handleFuncLit(paramMap, funcLit, funcName) } case *ast.TypeSpec: handleIdent(paramMap, specType.Name) initialStmts = v.handleExprs(paramMap, []ast.Expr{specType.Type}, initialStmts) case *ast.ImportSpec: // no-op, ImportSpecs do not contain functions default: log.Printf("ERROR: unknown spec type %T\n", specType) } } case *ast.FuncDecl: initialStmts = v.handleFuncDecl(paramMap, d, initialStmts) default: log.Printf("ERROR: unknown decl type %T\n", d) } } return initialStmts } // paramMap is passed in for cases where we have an outer function with a parameter // that is captured by closure by the function literal func (v *unusedVisitor) handleFuncLit(paramMap map[string]bool, funcLit *ast.FuncLit, funcName *ast.Ident) { if funcLit.Type != nil && funcLit.Type.Params != nil && len(funcLit.Type.Params.List) > 0 { // declare a separate parameter map for handling funcParamMap := make(map[string]bool) for _, param := range funcLit.Type.Params.List { for _, paramName := range param.Names { if paramName.Name != "_" { funcParamMap[paramName.Name] = false } } } // generate potential statements v.handleStmts(funcParamMap, []ast.Stmt{funcLit.Body}) v.handleStmts(paramMap, []ast.Stmt{funcLit.Body}) for paramName, used := range funcParamMap { if !used && paramName != "_" { //TODO: this append currently causes things to appear out of order (2) file := v.fileSet.File(funcLit.Pos()) resStr := fmt.Sprintf("%v:%v %v contains unused parameter %v\n", file.Name(), file.Position(funcLit.Pos()).Line, funcName.Name, paramName) v.resultsSet[resStr] = struct{}{} } } } } func (v *unusedVisitor) handleFuncDecl(paramMap map[string]bool, funcDecl *ast.FuncDecl, initialStmts []ast.Stmt) []ast.Stmt { if funcDecl.Body != nil { initialStmts = append(initialStmts, funcDecl.Body.List...) } if funcDecl.Type != nil { if funcDecl.Type.Params != nil { for _, paramList := range funcDecl.Type.Params.List { for _, name := range paramList.Names { if name.Name == "_" { continue } paramMap[name.Name] = false } } } if v.includeNamedReturns && funcDecl.Type.Results != nil { for _, paramList := range funcDecl.Type.Results.List { for _, name := range paramList.Names { if name.Name == "_" { continue } paramMap[name.Name] = false } } } } if v.includeReceivers && funcDecl.Recv != nil { for _, field := range funcDecl.Recv.List { for _, name := range field.Names { if name.Name == "_" { continue } paramMap[name.Name] = false } } } return initialStmts }
{ a[i], a[j] = a[j], a[i] }
identifier_body
nargs.go
package nargs import ( "fmt" "go/ast" "go/build" "go/token" "log" "sort" "strconv" "strings" ) func init() { build.Default.UseAllFiles = true } // Flags contains configuration specific to nargs // * IncludeTests - include test files in analysis // * SetExitStatus - set exit status to 1 if any issues are found // * IncludeNamedReturns - include unused named returns // * IncludeReceivers - include unused receivers type Flags struct { IncludeTests bool SetExitStatus bool IncludeNamedReturns bool IncludeReceivers bool } type unusedVisitor struct { fileSet *token.FileSet resultsSet map[string]struct{} includeNamedReturns bool includeReceivers bool errsFound bool } // CheckForUnusedFunctionArgs will parse the files/packages contained in args // and walk the AST searching for unused function parameters. func CheckForUnusedFunctionArgs(args []string, flags Flags) (results []string, exitWithStatus bool, _ error) { fset := token.NewFileSet() files, err := parseInput(args, fset, flags.IncludeTests) if err != nil { return nil, false, fmt.Errorf("could not parse input, %v", err) } retVis := &unusedVisitor{ fileSet: fset, includeNamedReturns: flags.IncludeNamedReturns, includeReceivers: flags.IncludeReceivers, resultsSet: make(map[string]struct{}), } // visitorResult contains the results for a specific visitor and is cleared on each // iteration var visitorResult []string for _, f := range files { if f == nil { continue } ast.Walk(retVis, f) for result, _ := range retVis.resultsSet { visitorResult = append(visitorResult, result) } // Due to our analysis, of the ast.File, we may end up getting our results out of order. Sort by line number to keep // the results in a consistent format. sort.Sort(byLineNumber(visitorResult)) results = append(results, visitorResult...) visitorResult = nil retVis.resultsSet = make(map[string]struct{}) } return results, retVis.errsFound && flags.SetExitStatus, nil } // ugly, but not sure if there's another option.. type byLineNumber []string func (a byLineNumber) Len() int { return len(a) } func (a byLineNumber) Less(i, j int) bool { iLine := strings.Split(a[i], ":") num := strings.Split(iLine[1], " ") iNum, _ := strconv.Atoi(num[0]) jLine := strings.Split(a[j], ":") num = strings.Split(jLine[1], " ") jNum, _ := strconv.Atoi(num[0]) return iNum < jNum } func (a byLineNumber) Swap(i, j int) { a[i], a[j] = a[j], a[i] } // Visit implements the ast.Visitor Visit method. func (v *unusedVisitor) Visit(node ast.Node) ast.Visitor { var stmtList []ast.Stmt var file *token.File paramMap := make(map[string]bool) var funcDecl *ast.FuncDecl switch topLevelType := node.(type) { case *ast.FuncDecl: funcDecl = topLevelType if funcDecl.Body == nil { // This means funcDecl is an external (non-Go) function, these // should not be included in the analysis return v } stmtList = v.handleFuncDecl(paramMap, funcDecl, stmtList) file = v.fileSet.File(funcDecl.Pos()) case *ast.File: file = v.fileSet.File(topLevelType.Pos()) if topLevelType.Decls != nil { stmtList = v.handleDecls(paramMap, topLevelType.Decls, stmtList) } default: return v } // We cannot exit if len(paramMap) == 0, we may have a function closure with // unused variables // Analyze body of function v.handleStmts(paramMap, stmtList) for funcName, used := range paramMap { if !used { if file != nil { if funcDecl != nil && funcDecl.Name != nil { //TODO print parameter vs parameter(s)? //TODO differentiation of used parameter vs. receiver? resStr := fmt.Sprintf("%v:%v %v contains unused parameter %v\n", file.Name(), file.Position(funcDecl.Pos()).Line, funcDecl.Name.Name, funcName) v.resultsSet[resStr] = struct{}{} v.errsFound = true } } } } return v } func (v *unusedVisitor) handleStmts(paramMap map[string]bool, stmtList []ast.Stmt) { for len(stmtList) != 0 { stmt := stmtList[0] switch s := stmt.(type) { case *ast.IfStmt: stmtList = append(stmtList, s.Init, s.Body, s.Else) stmtList = v.handleExprs(paramMap, []ast.Expr{s.Cond}, stmtList) case *ast.AssignStmt: assigned := false for index, right := range s.Rhs { funcLit, ok := right.(*ast.FuncLit) if !ok { continue } funcName, ok := s.Lhs[index].(*ast.Ident) if !ok { //TODO - understand this case a little more // log.Printf("@@@@@@@@@@@@@@@@@@@@@@@@@2 wat") continue } v.handleFuncLit(paramMap, funcLit, funcName) assigned = true } if !assigned { stmtList = v.handleExprs(paramMap, s.Lhs, stmtList) stmtList = v.handleExprs(paramMap, s.Rhs, stmtList) } case *ast.BlockStmt: stmtList = append(stmtList, s.List...) case *ast.ReturnStmt: stmtList = v.handleExprs(paramMap, s.Results, stmtList) case *ast.DeclStmt: stmtList = v.handleDecls(paramMap, []ast.Decl{s.Decl}, stmtList) case *ast.ExprStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList) case *ast.RangeStmt: stmtList = append(stmtList, s.Body) stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList) case *ast.ForStmt: stmtList = append(stmtList, s.Init) stmtList = append(stmtList, s.Body) stmtList = v.handleExprs(paramMap, []ast.Expr{s.Cond}, stmtList) stmtList = append(stmtList, s.Post) case *ast.TypeSwitchStmt: stmtList = append(stmtList, s.Body, s.Assign, s.Init) case *ast.CaseClause: stmtList = v.handleExprs(paramMap, s.List, stmtList) stmtList = append(stmtList, s.Body...) case *ast.SendStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.Chan, s.Value}, stmtList) case *ast.GoStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.Call}, stmtList) case *ast.DeferStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.Call}, stmtList) case *ast.SelectStmt: stmtList = append(stmtList, s.Body) case *ast.CommClause: stmtList = append(stmtList, s.Body...) stmtList = append(stmtList, s.Comm) case *ast.BranchStmt: handleIdent(paramMap, s.Label) case *ast.SwitchStmt: stmtList = append(stmtList, s.Body, s.Init) stmtList = v.handleExprs(paramMap, []ast.Expr{s.Tag}, stmtList) case *ast.LabeledStmt: handleIdent(paramMap, s.Label) stmtList = append(stmtList, s.Stmt) case *ast.IncDecStmt: stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList) case nil, *ast.EmptyStmt: //no-op default: log.Printf("ERROR: unknown stmt type %T\n", s) } stmtList = stmtList[1:] } } func handleIdents(paramMap map[string]bool, identList []*ast.Ident) { for _, ident := range identList { handleIdent(paramMap, ident) } } func handleIdent(paramMap map[string]bool, ident *ast.Ident) { if ident == nil { return } if ident.Obj != nil && ident.Obj.Kind == ast.Var { if _, ok := paramMap[ident.Obj.Name]; ok { paramMap[ident.Obj.Name] = true } /*else { if ident.Obj.Name != "_" { paramMap[ident.Obj.Name] = false } }*/ } //TODO - ensure this truly isn't needed - can we rely on the // ident object name? // if _, ok := paramMap[ident.Name]; ok { // paramMap[ident.Name] = true // } } func (v *unusedVisitor) handleExprs(paramMap map[string]bool, exprList []ast.Expr, stmtList []ast.Stmt) []ast.Stmt { for len(exprList) != 0 { expr := exprList[0] switch e := expr.(type) { case *ast.Ident: handleIdent(paramMap, e) case *ast.BinaryExpr: exprList = append(exprList, e.X) //TODO, do we need to then worry about x.left being used? exprList = append(exprList, e.Y) //TODO, do we need to then worry about x.left being used? case *ast.CallExpr: exprList = append(exprList, e.Args...) exprList = append(exprList, e.Fun) case *ast.IndexExpr: exprList = append(exprList, e.X) exprList = append(exprList, e.Index) case *ast.KeyValueExpr: exprList = append(exprList, e.Key, e.Value) case *ast.ParenExpr: exprList = append(exprList, e.X) case *ast.SelectorExpr: exprList = append(exprList, e.X) handleIdent(paramMap, e.Sel) case *ast.SliceExpr: exprList = append(exprList, e.Low, e.High, e.Max, e.X) case *ast.StarExpr: // need to dig deeper to see if this is a derefenced type exprList = append(exprList, e.X) case *ast.TypeAssertExpr: exprList = append(exprList, e.X, e.Type) case *ast.UnaryExpr: exprList = append(exprList, e.X) case *ast.BasicLit: // nothing to do here, no variable name case *ast.FuncLit: exprList = append(exprList, e.Type) stmtList = append(stmtList, e.Body) case *ast.CompositeLit: exprList = append(exprList, e.Elts...) case *ast.ArrayType: exprList = append(exprList, e.Elt, e.Len) case *ast.ChanType: exprList = append(exprList, e.Value) case *ast.FuncType: exprList, stmtList = handleFieldList(paramMap, e.Params, exprList, stmtList) exprList, stmtList = handleFieldList(paramMap, e.Results, exprList, stmtList) case *ast.InterfaceType: exprList, stmtList = handleFieldList(paramMap, e.Methods, exprList, stmtList) case *ast.MapType: exprList = append(exprList, e.Key, e.Value) case *ast.StructType: //TODO: no-op, unless it contains funcs I guess? revisit this // exprList, stmtList = handleFieldList(paramMap, e.Fields, exprList, stmtList) case *ast.Ellipsis: exprList = append(exprList, e.Elt) case nil: // no op default: log.Printf("ERROR: unknown expr type %T\n", e) } exprList = exprList[1:] } return stmtList } func handleFieldList(paramMap map[string]bool, fieldList *ast.FieldList, exprList []ast.Expr, stmtList []ast.Stmt) ([]ast.Expr, []ast.Stmt) { if fieldList == nil { return exprList, stmtList } for _, field := range fieldList.List { exprList = append(exprList, field.Type) handleIdents(paramMap, field.Names) } return exprList, stmtList } func (v *unusedVisitor) handleDecls(paramMap map[string]bool, decls []ast.Decl, initialStmts []ast.Stmt) []ast.Stmt { for _, decl := range decls { switch d := decl.(type) { case *ast.GenDecl: for _, spec := range d.Specs { switch specType := spec.(type) { case *ast.ValueSpec: //TODO - I think the only specs we care about here are when we have a function declaration handleIdents(paramMap, specType.Names) initialStmts = v.handleExprs(paramMap, []ast.Expr{specType.Type}, initialStmts) initialStmts = v.handleExprs(paramMap, specType.Values, initialStmts) for index, value := range specType.Values { funcLit, ok := value.(*ast.FuncLit) if !ok { continue } funcName := specType.Names[index] // get arguments of function, this is a candidate // with potentially unused arguments v.handleFuncLit(paramMap, funcLit, funcName) } case *ast.TypeSpec: handleIdent(paramMap, specType.Name) initialStmts = v.handleExprs(paramMap, []ast.Expr{specType.Type}, initialStmts) case *ast.ImportSpec:
default: log.Printf("ERROR: unknown spec type %T\n", specType) } } case *ast.FuncDecl: initialStmts = v.handleFuncDecl(paramMap, d, initialStmts) default: log.Printf("ERROR: unknown decl type %T\n", d) } } return initialStmts } // paramMap is passed in for cases where we have an outer function with a parameter // that is captured by closure by the function literal func (v *unusedVisitor) handleFuncLit(paramMap map[string]bool, funcLit *ast.FuncLit, funcName *ast.Ident) { if funcLit.Type != nil && funcLit.Type.Params != nil && len(funcLit.Type.Params.List) > 0 { // declare a separate parameter map for handling funcParamMap := make(map[string]bool) for _, param := range funcLit.Type.Params.List { for _, paramName := range param.Names { if paramName.Name != "_" { funcParamMap[paramName.Name] = false } } } // generate potential statements v.handleStmts(funcParamMap, []ast.Stmt{funcLit.Body}) v.handleStmts(paramMap, []ast.Stmt{funcLit.Body}) for paramName, used := range funcParamMap { if !used && paramName != "_" { //TODO: this append currently causes things to appear out of order (2) file := v.fileSet.File(funcLit.Pos()) resStr := fmt.Sprintf("%v:%v %v contains unused parameter %v\n", file.Name(), file.Position(funcLit.Pos()).Line, funcName.Name, paramName) v.resultsSet[resStr] = struct{}{} } } } } func (v *unusedVisitor) handleFuncDecl(paramMap map[string]bool, funcDecl *ast.FuncDecl, initialStmts []ast.Stmt) []ast.Stmt { if funcDecl.Body != nil { initialStmts = append(initialStmts, funcDecl.Body.List...) } if funcDecl.Type != nil { if funcDecl.Type.Params != nil { for _, paramList := range funcDecl.Type.Params.List { for _, name := range paramList.Names { if name.Name == "_" { continue } paramMap[name.Name] = false } } } if v.includeNamedReturns && funcDecl.Type.Results != nil { for _, paramList := range funcDecl.Type.Results.List { for _, name := range paramList.Names { if name.Name == "_" { continue } paramMap[name.Name] = false } } } } if v.includeReceivers && funcDecl.Recv != nil { for _, field := range funcDecl.Recv.List { for _, name := range field.Names { if name.Name == "_" { continue } paramMap[name.Name] = false } } } return initialStmts }
// no-op, ImportSpecs do not contain functions
random_line_split
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry // rf.GetState() (term, isLeader) // ask a Raft for its current term, and whether it thinks it is leader // ApplyMsg // each time a new entry is committed to the log, each Raft peer // should send an ApplyMsg to the service (or tester) // in the same server. // import ( // "bytes" "sync" "sync/atomic" "time" // "6.824/labgob" "6.824/labrpc" ) // // as each Raft peer becomes aware that successive log entries are // committed, the peer should send an ApplyMsg to the service (or // tester) on the same server, via the applyCh passed to Make(). set // CommandValid to true to indicate that the ApplyMsg contains a newly // committed log entry. // // in part 2D you'll want to send other kinds of messages (e.g., // snapshots) on the applyCh, but set CommandValid to false for these // other uses. // type ApplyMsg struct { CommandValid bool Command interface{} CommandIndex int // For 2D: SnapshotValid bool Snapshot []byte SnapshotTerm int SnapshotIndex int } // // A Go object implementing a single Raft peer. // type Raft struct { mu sync.Mutex // Lock to protect shared access to this peer's state peers []*labrpc.ClientEnd // RPC end points of all peers persister *Persister // Object to hold this peer's persisted state me int // this peer's index into peers[] dead int32 // set by Kill() // Your data here (2A, 2B, 2C). // Look at the paper's Figure 2 for a description of what // state a Raft server must maintain. n int // number of raft servers // Non-volatile fields on all servers // // Lastest term server has seen // (Initialized to 0 on first boot, increases monotonically) currentTerm int // CandidateId that received vote in current term (or null/-1 if none) votedFor int // LogEntry entries; each entry contains command for state machine, and term when // entry was received by leader (first index is 1) logs []LogEntry // Volatile fields on all servers // // Index of the highest log entry known to be committed // (Initialized to 0, increases monotonically) commitIndex int // Index of the highest log entry applied to state machine // (Initialized to 0, increases monotonically) lastApplied int // Refer to who is leader currentLeaderId int // Current raft node state currentState State // Reset election timeout ticker when received heartbeat from server resetElectionChan chan int // Number of granted votes after received RequestVoteRPC reply, reset after entering candidate state numberOfGrantedVotes int32 // Volatile fields on leader, reinitialized after election // // For each server, index of the highest log entry to send to that server // (Initialized to leader last log index + 1) nextIndex []int // For each server, index of the highest log entry known to be // replicated on server // (Initialized to 0, increases monotonically) matchIndex []int // Handle AppendEntriesRPC reply int this channel appendEntriesReplyHandler chan AppendEntriesReply // Use this handler to stop leader logic stopLeaderLogicHandler chan int // Handle RequestVoteRPC reply in this channel requestVoteReplyHandler chan RequestVoteReply } // return currentTerm and whether this server // believes it is the leader. func (rf *Raft) GetState() (int, bool) { //var term int //var isleader bool // Your code here (2A). rf.mu.Lock() defer rf.mu.Unlock() return rf.currentTerm, rf.currentState == StateLeader } // // save Raft's persistent state to stable storage, // where it can later be retrieved after a crash and restart. // see paper's Figure 2 for a description of what should be persistent. // func (rf *Raft) persist() { // Your code here (2C). // Example: // w := new(bytes.Buffer) // e := labgob.NewEncoder(w) // e.Encode(rf.xxx) // e.Encode(rf.yyy) // data := w.Bytes() // rf.persister.SaveRaftState(data) } // // restore previously persisted state. // func (rf *Raft) readPersist(data []byte) { if data == nil || len(data) < 1 { // bootstrap without any state? return } // Your code here (2C). // Example: // r := bytes.NewBuffer(data) // d := labgob.NewDecoder(r) // var xxx // var yyy // if d.Decode(&xxx) != nil || // d.Decode(&yyy) != nil { // error... // } else { // rf.xxx = xxx // rf.yyy = yyy // } } // // A service wants to switch to snapshot. Only do so if Raft hasn't // have more recent info since it communicate the snapshot on applyCh. // func (rf *Raft) CondInstallSnapshot(lastIncludedTerm int, lastIncludedIndex int, snapshot []byte) bool { // Your code here (2D). return true } // the service says it has created a snapshot that has // all info up to and including index. this means the // service no longer needs the log through (and including) // that index. Raft should now trim its log as much as possible. func (rf *Raft) Snapshot(index int, snapshot []byte) { // Your code here (2D). } // // example RequestVote RPC arguments structure. // field names must start with capital letters! // type RequestVoteArgs struct { // Your data here (2A, 2B). Term int // candidate's term CandidateId int // candidate requesting vote LastLogIndex int // index of candidate's last log entry LastLogTerm int // term of candidate's last log entry } // // example RequestVote RPC reply structure. // field names must start with capital letters! // type RequestVoteReply struct { // Your data here (2A). PeerId int // indicates who's vote Term int // currentTerm, for candidate to update itself VoteGranted bool // true means candidate received vote } // // example RequestVote RPC handler. // func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) { // Your code here (2A, 2B). DPrintf("Raft node (%d) handles with RequestVote, candidateId: %v\n", rf.me, args.CandidateId) rf.mu.Lock() defer rf.mu.Unlock() reply.Term = rf.currentTerm reply.PeerId = rf.me if rf.currentTerm == args.Term && rf.votedFor != -1 && rf.votedFor != args.CandidateId { DPrintf("Raft node (%v) denied vote, votedFor: %v, candidateId: %v.\n", rf.me, rf.votedFor, args.CandidateId) reply.VoteGranted = false return } lastLogIndex := len(rf.logs) - 1 lastLogEntry := rf.logs[lastLogIndex] if lastLogEntry.Term > args.LastLogTerm || lastLogIndex > args.LastLogIndex { // If this node is more up-to-date than candidate, then reject vote //DPrintf("Raft node (%v) LastLogIndex: %v, LastLogTerm: %v, args (%v, %v)\n", rf.me, // lastLogIndex, lastLogEntry.Term, args.LastLogIndex, args.LastLogTerm) reply.VoteGranted = false return } rf.tryEnterFollowState(args.Term) rf.currentTerm = args.Term rf.votedFor = args.CandidateId reply.VoteGranted = true } // // example code to send a RequestVote RPC to a server. // server is the index of the target server in rf.peers[]. // expects RPC arguments in args. // fills in *reply with RPC reply, so caller should // pass &reply. // the types of the args and reply passed to Call() must be // the same as the types of the arguments declared in the // handler function (including whether they are pointers). // // The labrpc package simulates a lossy network, in which servers // may be unreachable, and in which requests and replies may be lost. // Call() sends a request and waits for a reply. If a reply arrives // within a timeout interval, Call() returns true; otherwise // Call() returns false. Thus Call() may not return for a while. // A false return can be caused by a dead server, a live server that // can't be reached, a lost request, or a lost reply. // // Call() is guaranteed to return (perhaps after a delay) *except* if the // handler function on the server side does not return. Thus there // is no need to implement your own timeouts around Call(). // // look at the comments in ../labrpc/labrpc.go for more details. // // if you're having trouble getting RPC to work, check that you've // capitalized all field names in structs passed over RPC, and // that the caller passes the address of the reply struct with &, not // the struct itself. // func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool { ok := rf.peers[server].Call("Raft.RequestVote", args, reply) return ok } // // AppendEntries RPC handler // func (rf *Raft) AppendEntries(args *AppendEntriesArgs, reply *AppendEntriesReply) { rf.mu.Lock() defer rf.mu.Unlock() reply.Success = false reply.Term = rf.currentTerm reply.PeerId = rf.me if rf.currentTerm > args.Term { // 1. Reply false if term < currentTerm return } prevLogIndex := args.PrevLogIndex prevLogTerm := args.PrevLogTerm if prevLogIndex >= len(rf.logs) { return } if rf.logs[prevLogIndex].Term != prevLogTerm { // 2. Reply false if log dosen't contain an entry at prevLogIndex // whose term matches prevLogTerm return } var i, j = 0, prevLogIndex + 1 for ; i < len(args.Entries) && j < len(rf.logs); i, j = i + 1, j + 1 { if rf.logs[j].Term != args.Entries[i].Term { // 3. If an existing entry conflicts with a new one (same index but different terms), // delete the existing entry and all that follow it. rf.logs = rf.logs[:j] break } } // 4. Append any new entries not already in the log for ; i < len(args.Entries); i++ { rf.logs = append(rf.logs, args.Entries[i]) } if args.LeaderCommit > rf.commitIndex { // 5. If leaderCommit > commitIndex, set commitIndex = min(leaderCommit, index of last new entry) rf.commitIndex = Min(args.LeaderCommit, len(rf.logs) - 1) } rf.tryEnterFollowState(args.Term) rf.votedFor = -1 rf.currentLeaderId = args.LeaderId // Reset election timer after received AppendEntries rf.resetElectionChan <- 1 reply.Success = true } func (rf *Raft) sendAppendEntries(server int, args *AppendEntriesArgs, reply *AppendEntriesReply) bool { ok := rf.peers[server].Call("Raft.AppendEntries", args, reply) return ok } // // the service using Raft (e.g. a k/v server) wants to start // agreement on the next command to be appended to Raft's log. if this // server isn't the leader, returns false. otherwise start the // agreement and return immediately. there is no guarantee that this // command will ever be committed to the Raft log, since the leader // may fail or lose an election. even if the Raft instance has been killed, // this function should return gracefully. // // the first return value is the index that the command will appear at // if it's ever committed. the second return value is the current // term. the third return value is true if this server believes it is // the leader. // func (rf *Raft)
(command interface{}) (int, int, bool) { index := -1 term := -1 isLeader := true // Your code here (2B). rf.mu.Lock() defer rf.mu.Unlock() index = rf.commitIndex + 1 term = rf.currentTerm isLeader = rf.currentState == StateLeader return index, term, isLeader } // // the tester doesn't halt goroutines created by Raft after each test, // but it does call the Kill() method. your code can use killed() to // check whether Kill() has been called. the use of atomic avoids the // need for a lock. // // the issue is that long-running goroutines use memory and may chew // up CPU time, perhaps causing later tests to fail and generating // confusing debug output. any goroutine with a long-running loop // should call killed() to check whether it should stop. // func (rf *Raft) Kill() { atomic.StoreInt32(&rf.dead, 1) // Your code here, if desired. } func (rf *Raft) killed() bool { z := atomic.LoadInt32(&rf.dead) return z == 1 } func (rf *Raft) isLeader() bool { z := atomic.LoadInt32((*int32)(&rf.currentState)) return State(z) == StateLeader } func (rf *Raft) isCandidate() bool { z := atomic.LoadInt32((*int32)(&rf.currentState)) return State(z) == StateCandidate } // The ticker go routine starts a new election if this peer hasn't received // heartsbeats recently. func (rf *Raft) ticker() { for rf.killed() == false { // Your code here to check if a leader election should // be started and to randomize sleeping time using // time.Sleep(). select { case <- rf.resetElectionChan: DPrintf("Raft node (%v) reseted election timer, currentLeaderId: %v, currentTerm: %v, currentState: %v, votedFor: %v.\n", rf.me, rf.currentLeaderId, rf.currentTerm, rf.currentState, rf.votedFor) // Reset election timeout case <- time.After(time.Millisecond * time.Duration(RandInt(MinElectionTimeout, MaxElectionTimeout))): if !rf.isLeader() { rf.enterCandidateState() } else { // If a leader didn't receive any AppendEntries reply from peers, it reverts to follower state. rf.mu.Lock() rf.tryEnterFollowState(rf.currentTerm) rf.mu.Unlock() rf.stopLeaderLogicHandler <- 1 } } } } // --------------------------------------------------------------------------------------------------- // Follow logic // Revert Raft node into follow state, // after received RPC from other nodes and find its own term is out of date // **must be called in lock** func (rf *Raft) tryEnterFollowState(term int) { // If RPC request or response contains term T > currentTerm: // set currentTerm = T, convert to follower. if term >= rf.currentTerm && rf.currentState != StateFollower { DPrintf("Raft node (%v) reverted into follower, term: %v.\n", rf.me, term) rf.votedFor = -1 rf.currentTerm = term rf.currentState = StateFollower } } // --------------------------------------------------------------------------------------------------- // Candidate logic // Revert Raft node into candidate state func (rf *Raft) enterCandidateState() { rf.mu.Lock() rf.currentState = StateCandidate rf.currentTerm += 1 rf.votedFor = rf.me rf.numberOfGrantedVotes = int32(1) rf.mu.Unlock() DPrintf("Raft node (%v) reverted into candidate, currentTerm: %v.\n", rf.me, rf.currentTerm) // First, start a goroutine to handle RequestVote reply go rf.handleRequestVoteReply() for ii :=range rf.peers { if ii == rf.me { continue } go func(i int) { // Initialize RequestVoteArgs args := RequestVoteArgs{} args.Term = rf.currentTerm args.CandidateId = rf.me args.LastLogIndex = len(rf.logs) - 1 args.LastLogTerm = rf.logs[args.LastLogIndex].Term reply := RequestVoteReply{} rf.sendRequestVote(i, &args, &reply) // Handle RequestVoteRPC reply rf.requestVoteReplyHandler <- reply }(ii) } } func (rf *Raft) handleRequestVoteReply() { for rf.isCandidate() { select { case reply := <-rf.requestVoteReplyHandler: if !rf.isCandidate() { return } DPrintf("Raft node (%v) received RequestVote reply, PeerId: %v, VoteGranted: %v, Term: %v\n", rf.me, reply.PeerId, reply.VoteGranted, reply.Term) if reply.VoteGranted == true { nOfGrantedVotes := atomic.AddInt32(&rf.numberOfGrantedVotes, int32(1)) if int(nOfGrantedVotes) >= rf.n>>1 + 1 { // Hold a majority of raft servers's votes // enter into state of Leader rf.enterLeaderState() return } } else { rf.mu.Lock() if reply.Term > rf.currentTerm { rf.tryEnterFollowState(reply.Term) rf.mu.Unlock() return } rf.mu.Unlock() } } } } // --------------------------------------------------------------------------------------------------- // Leader logic func (rf *Raft) enterLeaderState() { DPrintf("Raft node (%v) reverted into leader.\n", rf.me) rf.mu.Lock() rf.currentState = StateLeader rf.currentLeaderId = rf.me // When a leader first comes to power, it initializes all nextIndex values // to the index just after the last one in its log. for i := range rf.peers { rf.nextIndex[i] = len(rf.logs) } rf.mu.Unlock() go rf.handleAppendEntriesReply() // Send heartbeats immediately to followers go rf.pulse() } // Send heartbeat to followers, only executed by leader func (rf *Raft) pulse() { for rf.isLeader() { // Start send AppendEntries RPC to the rest of cluster for ii := range rf.peers { if ii == rf.me { continue } go func(i int) { args := rf.makeAppendEntriesArgs(i) reply := AppendEntriesReply{} rf.sendAppendEntries(i, &args, &reply) rf.appendEntriesReplyHandler <- reply }(ii) } time.Sleep(time.Duration(HeartBeatsInterval) * time.Millisecond) } } func (rf *Raft) handleAppendEntriesReply() { for rf.isLeader() { select { case <- rf.stopLeaderLogicHandler: // Break out this loop case reply := <- rf.appendEntriesReplyHandler: if !rf.isLeader() { return } DPrintf("Raft node (%v) starts to handle AppendEntries reply.\n", rf.me) rf.mu.Lock() peerId := reply.PeerId if reply.Success { // Reset election timer to prevent reverting leader to follower rf.resetElectionChan <- 1 // TODO update nextIndex[], matchIndex[] rf.nextIndex[peerId] = len(rf.logs) rf.matchIndex[peerId] = rf.commitIndex } else { if reply.Term > rf.currentTerm { rf.tryEnterFollowState(reply.Term) rf.mu.Unlock() break } // TODO Sync logs //rf.nextIndex[peerId] -= 1 //go func(pId int) { // args := rf.makeAppendEntriesArgs(pId) // rep := AppendEntriesReply{} // rf.sendAppendEntries(peerId, &args, &rep) // rf.appendEntriesReplyHandler <- rep //}(peerId) } rf.mu.Unlock() } } } func (rf *Raft) makeAppendEntriesArgs(peerId int) AppendEntriesArgs { // Initialize AppendEntriesArgs rf.mu.Lock() defer rf.mu.Unlock() args := AppendEntriesArgs{} args.Term = rf.currentTerm args.LeaderId = rf.me args.PrevLogIndex = rf.nextIndex[peerId] - 1 if args.PrevLogIndex > 0 { args.PrevLogTerm = rf.logs[args.PrevLogIndex].Term } args.Entries = []LogEntry{} args.LeaderCommit = rf.commitIndex return args } // // the service or tester wants to create a Raft server. the ports // of all the Raft servers (including this one) are in peers[]. this // server's port is peers[me]. all the servers' peers[] arrays // have the same order. persister is a place for this server to // save its persistent state, and also initially holds the most // recent saved state, if any. applyCh is a channel on which the // tester or service expects Raft to send ApplyMsg messages. // Make() must return quickly, so it should start goroutines // for any long-running work. // func Make(peers []*labrpc.ClientEnd, me int, persister *Persister, applyCh chan ApplyMsg) *Raft { rf := &Raft{} rf.peers = peers rf.persister = persister rf.me = me rf.n = len(peers) rf.currentState = StateFollower rf.currentTerm = 0 rf.votedFor = -1 rf.logs = make([]LogEntry, 1) rf.logs[0] = LogEntry{ Term: 0, Type: NoOp, Command: nil, } rf.commitIndex = 0 rf.lastApplied = 0 rf.resetElectionChan = make(chan int) rf.numberOfGrantedVotes = 0 rf.nextIndex = make([]int, rf.n) for i := range rf.nextIndex { rf.nextIndex[i] = 1 } rf.matchIndex = make([]int, rf.n) rf.appendEntriesReplyHandler = make(chan AppendEntriesReply) rf.stopLeaderLogicHandler = make(chan int) rf.requestVoteReplyHandler = make(chan RequestVoteReply) // Your initialization code here (2A, 2B, 2C). // initialize from state persisted before a crash rf.readPersist(persister.ReadRaftState()) // start ticker goroutine to start elections go rf.ticker() DPrintf("Raft node (%v) starts up...\n", me) return rf }
Start
identifier_name
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry // rf.GetState() (term, isLeader) // ask a Raft for its current term, and whether it thinks it is leader // ApplyMsg // each time a new entry is committed to the log, each Raft peer // should send an ApplyMsg to the service (or tester) // in the same server. // import ( // "bytes" "sync" "sync/atomic" "time" // "6.824/labgob" "6.824/labrpc" ) // // as each Raft peer becomes aware that successive log entries are // committed, the peer should send an ApplyMsg to the service (or // tester) on the same server, via the applyCh passed to Make(). set // CommandValid to true to indicate that the ApplyMsg contains a newly // committed log entry. // // in part 2D you'll want to send other kinds of messages (e.g., // snapshots) on the applyCh, but set CommandValid to false for these // other uses. // type ApplyMsg struct { CommandValid bool Command interface{} CommandIndex int // For 2D: SnapshotValid bool Snapshot []byte SnapshotTerm int SnapshotIndex int } // // A Go object implementing a single Raft peer. // type Raft struct { mu sync.Mutex // Lock to protect shared access to this peer's state peers []*labrpc.ClientEnd // RPC end points of all peers persister *Persister // Object to hold this peer's persisted state me int // this peer's index into peers[] dead int32 // set by Kill() // Your data here (2A, 2B, 2C). // Look at the paper's Figure 2 for a description of what // state a Raft server must maintain. n int // number of raft servers // Non-volatile fields on all servers // // Lastest term server has seen // (Initialized to 0 on first boot, increases monotonically) currentTerm int // CandidateId that received vote in current term (or null/-1 if none) votedFor int // LogEntry entries; each entry contains command for state machine, and term when // entry was received by leader (first index is 1) logs []LogEntry // Volatile fields on all servers // // Index of the highest log entry known to be committed // (Initialized to 0, increases monotonically) commitIndex int // Index of the highest log entry applied to state machine // (Initialized to 0, increases monotonically) lastApplied int // Refer to who is leader currentLeaderId int // Current raft node state currentState State // Reset election timeout ticker when received heartbeat from server resetElectionChan chan int // Number of granted votes after received RequestVoteRPC reply, reset after entering candidate state numberOfGrantedVotes int32 // Volatile fields on leader, reinitialized after election // // For each server, index of the highest log entry to send to that server // (Initialized to leader last log index + 1) nextIndex []int // For each server, index of the highest log entry known to be // replicated on server // (Initialized to 0, increases monotonically) matchIndex []int // Handle AppendEntriesRPC reply int this channel appendEntriesReplyHandler chan AppendEntriesReply // Use this handler to stop leader logic stopLeaderLogicHandler chan int // Handle RequestVoteRPC reply in this channel requestVoteReplyHandler chan RequestVoteReply } // return currentTerm and whether this server // believes it is the leader. func (rf *Raft) GetState() (int, bool) { //var term int //var isleader bool // Your code here (2A). rf.mu.Lock() defer rf.mu.Unlock() return rf.currentTerm, rf.currentState == StateLeader } // // save Raft's persistent state to stable storage, // where it can later be retrieved after a crash and restart. // see paper's Figure 2 for a description of what should be persistent. // func (rf *Raft) persist() { // Your code here (2C). // Example: // w := new(bytes.Buffer) // e := labgob.NewEncoder(w) // e.Encode(rf.xxx) // e.Encode(rf.yyy) // data := w.Bytes() // rf.persister.SaveRaftState(data) } // // restore previously persisted state. // func (rf *Raft) readPersist(data []byte) { if data == nil || len(data) < 1 { // bootstrap without any state? return } // Your code here (2C). // Example: // r := bytes.NewBuffer(data) // d := labgob.NewDecoder(r) // var xxx // var yyy // if d.Decode(&xxx) != nil || // d.Decode(&yyy) != nil { // error... // } else { // rf.xxx = xxx // rf.yyy = yyy // } } // // A service wants to switch to snapshot. Only do so if Raft hasn't // have more recent info since it communicate the snapshot on applyCh. // func (rf *Raft) CondInstallSnapshot(lastIncludedTerm int, lastIncludedIndex int, snapshot []byte) bool { // Your code here (2D). return true } // the service says it has created a snapshot that has // all info up to and including index. this means the // service no longer needs the log through (and including) // that index. Raft should now trim its log as much as possible. func (rf *Raft) Snapshot(index int, snapshot []byte) { // Your code here (2D). } // // example RequestVote RPC arguments structure. // field names must start with capital letters! // type RequestVoteArgs struct { // Your data here (2A, 2B). Term int // candidate's term CandidateId int // candidate requesting vote LastLogIndex int // index of candidate's last log entry LastLogTerm int // term of candidate's last log entry } // // example RequestVote RPC reply structure. // field names must start with capital letters! // type RequestVoteReply struct { // Your data here (2A). PeerId int // indicates who's vote Term int // currentTerm, for candidate to update itself VoteGranted bool // true means candidate received vote } // // example RequestVote RPC handler. // func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) { // Your code here (2A, 2B). DPrintf("Raft node (%d) handles with RequestVote, candidateId: %v\n", rf.me, args.CandidateId) rf.mu.Lock() defer rf.mu.Unlock() reply.Term = rf.currentTerm reply.PeerId = rf.me if rf.currentTerm == args.Term && rf.votedFor != -1 && rf.votedFor != args.CandidateId { DPrintf("Raft node (%v) denied vote, votedFor: %v, candidateId: %v.\n", rf.me, rf.votedFor, args.CandidateId) reply.VoteGranted = false return } lastLogIndex := len(rf.logs) - 1 lastLogEntry := rf.logs[lastLogIndex] if lastLogEntry.Term > args.LastLogTerm || lastLogIndex > args.LastLogIndex
rf.tryEnterFollowState(args.Term) rf.currentTerm = args.Term rf.votedFor = args.CandidateId reply.VoteGranted = true } // // example code to send a RequestVote RPC to a server. // server is the index of the target server in rf.peers[]. // expects RPC arguments in args. // fills in *reply with RPC reply, so caller should // pass &reply. // the types of the args and reply passed to Call() must be // the same as the types of the arguments declared in the // handler function (including whether they are pointers). // // The labrpc package simulates a lossy network, in which servers // may be unreachable, and in which requests and replies may be lost. // Call() sends a request and waits for a reply. If a reply arrives // within a timeout interval, Call() returns true; otherwise // Call() returns false. Thus Call() may not return for a while. // A false return can be caused by a dead server, a live server that // can't be reached, a lost request, or a lost reply. // // Call() is guaranteed to return (perhaps after a delay) *except* if the // handler function on the server side does not return. Thus there // is no need to implement your own timeouts around Call(). // // look at the comments in ../labrpc/labrpc.go for more details. // // if you're having trouble getting RPC to work, check that you've // capitalized all field names in structs passed over RPC, and // that the caller passes the address of the reply struct with &, not // the struct itself. // func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool { ok := rf.peers[server].Call("Raft.RequestVote", args, reply) return ok } // // AppendEntries RPC handler // func (rf *Raft) AppendEntries(args *AppendEntriesArgs, reply *AppendEntriesReply) { rf.mu.Lock() defer rf.mu.Unlock() reply.Success = false reply.Term = rf.currentTerm reply.PeerId = rf.me if rf.currentTerm > args.Term { // 1. Reply false if term < currentTerm return } prevLogIndex := args.PrevLogIndex prevLogTerm := args.PrevLogTerm if prevLogIndex >= len(rf.logs) { return } if rf.logs[prevLogIndex].Term != prevLogTerm { // 2. Reply false if log dosen't contain an entry at prevLogIndex // whose term matches prevLogTerm return } var i, j = 0, prevLogIndex + 1 for ; i < len(args.Entries) && j < len(rf.logs); i, j = i + 1, j + 1 { if rf.logs[j].Term != args.Entries[i].Term { // 3. If an existing entry conflicts with a new one (same index but different terms), // delete the existing entry and all that follow it. rf.logs = rf.logs[:j] break } } // 4. Append any new entries not already in the log for ; i < len(args.Entries); i++ { rf.logs = append(rf.logs, args.Entries[i]) } if args.LeaderCommit > rf.commitIndex { // 5. If leaderCommit > commitIndex, set commitIndex = min(leaderCommit, index of last new entry) rf.commitIndex = Min(args.LeaderCommit, len(rf.logs) - 1) } rf.tryEnterFollowState(args.Term) rf.votedFor = -1 rf.currentLeaderId = args.LeaderId // Reset election timer after received AppendEntries rf.resetElectionChan <- 1 reply.Success = true } func (rf *Raft) sendAppendEntries(server int, args *AppendEntriesArgs, reply *AppendEntriesReply) bool { ok := rf.peers[server].Call("Raft.AppendEntries", args, reply) return ok } // // the service using Raft (e.g. a k/v server) wants to start // agreement on the next command to be appended to Raft's log. if this // server isn't the leader, returns false. otherwise start the // agreement and return immediately. there is no guarantee that this // command will ever be committed to the Raft log, since the leader // may fail or lose an election. even if the Raft instance has been killed, // this function should return gracefully. // // the first return value is the index that the command will appear at // if it's ever committed. the second return value is the current // term. the third return value is true if this server believes it is // the leader. // func (rf *Raft) Start(command interface{}) (int, int, bool) { index := -1 term := -1 isLeader := true // Your code here (2B). rf.mu.Lock() defer rf.mu.Unlock() index = rf.commitIndex + 1 term = rf.currentTerm isLeader = rf.currentState == StateLeader return index, term, isLeader } // // the tester doesn't halt goroutines created by Raft after each test, // but it does call the Kill() method. your code can use killed() to // check whether Kill() has been called. the use of atomic avoids the // need for a lock. // // the issue is that long-running goroutines use memory and may chew // up CPU time, perhaps causing later tests to fail and generating // confusing debug output. any goroutine with a long-running loop // should call killed() to check whether it should stop. // func (rf *Raft) Kill() { atomic.StoreInt32(&rf.dead, 1) // Your code here, if desired. } func (rf *Raft) killed() bool { z := atomic.LoadInt32(&rf.dead) return z == 1 } func (rf *Raft) isLeader() bool { z := atomic.LoadInt32((*int32)(&rf.currentState)) return State(z) == StateLeader } func (rf *Raft) isCandidate() bool { z := atomic.LoadInt32((*int32)(&rf.currentState)) return State(z) == StateCandidate } // The ticker go routine starts a new election if this peer hasn't received // heartsbeats recently. func (rf *Raft) ticker() { for rf.killed() == false { // Your code here to check if a leader election should // be started and to randomize sleeping time using // time.Sleep(). select { case <- rf.resetElectionChan: DPrintf("Raft node (%v) reseted election timer, currentLeaderId: %v, currentTerm: %v, currentState: %v, votedFor: %v.\n", rf.me, rf.currentLeaderId, rf.currentTerm, rf.currentState, rf.votedFor) // Reset election timeout case <- time.After(time.Millisecond * time.Duration(RandInt(MinElectionTimeout, MaxElectionTimeout))): if !rf.isLeader() { rf.enterCandidateState() } else { // If a leader didn't receive any AppendEntries reply from peers, it reverts to follower state. rf.mu.Lock() rf.tryEnterFollowState(rf.currentTerm) rf.mu.Unlock() rf.stopLeaderLogicHandler <- 1 } } } } // --------------------------------------------------------------------------------------------------- // Follow logic // Revert Raft node into follow state, // after received RPC from other nodes and find its own term is out of date // **must be called in lock** func (rf *Raft) tryEnterFollowState(term int) { // If RPC request or response contains term T > currentTerm: // set currentTerm = T, convert to follower. if term >= rf.currentTerm && rf.currentState != StateFollower { DPrintf("Raft node (%v) reverted into follower, term: %v.\n", rf.me, term) rf.votedFor = -1 rf.currentTerm = term rf.currentState = StateFollower } } // --------------------------------------------------------------------------------------------------- // Candidate logic // Revert Raft node into candidate state func (rf *Raft) enterCandidateState() { rf.mu.Lock() rf.currentState = StateCandidate rf.currentTerm += 1 rf.votedFor = rf.me rf.numberOfGrantedVotes = int32(1) rf.mu.Unlock() DPrintf("Raft node (%v) reverted into candidate, currentTerm: %v.\n", rf.me, rf.currentTerm) // First, start a goroutine to handle RequestVote reply go rf.handleRequestVoteReply() for ii :=range rf.peers { if ii == rf.me { continue } go func(i int) { // Initialize RequestVoteArgs args := RequestVoteArgs{} args.Term = rf.currentTerm args.CandidateId = rf.me args.LastLogIndex = len(rf.logs) - 1 args.LastLogTerm = rf.logs[args.LastLogIndex].Term reply := RequestVoteReply{} rf.sendRequestVote(i, &args, &reply) // Handle RequestVoteRPC reply rf.requestVoteReplyHandler <- reply }(ii) } } func (rf *Raft) handleRequestVoteReply() { for rf.isCandidate() { select { case reply := <-rf.requestVoteReplyHandler: if !rf.isCandidate() { return } DPrintf("Raft node (%v) received RequestVote reply, PeerId: %v, VoteGranted: %v, Term: %v\n", rf.me, reply.PeerId, reply.VoteGranted, reply.Term) if reply.VoteGranted == true { nOfGrantedVotes := atomic.AddInt32(&rf.numberOfGrantedVotes, int32(1)) if int(nOfGrantedVotes) >= rf.n>>1 + 1 { // Hold a majority of raft servers's votes // enter into state of Leader rf.enterLeaderState() return } } else { rf.mu.Lock() if reply.Term > rf.currentTerm { rf.tryEnterFollowState(reply.Term) rf.mu.Unlock() return } rf.mu.Unlock() } } } } // --------------------------------------------------------------------------------------------------- // Leader logic func (rf *Raft) enterLeaderState() { DPrintf("Raft node (%v) reverted into leader.\n", rf.me) rf.mu.Lock() rf.currentState = StateLeader rf.currentLeaderId = rf.me // When a leader first comes to power, it initializes all nextIndex values // to the index just after the last one in its log. for i := range rf.peers { rf.nextIndex[i] = len(rf.logs) } rf.mu.Unlock() go rf.handleAppendEntriesReply() // Send heartbeats immediately to followers go rf.pulse() } // Send heartbeat to followers, only executed by leader func (rf *Raft) pulse() { for rf.isLeader() { // Start send AppendEntries RPC to the rest of cluster for ii := range rf.peers { if ii == rf.me { continue } go func(i int) { args := rf.makeAppendEntriesArgs(i) reply := AppendEntriesReply{} rf.sendAppendEntries(i, &args, &reply) rf.appendEntriesReplyHandler <- reply }(ii) } time.Sleep(time.Duration(HeartBeatsInterval) * time.Millisecond) } } func (rf *Raft) handleAppendEntriesReply() { for rf.isLeader() { select { case <- rf.stopLeaderLogicHandler: // Break out this loop case reply := <- rf.appendEntriesReplyHandler: if !rf.isLeader() { return } DPrintf("Raft node (%v) starts to handle AppendEntries reply.\n", rf.me) rf.mu.Lock() peerId := reply.PeerId if reply.Success { // Reset election timer to prevent reverting leader to follower rf.resetElectionChan <- 1 // TODO update nextIndex[], matchIndex[] rf.nextIndex[peerId] = len(rf.logs) rf.matchIndex[peerId] = rf.commitIndex } else { if reply.Term > rf.currentTerm { rf.tryEnterFollowState(reply.Term) rf.mu.Unlock() break } // TODO Sync logs //rf.nextIndex[peerId] -= 1 //go func(pId int) { // args := rf.makeAppendEntriesArgs(pId) // rep := AppendEntriesReply{} // rf.sendAppendEntries(peerId, &args, &rep) // rf.appendEntriesReplyHandler <- rep //}(peerId) } rf.mu.Unlock() } } } func (rf *Raft) makeAppendEntriesArgs(peerId int) AppendEntriesArgs { // Initialize AppendEntriesArgs rf.mu.Lock() defer rf.mu.Unlock() args := AppendEntriesArgs{} args.Term = rf.currentTerm args.LeaderId = rf.me args.PrevLogIndex = rf.nextIndex[peerId] - 1 if args.PrevLogIndex > 0 { args.PrevLogTerm = rf.logs[args.PrevLogIndex].Term } args.Entries = []LogEntry{} args.LeaderCommit = rf.commitIndex return args } // // the service or tester wants to create a Raft server. the ports // of all the Raft servers (including this one) are in peers[]. this // server's port is peers[me]. all the servers' peers[] arrays // have the same order. persister is a place for this server to // save its persistent state, and also initially holds the most // recent saved state, if any. applyCh is a channel on which the // tester or service expects Raft to send ApplyMsg messages. // Make() must return quickly, so it should start goroutines // for any long-running work. // func Make(peers []*labrpc.ClientEnd, me int, persister *Persister, applyCh chan ApplyMsg) *Raft { rf := &Raft{} rf.peers = peers rf.persister = persister rf.me = me rf.n = len(peers) rf.currentState = StateFollower rf.currentTerm = 0 rf.votedFor = -1 rf.logs = make([]LogEntry, 1) rf.logs[0] = LogEntry{ Term: 0, Type: NoOp, Command: nil, } rf.commitIndex = 0 rf.lastApplied = 0 rf.resetElectionChan = make(chan int) rf.numberOfGrantedVotes = 0 rf.nextIndex = make([]int, rf.n) for i := range rf.nextIndex { rf.nextIndex[i] = 1 } rf.matchIndex = make([]int, rf.n) rf.appendEntriesReplyHandler = make(chan AppendEntriesReply) rf.stopLeaderLogicHandler = make(chan int) rf.requestVoteReplyHandler = make(chan RequestVoteReply) // Your initialization code here (2A, 2B, 2C). // initialize from state persisted before a crash rf.readPersist(persister.ReadRaftState()) // start ticker goroutine to start elections go rf.ticker() DPrintf("Raft node (%v) starts up...\n", me) return rf }
{ // If this node is more up-to-date than candidate, then reject vote //DPrintf("Raft node (%v) LastLogIndex: %v, LastLogTerm: %v, args (%v, %v)\n", rf.me, // lastLogIndex, lastLogEntry.Term, args.LastLogIndex, args.LastLogTerm) reply.VoteGranted = false return }
conditional_block
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry // rf.GetState() (term, isLeader) // ask a Raft for its current term, and whether it thinks it is leader // ApplyMsg // each time a new entry is committed to the log, each Raft peer // should send an ApplyMsg to the service (or tester) // in the same server. // import ( // "bytes" "sync" "sync/atomic" "time" // "6.824/labgob" "6.824/labrpc" ) // // as each Raft peer becomes aware that successive log entries are // committed, the peer should send an ApplyMsg to the service (or // tester) on the same server, via the applyCh passed to Make(). set // CommandValid to true to indicate that the ApplyMsg contains a newly // committed log entry. // // in part 2D you'll want to send other kinds of messages (e.g., // snapshots) on the applyCh, but set CommandValid to false for these // other uses. // type ApplyMsg struct { CommandValid bool Command interface{} CommandIndex int // For 2D: SnapshotValid bool Snapshot []byte SnapshotTerm int SnapshotIndex int } // // A Go object implementing a single Raft peer. // type Raft struct { mu sync.Mutex // Lock to protect shared access to this peer's state peers []*labrpc.ClientEnd // RPC end points of all peers persister *Persister // Object to hold this peer's persisted state me int // this peer's index into peers[] dead int32 // set by Kill() // Your data here (2A, 2B, 2C). // Look at the paper's Figure 2 for a description of what // state a Raft server must maintain. n int // number of raft servers // Non-volatile fields on all servers // // Lastest term server has seen // (Initialized to 0 on first boot, increases monotonically) currentTerm int // CandidateId that received vote in current term (or null/-1 if none) votedFor int // LogEntry entries; each entry contains command for state machine, and term when // entry was received by leader (first index is 1) logs []LogEntry // Volatile fields on all servers // // Index of the highest log entry known to be committed // (Initialized to 0, increases monotonically) commitIndex int // Index of the highest log entry applied to state machine // (Initialized to 0, increases monotonically) lastApplied int // Refer to who is leader currentLeaderId int // Current raft node state currentState State // Reset election timeout ticker when received heartbeat from server resetElectionChan chan int // Number of granted votes after received RequestVoteRPC reply, reset after entering candidate state numberOfGrantedVotes int32 // Volatile fields on leader, reinitialized after election // // For each server, index of the highest log entry to send to that server // (Initialized to leader last log index + 1) nextIndex []int // For each server, index of the highest log entry known to be // replicated on server // (Initialized to 0, increases monotonically) matchIndex []int // Handle AppendEntriesRPC reply int this channel appendEntriesReplyHandler chan AppendEntriesReply // Use this handler to stop leader logic stopLeaderLogicHandler chan int // Handle RequestVoteRPC reply in this channel requestVoteReplyHandler chan RequestVoteReply } // return currentTerm and whether this server // believes it is the leader. func (rf *Raft) GetState() (int, bool)
// // save Raft's persistent state to stable storage, // where it can later be retrieved after a crash and restart. // see paper's Figure 2 for a description of what should be persistent. // func (rf *Raft) persist() { // Your code here (2C). // Example: // w := new(bytes.Buffer) // e := labgob.NewEncoder(w) // e.Encode(rf.xxx) // e.Encode(rf.yyy) // data := w.Bytes() // rf.persister.SaveRaftState(data) } // // restore previously persisted state. // func (rf *Raft) readPersist(data []byte) { if data == nil || len(data) < 1 { // bootstrap without any state? return } // Your code here (2C). // Example: // r := bytes.NewBuffer(data) // d := labgob.NewDecoder(r) // var xxx // var yyy // if d.Decode(&xxx) != nil || // d.Decode(&yyy) != nil { // error... // } else { // rf.xxx = xxx // rf.yyy = yyy // } } // // A service wants to switch to snapshot. Only do so if Raft hasn't // have more recent info since it communicate the snapshot on applyCh. // func (rf *Raft) CondInstallSnapshot(lastIncludedTerm int, lastIncludedIndex int, snapshot []byte) bool { // Your code here (2D). return true } // the service says it has created a snapshot that has // all info up to and including index. this means the // service no longer needs the log through (and including) // that index. Raft should now trim its log as much as possible. func (rf *Raft) Snapshot(index int, snapshot []byte) { // Your code here (2D). } // // example RequestVote RPC arguments structure. // field names must start with capital letters! // type RequestVoteArgs struct { // Your data here (2A, 2B). Term int // candidate's term CandidateId int // candidate requesting vote LastLogIndex int // index of candidate's last log entry LastLogTerm int // term of candidate's last log entry } // // example RequestVote RPC reply structure. // field names must start with capital letters! // type RequestVoteReply struct { // Your data here (2A). PeerId int // indicates who's vote Term int // currentTerm, for candidate to update itself VoteGranted bool // true means candidate received vote } // // example RequestVote RPC handler. // func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) { // Your code here (2A, 2B). DPrintf("Raft node (%d) handles with RequestVote, candidateId: %v\n", rf.me, args.CandidateId) rf.mu.Lock() defer rf.mu.Unlock() reply.Term = rf.currentTerm reply.PeerId = rf.me if rf.currentTerm == args.Term && rf.votedFor != -1 && rf.votedFor != args.CandidateId { DPrintf("Raft node (%v) denied vote, votedFor: %v, candidateId: %v.\n", rf.me, rf.votedFor, args.CandidateId) reply.VoteGranted = false return } lastLogIndex := len(rf.logs) - 1 lastLogEntry := rf.logs[lastLogIndex] if lastLogEntry.Term > args.LastLogTerm || lastLogIndex > args.LastLogIndex { // If this node is more up-to-date than candidate, then reject vote //DPrintf("Raft node (%v) LastLogIndex: %v, LastLogTerm: %v, args (%v, %v)\n", rf.me, // lastLogIndex, lastLogEntry.Term, args.LastLogIndex, args.LastLogTerm) reply.VoteGranted = false return } rf.tryEnterFollowState(args.Term) rf.currentTerm = args.Term rf.votedFor = args.CandidateId reply.VoteGranted = true } // // example code to send a RequestVote RPC to a server. // server is the index of the target server in rf.peers[]. // expects RPC arguments in args. // fills in *reply with RPC reply, so caller should // pass &reply. // the types of the args and reply passed to Call() must be // the same as the types of the arguments declared in the // handler function (including whether they are pointers). // // The labrpc package simulates a lossy network, in which servers // may be unreachable, and in which requests and replies may be lost. // Call() sends a request and waits for a reply. If a reply arrives // within a timeout interval, Call() returns true; otherwise // Call() returns false. Thus Call() may not return for a while. // A false return can be caused by a dead server, a live server that // can't be reached, a lost request, or a lost reply. // // Call() is guaranteed to return (perhaps after a delay) *except* if the // handler function on the server side does not return. Thus there // is no need to implement your own timeouts around Call(). // // look at the comments in ../labrpc/labrpc.go for more details. // // if you're having trouble getting RPC to work, check that you've // capitalized all field names in structs passed over RPC, and // that the caller passes the address of the reply struct with &, not // the struct itself. // func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool { ok := rf.peers[server].Call("Raft.RequestVote", args, reply) return ok } // // AppendEntries RPC handler // func (rf *Raft) AppendEntries(args *AppendEntriesArgs, reply *AppendEntriesReply) { rf.mu.Lock() defer rf.mu.Unlock() reply.Success = false reply.Term = rf.currentTerm reply.PeerId = rf.me if rf.currentTerm > args.Term { // 1. Reply false if term < currentTerm return } prevLogIndex := args.PrevLogIndex prevLogTerm := args.PrevLogTerm if prevLogIndex >= len(rf.logs) { return } if rf.logs[prevLogIndex].Term != prevLogTerm { // 2. Reply false if log dosen't contain an entry at prevLogIndex // whose term matches prevLogTerm return } var i, j = 0, prevLogIndex + 1 for ; i < len(args.Entries) && j < len(rf.logs); i, j = i + 1, j + 1 { if rf.logs[j].Term != args.Entries[i].Term { // 3. If an existing entry conflicts with a new one (same index but different terms), // delete the existing entry and all that follow it. rf.logs = rf.logs[:j] break } } // 4. Append any new entries not already in the log for ; i < len(args.Entries); i++ { rf.logs = append(rf.logs, args.Entries[i]) } if args.LeaderCommit > rf.commitIndex { // 5. If leaderCommit > commitIndex, set commitIndex = min(leaderCommit, index of last new entry) rf.commitIndex = Min(args.LeaderCommit, len(rf.logs) - 1) } rf.tryEnterFollowState(args.Term) rf.votedFor = -1 rf.currentLeaderId = args.LeaderId // Reset election timer after received AppendEntries rf.resetElectionChan <- 1 reply.Success = true } func (rf *Raft) sendAppendEntries(server int, args *AppendEntriesArgs, reply *AppendEntriesReply) bool { ok := rf.peers[server].Call("Raft.AppendEntries", args, reply) return ok } // // the service using Raft (e.g. a k/v server) wants to start // agreement on the next command to be appended to Raft's log. if this // server isn't the leader, returns false. otherwise start the // agreement and return immediately. there is no guarantee that this // command will ever be committed to the Raft log, since the leader // may fail or lose an election. even if the Raft instance has been killed, // this function should return gracefully. // // the first return value is the index that the command will appear at // if it's ever committed. the second return value is the current // term. the third return value is true if this server believes it is // the leader. // func (rf *Raft) Start(command interface{}) (int, int, bool) { index := -1 term := -1 isLeader := true // Your code here (2B). rf.mu.Lock() defer rf.mu.Unlock() index = rf.commitIndex + 1 term = rf.currentTerm isLeader = rf.currentState == StateLeader return index, term, isLeader } // // the tester doesn't halt goroutines created by Raft after each test, // but it does call the Kill() method. your code can use killed() to // check whether Kill() has been called. the use of atomic avoids the // need for a lock. // // the issue is that long-running goroutines use memory and may chew // up CPU time, perhaps causing later tests to fail and generating // confusing debug output. any goroutine with a long-running loop // should call killed() to check whether it should stop. // func (rf *Raft) Kill() { atomic.StoreInt32(&rf.dead, 1) // Your code here, if desired. } func (rf *Raft) killed() bool { z := atomic.LoadInt32(&rf.dead) return z == 1 } func (rf *Raft) isLeader() bool { z := atomic.LoadInt32((*int32)(&rf.currentState)) return State(z) == StateLeader } func (rf *Raft) isCandidate() bool { z := atomic.LoadInt32((*int32)(&rf.currentState)) return State(z) == StateCandidate } // The ticker go routine starts a new election if this peer hasn't received // heartsbeats recently. func (rf *Raft) ticker() { for rf.killed() == false { // Your code here to check if a leader election should // be started and to randomize sleeping time using // time.Sleep(). select { case <- rf.resetElectionChan: DPrintf("Raft node (%v) reseted election timer, currentLeaderId: %v, currentTerm: %v, currentState: %v, votedFor: %v.\n", rf.me, rf.currentLeaderId, rf.currentTerm, rf.currentState, rf.votedFor) // Reset election timeout case <- time.After(time.Millisecond * time.Duration(RandInt(MinElectionTimeout, MaxElectionTimeout))): if !rf.isLeader() { rf.enterCandidateState() } else { // If a leader didn't receive any AppendEntries reply from peers, it reverts to follower state. rf.mu.Lock() rf.tryEnterFollowState(rf.currentTerm) rf.mu.Unlock() rf.stopLeaderLogicHandler <- 1 } } } } // --------------------------------------------------------------------------------------------------- // Follow logic // Revert Raft node into follow state, // after received RPC from other nodes and find its own term is out of date // **must be called in lock** func (rf *Raft) tryEnterFollowState(term int) { // If RPC request or response contains term T > currentTerm: // set currentTerm = T, convert to follower. if term >= rf.currentTerm && rf.currentState != StateFollower { DPrintf("Raft node (%v) reverted into follower, term: %v.\n", rf.me, term) rf.votedFor = -1 rf.currentTerm = term rf.currentState = StateFollower } } // --------------------------------------------------------------------------------------------------- // Candidate logic // Revert Raft node into candidate state func (rf *Raft) enterCandidateState() { rf.mu.Lock() rf.currentState = StateCandidate rf.currentTerm += 1 rf.votedFor = rf.me rf.numberOfGrantedVotes = int32(1) rf.mu.Unlock() DPrintf("Raft node (%v) reverted into candidate, currentTerm: %v.\n", rf.me, rf.currentTerm) // First, start a goroutine to handle RequestVote reply go rf.handleRequestVoteReply() for ii :=range rf.peers { if ii == rf.me { continue } go func(i int) { // Initialize RequestVoteArgs args := RequestVoteArgs{} args.Term = rf.currentTerm args.CandidateId = rf.me args.LastLogIndex = len(rf.logs) - 1 args.LastLogTerm = rf.logs[args.LastLogIndex].Term reply := RequestVoteReply{} rf.sendRequestVote(i, &args, &reply) // Handle RequestVoteRPC reply rf.requestVoteReplyHandler <- reply }(ii) } } func (rf *Raft) handleRequestVoteReply() { for rf.isCandidate() { select { case reply := <-rf.requestVoteReplyHandler: if !rf.isCandidate() { return } DPrintf("Raft node (%v) received RequestVote reply, PeerId: %v, VoteGranted: %v, Term: %v\n", rf.me, reply.PeerId, reply.VoteGranted, reply.Term) if reply.VoteGranted == true { nOfGrantedVotes := atomic.AddInt32(&rf.numberOfGrantedVotes, int32(1)) if int(nOfGrantedVotes) >= rf.n>>1 + 1 { // Hold a majority of raft servers's votes // enter into state of Leader rf.enterLeaderState() return } } else { rf.mu.Lock() if reply.Term > rf.currentTerm { rf.tryEnterFollowState(reply.Term) rf.mu.Unlock() return } rf.mu.Unlock() } } } } // --------------------------------------------------------------------------------------------------- // Leader logic func (rf *Raft) enterLeaderState() { DPrintf("Raft node (%v) reverted into leader.\n", rf.me) rf.mu.Lock() rf.currentState = StateLeader rf.currentLeaderId = rf.me // When a leader first comes to power, it initializes all nextIndex values // to the index just after the last one in its log. for i := range rf.peers { rf.nextIndex[i] = len(rf.logs) } rf.mu.Unlock() go rf.handleAppendEntriesReply() // Send heartbeats immediately to followers go rf.pulse() } // Send heartbeat to followers, only executed by leader func (rf *Raft) pulse() { for rf.isLeader() { // Start send AppendEntries RPC to the rest of cluster for ii := range rf.peers { if ii == rf.me { continue } go func(i int) { args := rf.makeAppendEntriesArgs(i) reply := AppendEntriesReply{} rf.sendAppendEntries(i, &args, &reply) rf.appendEntriesReplyHandler <- reply }(ii) } time.Sleep(time.Duration(HeartBeatsInterval) * time.Millisecond) } } func (rf *Raft) handleAppendEntriesReply() { for rf.isLeader() { select { case <- rf.stopLeaderLogicHandler: // Break out this loop case reply := <- rf.appendEntriesReplyHandler: if !rf.isLeader() { return } DPrintf("Raft node (%v) starts to handle AppendEntries reply.\n", rf.me) rf.mu.Lock() peerId := reply.PeerId if reply.Success { // Reset election timer to prevent reverting leader to follower rf.resetElectionChan <- 1 // TODO update nextIndex[], matchIndex[] rf.nextIndex[peerId] = len(rf.logs) rf.matchIndex[peerId] = rf.commitIndex } else { if reply.Term > rf.currentTerm { rf.tryEnterFollowState(reply.Term) rf.mu.Unlock() break } // TODO Sync logs //rf.nextIndex[peerId] -= 1 //go func(pId int) { // args := rf.makeAppendEntriesArgs(pId) // rep := AppendEntriesReply{} // rf.sendAppendEntries(peerId, &args, &rep) // rf.appendEntriesReplyHandler <- rep //}(peerId) } rf.mu.Unlock() } } } func (rf *Raft) makeAppendEntriesArgs(peerId int) AppendEntriesArgs { // Initialize AppendEntriesArgs rf.mu.Lock() defer rf.mu.Unlock() args := AppendEntriesArgs{} args.Term = rf.currentTerm args.LeaderId = rf.me args.PrevLogIndex = rf.nextIndex[peerId] - 1 if args.PrevLogIndex > 0 { args.PrevLogTerm = rf.logs[args.PrevLogIndex].Term } args.Entries = []LogEntry{} args.LeaderCommit = rf.commitIndex return args } // // the service or tester wants to create a Raft server. the ports // of all the Raft servers (including this one) are in peers[]. this // server's port is peers[me]. all the servers' peers[] arrays // have the same order. persister is a place for this server to // save its persistent state, and also initially holds the most // recent saved state, if any. applyCh is a channel on which the // tester or service expects Raft to send ApplyMsg messages. // Make() must return quickly, so it should start goroutines // for any long-running work. // func Make(peers []*labrpc.ClientEnd, me int, persister *Persister, applyCh chan ApplyMsg) *Raft { rf := &Raft{} rf.peers = peers rf.persister = persister rf.me = me rf.n = len(peers) rf.currentState = StateFollower rf.currentTerm = 0 rf.votedFor = -1 rf.logs = make([]LogEntry, 1) rf.logs[0] = LogEntry{ Term: 0, Type: NoOp, Command: nil, } rf.commitIndex = 0 rf.lastApplied = 0 rf.resetElectionChan = make(chan int) rf.numberOfGrantedVotes = 0 rf.nextIndex = make([]int, rf.n) for i := range rf.nextIndex { rf.nextIndex[i] = 1 } rf.matchIndex = make([]int, rf.n) rf.appendEntriesReplyHandler = make(chan AppendEntriesReply) rf.stopLeaderLogicHandler = make(chan int) rf.requestVoteReplyHandler = make(chan RequestVoteReply) // Your initialization code here (2A, 2B, 2C). // initialize from state persisted before a crash rf.readPersist(persister.ReadRaftState()) // start ticker goroutine to start elections go rf.ticker() DPrintf("Raft node (%v) starts up...\n", me) return rf }
{ //var term int //var isleader bool // Your code here (2A). rf.mu.Lock() defer rf.mu.Unlock() return rf.currentTerm, rf.currentState == StateLeader }
identifier_body
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry // rf.GetState() (term, isLeader) // ask a Raft for its current term, and whether it thinks it is leader // ApplyMsg // each time a new entry is committed to the log, each Raft peer // should send an ApplyMsg to the service (or tester) // in the same server. // import ( // "bytes" "sync" "sync/atomic" "time" // "6.824/labgob" "6.824/labrpc" ) // // as each Raft peer becomes aware that successive log entries are // committed, the peer should send an ApplyMsg to the service (or // tester) on the same server, via the applyCh passed to Make(). set // CommandValid to true to indicate that the ApplyMsg contains a newly // committed log entry. // // in part 2D you'll want to send other kinds of messages (e.g., // snapshots) on the applyCh, but set CommandValid to false for these // other uses. // type ApplyMsg struct { CommandValid bool Command interface{} CommandIndex int // For 2D: SnapshotValid bool Snapshot []byte SnapshotTerm int SnapshotIndex int } // // A Go object implementing a single Raft peer. // type Raft struct { mu sync.Mutex // Lock to protect shared access to this peer's state peers []*labrpc.ClientEnd // RPC end points of all peers persister *Persister // Object to hold this peer's persisted state me int // this peer's index into peers[] dead int32 // set by Kill() // Your data here (2A, 2B, 2C). // Look at the paper's Figure 2 for a description of what // state a Raft server must maintain. n int // number of raft servers // Non-volatile fields on all servers // // Lastest term server has seen // (Initialized to 0 on first boot, increases monotonically) currentTerm int // CandidateId that received vote in current term (or null/-1 if none) votedFor int // LogEntry entries; each entry contains command for state machine, and term when // entry was received by leader (first index is 1) logs []LogEntry // Volatile fields on all servers // // Index of the highest log entry known to be committed // (Initialized to 0, increases monotonically) commitIndex int // Index of the highest log entry applied to state machine // (Initialized to 0, increases monotonically) lastApplied int // Refer to who is leader currentLeaderId int // Current raft node state currentState State // Reset election timeout ticker when received heartbeat from server resetElectionChan chan int // Number of granted votes after received RequestVoteRPC reply, reset after entering candidate state numberOfGrantedVotes int32
// (Initialized to leader last log index + 1) nextIndex []int // For each server, index of the highest log entry known to be // replicated on server // (Initialized to 0, increases monotonically) matchIndex []int // Handle AppendEntriesRPC reply int this channel appendEntriesReplyHandler chan AppendEntriesReply // Use this handler to stop leader logic stopLeaderLogicHandler chan int // Handle RequestVoteRPC reply in this channel requestVoteReplyHandler chan RequestVoteReply } // return currentTerm and whether this server // believes it is the leader. func (rf *Raft) GetState() (int, bool) { //var term int //var isleader bool // Your code here (2A). rf.mu.Lock() defer rf.mu.Unlock() return rf.currentTerm, rf.currentState == StateLeader } // // save Raft's persistent state to stable storage, // where it can later be retrieved after a crash and restart. // see paper's Figure 2 for a description of what should be persistent. // func (rf *Raft) persist() { // Your code here (2C). // Example: // w := new(bytes.Buffer) // e := labgob.NewEncoder(w) // e.Encode(rf.xxx) // e.Encode(rf.yyy) // data := w.Bytes() // rf.persister.SaveRaftState(data) } // // restore previously persisted state. // func (rf *Raft) readPersist(data []byte) { if data == nil || len(data) < 1 { // bootstrap without any state? return } // Your code here (2C). // Example: // r := bytes.NewBuffer(data) // d := labgob.NewDecoder(r) // var xxx // var yyy // if d.Decode(&xxx) != nil || // d.Decode(&yyy) != nil { // error... // } else { // rf.xxx = xxx // rf.yyy = yyy // } } // // A service wants to switch to snapshot. Only do so if Raft hasn't // have more recent info since it communicate the snapshot on applyCh. // func (rf *Raft) CondInstallSnapshot(lastIncludedTerm int, lastIncludedIndex int, snapshot []byte) bool { // Your code here (2D). return true } // the service says it has created a snapshot that has // all info up to and including index. this means the // service no longer needs the log through (and including) // that index. Raft should now trim its log as much as possible. func (rf *Raft) Snapshot(index int, snapshot []byte) { // Your code here (2D). } // // example RequestVote RPC arguments structure. // field names must start with capital letters! // type RequestVoteArgs struct { // Your data here (2A, 2B). Term int // candidate's term CandidateId int // candidate requesting vote LastLogIndex int // index of candidate's last log entry LastLogTerm int // term of candidate's last log entry } // // example RequestVote RPC reply structure. // field names must start with capital letters! // type RequestVoteReply struct { // Your data here (2A). PeerId int // indicates who's vote Term int // currentTerm, for candidate to update itself VoteGranted bool // true means candidate received vote } // // example RequestVote RPC handler. // func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) { // Your code here (2A, 2B). DPrintf("Raft node (%d) handles with RequestVote, candidateId: %v\n", rf.me, args.CandidateId) rf.mu.Lock() defer rf.mu.Unlock() reply.Term = rf.currentTerm reply.PeerId = rf.me if rf.currentTerm == args.Term && rf.votedFor != -1 && rf.votedFor != args.CandidateId { DPrintf("Raft node (%v) denied vote, votedFor: %v, candidateId: %v.\n", rf.me, rf.votedFor, args.CandidateId) reply.VoteGranted = false return } lastLogIndex := len(rf.logs) - 1 lastLogEntry := rf.logs[lastLogIndex] if lastLogEntry.Term > args.LastLogTerm || lastLogIndex > args.LastLogIndex { // If this node is more up-to-date than candidate, then reject vote //DPrintf("Raft node (%v) LastLogIndex: %v, LastLogTerm: %v, args (%v, %v)\n", rf.me, // lastLogIndex, lastLogEntry.Term, args.LastLogIndex, args.LastLogTerm) reply.VoteGranted = false return } rf.tryEnterFollowState(args.Term) rf.currentTerm = args.Term rf.votedFor = args.CandidateId reply.VoteGranted = true } // // example code to send a RequestVote RPC to a server. // server is the index of the target server in rf.peers[]. // expects RPC arguments in args. // fills in *reply with RPC reply, so caller should // pass &reply. // the types of the args and reply passed to Call() must be // the same as the types of the arguments declared in the // handler function (including whether they are pointers). // // The labrpc package simulates a lossy network, in which servers // may be unreachable, and in which requests and replies may be lost. // Call() sends a request and waits for a reply. If a reply arrives // within a timeout interval, Call() returns true; otherwise // Call() returns false. Thus Call() may not return for a while. // A false return can be caused by a dead server, a live server that // can't be reached, a lost request, or a lost reply. // // Call() is guaranteed to return (perhaps after a delay) *except* if the // handler function on the server side does not return. Thus there // is no need to implement your own timeouts around Call(). // // look at the comments in ../labrpc/labrpc.go for more details. // // if you're having trouble getting RPC to work, check that you've // capitalized all field names in structs passed over RPC, and // that the caller passes the address of the reply struct with &, not // the struct itself. // func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool { ok := rf.peers[server].Call("Raft.RequestVote", args, reply) return ok } // // AppendEntries RPC handler // func (rf *Raft) AppendEntries(args *AppendEntriesArgs, reply *AppendEntriesReply) { rf.mu.Lock() defer rf.mu.Unlock() reply.Success = false reply.Term = rf.currentTerm reply.PeerId = rf.me if rf.currentTerm > args.Term { // 1. Reply false if term < currentTerm return } prevLogIndex := args.PrevLogIndex prevLogTerm := args.PrevLogTerm if prevLogIndex >= len(rf.logs) { return } if rf.logs[prevLogIndex].Term != prevLogTerm { // 2. Reply false if log dosen't contain an entry at prevLogIndex // whose term matches prevLogTerm return } var i, j = 0, prevLogIndex + 1 for ; i < len(args.Entries) && j < len(rf.logs); i, j = i + 1, j + 1 { if rf.logs[j].Term != args.Entries[i].Term { // 3. If an existing entry conflicts with a new one (same index but different terms), // delete the existing entry and all that follow it. rf.logs = rf.logs[:j] break } } // 4. Append any new entries not already in the log for ; i < len(args.Entries); i++ { rf.logs = append(rf.logs, args.Entries[i]) } if args.LeaderCommit > rf.commitIndex { // 5. If leaderCommit > commitIndex, set commitIndex = min(leaderCommit, index of last new entry) rf.commitIndex = Min(args.LeaderCommit, len(rf.logs) - 1) } rf.tryEnterFollowState(args.Term) rf.votedFor = -1 rf.currentLeaderId = args.LeaderId // Reset election timer after received AppendEntries rf.resetElectionChan <- 1 reply.Success = true } func (rf *Raft) sendAppendEntries(server int, args *AppendEntriesArgs, reply *AppendEntriesReply) bool { ok := rf.peers[server].Call("Raft.AppendEntries", args, reply) return ok } // // the service using Raft (e.g. a k/v server) wants to start // agreement on the next command to be appended to Raft's log. if this // server isn't the leader, returns false. otherwise start the // agreement and return immediately. there is no guarantee that this // command will ever be committed to the Raft log, since the leader // may fail or lose an election. even if the Raft instance has been killed, // this function should return gracefully. // // the first return value is the index that the command will appear at // if it's ever committed. the second return value is the current // term. the third return value is true if this server believes it is // the leader. // func (rf *Raft) Start(command interface{}) (int, int, bool) { index := -1 term := -1 isLeader := true // Your code here (2B). rf.mu.Lock() defer rf.mu.Unlock() index = rf.commitIndex + 1 term = rf.currentTerm isLeader = rf.currentState == StateLeader return index, term, isLeader } // // the tester doesn't halt goroutines created by Raft after each test, // but it does call the Kill() method. your code can use killed() to // check whether Kill() has been called. the use of atomic avoids the // need for a lock. // // the issue is that long-running goroutines use memory and may chew // up CPU time, perhaps causing later tests to fail and generating // confusing debug output. any goroutine with a long-running loop // should call killed() to check whether it should stop. // func (rf *Raft) Kill() { atomic.StoreInt32(&rf.dead, 1) // Your code here, if desired. } func (rf *Raft) killed() bool { z := atomic.LoadInt32(&rf.dead) return z == 1 } func (rf *Raft) isLeader() bool { z := atomic.LoadInt32((*int32)(&rf.currentState)) return State(z) == StateLeader } func (rf *Raft) isCandidate() bool { z := atomic.LoadInt32((*int32)(&rf.currentState)) return State(z) == StateCandidate } // The ticker go routine starts a new election if this peer hasn't received // heartsbeats recently. func (rf *Raft) ticker() { for rf.killed() == false { // Your code here to check if a leader election should // be started and to randomize sleeping time using // time.Sleep(). select { case <- rf.resetElectionChan: DPrintf("Raft node (%v) reseted election timer, currentLeaderId: %v, currentTerm: %v, currentState: %v, votedFor: %v.\n", rf.me, rf.currentLeaderId, rf.currentTerm, rf.currentState, rf.votedFor) // Reset election timeout case <- time.After(time.Millisecond * time.Duration(RandInt(MinElectionTimeout, MaxElectionTimeout))): if !rf.isLeader() { rf.enterCandidateState() } else { // If a leader didn't receive any AppendEntries reply from peers, it reverts to follower state. rf.mu.Lock() rf.tryEnterFollowState(rf.currentTerm) rf.mu.Unlock() rf.stopLeaderLogicHandler <- 1 } } } } // --------------------------------------------------------------------------------------------------- // Follow logic // Revert Raft node into follow state, // after received RPC from other nodes and find its own term is out of date // **must be called in lock** func (rf *Raft) tryEnterFollowState(term int) { // If RPC request or response contains term T > currentTerm: // set currentTerm = T, convert to follower. if term >= rf.currentTerm && rf.currentState != StateFollower { DPrintf("Raft node (%v) reverted into follower, term: %v.\n", rf.me, term) rf.votedFor = -1 rf.currentTerm = term rf.currentState = StateFollower } } // --------------------------------------------------------------------------------------------------- // Candidate logic // Revert Raft node into candidate state func (rf *Raft) enterCandidateState() { rf.mu.Lock() rf.currentState = StateCandidate rf.currentTerm += 1 rf.votedFor = rf.me rf.numberOfGrantedVotes = int32(1) rf.mu.Unlock() DPrintf("Raft node (%v) reverted into candidate, currentTerm: %v.\n", rf.me, rf.currentTerm) // First, start a goroutine to handle RequestVote reply go rf.handleRequestVoteReply() for ii :=range rf.peers { if ii == rf.me { continue } go func(i int) { // Initialize RequestVoteArgs args := RequestVoteArgs{} args.Term = rf.currentTerm args.CandidateId = rf.me args.LastLogIndex = len(rf.logs) - 1 args.LastLogTerm = rf.logs[args.LastLogIndex].Term reply := RequestVoteReply{} rf.sendRequestVote(i, &args, &reply) // Handle RequestVoteRPC reply rf.requestVoteReplyHandler <- reply }(ii) } } func (rf *Raft) handleRequestVoteReply() { for rf.isCandidate() { select { case reply := <-rf.requestVoteReplyHandler: if !rf.isCandidate() { return } DPrintf("Raft node (%v) received RequestVote reply, PeerId: %v, VoteGranted: %v, Term: %v\n", rf.me, reply.PeerId, reply.VoteGranted, reply.Term) if reply.VoteGranted == true { nOfGrantedVotes := atomic.AddInt32(&rf.numberOfGrantedVotes, int32(1)) if int(nOfGrantedVotes) >= rf.n>>1 + 1 { // Hold a majority of raft servers's votes // enter into state of Leader rf.enterLeaderState() return } } else { rf.mu.Lock() if reply.Term > rf.currentTerm { rf.tryEnterFollowState(reply.Term) rf.mu.Unlock() return } rf.mu.Unlock() } } } } // --------------------------------------------------------------------------------------------------- // Leader logic func (rf *Raft) enterLeaderState() { DPrintf("Raft node (%v) reverted into leader.\n", rf.me) rf.mu.Lock() rf.currentState = StateLeader rf.currentLeaderId = rf.me // When a leader first comes to power, it initializes all nextIndex values // to the index just after the last one in its log. for i := range rf.peers { rf.nextIndex[i] = len(rf.logs) } rf.mu.Unlock() go rf.handleAppendEntriesReply() // Send heartbeats immediately to followers go rf.pulse() } // Send heartbeat to followers, only executed by leader func (rf *Raft) pulse() { for rf.isLeader() { // Start send AppendEntries RPC to the rest of cluster for ii := range rf.peers { if ii == rf.me { continue } go func(i int) { args := rf.makeAppendEntriesArgs(i) reply := AppendEntriesReply{} rf.sendAppendEntries(i, &args, &reply) rf.appendEntriesReplyHandler <- reply }(ii) } time.Sleep(time.Duration(HeartBeatsInterval) * time.Millisecond) } } func (rf *Raft) handleAppendEntriesReply() { for rf.isLeader() { select { case <- rf.stopLeaderLogicHandler: // Break out this loop case reply := <- rf.appendEntriesReplyHandler: if !rf.isLeader() { return } DPrintf("Raft node (%v) starts to handle AppendEntries reply.\n", rf.me) rf.mu.Lock() peerId := reply.PeerId if reply.Success { // Reset election timer to prevent reverting leader to follower rf.resetElectionChan <- 1 // TODO update nextIndex[], matchIndex[] rf.nextIndex[peerId] = len(rf.logs) rf.matchIndex[peerId] = rf.commitIndex } else { if reply.Term > rf.currentTerm { rf.tryEnterFollowState(reply.Term) rf.mu.Unlock() break } // TODO Sync logs //rf.nextIndex[peerId] -= 1 //go func(pId int) { // args := rf.makeAppendEntriesArgs(pId) // rep := AppendEntriesReply{} // rf.sendAppendEntries(peerId, &args, &rep) // rf.appendEntriesReplyHandler <- rep //}(peerId) } rf.mu.Unlock() } } } func (rf *Raft) makeAppendEntriesArgs(peerId int) AppendEntriesArgs { // Initialize AppendEntriesArgs rf.mu.Lock() defer rf.mu.Unlock() args := AppendEntriesArgs{} args.Term = rf.currentTerm args.LeaderId = rf.me args.PrevLogIndex = rf.nextIndex[peerId] - 1 if args.PrevLogIndex > 0 { args.PrevLogTerm = rf.logs[args.PrevLogIndex].Term } args.Entries = []LogEntry{} args.LeaderCommit = rf.commitIndex return args } // // the service or tester wants to create a Raft server. the ports // of all the Raft servers (including this one) are in peers[]. this // server's port is peers[me]. all the servers' peers[] arrays // have the same order. persister is a place for this server to // save its persistent state, and also initially holds the most // recent saved state, if any. applyCh is a channel on which the // tester or service expects Raft to send ApplyMsg messages. // Make() must return quickly, so it should start goroutines // for any long-running work. // func Make(peers []*labrpc.ClientEnd, me int, persister *Persister, applyCh chan ApplyMsg) *Raft { rf := &Raft{} rf.peers = peers rf.persister = persister rf.me = me rf.n = len(peers) rf.currentState = StateFollower rf.currentTerm = 0 rf.votedFor = -1 rf.logs = make([]LogEntry, 1) rf.logs[0] = LogEntry{ Term: 0, Type: NoOp, Command: nil, } rf.commitIndex = 0 rf.lastApplied = 0 rf.resetElectionChan = make(chan int) rf.numberOfGrantedVotes = 0 rf.nextIndex = make([]int, rf.n) for i := range rf.nextIndex { rf.nextIndex[i] = 1 } rf.matchIndex = make([]int, rf.n) rf.appendEntriesReplyHandler = make(chan AppendEntriesReply) rf.stopLeaderLogicHandler = make(chan int) rf.requestVoteReplyHandler = make(chan RequestVoteReply) // Your initialization code here (2A, 2B, 2C). // initialize from state persisted before a crash rf.readPersist(persister.ReadRaftState()) // start ticker goroutine to start elections go rf.ticker() DPrintf("Raft node (%v) starts up...\n", me) return rf }
// Volatile fields on leader, reinitialized after election // // For each server, index of the highest log entry to send to that server
random_line_split
svc.go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package manifest import ( "errors" "fmt" "math" "strconv" "strings" "time" "github.com/aws/aws-sdk-go/aws" "gopkg.in/yaml.v3" ) const ( // LoadBalancedWebServiceType is a web service with a load balancer and Fargate as compute. LoadBalancedWebServiceType = "Load Balanced Web Service" // RequestDrivenWebServiceType is a Request-Driven Web Service managed by AppRunner RequestDrivenWebServiceType = "Request-Driven Web Service" // BackendServiceType is a service that cannot be accessed from the internet but can be reached from other services. BackendServiceType = "Backend Service" // WorkerServiceType is a worker service that manages the consumption of messages. WorkerServiceType = "Worker Service" ) // ServiceTypes returns the list of supported service manifest types. func ServiceTypes() []string { return []string{ RequestDrivenWebServiceType, LoadBalancedWebServiceType, BackendServiceType, WorkerServiceType, } } // Range contains either a Range or a range configuration for Autoscaling ranges. type Range struct { Value *IntRangeBand // Mutually exclusive with RangeConfig RangeConfig RangeConfig } // IsEmpty returns whether Range is empty. func (r *Range) IsEmpty() bool { return r.Value == nil && r.RangeConfig.IsEmpty() } // Parse extracts the min and max from RangeOpts. func (r *Range) Parse() (min int, max int, err error) { if r.Value != nil { return r.Value.Parse() } return aws.IntValue(r.RangeConfig.Min), aws.IntValue(r.RangeConfig.Max), nil } // UnmarshalYAML overrides the default YAML unmarshaling logic for the RangeOpts // struct, allowing it to perform more complex unmarshaling behavior. // This method implements the yaml.Unmarshaler (v3) interface. func (r *Range) UnmarshalYAML(value *yaml.Node) error { if err := value.Decode(&r.RangeConfig); err != nil { switch err.(type) { case *yaml.TypeError: break default: return err } } if !r.RangeConfig.IsEmpty() { // Unmarshaled successfully to r.RangeConfig, unset r.Range, and return. r.Value = nil return nil } if err := value.Decode(&r.Value); err != nil { return errUnmarshalRangeOpts } return nil } // IntRangeBand is a number range with maximum and minimum values. type IntRangeBand string // Parse parses Range string and returns the min and max values. // For example: 1-100 returns 1 and 100. func (r IntRangeBand) Parse() (min int, max int, err error) { minMax := strings.Split(string(r), "-") if len(minMax) != 2 { return 0, 0, fmt.Errorf("invalid range value %s. Should be in format of ${min}-${max}", string(r)) } min, err = strconv.Atoi(minMax[0]) if err != nil { return 0, 0, fmt.Errorf("cannot convert minimum value %s to integer", minMax[0]) } max, err = strconv.Atoi(minMax[1]) if err != nil { return 0, 0, fmt.Errorf("cannot convert maximum value %s to integer", minMax[1]) } return min, max, nil } // RangeConfig containers a Min/Max and an optional SpotFrom field which // specifies the number of services you want to start placing on spot. For // example, if your range is 1-10 and `spot_from` is 5, up to 4 services will // be placed on dedicated Fargate capacity, and then after that, any scaling // event will place additioanl services on spot capacity. type RangeConfig struct { Min *int `yaml:"min"` Max *int `yaml:"max"` SpotFrom *int `yaml:"spot_from"` } // IsEmpty returns whether RangeConfig is empty. func (r *RangeConfig) IsEmpty() bool { return r.Min == nil && r.Max == nil && r.SpotFrom == nil } // Count is a custom type which supports unmarshaling yaml which // can either be of type int or type AdvancedCount. type Count struct { Value *int // 0 is a valid value, so we want the default value to be nil. AdvancedCount AdvancedCount // Mutually exclusive with Value. } // UnmarshalYAML overrides the default YAML unmarshaling logic for the Count // struct, allowing it to perform more complex unmarshaling behavior. // This method implements the yaml.Unmarshaler (v3) interface. func (c *Count) UnmarshalYAML(value *yaml.Node) error { if err := value.Decode(&c.AdvancedCount); err != nil { switch err.(type) { case *yaml.TypeError: break default: return err } } if !c.AdvancedCount.IsEmpty() { // Successfully unmarshalled AdvancedCount fields, return return nil } if err := value.Decode(&c.Value); err != nil { return errUnmarshalCountOpts } return nil } // UnmarshalYAML overrides the default YAML unmarshaling logic for the ScalingConfigOrT // struct, allowing it to perform more complex unmarshaling behavior. // This method implements the yaml.Unmarshaler (v3) interface. func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error { if err := value.Decode(&r.ScalingConfig); err != nil { switch err.(type) { case *yaml.TypeError: break default: return err } } if !r.ScalingConfig.IsEmpty() { // Successfully unmarshalled ScalingConfig fields, return return nil } if err := value.Decode(&r.Value); err != nil { return errors.New(`unable to unmarshal into int or composite-style map`) } return nil } // IsEmpty returns whether Count is empty. func (c *Count) IsEmpty() bool { return c.Value == nil && c.AdvancedCount.IsEmpty() } // Desired returns the desiredCount to be set on the CFN template func (c *Count) Desired() (*int, error) { if c.AdvancedCount.IsEmpty() { return c.Value, nil } if c.AdvancedCount.IgnoreRange() { return c.AdvancedCount.Spot, nil } min, _, err := c.AdvancedCount.Range.Parse() if err != nil { return nil, fmt.Errorf("parse task count value %s: %w", aws.StringValue((*string)(c.AdvancedCount.Range.Value)), err) } return aws.Int(min), nil } // Percentage represents a valid percentage integer ranging from 0 to 100. type Percentage int // ScalingConfigOrT represents a resource that has autoscaling configurations or a generic value. type ScalingConfigOrT[T ~int | time.Duration] struct { Value *T ScalingConfig AdvancedScalingConfig[T] // mutually exclusive with Value } // AdvancedScalingConfig represents advanced configurable options for a scaling policy. type AdvancedScalingConfig[T ~int | time.Duration] struct { Value *T `yaml:"value"` Cooldown Cooldown `yaml:"cooldown"` } // Cooldown represents the autoscaling cooldown of resources. type Cooldown struct { ScaleInCooldown *time.Duration `yaml:"in"` ScaleOutCooldown *time.Duration `yaml:"out"` } // AdvancedCount represents the configurable options for Auto Scaling as well as // Capacity configuration (spot). type AdvancedCount struct { Spot *int `yaml:"spot"` // mutually exclusive with other fields Range Range `yaml:"range"` Cooldown Cooldown `yaml:"cooldown"` CPU ScalingConfigOrT[Percentage] `yaml:"cpu_percentage"` Memory ScalingConfigOrT[Percentage] `yaml:"memory_percentage"` Requests ScalingConfigOrT[int] `yaml:"requests"` ResponseTime ScalingConfigOrT[time.Duration] `yaml:"response_time"` QueueScaling QueueScaling `yaml:"queue_delay"` workloadType string } // IsEmpty returns whether ScalingConfigOrT is empty func (r *ScalingConfigOrT[_])
() bool { return r.ScalingConfig.IsEmpty() && r.Value == nil } // IsEmpty returns whether AdvancedScalingConfig is empty func (a *AdvancedScalingConfig[_]) IsEmpty() bool { return a.Cooldown.IsEmpty() && a.Value == nil } // IsEmpty returns whether Cooldown is empty func (c *Cooldown) IsEmpty() bool { return c.ScaleInCooldown == nil && c.ScaleOutCooldown == nil } // IsEmpty returns whether AdvancedCount is empty. func (a *AdvancedCount) IsEmpty() bool { return a.Range.IsEmpty() && a.CPU.IsEmpty() && a.Memory.IsEmpty() && a.Cooldown.IsEmpty() && a.Requests.IsEmpty() && a.ResponseTime.IsEmpty() && a.Spot == nil && a.QueueScaling.IsEmpty() } // IgnoreRange returns whether desiredCount is specified on spot capacity func (a *AdvancedCount) IgnoreRange() bool { return a.Spot != nil } func (a *AdvancedCount) hasAutoscaling() bool { return !a.Range.IsEmpty() || a.hasScalingFieldsSet() } func (a *AdvancedCount) validScalingFields() []string { switch a.workloadType { case LoadBalancedWebServiceType: return []string{"cpu_percentage", "memory_percentage", "requests", "response_time"} case BackendServiceType: return []string{"cpu_percentage", "memory_percentage", "requests", "response_time"} case WorkerServiceType: return []string{"cpu_percentage", "memory_percentage", "queue_delay"} default: return nil } } func (a *AdvancedCount) hasScalingFieldsSet() bool { switch a.workloadType { case LoadBalancedWebServiceType: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.Requests.IsEmpty() || !a.ResponseTime.IsEmpty() case BackendServiceType: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.Requests.IsEmpty() || !a.ResponseTime.IsEmpty() case WorkerServiceType: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.QueueScaling.IsEmpty() default: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.Requests.IsEmpty() || !a.ResponseTime.IsEmpty() || !a.QueueScaling.IsEmpty() } } func (a *AdvancedCount) getInvalidFieldsSet() []string { var invalidFields []string switch a.workloadType { case LoadBalancedWebServiceType: if !a.QueueScaling.IsEmpty() { invalidFields = append(invalidFields, "queue_delay") } case BackendServiceType: if !a.QueueScaling.IsEmpty() { invalidFields = append(invalidFields, "queue_delay") } case WorkerServiceType: if !a.Requests.IsEmpty() { invalidFields = append(invalidFields, "requests") } if !a.ResponseTime.IsEmpty() { invalidFields = append(invalidFields, "response_time") } } return invalidFields } func (a *AdvancedCount) unsetAutoscaling() { a.Range = Range{} a.Cooldown = Cooldown{} a.CPU = ScalingConfigOrT[Percentage]{} a.Memory = ScalingConfigOrT[Percentage]{} a.Requests = ScalingConfigOrT[int]{} a.ResponseTime = ScalingConfigOrT[time.Duration]{} a.QueueScaling = QueueScaling{} } // QueueScaling represents the configuration to scale a service based on a SQS queue. type QueueScaling struct { AcceptableLatency *time.Duration `yaml:"acceptable_latency"` AvgProcessingTime *time.Duration `yaml:"msg_processing_time"` Cooldown Cooldown `yaml:"cooldown"` } // IsEmpty returns true if the QueueScaling is set. func (qs *QueueScaling) IsEmpty() bool { return qs.AcceptableLatency == nil && qs.AvgProcessingTime == nil && qs.Cooldown.IsEmpty() } // AcceptableBacklogPerTask returns the total number of messages that each task can accumulate in the queue // while maintaining the AcceptableLatency given the AvgProcessingTime. func (qs *QueueScaling) AcceptableBacklogPerTask() (int, error) { if qs.IsEmpty() { return 0, errors.New(`"queue_delay" must be specified in order to calculate the acceptable backlog`) } v := math.Ceil(float64(*qs.AcceptableLatency) / float64(*qs.AvgProcessingTime)) return int(v), nil } // IsTypeAService returns if manifest type is service. func IsTypeAService(t string) bool { for _, serviceType := range ServiceTypes() { if t == serviceType { return true } } return false } // HTTPHealthCheckArgs holds the configuration to determine if the load balanced web service is healthy. // These options are specifiable under the "healthcheck" field. // See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html. type HTTPHealthCheckArgs struct { Path *string `yaml:"path"` Port *int `yaml:"port"` SuccessCodes *string `yaml:"success_codes"` HealthyThreshold *int64 `yaml:"healthy_threshold"` UnhealthyThreshold *int64 `yaml:"unhealthy_threshold"` Timeout *time.Duration `yaml:"timeout"` Interval *time.Duration `yaml:"interval"` GracePeriod *time.Duration `yaml:"grace_period"` } // HealthCheckArgsOrString is a custom type which supports unmarshaling yaml which // can either be of type string or type HealthCheckArgs. type HealthCheckArgsOrString struct { Union[string, HTTPHealthCheckArgs] } // Path returns the default health check path if provided otherwise, returns the path from the advanced configuration. func (hc *HealthCheckArgsOrString) Path() *string { if hc.IsBasic() { return aws.String(hc.Basic) } return hc.Advanced.Path } // NLBHealthCheckArgs holds the configuration to determine if the network load balanced web service is healthy. // These options are specifiable under the "healthcheck" field. // See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html. type NLBHealthCheckArgs struct { Port *int `yaml:"port"` HealthyThreshold *int64 `yaml:"healthy_threshold"` UnhealthyThreshold *int64 `yaml:"unhealthy_threshold"` Timeout *time.Duration `yaml:"timeout"` Interval *time.Duration `yaml:"interval"` } func (h *NLBHealthCheckArgs) isEmpty() bool { return h.Port == nil && h.HealthyThreshold == nil && h.UnhealthyThreshold == nil && h.Timeout == nil && h.Interval == nil } // ParsePortMapping parses port-protocol string into individual port and protocol strings. // Valid examples: 2000/udp, or 2000. func ParsePortMapping(s *string) (port *string, protocol *string, err error) { if s == nil { return nil, nil, nil } portProtocol := strings.Split(*s, "/") switch len(portProtocol) { case 1: return aws.String(portProtocol[0]), nil, nil case 2: return aws.String(portProtocol[0]), aws.String(portProtocol[1]), nil default: return nil, nil, fmt.Errorf("cannot parse port mapping from %s", *s) } }
IsEmpty
identifier_name
svc.go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package manifest import ( "errors" "fmt" "math" "strconv" "strings" "time" "github.com/aws/aws-sdk-go/aws" "gopkg.in/yaml.v3" ) const ( // LoadBalancedWebServiceType is a web service with a load balancer and Fargate as compute. LoadBalancedWebServiceType = "Load Balanced Web Service" // RequestDrivenWebServiceType is a Request-Driven Web Service managed by AppRunner RequestDrivenWebServiceType = "Request-Driven Web Service" // BackendServiceType is a service that cannot be accessed from the internet but can be reached from other services. BackendServiceType = "Backend Service" // WorkerServiceType is a worker service that manages the consumption of messages. WorkerServiceType = "Worker Service" ) // ServiceTypes returns the list of supported service manifest types. func ServiceTypes() []string { return []string{ RequestDrivenWebServiceType, LoadBalancedWebServiceType, BackendServiceType, WorkerServiceType, } } // Range contains either a Range or a range configuration for Autoscaling ranges. type Range struct { Value *IntRangeBand // Mutually exclusive with RangeConfig RangeConfig RangeConfig } // IsEmpty returns whether Range is empty. func (r *Range) IsEmpty() bool { return r.Value == nil && r.RangeConfig.IsEmpty() } // Parse extracts the min and max from RangeOpts. func (r *Range) Parse() (min int, max int, err error) { if r.Value != nil { return r.Value.Parse() } return aws.IntValue(r.RangeConfig.Min), aws.IntValue(r.RangeConfig.Max), nil } // UnmarshalYAML overrides the default YAML unmarshaling logic for the RangeOpts // struct, allowing it to perform more complex unmarshaling behavior. // This method implements the yaml.Unmarshaler (v3) interface. func (r *Range) UnmarshalYAML(value *yaml.Node) error { if err := value.Decode(&r.RangeConfig); err != nil { switch err.(type) { case *yaml.TypeError: break default: return err } } if !r.RangeConfig.IsEmpty() { // Unmarshaled successfully to r.RangeConfig, unset r.Range, and return. r.Value = nil return nil } if err := value.Decode(&r.Value); err != nil { return errUnmarshalRangeOpts } return nil } // IntRangeBand is a number range with maximum and minimum values. type IntRangeBand string // Parse parses Range string and returns the min and max values. // For example: 1-100 returns 1 and 100. func (r IntRangeBand) Parse() (min int, max int, err error)
// RangeConfig containers a Min/Max and an optional SpotFrom field which // specifies the number of services you want to start placing on spot. For // example, if your range is 1-10 and `spot_from` is 5, up to 4 services will // be placed on dedicated Fargate capacity, and then after that, any scaling // event will place additioanl services on spot capacity. type RangeConfig struct { Min *int `yaml:"min"` Max *int `yaml:"max"` SpotFrom *int `yaml:"spot_from"` } // IsEmpty returns whether RangeConfig is empty. func (r *RangeConfig) IsEmpty() bool { return r.Min == nil && r.Max == nil && r.SpotFrom == nil } // Count is a custom type which supports unmarshaling yaml which // can either be of type int or type AdvancedCount. type Count struct { Value *int // 0 is a valid value, so we want the default value to be nil. AdvancedCount AdvancedCount // Mutually exclusive with Value. } // UnmarshalYAML overrides the default YAML unmarshaling logic for the Count // struct, allowing it to perform more complex unmarshaling behavior. // This method implements the yaml.Unmarshaler (v3) interface. func (c *Count) UnmarshalYAML(value *yaml.Node) error { if err := value.Decode(&c.AdvancedCount); err != nil { switch err.(type) { case *yaml.TypeError: break default: return err } } if !c.AdvancedCount.IsEmpty() { // Successfully unmarshalled AdvancedCount fields, return return nil } if err := value.Decode(&c.Value); err != nil { return errUnmarshalCountOpts } return nil } // UnmarshalYAML overrides the default YAML unmarshaling logic for the ScalingConfigOrT // struct, allowing it to perform more complex unmarshaling behavior. // This method implements the yaml.Unmarshaler (v3) interface. func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error { if err := value.Decode(&r.ScalingConfig); err != nil { switch err.(type) { case *yaml.TypeError: break default: return err } } if !r.ScalingConfig.IsEmpty() { // Successfully unmarshalled ScalingConfig fields, return return nil } if err := value.Decode(&r.Value); err != nil { return errors.New(`unable to unmarshal into int or composite-style map`) } return nil } // IsEmpty returns whether Count is empty. func (c *Count) IsEmpty() bool { return c.Value == nil && c.AdvancedCount.IsEmpty() } // Desired returns the desiredCount to be set on the CFN template func (c *Count) Desired() (*int, error) { if c.AdvancedCount.IsEmpty() { return c.Value, nil } if c.AdvancedCount.IgnoreRange() { return c.AdvancedCount.Spot, nil } min, _, err := c.AdvancedCount.Range.Parse() if err != nil { return nil, fmt.Errorf("parse task count value %s: %w", aws.StringValue((*string)(c.AdvancedCount.Range.Value)), err) } return aws.Int(min), nil } // Percentage represents a valid percentage integer ranging from 0 to 100. type Percentage int // ScalingConfigOrT represents a resource that has autoscaling configurations or a generic value. type ScalingConfigOrT[T ~int | time.Duration] struct { Value *T ScalingConfig AdvancedScalingConfig[T] // mutually exclusive with Value } // AdvancedScalingConfig represents advanced configurable options for a scaling policy. type AdvancedScalingConfig[T ~int | time.Duration] struct { Value *T `yaml:"value"` Cooldown Cooldown `yaml:"cooldown"` } // Cooldown represents the autoscaling cooldown of resources. type Cooldown struct { ScaleInCooldown *time.Duration `yaml:"in"` ScaleOutCooldown *time.Duration `yaml:"out"` } // AdvancedCount represents the configurable options for Auto Scaling as well as // Capacity configuration (spot). type AdvancedCount struct { Spot *int `yaml:"spot"` // mutually exclusive with other fields Range Range `yaml:"range"` Cooldown Cooldown `yaml:"cooldown"` CPU ScalingConfigOrT[Percentage] `yaml:"cpu_percentage"` Memory ScalingConfigOrT[Percentage] `yaml:"memory_percentage"` Requests ScalingConfigOrT[int] `yaml:"requests"` ResponseTime ScalingConfigOrT[time.Duration] `yaml:"response_time"` QueueScaling QueueScaling `yaml:"queue_delay"` workloadType string } // IsEmpty returns whether ScalingConfigOrT is empty func (r *ScalingConfigOrT[_]) IsEmpty() bool { return r.ScalingConfig.IsEmpty() && r.Value == nil } // IsEmpty returns whether AdvancedScalingConfig is empty func (a *AdvancedScalingConfig[_]) IsEmpty() bool { return a.Cooldown.IsEmpty() && a.Value == nil } // IsEmpty returns whether Cooldown is empty func (c *Cooldown) IsEmpty() bool { return c.ScaleInCooldown == nil && c.ScaleOutCooldown == nil } // IsEmpty returns whether AdvancedCount is empty. func (a *AdvancedCount) IsEmpty() bool { return a.Range.IsEmpty() && a.CPU.IsEmpty() && a.Memory.IsEmpty() && a.Cooldown.IsEmpty() && a.Requests.IsEmpty() && a.ResponseTime.IsEmpty() && a.Spot == nil && a.QueueScaling.IsEmpty() } // IgnoreRange returns whether desiredCount is specified on spot capacity func (a *AdvancedCount) IgnoreRange() bool { return a.Spot != nil } func (a *AdvancedCount) hasAutoscaling() bool { return !a.Range.IsEmpty() || a.hasScalingFieldsSet() } func (a *AdvancedCount) validScalingFields() []string { switch a.workloadType { case LoadBalancedWebServiceType: return []string{"cpu_percentage", "memory_percentage", "requests", "response_time"} case BackendServiceType: return []string{"cpu_percentage", "memory_percentage", "requests", "response_time"} case WorkerServiceType: return []string{"cpu_percentage", "memory_percentage", "queue_delay"} default: return nil } } func (a *AdvancedCount) hasScalingFieldsSet() bool { switch a.workloadType { case LoadBalancedWebServiceType: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.Requests.IsEmpty() || !a.ResponseTime.IsEmpty() case BackendServiceType: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.Requests.IsEmpty() || !a.ResponseTime.IsEmpty() case WorkerServiceType: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.QueueScaling.IsEmpty() default: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.Requests.IsEmpty() || !a.ResponseTime.IsEmpty() || !a.QueueScaling.IsEmpty() } } func (a *AdvancedCount) getInvalidFieldsSet() []string { var invalidFields []string switch a.workloadType { case LoadBalancedWebServiceType: if !a.QueueScaling.IsEmpty() { invalidFields = append(invalidFields, "queue_delay") } case BackendServiceType: if !a.QueueScaling.IsEmpty() { invalidFields = append(invalidFields, "queue_delay") } case WorkerServiceType: if !a.Requests.IsEmpty() { invalidFields = append(invalidFields, "requests") } if !a.ResponseTime.IsEmpty() { invalidFields = append(invalidFields, "response_time") } } return invalidFields } func (a *AdvancedCount) unsetAutoscaling() { a.Range = Range{} a.Cooldown = Cooldown{} a.CPU = ScalingConfigOrT[Percentage]{} a.Memory = ScalingConfigOrT[Percentage]{} a.Requests = ScalingConfigOrT[int]{} a.ResponseTime = ScalingConfigOrT[time.Duration]{} a.QueueScaling = QueueScaling{} } // QueueScaling represents the configuration to scale a service based on a SQS queue. type QueueScaling struct { AcceptableLatency *time.Duration `yaml:"acceptable_latency"` AvgProcessingTime *time.Duration `yaml:"msg_processing_time"` Cooldown Cooldown `yaml:"cooldown"` } // IsEmpty returns true if the QueueScaling is set. func (qs *QueueScaling) IsEmpty() bool { return qs.AcceptableLatency == nil && qs.AvgProcessingTime == nil && qs.Cooldown.IsEmpty() } // AcceptableBacklogPerTask returns the total number of messages that each task can accumulate in the queue // while maintaining the AcceptableLatency given the AvgProcessingTime. func (qs *QueueScaling) AcceptableBacklogPerTask() (int, error) { if qs.IsEmpty() { return 0, errors.New(`"queue_delay" must be specified in order to calculate the acceptable backlog`) } v := math.Ceil(float64(*qs.AcceptableLatency) / float64(*qs.AvgProcessingTime)) return int(v), nil } // IsTypeAService returns if manifest type is service. func IsTypeAService(t string) bool { for _, serviceType := range ServiceTypes() { if t == serviceType { return true } } return false } // HTTPHealthCheckArgs holds the configuration to determine if the load balanced web service is healthy. // These options are specifiable under the "healthcheck" field. // See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html. type HTTPHealthCheckArgs struct { Path *string `yaml:"path"` Port *int `yaml:"port"` SuccessCodes *string `yaml:"success_codes"` HealthyThreshold *int64 `yaml:"healthy_threshold"` UnhealthyThreshold *int64 `yaml:"unhealthy_threshold"` Timeout *time.Duration `yaml:"timeout"` Interval *time.Duration `yaml:"interval"` GracePeriod *time.Duration `yaml:"grace_period"` } // HealthCheckArgsOrString is a custom type which supports unmarshaling yaml which // can either be of type string or type HealthCheckArgs. type HealthCheckArgsOrString struct { Union[string, HTTPHealthCheckArgs] } // Path returns the default health check path if provided otherwise, returns the path from the advanced configuration. func (hc *HealthCheckArgsOrString) Path() *string { if hc.IsBasic() { return aws.String(hc.Basic) } return hc.Advanced.Path } // NLBHealthCheckArgs holds the configuration to determine if the network load balanced web service is healthy. // These options are specifiable under the "healthcheck" field. // See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html. type NLBHealthCheckArgs struct { Port *int `yaml:"port"` HealthyThreshold *int64 `yaml:"healthy_threshold"` UnhealthyThreshold *int64 `yaml:"unhealthy_threshold"` Timeout *time.Duration `yaml:"timeout"` Interval *time.Duration `yaml:"interval"` } func (h *NLBHealthCheckArgs) isEmpty() bool { return h.Port == nil && h.HealthyThreshold == nil && h.UnhealthyThreshold == nil && h.Timeout == nil && h.Interval == nil } // ParsePortMapping parses port-protocol string into individual port and protocol strings. // Valid examples: 2000/udp, or 2000. func ParsePortMapping(s *string) (port *string, protocol *string, err error) { if s == nil { return nil, nil, nil } portProtocol := strings.Split(*s, "/") switch len(portProtocol) { case 1: return aws.String(portProtocol[0]), nil, nil case 2: return aws.String(portProtocol[0]), aws.String(portProtocol[1]), nil default: return nil, nil, fmt.Errorf("cannot parse port mapping from %s", *s) } }
{ minMax := strings.Split(string(r), "-") if len(minMax) != 2 { return 0, 0, fmt.Errorf("invalid range value %s. Should be in format of ${min}-${max}", string(r)) } min, err = strconv.Atoi(minMax[0]) if err != nil { return 0, 0, fmt.Errorf("cannot convert minimum value %s to integer", minMax[0]) } max, err = strconv.Atoi(minMax[1]) if err != nil { return 0, 0, fmt.Errorf("cannot convert maximum value %s to integer", minMax[1]) } return min, max, nil }
identifier_body
svc.go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package manifest import ( "errors" "fmt" "math" "strconv" "strings" "time" "github.com/aws/aws-sdk-go/aws" "gopkg.in/yaml.v3" ) const ( // LoadBalancedWebServiceType is a web service with a load balancer and Fargate as compute. LoadBalancedWebServiceType = "Load Balanced Web Service" // RequestDrivenWebServiceType is a Request-Driven Web Service managed by AppRunner RequestDrivenWebServiceType = "Request-Driven Web Service" // BackendServiceType is a service that cannot be accessed from the internet but can be reached from other services. BackendServiceType = "Backend Service" // WorkerServiceType is a worker service that manages the consumption of messages. WorkerServiceType = "Worker Service" ) // ServiceTypes returns the list of supported service manifest types. func ServiceTypes() []string { return []string{ RequestDrivenWebServiceType, LoadBalancedWebServiceType, BackendServiceType, WorkerServiceType, } } // Range contains either a Range or a range configuration for Autoscaling ranges. type Range struct { Value *IntRangeBand // Mutually exclusive with RangeConfig RangeConfig RangeConfig } // IsEmpty returns whether Range is empty. func (r *Range) IsEmpty() bool { return r.Value == nil && r.RangeConfig.IsEmpty() } // Parse extracts the min and max from RangeOpts. func (r *Range) Parse() (min int, max int, err error) { if r.Value != nil { return r.Value.Parse() } return aws.IntValue(r.RangeConfig.Min), aws.IntValue(r.RangeConfig.Max), nil } // UnmarshalYAML overrides the default YAML unmarshaling logic for the RangeOpts // struct, allowing it to perform more complex unmarshaling behavior. // This method implements the yaml.Unmarshaler (v3) interface. func (r *Range) UnmarshalYAML(value *yaml.Node) error { if err := value.Decode(&r.RangeConfig); err != nil { switch err.(type) { case *yaml.TypeError: break default: return err } } if !r.RangeConfig.IsEmpty() { // Unmarshaled successfully to r.RangeConfig, unset r.Range, and return. r.Value = nil return nil } if err := value.Decode(&r.Value); err != nil { return errUnmarshalRangeOpts } return nil } // IntRangeBand is a number range with maximum and minimum values. type IntRangeBand string // Parse parses Range string and returns the min and max values. // For example: 1-100 returns 1 and 100. func (r IntRangeBand) Parse() (min int, max int, err error) { minMax := strings.Split(string(r), "-") if len(minMax) != 2 { return 0, 0, fmt.Errorf("invalid range value %s. Should be in format of ${min}-${max}", string(r)) } min, err = strconv.Atoi(minMax[0]) if err != nil { return 0, 0, fmt.Errorf("cannot convert minimum value %s to integer", minMax[0]) } max, err = strconv.Atoi(minMax[1]) if err != nil { return 0, 0, fmt.Errorf("cannot convert maximum value %s to integer", minMax[1]) } return min, max, nil } // RangeConfig containers a Min/Max and an optional SpotFrom field which // specifies the number of services you want to start placing on spot. For // example, if your range is 1-10 and `spot_from` is 5, up to 4 services will // be placed on dedicated Fargate capacity, and then after that, any scaling // event will place additioanl services on spot capacity. type RangeConfig struct { Min *int `yaml:"min"` Max *int `yaml:"max"` SpotFrom *int `yaml:"spot_from"` } // IsEmpty returns whether RangeConfig is empty. func (r *RangeConfig) IsEmpty() bool { return r.Min == nil && r.Max == nil && r.SpotFrom == nil } // Count is a custom type which supports unmarshaling yaml which // can either be of type int or type AdvancedCount. type Count struct { Value *int // 0 is a valid value, so we want the default value to be nil. AdvancedCount AdvancedCount // Mutually exclusive with Value. } // UnmarshalYAML overrides the default YAML unmarshaling logic for the Count // struct, allowing it to perform more complex unmarshaling behavior. // This method implements the yaml.Unmarshaler (v3) interface. func (c *Count) UnmarshalYAML(value *yaml.Node) error { if err := value.Decode(&c.AdvancedCount); err != nil { switch err.(type) { case *yaml.TypeError: break default: return err } } if !c.AdvancedCount.IsEmpty() { // Successfully unmarshalled AdvancedCount fields, return return nil } if err := value.Decode(&c.Value); err != nil { return errUnmarshalCountOpts } return nil } // UnmarshalYAML overrides the default YAML unmarshaling logic for the ScalingConfigOrT // struct, allowing it to perform more complex unmarshaling behavior. // This method implements the yaml.Unmarshaler (v3) interface. func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error { if err := value.Decode(&r.ScalingConfig); err != nil { switch err.(type) { case *yaml.TypeError: break default: return err } } if !r.ScalingConfig.IsEmpty() { // Successfully unmarshalled ScalingConfig fields, return
if err := value.Decode(&r.Value); err != nil { return errors.New(`unable to unmarshal into int or composite-style map`) } return nil } // IsEmpty returns whether Count is empty. func (c *Count) IsEmpty() bool { return c.Value == nil && c.AdvancedCount.IsEmpty() } // Desired returns the desiredCount to be set on the CFN template func (c *Count) Desired() (*int, error) { if c.AdvancedCount.IsEmpty() { return c.Value, nil } if c.AdvancedCount.IgnoreRange() { return c.AdvancedCount.Spot, nil } min, _, err := c.AdvancedCount.Range.Parse() if err != nil { return nil, fmt.Errorf("parse task count value %s: %w", aws.StringValue((*string)(c.AdvancedCount.Range.Value)), err) } return aws.Int(min), nil } // Percentage represents a valid percentage integer ranging from 0 to 100. type Percentage int // ScalingConfigOrT represents a resource that has autoscaling configurations or a generic value. type ScalingConfigOrT[T ~int | time.Duration] struct { Value *T ScalingConfig AdvancedScalingConfig[T] // mutually exclusive with Value } // AdvancedScalingConfig represents advanced configurable options for a scaling policy. type AdvancedScalingConfig[T ~int | time.Duration] struct { Value *T `yaml:"value"` Cooldown Cooldown `yaml:"cooldown"` } // Cooldown represents the autoscaling cooldown of resources. type Cooldown struct { ScaleInCooldown *time.Duration `yaml:"in"` ScaleOutCooldown *time.Duration `yaml:"out"` } // AdvancedCount represents the configurable options for Auto Scaling as well as // Capacity configuration (spot). type AdvancedCount struct { Spot *int `yaml:"spot"` // mutually exclusive with other fields Range Range `yaml:"range"` Cooldown Cooldown `yaml:"cooldown"` CPU ScalingConfigOrT[Percentage] `yaml:"cpu_percentage"` Memory ScalingConfigOrT[Percentage] `yaml:"memory_percentage"` Requests ScalingConfigOrT[int] `yaml:"requests"` ResponseTime ScalingConfigOrT[time.Duration] `yaml:"response_time"` QueueScaling QueueScaling `yaml:"queue_delay"` workloadType string } // IsEmpty returns whether ScalingConfigOrT is empty func (r *ScalingConfigOrT[_]) IsEmpty() bool { return r.ScalingConfig.IsEmpty() && r.Value == nil } // IsEmpty returns whether AdvancedScalingConfig is empty func (a *AdvancedScalingConfig[_]) IsEmpty() bool { return a.Cooldown.IsEmpty() && a.Value == nil } // IsEmpty returns whether Cooldown is empty func (c *Cooldown) IsEmpty() bool { return c.ScaleInCooldown == nil && c.ScaleOutCooldown == nil } // IsEmpty returns whether AdvancedCount is empty. func (a *AdvancedCount) IsEmpty() bool { return a.Range.IsEmpty() && a.CPU.IsEmpty() && a.Memory.IsEmpty() && a.Cooldown.IsEmpty() && a.Requests.IsEmpty() && a.ResponseTime.IsEmpty() && a.Spot == nil && a.QueueScaling.IsEmpty() } // IgnoreRange returns whether desiredCount is specified on spot capacity func (a *AdvancedCount) IgnoreRange() bool { return a.Spot != nil } func (a *AdvancedCount) hasAutoscaling() bool { return !a.Range.IsEmpty() || a.hasScalingFieldsSet() } func (a *AdvancedCount) validScalingFields() []string { switch a.workloadType { case LoadBalancedWebServiceType: return []string{"cpu_percentage", "memory_percentage", "requests", "response_time"} case BackendServiceType: return []string{"cpu_percentage", "memory_percentage", "requests", "response_time"} case WorkerServiceType: return []string{"cpu_percentage", "memory_percentage", "queue_delay"} default: return nil } } func (a *AdvancedCount) hasScalingFieldsSet() bool { switch a.workloadType { case LoadBalancedWebServiceType: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.Requests.IsEmpty() || !a.ResponseTime.IsEmpty() case BackendServiceType: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.Requests.IsEmpty() || !a.ResponseTime.IsEmpty() case WorkerServiceType: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.QueueScaling.IsEmpty() default: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.Requests.IsEmpty() || !a.ResponseTime.IsEmpty() || !a.QueueScaling.IsEmpty() } } func (a *AdvancedCount) getInvalidFieldsSet() []string { var invalidFields []string switch a.workloadType { case LoadBalancedWebServiceType: if !a.QueueScaling.IsEmpty() { invalidFields = append(invalidFields, "queue_delay") } case BackendServiceType: if !a.QueueScaling.IsEmpty() { invalidFields = append(invalidFields, "queue_delay") } case WorkerServiceType: if !a.Requests.IsEmpty() { invalidFields = append(invalidFields, "requests") } if !a.ResponseTime.IsEmpty() { invalidFields = append(invalidFields, "response_time") } } return invalidFields } func (a *AdvancedCount) unsetAutoscaling() { a.Range = Range{} a.Cooldown = Cooldown{} a.CPU = ScalingConfigOrT[Percentage]{} a.Memory = ScalingConfigOrT[Percentage]{} a.Requests = ScalingConfigOrT[int]{} a.ResponseTime = ScalingConfigOrT[time.Duration]{} a.QueueScaling = QueueScaling{} } // QueueScaling represents the configuration to scale a service based on a SQS queue. type QueueScaling struct { AcceptableLatency *time.Duration `yaml:"acceptable_latency"` AvgProcessingTime *time.Duration `yaml:"msg_processing_time"` Cooldown Cooldown `yaml:"cooldown"` } // IsEmpty returns true if the QueueScaling is set. func (qs *QueueScaling) IsEmpty() bool { return qs.AcceptableLatency == nil && qs.AvgProcessingTime == nil && qs.Cooldown.IsEmpty() } // AcceptableBacklogPerTask returns the total number of messages that each task can accumulate in the queue // while maintaining the AcceptableLatency given the AvgProcessingTime. func (qs *QueueScaling) AcceptableBacklogPerTask() (int, error) { if qs.IsEmpty() { return 0, errors.New(`"queue_delay" must be specified in order to calculate the acceptable backlog`) } v := math.Ceil(float64(*qs.AcceptableLatency) / float64(*qs.AvgProcessingTime)) return int(v), nil } // IsTypeAService returns if manifest type is service. func IsTypeAService(t string) bool { for _, serviceType := range ServiceTypes() { if t == serviceType { return true } } return false } // HTTPHealthCheckArgs holds the configuration to determine if the load balanced web service is healthy. // These options are specifiable under the "healthcheck" field. // See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html. type HTTPHealthCheckArgs struct { Path *string `yaml:"path"` Port *int `yaml:"port"` SuccessCodes *string `yaml:"success_codes"` HealthyThreshold *int64 `yaml:"healthy_threshold"` UnhealthyThreshold *int64 `yaml:"unhealthy_threshold"` Timeout *time.Duration `yaml:"timeout"` Interval *time.Duration `yaml:"interval"` GracePeriod *time.Duration `yaml:"grace_period"` } // HealthCheckArgsOrString is a custom type which supports unmarshaling yaml which // can either be of type string or type HealthCheckArgs. type HealthCheckArgsOrString struct { Union[string, HTTPHealthCheckArgs] } // Path returns the default health check path if provided otherwise, returns the path from the advanced configuration. func (hc *HealthCheckArgsOrString) Path() *string { if hc.IsBasic() { return aws.String(hc.Basic) } return hc.Advanced.Path } // NLBHealthCheckArgs holds the configuration to determine if the network load balanced web service is healthy. // These options are specifiable under the "healthcheck" field. // See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html. type NLBHealthCheckArgs struct { Port *int `yaml:"port"` HealthyThreshold *int64 `yaml:"healthy_threshold"` UnhealthyThreshold *int64 `yaml:"unhealthy_threshold"` Timeout *time.Duration `yaml:"timeout"` Interval *time.Duration `yaml:"interval"` } func (h *NLBHealthCheckArgs) isEmpty() bool { return h.Port == nil && h.HealthyThreshold == nil && h.UnhealthyThreshold == nil && h.Timeout == nil && h.Interval == nil } // ParsePortMapping parses port-protocol string into individual port and protocol strings. // Valid examples: 2000/udp, or 2000. func ParsePortMapping(s *string) (port *string, protocol *string, err error) { if s == nil { return nil, nil, nil } portProtocol := strings.Split(*s, "/") switch len(portProtocol) { case 1: return aws.String(portProtocol[0]), nil, nil case 2: return aws.String(portProtocol[0]), aws.String(portProtocol[1]), nil default: return nil, nil, fmt.Errorf("cannot parse port mapping from %s", *s) } }
return nil }
random_line_split
svc.go
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package manifest import ( "errors" "fmt" "math" "strconv" "strings" "time" "github.com/aws/aws-sdk-go/aws" "gopkg.in/yaml.v3" ) const ( // LoadBalancedWebServiceType is a web service with a load balancer and Fargate as compute. LoadBalancedWebServiceType = "Load Balanced Web Service" // RequestDrivenWebServiceType is a Request-Driven Web Service managed by AppRunner RequestDrivenWebServiceType = "Request-Driven Web Service" // BackendServiceType is a service that cannot be accessed from the internet but can be reached from other services. BackendServiceType = "Backend Service" // WorkerServiceType is a worker service that manages the consumption of messages. WorkerServiceType = "Worker Service" ) // ServiceTypes returns the list of supported service manifest types. func ServiceTypes() []string { return []string{ RequestDrivenWebServiceType, LoadBalancedWebServiceType, BackendServiceType, WorkerServiceType, } } // Range contains either a Range or a range configuration for Autoscaling ranges. type Range struct { Value *IntRangeBand // Mutually exclusive with RangeConfig RangeConfig RangeConfig } // IsEmpty returns whether Range is empty. func (r *Range) IsEmpty() bool { return r.Value == nil && r.RangeConfig.IsEmpty() } // Parse extracts the min and max from RangeOpts. func (r *Range) Parse() (min int, max int, err error) { if r.Value != nil { return r.Value.Parse() } return aws.IntValue(r.RangeConfig.Min), aws.IntValue(r.RangeConfig.Max), nil } // UnmarshalYAML overrides the default YAML unmarshaling logic for the RangeOpts // struct, allowing it to perform more complex unmarshaling behavior. // This method implements the yaml.Unmarshaler (v3) interface. func (r *Range) UnmarshalYAML(value *yaml.Node) error { if err := value.Decode(&r.RangeConfig); err != nil { switch err.(type) { case *yaml.TypeError: break default: return err } } if !r.RangeConfig.IsEmpty() { // Unmarshaled successfully to r.RangeConfig, unset r.Range, and return. r.Value = nil return nil } if err := value.Decode(&r.Value); err != nil { return errUnmarshalRangeOpts } return nil } // IntRangeBand is a number range with maximum and minimum values. type IntRangeBand string // Parse parses Range string and returns the min and max values. // For example: 1-100 returns 1 and 100. func (r IntRangeBand) Parse() (min int, max int, err error) { minMax := strings.Split(string(r), "-") if len(minMax) != 2 { return 0, 0, fmt.Errorf("invalid range value %s. Should be in format of ${min}-${max}", string(r)) } min, err = strconv.Atoi(minMax[0]) if err != nil { return 0, 0, fmt.Errorf("cannot convert minimum value %s to integer", minMax[0]) } max, err = strconv.Atoi(minMax[1]) if err != nil { return 0, 0, fmt.Errorf("cannot convert maximum value %s to integer", minMax[1]) } return min, max, nil } // RangeConfig containers a Min/Max and an optional SpotFrom field which // specifies the number of services you want to start placing on spot. For // example, if your range is 1-10 and `spot_from` is 5, up to 4 services will // be placed on dedicated Fargate capacity, and then after that, any scaling // event will place additioanl services on spot capacity. type RangeConfig struct { Min *int `yaml:"min"` Max *int `yaml:"max"` SpotFrom *int `yaml:"spot_from"` } // IsEmpty returns whether RangeConfig is empty. func (r *RangeConfig) IsEmpty() bool { return r.Min == nil && r.Max == nil && r.SpotFrom == nil } // Count is a custom type which supports unmarshaling yaml which // can either be of type int or type AdvancedCount. type Count struct { Value *int // 0 is a valid value, so we want the default value to be nil. AdvancedCount AdvancedCount // Mutually exclusive with Value. } // UnmarshalYAML overrides the default YAML unmarshaling logic for the Count // struct, allowing it to perform more complex unmarshaling behavior. // This method implements the yaml.Unmarshaler (v3) interface. func (c *Count) UnmarshalYAML(value *yaml.Node) error { if err := value.Decode(&c.AdvancedCount); err != nil { switch err.(type) { case *yaml.TypeError: break default: return err } } if !c.AdvancedCount.IsEmpty() { // Successfully unmarshalled AdvancedCount fields, return return nil } if err := value.Decode(&c.Value); err != nil { return errUnmarshalCountOpts } return nil } // UnmarshalYAML overrides the default YAML unmarshaling logic for the ScalingConfigOrT // struct, allowing it to perform more complex unmarshaling behavior. // This method implements the yaml.Unmarshaler (v3) interface. func (r *ScalingConfigOrT[_]) UnmarshalYAML(value *yaml.Node) error { if err := value.Decode(&r.ScalingConfig); err != nil
if !r.ScalingConfig.IsEmpty() { // Successfully unmarshalled ScalingConfig fields, return return nil } if err := value.Decode(&r.Value); err != nil { return errors.New(`unable to unmarshal into int or composite-style map`) } return nil } // IsEmpty returns whether Count is empty. func (c *Count) IsEmpty() bool { return c.Value == nil && c.AdvancedCount.IsEmpty() } // Desired returns the desiredCount to be set on the CFN template func (c *Count) Desired() (*int, error) { if c.AdvancedCount.IsEmpty() { return c.Value, nil } if c.AdvancedCount.IgnoreRange() { return c.AdvancedCount.Spot, nil } min, _, err := c.AdvancedCount.Range.Parse() if err != nil { return nil, fmt.Errorf("parse task count value %s: %w", aws.StringValue((*string)(c.AdvancedCount.Range.Value)), err) } return aws.Int(min), nil } // Percentage represents a valid percentage integer ranging from 0 to 100. type Percentage int // ScalingConfigOrT represents a resource that has autoscaling configurations or a generic value. type ScalingConfigOrT[T ~int | time.Duration] struct { Value *T ScalingConfig AdvancedScalingConfig[T] // mutually exclusive with Value } // AdvancedScalingConfig represents advanced configurable options for a scaling policy. type AdvancedScalingConfig[T ~int | time.Duration] struct { Value *T `yaml:"value"` Cooldown Cooldown `yaml:"cooldown"` } // Cooldown represents the autoscaling cooldown of resources. type Cooldown struct { ScaleInCooldown *time.Duration `yaml:"in"` ScaleOutCooldown *time.Duration `yaml:"out"` } // AdvancedCount represents the configurable options for Auto Scaling as well as // Capacity configuration (spot). type AdvancedCount struct { Spot *int `yaml:"spot"` // mutually exclusive with other fields Range Range `yaml:"range"` Cooldown Cooldown `yaml:"cooldown"` CPU ScalingConfigOrT[Percentage] `yaml:"cpu_percentage"` Memory ScalingConfigOrT[Percentage] `yaml:"memory_percentage"` Requests ScalingConfigOrT[int] `yaml:"requests"` ResponseTime ScalingConfigOrT[time.Duration] `yaml:"response_time"` QueueScaling QueueScaling `yaml:"queue_delay"` workloadType string } // IsEmpty returns whether ScalingConfigOrT is empty func (r *ScalingConfigOrT[_]) IsEmpty() bool { return r.ScalingConfig.IsEmpty() && r.Value == nil } // IsEmpty returns whether AdvancedScalingConfig is empty func (a *AdvancedScalingConfig[_]) IsEmpty() bool { return a.Cooldown.IsEmpty() && a.Value == nil } // IsEmpty returns whether Cooldown is empty func (c *Cooldown) IsEmpty() bool { return c.ScaleInCooldown == nil && c.ScaleOutCooldown == nil } // IsEmpty returns whether AdvancedCount is empty. func (a *AdvancedCount) IsEmpty() bool { return a.Range.IsEmpty() && a.CPU.IsEmpty() && a.Memory.IsEmpty() && a.Cooldown.IsEmpty() && a.Requests.IsEmpty() && a.ResponseTime.IsEmpty() && a.Spot == nil && a.QueueScaling.IsEmpty() } // IgnoreRange returns whether desiredCount is specified on spot capacity func (a *AdvancedCount) IgnoreRange() bool { return a.Spot != nil } func (a *AdvancedCount) hasAutoscaling() bool { return !a.Range.IsEmpty() || a.hasScalingFieldsSet() } func (a *AdvancedCount) validScalingFields() []string { switch a.workloadType { case LoadBalancedWebServiceType: return []string{"cpu_percentage", "memory_percentage", "requests", "response_time"} case BackendServiceType: return []string{"cpu_percentage", "memory_percentage", "requests", "response_time"} case WorkerServiceType: return []string{"cpu_percentage", "memory_percentage", "queue_delay"} default: return nil } } func (a *AdvancedCount) hasScalingFieldsSet() bool { switch a.workloadType { case LoadBalancedWebServiceType: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.Requests.IsEmpty() || !a.ResponseTime.IsEmpty() case BackendServiceType: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.Requests.IsEmpty() || !a.ResponseTime.IsEmpty() case WorkerServiceType: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.QueueScaling.IsEmpty() default: return !a.CPU.IsEmpty() || !a.Memory.IsEmpty() || !a.Requests.IsEmpty() || !a.ResponseTime.IsEmpty() || !a.QueueScaling.IsEmpty() } } func (a *AdvancedCount) getInvalidFieldsSet() []string { var invalidFields []string switch a.workloadType { case LoadBalancedWebServiceType: if !a.QueueScaling.IsEmpty() { invalidFields = append(invalidFields, "queue_delay") } case BackendServiceType: if !a.QueueScaling.IsEmpty() { invalidFields = append(invalidFields, "queue_delay") } case WorkerServiceType: if !a.Requests.IsEmpty() { invalidFields = append(invalidFields, "requests") } if !a.ResponseTime.IsEmpty() { invalidFields = append(invalidFields, "response_time") } } return invalidFields } func (a *AdvancedCount) unsetAutoscaling() { a.Range = Range{} a.Cooldown = Cooldown{} a.CPU = ScalingConfigOrT[Percentage]{} a.Memory = ScalingConfigOrT[Percentage]{} a.Requests = ScalingConfigOrT[int]{} a.ResponseTime = ScalingConfigOrT[time.Duration]{} a.QueueScaling = QueueScaling{} } // QueueScaling represents the configuration to scale a service based on a SQS queue. type QueueScaling struct { AcceptableLatency *time.Duration `yaml:"acceptable_latency"` AvgProcessingTime *time.Duration `yaml:"msg_processing_time"` Cooldown Cooldown `yaml:"cooldown"` } // IsEmpty returns true if the QueueScaling is set. func (qs *QueueScaling) IsEmpty() bool { return qs.AcceptableLatency == nil && qs.AvgProcessingTime == nil && qs.Cooldown.IsEmpty() } // AcceptableBacklogPerTask returns the total number of messages that each task can accumulate in the queue // while maintaining the AcceptableLatency given the AvgProcessingTime. func (qs *QueueScaling) AcceptableBacklogPerTask() (int, error) { if qs.IsEmpty() { return 0, errors.New(`"queue_delay" must be specified in order to calculate the acceptable backlog`) } v := math.Ceil(float64(*qs.AcceptableLatency) / float64(*qs.AvgProcessingTime)) return int(v), nil } // IsTypeAService returns if manifest type is service. func IsTypeAService(t string) bool { for _, serviceType := range ServiceTypes() { if t == serviceType { return true } } return false } // HTTPHealthCheckArgs holds the configuration to determine if the load balanced web service is healthy. // These options are specifiable under the "healthcheck" field. // See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html. type HTTPHealthCheckArgs struct { Path *string `yaml:"path"` Port *int `yaml:"port"` SuccessCodes *string `yaml:"success_codes"` HealthyThreshold *int64 `yaml:"healthy_threshold"` UnhealthyThreshold *int64 `yaml:"unhealthy_threshold"` Timeout *time.Duration `yaml:"timeout"` Interval *time.Duration `yaml:"interval"` GracePeriod *time.Duration `yaml:"grace_period"` } // HealthCheckArgsOrString is a custom type which supports unmarshaling yaml which // can either be of type string or type HealthCheckArgs. type HealthCheckArgsOrString struct { Union[string, HTTPHealthCheckArgs] } // Path returns the default health check path if provided otherwise, returns the path from the advanced configuration. func (hc *HealthCheckArgsOrString) Path() *string { if hc.IsBasic() { return aws.String(hc.Basic) } return hc.Advanced.Path } // NLBHealthCheckArgs holds the configuration to determine if the network load balanced web service is healthy. // These options are specifiable under the "healthcheck" field. // See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html. type NLBHealthCheckArgs struct { Port *int `yaml:"port"` HealthyThreshold *int64 `yaml:"healthy_threshold"` UnhealthyThreshold *int64 `yaml:"unhealthy_threshold"` Timeout *time.Duration `yaml:"timeout"` Interval *time.Duration `yaml:"interval"` } func (h *NLBHealthCheckArgs) isEmpty() bool { return h.Port == nil && h.HealthyThreshold == nil && h.UnhealthyThreshold == nil && h.Timeout == nil && h.Interval == nil } // ParsePortMapping parses port-protocol string into individual port and protocol strings. // Valid examples: 2000/udp, or 2000. func ParsePortMapping(s *string) (port *string, protocol *string, err error) { if s == nil { return nil, nil, nil } portProtocol := strings.Split(*s, "/") switch len(portProtocol) { case 1: return aws.String(portProtocol[0]), nil, nil case 2: return aws.String(portProtocol[0]), aws.String(portProtocol[1]), nil default: return nil, nil, fmt.Errorf("cannot parse port mapping from %s", *s) } }
{ switch err.(type) { case *yaml.TypeError: break default: return err } }
conditional_block
lib.rs
//! dfconfig is a lib for parsing and manipulating Dwarf Fortress' `init.txt` and `d_init.txt` config files (and possibly many others using the same format). //! This lib's functionality has been specifically tailored to behave similar as DF internal parser, which implies: //! //! * [`Config::get`] returns the last occurrence value, if config specifies the key more than once. //! * Whitespaces are not allowed at the start of lines, any line not starting with `[` character is treated as a comment. //! //! Other notable functionality is that the parser preserves all of the parsed string content, including blank lines and comments. //! //! # Examples //! //! ```no_run //! # use std::io; //! use std::fs::{read_to_string, write}; //! use dfconfig::Config; //! //! // Parse existing config //! let path = r"/path/to/df/data/init/init.txt"; //! let mut conf = Config::read_str(read_to_string(path)?); //! //! // Read some value //! let sound = conf.get("SOUND"); //! //! // Modify and save the config //! conf.set("VOLUME", "128"); //! write(path, conf.print())?; //! # Ok::<(), io::Error>(()) //! ``` #[macro_use] extern crate lazy_static; use std::collections::HashMap; use regex::Regex; #[derive(Clone, Debug)] enum Line { Blank, Comment(String), Entry(Entry), } #[derive(Clone, Debug)] struct Entry { key: String, value: String, } impl Entry { pub fn new(key: String, value: String) -> Self { Self { key, value } } pub fn
(&self) -> &str { &self.value } pub fn get_key(&self) -> &str { &self.key } pub fn set_value(&mut self, value: String) { self.value = value; } } /// The main struct of this crate. Represents DF config file, while also providing functions to parse and manipulate the data. /// See crate doc for example usage. #[doc(inline)] #[derive(Clone, Debug)] pub struct Config { lines: Vec<Line>, } impl Config { /// Creates an empty config. pub fn new() -> Self { Self { lines: vec![] } } /// Parse the config from a string. pub fn read_str<T: AsRef<str>>(input: T) -> Self { lazy_static! { static ref RE: Regex = Regex::new(r"^\[([\w\d]+):([\w\d:]+)\]$").unwrap(); } let mut lines = Vec::<Line>::new(); for l in input.as_ref().lines() { let lt = l.trim_end(); if lt.is_empty() { lines.push(Line::Blank); continue; } let captures = RE.captures(lt); match captures { Some(c) => lines.push(Line::Entry(Entry::new( c.get(1).unwrap().as_str().to_owned(), c.get(2).unwrap().as_str().to_owned(), ))), None => lines.push(Line::Comment(l.to_owned())), }; } Self { lines } } /// Tries to retrieve the value for `key`. /// If the key is defined more than once, returns the value of the last occurrence. pub fn get<T: AsRef<str>>(&self, key: T) -> Option<&str> { self.lines.iter().rev().find_map(|x| match x { Line::Entry(entry) => { if entry.get_key() == key.as_ref() { Some(entry.get_value()) } else { None } } _ => None, }) } /// Sets all the occurrences of `key` to `value` /// /// # Panics /// /// Panics if `key` or `value` is either empty or non-alphanumeric. pub fn set<T: AsRef<str>, U: Into<String>>(&mut self, key: T, value: U) { let key = key.as_ref(); let value = value.into(); if key.is_empty() || !key.chars().all(|x| x.is_alphanumeric()) || value.is_empty() || !value.chars().all(|x| x.is_alphanumeric()) { panic!("Both key and value have to be non-empty alphanumeric strings!") } let mut n = 0; for e in self.lines.iter_mut() { if let Line::Entry(entry) = e { if entry.get_key() == key { entry.set_value(value.clone()); n += 1; } } } if n == 0 { self.lines .push(Line::Entry(Entry::new(key.to_string(), value))); } } /// Removes all occurrences of `key` from this `Config`. Returns the number of keys removed. pub fn remove<T: AsRef<str>>(&mut self, key: T) -> usize { let mut n: usize = 0; loop { let to_remove = self.lines.iter().enumerate().find_map(|(i, x)| { if let Line::Entry(entry) = x { if entry.get_key() == key.as_ref() { return Some(i); } } None }); match to_remove { None => break, Some(i) => { self.lines.remove(i); n += 1; } }; } n } /// Returns number of configuration entries present in this `Config`. pub fn len(&self) -> usize { self.lines .iter() .filter(|&x| matches!(x, Line::Entry(_))) .count() } /// Returns true if there are no entries defined in this `Config`. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns an iterator over the `key` strings. pub fn keys_iter(&self) -> impl Iterator<Item = &str> + '_ { self.lines.iter().filter_map(|x| { if let Line::Entry(entry) = x { Some(entry.get_key()) } else { None } }) } /// Returns an iterator over (`key`, `value`) tuples. pub fn keys_values_iter(&self) -> impl Iterator<Item = (&str, &str)> + '_ { self.lines.iter().filter_map(|x| { if let Line::Entry(entry) = x { Some((entry.get_key(), entry.get_value())) } else { None } }) } /// Returns the string representing the configuration in its current state (aka what you'd write to the file usually). pub fn print(&self) -> String { let mut buff = Vec::<String>::with_capacity(self.lines.len()); for l in self.lines.iter() { match l { Line::Blank => buff.push("".to_string()), Line::Comment(x) => buff.push(x.to_string()), Line::Entry(entry) => { buff.push(format!("[{}:{}]", entry.get_key(), entry.get_value())) } } } buff.join("\r\n") } } impl From<Config> for HashMap<String, String> { fn from(conf: Config) -> Self { let mut output = HashMap::new(); conf.keys_values_iter().for_each(|(key, value)| { output.insert(key.to_owned(), value.to_owned()); }); output } } impl Default for Config { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use std::fs::read_to_string; use std::iter; use super::*; fn random_alphanumeric() -> String { let mut rng = thread_rng(); iter::repeat(()) .map(|()| rng.sample(Alphanumeric)) .map(char::from) .take(thread_rng().gen_range(1..50)) .collect() } #[test] fn test_basic_parse() { let key = random_alphanumeric(); let key2 = random_alphanumeric(); let value: String = random_alphanumeric(); let c = Config::read_str(format!("[{}:{}]", key, value)); assert_eq!(c.get(key).unwrap(), value); assert_eq!(c.get(key2), None); } #[test] fn test_multi_value() { let key = random_alphanumeric(); let value: String = format!("{}:{}", random_alphanumeric(), random_alphanumeric()); let c = Config::read_str(format!("[{}:{}]", key, value)); assert_eq!(c.get(key).unwrap(), value); } #[test] fn test_basic_set() { let key = random_alphanumeric(); let value: String = random_alphanumeric(); let mut c = Config::new(); c.set(&key, &value); assert_eq!(c.get(key).unwrap(), value); } #[test] fn test_read_modify() { let key_a = random_alphanumeric(); let value_b: String = random_alphanumeric(); let value_c: String = random_alphanumeric(); let key_d = random_alphanumeric(); let value_e: String = random_alphanumeric(); let mut c = Config::read_str(format!("[{}:{}]", key_a, value_b)); assert_eq!(c.get(&key_a).unwrap(), value_b); c.set(&key_a, &value_c); assert_eq!(c.get(&key_a).unwrap(), value_c); c.set(&key_d, &value_e); assert_eq!(c.get(&key_a).unwrap(), value_c); assert_eq!(c.get(&key_d).unwrap(), value_e); } #[test] fn test_read_file_smoke() { let s = read_to_string("test-data/test.init").unwrap(); let c = Config::read_str(&s); s.lines() .zip(c.print().lines()) .for_each(|(a, b)| assert_eq!(a, b)); } #[test] fn test_len() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let c: String = random_alphanumeric(); let d: String = random_alphanumeric(); let e: String = random_alphanumeric(); let f: String = random_alphanumeric(); let g: String = random_alphanumeric(); let mut conf = Config::read_str(format!("[{}:{}]\r\nfoo bar\r\n[{}:{}]", a, b, c, d)); assert_eq!(conf.len(), 2); conf.set(&e, &f); assert_eq!(conf.len(), 3); conf.set(&e, &g); assert_eq!(conf.len(), 3); } #[test] #[should_panic] fn panic_on_empty_set() { let mut c = Config::new(); c.set("", ""); } #[test] #[should_panic] fn panic_on_non_alphanumeric_set() { let mut c = Config::new(); c.set("\r", "\n"); } #[test] fn test_keys_iter() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let mut iter = conf.keys_iter(); assert_eq!(Some(a.as_ref()), iter.next()); assert_eq!(Some(b.as_ref()), iter.next()); assert_eq!(None, iter.next()); } #[test] fn test_remove() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let c: String = random_alphanumeric(); let d: String = random_alphanumeric(); let mut conf = Config::read_str(format!( "[{}:foo]\r\n[{}:bar]\r\n[{}:bar2]\r\n[{}:foobar]\r\n[{}:foobar2]", a, b, b, c, d )); assert_eq!(conf.len(), 5); assert_eq!(conf.remove(&b), 2); assert_eq!(conf.len(), 3); assert_eq!(conf.get(&b), None); assert_eq!(conf.remove(&a), 1); assert_eq!(conf.len(), 2); assert_eq!(conf.get(&a), None); assert_eq!(conf.remove(random_alphanumeric()), 0); } #[test] fn test_keys_values_iter() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let mut iter = conf.keys_values_iter(); assert_eq!(Some((a.as_ref(), "foo")), iter.next()); assert_eq!(Some((b.as_ref(), "bar")), iter.next()); assert_eq!(None, iter.next()); } #[test] fn test_hashmap() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let hash_map_owned: HashMap<String, String> = conf.into(); assert_eq!(hash_map_owned.len(), 2); assert_eq!(hash_map_owned.get(&a).unwrap(), "foo"); assert_eq!(hash_map_owned.get(&b).unwrap(), "bar"); } }
get_value
identifier_name
lib.rs
//! dfconfig is a lib for parsing and manipulating Dwarf Fortress' `init.txt` and `d_init.txt` config files (and possibly many others using the same format). //! This lib's functionality has been specifically tailored to behave similar as DF internal parser, which implies: //! //! * [`Config::get`] returns the last occurrence value, if config specifies the key more than once. //! * Whitespaces are not allowed at the start of lines, any line not starting with `[` character is treated as a comment. //! //! Other notable functionality is that the parser preserves all of the parsed string content, including blank lines and comments. //! //! # Examples //! //! ```no_run //! # use std::io; //! use std::fs::{read_to_string, write}; //! use dfconfig::Config; //! //! // Parse existing config //! let path = r"/path/to/df/data/init/init.txt"; //! let mut conf = Config::read_str(read_to_string(path)?); //! //! // Read some value //! let sound = conf.get("SOUND"); //! //! // Modify and save the config //! conf.set("VOLUME", "128"); //! write(path, conf.print())?; //! # Ok::<(), io::Error>(()) //! ``` #[macro_use] extern crate lazy_static; use std::collections::HashMap; use regex::Regex; #[derive(Clone, Debug)] enum Line { Blank, Comment(String), Entry(Entry), } #[derive(Clone, Debug)] struct Entry { key: String, value: String, } impl Entry { pub fn new(key: String, value: String) -> Self { Self { key, value } } pub fn get_value(&self) -> &str { &self.value } pub fn get_key(&self) -> &str { &self.key } pub fn set_value(&mut self, value: String) { self.value = value; } } /// The main struct of this crate. Represents DF config file, while also providing functions to parse and manipulate the data. /// See crate doc for example usage. #[doc(inline)] #[derive(Clone, Debug)] pub struct Config { lines: Vec<Line>, } impl Config { /// Creates an empty config. pub fn new() -> Self { Self { lines: vec![] } } /// Parse the config from a string. pub fn read_str<T: AsRef<str>>(input: T) -> Self { lazy_static! { static ref RE: Regex = Regex::new(r"^\[([\w\d]+):([\w\d:]+)\]$").unwrap(); } let mut lines = Vec::<Line>::new(); for l in input.as_ref().lines() { let lt = l.trim_end(); if lt.is_empty() { lines.push(Line::Blank); continue; } let captures = RE.captures(lt); match captures { Some(c) => lines.push(Line::Entry(Entry::new( c.get(1).unwrap().as_str().to_owned(), c.get(2).unwrap().as_str().to_owned(), ))), None => lines.push(Line::Comment(l.to_owned())), }; } Self { lines } } /// Tries to retrieve the value for `key`. /// If the key is defined more than once, returns the value of the last occurrence. pub fn get<T: AsRef<str>>(&self, key: T) -> Option<&str> { self.lines.iter().rev().find_map(|x| match x { Line::Entry(entry) => { if entry.get_key() == key.as_ref() { Some(entry.get_value()) } else { None } } _ => None, }) } /// Sets all the occurrences of `key` to `value` /// /// # Panics /// /// Panics if `key` or `value` is either empty or non-alphanumeric. pub fn set<T: AsRef<str>, U: Into<String>>(&mut self, key: T, value: U) { let key = key.as_ref(); let value = value.into(); if key.is_empty() || !key.chars().all(|x| x.is_alphanumeric()) || value.is_empty() || !value.chars().all(|x| x.is_alphanumeric()) { panic!("Both key and value have to be non-empty alphanumeric strings!")
if let Line::Entry(entry) = e { if entry.get_key() == key { entry.set_value(value.clone()); n += 1; } } } if n == 0 { self.lines .push(Line::Entry(Entry::new(key.to_string(), value))); } } /// Removes all occurrences of `key` from this `Config`. Returns the number of keys removed. pub fn remove<T: AsRef<str>>(&mut self, key: T) -> usize { let mut n: usize = 0; loop { let to_remove = self.lines.iter().enumerate().find_map(|(i, x)| { if let Line::Entry(entry) = x { if entry.get_key() == key.as_ref() { return Some(i); } } None }); match to_remove { None => break, Some(i) => { self.lines.remove(i); n += 1; } }; } n } /// Returns number of configuration entries present in this `Config`. pub fn len(&self) -> usize { self.lines .iter() .filter(|&x| matches!(x, Line::Entry(_))) .count() } /// Returns true if there are no entries defined in this `Config`. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns an iterator over the `key` strings. pub fn keys_iter(&self) -> impl Iterator<Item = &str> + '_ { self.lines.iter().filter_map(|x| { if let Line::Entry(entry) = x { Some(entry.get_key()) } else { None } }) } /// Returns an iterator over (`key`, `value`) tuples. pub fn keys_values_iter(&self) -> impl Iterator<Item = (&str, &str)> + '_ { self.lines.iter().filter_map(|x| { if let Line::Entry(entry) = x { Some((entry.get_key(), entry.get_value())) } else { None } }) } /// Returns the string representing the configuration in its current state (aka what you'd write to the file usually). pub fn print(&self) -> String { let mut buff = Vec::<String>::with_capacity(self.lines.len()); for l in self.lines.iter() { match l { Line::Blank => buff.push("".to_string()), Line::Comment(x) => buff.push(x.to_string()), Line::Entry(entry) => { buff.push(format!("[{}:{}]", entry.get_key(), entry.get_value())) } } } buff.join("\r\n") } } impl From<Config> for HashMap<String, String> { fn from(conf: Config) -> Self { let mut output = HashMap::new(); conf.keys_values_iter().for_each(|(key, value)| { output.insert(key.to_owned(), value.to_owned()); }); output } } impl Default for Config { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use std::fs::read_to_string; use std::iter; use super::*; fn random_alphanumeric() -> String { let mut rng = thread_rng(); iter::repeat(()) .map(|()| rng.sample(Alphanumeric)) .map(char::from) .take(thread_rng().gen_range(1..50)) .collect() } #[test] fn test_basic_parse() { let key = random_alphanumeric(); let key2 = random_alphanumeric(); let value: String = random_alphanumeric(); let c = Config::read_str(format!("[{}:{}]", key, value)); assert_eq!(c.get(key).unwrap(), value); assert_eq!(c.get(key2), None); } #[test] fn test_multi_value() { let key = random_alphanumeric(); let value: String = format!("{}:{}", random_alphanumeric(), random_alphanumeric()); let c = Config::read_str(format!("[{}:{}]", key, value)); assert_eq!(c.get(key).unwrap(), value); } #[test] fn test_basic_set() { let key = random_alphanumeric(); let value: String = random_alphanumeric(); let mut c = Config::new(); c.set(&key, &value); assert_eq!(c.get(key).unwrap(), value); } #[test] fn test_read_modify() { let key_a = random_alphanumeric(); let value_b: String = random_alphanumeric(); let value_c: String = random_alphanumeric(); let key_d = random_alphanumeric(); let value_e: String = random_alphanumeric(); let mut c = Config::read_str(format!("[{}:{}]", key_a, value_b)); assert_eq!(c.get(&key_a).unwrap(), value_b); c.set(&key_a, &value_c); assert_eq!(c.get(&key_a).unwrap(), value_c); c.set(&key_d, &value_e); assert_eq!(c.get(&key_a).unwrap(), value_c); assert_eq!(c.get(&key_d).unwrap(), value_e); } #[test] fn test_read_file_smoke() { let s = read_to_string("test-data/test.init").unwrap(); let c = Config::read_str(&s); s.lines() .zip(c.print().lines()) .for_each(|(a, b)| assert_eq!(a, b)); } #[test] fn test_len() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let c: String = random_alphanumeric(); let d: String = random_alphanumeric(); let e: String = random_alphanumeric(); let f: String = random_alphanumeric(); let g: String = random_alphanumeric(); let mut conf = Config::read_str(format!("[{}:{}]\r\nfoo bar\r\n[{}:{}]", a, b, c, d)); assert_eq!(conf.len(), 2); conf.set(&e, &f); assert_eq!(conf.len(), 3); conf.set(&e, &g); assert_eq!(conf.len(), 3); } #[test] #[should_panic] fn panic_on_empty_set() { let mut c = Config::new(); c.set("", ""); } #[test] #[should_panic] fn panic_on_non_alphanumeric_set() { let mut c = Config::new(); c.set("\r", "\n"); } #[test] fn test_keys_iter() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let mut iter = conf.keys_iter(); assert_eq!(Some(a.as_ref()), iter.next()); assert_eq!(Some(b.as_ref()), iter.next()); assert_eq!(None, iter.next()); } #[test] fn test_remove() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let c: String = random_alphanumeric(); let d: String = random_alphanumeric(); let mut conf = Config::read_str(format!( "[{}:foo]\r\n[{}:bar]\r\n[{}:bar2]\r\n[{}:foobar]\r\n[{}:foobar2]", a, b, b, c, d )); assert_eq!(conf.len(), 5); assert_eq!(conf.remove(&b), 2); assert_eq!(conf.len(), 3); assert_eq!(conf.get(&b), None); assert_eq!(conf.remove(&a), 1); assert_eq!(conf.len(), 2); assert_eq!(conf.get(&a), None); assert_eq!(conf.remove(random_alphanumeric()), 0); } #[test] fn test_keys_values_iter() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let mut iter = conf.keys_values_iter(); assert_eq!(Some((a.as_ref(), "foo")), iter.next()); assert_eq!(Some((b.as_ref(), "bar")), iter.next()); assert_eq!(None, iter.next()); } #[test] fn test_hashmap() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let hash_map_owned: HashMap<String, String> = conf.into(); assert_eq!(hash_map_owned.len(), 2); assert_eq!(hash_map_owned.get(&a).unwrap(), "foo"); assert_eq!(hash_map_owned.get(&b).unwrap(), "bar"); } }
} let mut n = 0; for e in self.lines.iter_mut() {
random_line_split
lib.rs
//! dfconfig is a lib for parsing and manipulating Dwarf Fortress' `init.txt` and `d_init.txt` config files (and possibly many others using the same format). //! This lib's functionality has been specifically tailored to behave similar as DF internal parser, which implies: //! //! * [`Config::get`] returns the last occurrence value, if config specifies the key more than once. //! * Whitespaces are not allowed at the start of lines, any line not starting with `[` character is treated as a comment. //! //! Other notable functionality is that the parser preserves all of the parsed string content, including blank lines and comments. //! //! # Examples //! //! ```no_run //! # use std::io; //! use std::fs::{read_to_string, write}; //! use dfconfig::Config; //! //! // Parse existing config //! let path = r"/path/to/df/data/init/init.txt"; //! let mut conf = Config::read_str(read_to_string(path)?); //! //! // Read some value //! let sound = conf.get("SOUND"); //! //! // Modify and save the config //! conf.set("VOLUME", "128"); //! write(path, conf.print())?; //! # Ok::<(), io::Error>(()) //! ``` #[macro_use] extern crate lazy_static; use std::collections::HashMap; use regex::Regex; #[derive(Clone, Debug)] enum Line { Blank, Comment(String), Entry(Entry), } #[derive(Clone, Debug)] struct Entry { key: String, value: String, } impl Entry { pub fn new(key: String, value: String) -> Self { Self { key, value } } pub fn get_value(&self) -> &str { &self.value } pub fn get_key(&self) -> &str { &self.key } pub fn set_value(&mut self, value: String) { self.value = value; } } /// The main struct of this crate. Represents DF config file, while also providing functions to parse and manipulate the data. /// See crate doc for example usage. #[doc(inline)] #[derive(Clone, Debug)] pub struct Config { lines: Vec<Line>, } impl Config { /// Creates an empty config. pub fn new() -> Self { Self { lines: vec![] } } /// Parse the config from a string. pub fn read_str<T: AsRef<str>>(input: T) -> Self { lazy_static! { static ref RE: Regex = Regex::new(r"^\[([\w\d]+):([\w\d:]+)\]$").unwrap(); } let mut lines = Vec::<Line>::new(); for l in input.as_ref().lines() { let lt = l.trim_end(); if lt.is_empty() { lines.push(Line::Blank); continue; } let captures = RE.captures(lt); match captures { Some(c) => lines.push(Line::Entry(Entry::new( c.get(1).unwrap().as_str().to_owned(), c.get(2).unwrap().as_str().to_owned(), ))), None => lines.push(Line::Comment(l.to_owned())), }; } Self { lines } } /// Tries to retrieve the value for `key`. /// If the key is defined more than once, returns the value of the last occurrence. pub fn get<T: AsRef<str>>(&self, key: T) -> Option<&str> { self.lines.iter().rev().find_map(|x| match x { Line::Entry(entry) => { if entry.get_key() == key.as_ref() { Some(entry.get_value()) } else { None } } _ => None, }) } /// Sets all the occurrences of `key` to `value` /// /// # Panics /// /// Panics if `key` or `value` is either empty or non-alphanumeric. pub fn set<T: AsRef<str>, U: Into<String>>(&mut self, key: T, value: U) { let key = key.as_ref(); let value = value.into(); if key.is_empty() || !key.chars().all(|x| x.is_alphanumeric()) || value.is_empty() || !value.chars().all(|x| x.is_alphanumeric()) { panic!("Both key and value have to be non-empty alphanumeric strings!") } let mut n = 0; for e in self.lines.iter_mut() { if let Line::Entry(entry) = e { if entry.get_key() == key { entry.set_value(value.clone()); n += 1; } } } if n == 0 { self.lines .push(Line::Entry(Entry::new(key.to_string(), value))); } } /// Removes all occurrences of `key` from this `Config`. Returns the number of keys removed. pub fn remove<T: AsRef<str>>(&mut self, key: T) -> usize { let mut n: usize = 0; loop { let to_remove = self.lines.iter().enumerate().find_map(|(i, x)| { if let Line::Entry(entry) = x { if entry.get_key() == key.as_ref() { return Some(i); } } None }); match to_remove { None => break, Some(i) => { self.lines.remove(i); n += 1; } }; } n } /// Returns number of configuration entries present in this `Config`. pub fn len(&self) -> usize { self.lines .iter() .filter(|&x| matches!(x, Line::Entry(_))) .count() } /// Returns true if there are no entries defined in this `Config`. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns an iterator over the `key` strings. pub fn keys_iter(&self) -> impl Iterator<Item = &str> + '_ { self.lines.iter().filter_map(|x| { if let Line::Entry(entry) = x { Some(entry.get_key()) } else { None } }) } /// Returns an iterator over (`key`, `value`) tuples. pub fn keys_values_iter(&self) -> impl Iterator<Item = (&str, &str)> + '_ { self.lines.iter().filter_map(|x| { if let Line::Entry(entry) = x { Some((entry.get_key(), entry.get_value())) } else { None } }) } /// Returns the string representing the configuration in its current state (aka what you'd write to the file usually). pub fn print(&self) -> String { let mut buff = Vec::<String>::with_capacity(self.lines.len()); for l in self.lines.iter() { match l { Line::Blank => buff.push("".to_string()), Line::Comment(x) => buff.push(x.to_string()), Line::Entry(entry) => { buff.push(format!("[{}:{}]", entry.get_key(), entry.get_value())) } } } buff.join("\r\n") } } impl From<Config> for HashMap<String, String> { fn from(conf: Config) -> Self
} impl Default for Config { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use std::fs::read_to_string; use std::iter; use super::*; fn random_alphanumeric() -> String { let mut rng = thread_rng(); iter::repeat(()) .map(|()| rng.sample(Alphanumeric)) .map(char::from) .take(thread_rng().gen_range(1..50)) .collect() } #[test] fn test_basic_parse() { let key = random_alphanumeric(); let key2 = random_alphanumeric(); let value: String = random_alphanumeric(); let c = Config::read_str(format!("[{}:{}]", key, value)); assert_eq!(c.get(key).unwrap(), value); assert_eq!(c.get(key2), None); } #[test] fn test_multi_value() { let key = random_alphanumeric(); let value: String = format!("{}:{}", random_alphanumeric(), random_alphanumeric()); let c = Config::read_str(format!("[{}:{}]", key, value)); assert_eq!(c.get(key).unwrap(), value); } #[test] fn test_basic_set() { let key = random_alphanumeric(); let value: String = random_alphanumeric(); let mut c = Config::new(); c.set(&key, &value); assert_eq!(c.get(key).unwrap(), value); } #[test] fn test_read_modify() { let key_a = random_alphanumeric(); let value_b: String = random_alphanumeric(); let value_c: String = random_alphanumeric(); let key_d = random_alphanumeric(); let value_e: String = random_alphanumeric(); let mut c = Config::read_str(format!("[{}:{}]", key_a, value_b)); assert_eq!(c.get(&key_a).unwrap(), value_b); c.set(&key_a, &value_c); assert_eq!(c.get(&key_a).unwrap(), value_c); c.set(&key_d, &value_e); assert_eq!(c.get(&key_a).unwrap(), value_c); assert_eq!(c.get(&key_d).unwrap(), value_e); } #[test] fn test_read_file_smoke() { let s = read_to_string("test-data/test.init").unwrap(); let c = Config::read_str(&s); s.lines() .zip(c.print().lines()) .for_each(|(a, b)| assert_eq!(a, b)); } #[test] fn test_len() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let c: String = random_alphanumeric(); let d: String = random_alphanumeric(); let e: String = random_alphanumeric(); let f: String = random_alphanumeric(); let g: String = random_alphanumeric(); let mut conf = Config::read_str(format!("[{}:{}]\r\nfoo bar\r\n[{}:{}]", a, b, c, d)); assert_eq!(conf.len(), 2); conf.set(&e, &f); assert_eq!(conf.len(), 3); conf.set(&e, &g); assert_eq!(conf.len(), 3); } #[test] #[should_panic] fn panic_on_empty_set() { let mut c = Config::new(); c.set("", ""); } #[test] #[should_panic] fn panic_on_non_alphanumeric_set() { let mut c = Config::new(); c.set("\r", "\n"); } #[test] fn test_keys_iter() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let mut iter = conf.keys_iter(); assert_eq!(Some(a.as_ref()), iter.next()); assert_eq!(Some(b.as_ref()), iter.next()); assert_eq!(None, iter.next()); } #[test] fn test_remove() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let c: String = random_alphanumeric(); let d: String = random_alphanumeric(); let mut conf = Config::read_str(format!( "[{}:foo]\r\n[{}:bar]\r\n[{}:bar2]\r\n[{}:foobar]\r\n[{}:foobar2]", a, b, b, c, d )); assert_eq!(conf.len(), 5); assert_eq!(conf.remove(&b), 2); assert_eq!(conf.len(), 3); assert_eq!(conf.get(&b), None); assert_eq!(conf.remove(&a), 1); assert_eq!(conf.len(), 2); assert_eq!(conf.get(&a), None); assert_eq!(conf.remove(random_alphanumeric()), 0); } #[test] fn test_keys_values_iter() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let mut iter = conf.keys_values_iter(); assert_eq!(Some((a.as_ref(), "foo")), iter.next()); assert_eq!(Some((b.as_ref(), "bar")), iter.next()); assert_eq!(None, iter.next()); } #[test] fn test_hashmap() { let a: String = random_alphanumeric(); let b: String = random_alphanumeric(); let mut conf = Config::new(); conf.set(&a, "foo"); conf.set(&b, "bar"); let hash_map_owned: HashMap<String, String> = conf.into(); assert_eq!(hash_map_owned.len(), 2); assert_eq!(hash_map_owned.get(&a).unwrap(), "foo"); assert_eq!(hash_map_owned.get(&b).unwrap(), "bar"); } }
{ let mut output = HashMap::new(); conf.keys_values_iter().for_each(|(key, value)| { output.insert(key.to_owned(), value.to_owned()); }); output }
identifier_body
ctrl_map.rs
//! Maps MIDI controllers to synth parameters. use super::{ParamId, MenuItem}; use super::SoundData; use super::SynthParam; use super::ValueRange; use log::{info, trace}; use serde::{Serialize, Deserialize}; use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] pub enum MappingType { None, Absolute, Relative } #[derive(Clone, Copy, Debug)] pub struct CtrlMapEntry { id: ParamId, map_type: MappingType, val_range: &'static ValueRange, } /// ValueRange contains a reference, so it can't be stored easily. Instead we /// store only ParamId and MappingType and rely on the TUI to look up the /// value range when loading the data. /// #[derive(Serialize, Deserialize, Clone, Copy, Debug)] pub struct CtrlMapStorageEntry { id: ParamId, map_type: MappingType, } type CtrlHashMap = HashMap<u64, CtrlMapEntry>; type CtrlHashMapStorage = HashMap<u64, CtrlMapStorageEntry>; pub struct CtrlMap { map: Vec<CtrlHashMap> } impl CtrlMap { pub fn new() -> CtrlMap { // 36 sets of controller mappings (0-9, a-z) CtrlMap{map: vec!(CtrlHashMap::new(); 36)} } /// Reset the map, removing all controller assignments. pub fn reset(&mut self) { for m in &mut self.map { m.clear(); } } /// Add a new mapping entry for a controller. /// /// set: The selected controller map set /// controller: The controller number to add /// map_type: Type of value change (absolute or relative) /// parameter: The parameter changed with this controller /// val_range: The valid values for the parameter /// pub fn add_mapping(&mut self, set: usize, controller: u64, map_type: MappingType, parameter: ParamId, val_range: &'static ValueRange) { trace!("add_mapping: Set {}, ctrl {}, type {:?}, param {:?}, val range {:?}", set, controller, map_type, parameter, val_range); self.map[set].insert(controller, CtrlMapEntry{id: parameter, map_type, val_range}); } /// Delete all mappings for a parameter. /// /// Returns true if one or more mappings were deleted, false otherwise pub fn delete_mapping(&mut self, set: usize, parameter: ParamId) -> bool { trace!("delete_mapping: Set {}, param {:?}", set, parameter); let mut controller: u64; let mut found = false; loop { controller = 0; for (key, val) in self.map[set].iter() { if val.id == parameter { controller = *key; } } if controller > 0 { self.map[set].remove(&controller); found = true; } else { break; } } found } /// Update a value according to the controller value. /// /// Uses the parameter's val_range to translate the controller value into /// a valid parameter value. /// /// set: The selected controller map set /// controller: The controller number to look up /// value: New value of the controller /// sound: Currently active sound /// result: SynthParam that receives the changed value /// /// Return true if result was updated, false otherwise /// pub fn get_value(&self, set: usize, controller: u64, value: u64, sound: &SoundData) -> Result<SynthParam, ()> { // Get mapping if !self.map[set].contains_key(&controller) { return Err(()); } let mapping = &self.map[set][&controller]; let mut result = SynthParam::new_from(&mapping.id); match mapping.map_type { MappingType::Absolute => { // For absolute: Translate value let trans_val = mapping.val_range.translate_value(value); result.value = trans_val; } MappingType::Relative => { // For relative: Increase/ decrease value let sound_value = sound.get_value(&mapping.id); let delta = if value >= 64 { -1 } else { 1 }; result.value = mapping.val_range.add_value(sound_value, delta); } MappingType::None => panic!(), }; Ok(result) } // Load controller mappings from file pub fn load(&mut self, filename: &str) -> std::io::Result<()> { info!("Reading controller mapping from {}", filename); let file = File::open(filename)?; let mut reader = BufReader::new(file); self.reset(); let mut serialized = String::new(); reader.read_to_string(&mut serialized)?; let storage_map: Vec<CtrlHashMapStorage> = serde_json::from_str(&serialized).unwrap(); for (i, item) in storage_map.iter().enumerate() { for (key, value) in item { let val_range = MenuItem::get_val_range(value.id.function, value.id.parameter); self.map[i].insert(*key, CtrlMapEntry{id: value.id, map_type: value.map_type, val_range}); } } Ok(()) } // Store controller mappings to file pub fn save(&self, filename: &str) -> std::io::Result<()> { info!("Writing controller mapping to {}", filename); // Transfer data into serializable format let mut storage_map = vec!(CtrlHashMapStorage::new(); 36); for (i, item) in self.map.iter().enumerate() { for (key, value) in item { storage_map[i].insert(*key, CtrlMapStorageEntry{id: value.id, map_type: value.map_type}); } } let mut file = File::create(filename)?; let serialized = serde_json::to_string_pretty(&storage_map).unwrap(); file.write_all(serialized.as_bytes())?; Ok(()) } } // ---------------------------------------------- // Unit tests // ---------------------------------------------- #[cfg(test)] mod tests { use super::{CtrlMap, MappingType}; use super::super::Float; use super::super::{Parameter, ParamId, ParameterValue, MenuItem}; use super::super::{SoundData, SoundPatch}; use super::super::SynthParam; use std::cell::RefCell; use std::rc::Rc; struct TestContext { map: CtrlMap, sound: SoundPatch, sound_data: Rc<RefCell<SoundData>>, param_id: ParamId, synth_param: SynthParam, } impl TestContext { fn new() -> TestContext { let map = CtrlMap::new(); let sound = SoundPatch::new(); let sound_data = Rc::new(RefCell::new(sound.data)); let param_id = ParamId::new(Parameter::Oscillator, 1, Parameter::Level); let synth_param = SynthParam::new(Parameter::Oscillator, 1, Parameter::Level, ParameterValue::Float(0.0)); TestContext{map, sound, sound_data, param_id, synth_param} } pub fn
(&mut self, ctrl_no: u64, ctrl_type: MappingType) { let val_range = MenuItem::get_val_range(self.param_id.function, self.param_id.parameter); self.map.add_mapping(1, ctrl_no, ctrl_type, self.param_id, val_range); } pub fn handle_controller(&mut self, ctrl_no: u64, value: u64) -> bool { let sound_data = &mut self.sound_data.borrow_mut(); match self.map.get_value(1, ctrl_no, value, sound_data) { Ok(result) => { sound_data.set_parameter(&result); true } Err(()) => false } } pub fn has_value(&mut self, value: Float) -> bool { let pval = self.sound_data.borrow().get_value(&self.param_id); if let ParameterValue::Float(x) = pval { println!("\nIs: {} Expected: {}", x, value); x == value } else { false } } pub fn delete_controller(&mut self) -> bool { self.map.delete_mapping(1, self.param_id) } } #[test] fn controller_without_mapping_returns_no_value() { let mut context = TestContext::new(); assert_eq!(context.handle_controller(1, 50), false); } #[test] fn absolute_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_absolute() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(0.0), true); } #[test] fn relative_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_relative() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Relative); // Increase value assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(51.0), true); // Decrease value assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.has_value(50.0), true); } #[test] fn mapping_can_be_deleted() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.delete_controller(), true); assert_eq!(context.handle_controller(1, 127), false); } #[test] fn nonexisting_mapping_isnt_deleted() { let mut context = TestContext::new(); assert_eq!(context.delete_controller(), false); } } // mod tests
add_controller
identifier_name
ctrl_map.rs
//! Maps MIDI controllers to synth parameters. use super::{ParamId, MenuItem}; use super::SoundData; use super::SynthParam; use super::ValueRange; use log::{info, trace}; use serde::{Serialize, Deserialize}; use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] pub enum MappingType { None, Absolute, Relative } #[derive(Clone, Copy, Debug)] pub struct CtrlMapEntry { id: ParamId, map_type: MappingType, val_range: &'static ValueRange, } /// ValueRange contains a reference, so it can't be stored easily. Instead we /// store only ParamId and MappingType and rely on the TUI to look up the /// value range when loading the data. /// #[derive(Serialize, Deserialize, Clone, Copy, Debug)] pub struct CtrlMapStorageEntry { id: ParamId, map_type: MappingType, } type CtrlHashMap = HashMap<u64, CtrlMapEntry>; type CtrlHashMapStorage = HashMap<u64, CtrlMapStorageEntry>; pub struct CtrlMap { map: Vec<CtrlHashMap> } impl CtrlMap { pub fn new() -> CtrlMap { // 36 sets of controller mappings (0-9, a-z) CtrlMap{map: vec!(CtrlHashMap::new(); 36)} } /// Reset the map, removing all controller assignments. pub fn reset(&mut self) { for m in &mut self.map { m.clear(); } } /// Add a new mapping entry for a controller. /// /// set: The selected controller map set /// controller: The controller number to add /// map_type: Type of value change (absolute or relative) /// parameter: The parameter changed with this controller /// val_range: The valid values for the parameter /// pub fn add_mapping(&mut self, set: usize, controller: u64, map_type: MappingType, parameter: ParamId, val_range: &'static ValueRange) { trace!("add_mapping: Set {}, ctrl {}, type {:?}, param {:?}, val range {:?}", set, controller, map_type, parameter, val_range); self.map[set].insert(controller, CtrlMapEntry{id: parameter, map_type, val_range}); } /// Delete all mappings for a parameter. /// /// Returns true if one or more mappings were deleted, false otherwise pub fn delete_mapping(&mut self, set: usize, parameter: ParamId) -> bool { trace!("delete_mapping: Set {}, param {:?}", set, parameter); let mut controller: u64; let mut found = false; loop { controller = 0; for (key, val) in self.map[set].iter() { if val.id == parameter { controller = *key; } } if controller > 0 { self.map[set].remove(&controller); found = true; } else { break; } } found } /// Update a value according to the controller value. /// /// Uses the parameter's val_range to translate the controller value into /// a valid parameter value. /// /// set: The selected controller map set /// controller: The controller number to look up /// value: New value of the controller /// sound: Currently active sound /// result: SynthParam that receives the changed value /// /// Return true if result was updated, false otherwise /// pub fn get_value(&self, set: usize, controller: u64, value: u64, sound: &SoundData) -> Result<SynthParam, ()> { // Get mapping if !self.map[set].contains_key(&controller) { return Err(()); } let mapping = &self.map[set][&controller]; let mut result = SynthParam::new_from(&mapping.id); match mapping.map_type { MappingType::Absolute => { // For absolute: Translate value let trans_val = mapping.val_range.translate_value(value); result.value = trans_val; } MappingType::Relative =>
MappingType::None => panic!(), }; Ok(result) } // Load controller mappings from file pub fn load(&mut self, filename: &str) -> std::io::Result<()> { info!("Reading controller mapping from {}", filename); let file = File::open(filename)?; let mut reader = BufReader::new(file); self.reset(); let mut serialized = String::new(); reader.read_to_string(&mut serialized)?; let storage_map: Vec<CtrlHashMapStorage> = serde_json::from_str(&serialized).unwrap(); for (i, item) in storage_map.iter().enumerate() { for (key, value) in item { let val_range = MenuItem::get_val_range(value.id.function, value.id.parameter); self.map[i].insert(*key, CtrlMapEntry{id: value.id, map_type: value.map_type, val_range}); } } Ok(()) } // Store controller mappings to file pub fn save(&self, filename: &str) -> std::io::Result<()> { info!("Writing controller mapping to {}", filename); // Transfer data into serializable format let mut storage_map = vec!(CtrlHashMapStorage::new(); 36); for (i, item) in self.map.iter().enumerate() { for (key, value) in item { storage_map[i].insert(*key, CtrlMapStorageEntry{id: value.id, map_type: value.map_type}); } } let mut file = File::create(filename)?; let serialized = serde_json::to_string_pretty(&storage_map).unwrap(); file.write_all(serialized.as_bytes())?; Ok(()) } } // ---------------------------------------------- // Unit tests // ---------------------------------------------- #[cfg(test)] mod tests { use super::{CtrlMap, MappingType}; use super::super::Float; use super::super::{Parameter, ParamId, ParameterValue, MenuItem}; use super::super::{SoundData, SoundPatch}; use super::super::SynthParam; use std::cell::RefCell; use std::rc::Rc; struct TestContext { map: CtrlMap, sound: SoundPatch, sound_data: Rc<RefCell<SoundData>>, param_id: ParamId, synth_param: SynthParam, } impl TestContext { fn new() -> TestContext { let map = CtrlMap::new(); let sound = SoundPatch::new(); let sound_data = Rc::new(RefCell::new(sound.data)); let param_id = ParamId::new(Parameter::Oscillator, 1, Parameter::Level); let synth_param = SynthParam::new(Parameter::Oscillator, 1, Parameter::Level, ParameterValue::Float(0.0)); TestContext{map, sound, sound_data, param_id, synth_param} } pub fn add_controller(&mut self, ctrl_no: u64, ctrl_type: MappingType) { let val_range = MenuItem::get_val_range(self.param_id.function, self.param_id.parameter); self.map.add_mapping(1, ctrl_no, ctrl_type, self.param_id, val_range); } pub fn handle_controller(&mut self, ctrl_no: u64, value: u64) -> bool { let sound_data = &mut self.sound_data.borrow_mut(); match self.map.get_value(1, ctrl_no, value, sound_data) { Ok(result) => { sound_data.set_parameter(&result); true } Err(()) => false } } pub fn has_value(&mut self, value: Float) -> bool { let pval = self.sound_data.borrow().get_value(&self.param_id); if let ParameterValue::Float(x) = pval { println!("\nIs: {} Expected: {}", x, value); x == value } else { false } } pub fn delete_controller(&mut self) -> bool { self.map.delete_mapping(1, self.param_id) } } #[test] fn controller_without_mapping_returns_no_value() { let mut context = TestContext::new(); assert_eq!(context.handle_controller(1, 50), false); } #[test] fn absolute_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_absolute() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(0.0), true); } #[test] fn relative_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_relative() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Relative); // Increase value assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(51.0), true); // Decrease value assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.has_value(50.0), true); } #[test] fn mapping_can_be_deleted() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.delete_controller(), true); assert_eq!(context.handle_controller(1, 127), false); } #[test] fn nonexisting_mapping_isnt_deleted() { let mut context = TestContext::new(); assert_eq!(context.delete_controller(), false); } } // mod tests
{ // For relative: Increase/ decrease value let sound_value = sound.get_value(&mapping.id); let delta = if value >= 64 { -1 } else { 1 }; result.value = mapping.val_range.add_value(sound_value, delta); }
conditional_block
ctrl_map.rs
//! Maps MIDI controllers to synth parameters. use super::{ParamId, MenuItem}; use super::SoundData; use super::SynthParam; use super::ValueRange; use log::{info, trace}; use serde::{Serialize, Deserialize}; use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] pub enum MappingType { None, Absolute, Relative } #[derive(Clone, Copy, Debug)] pub struct CtrlMapEntry { id: ParamId, map_type: MappingType, val_range: &'static ValueRange, } /// ValueRange contains a reference, so it can't be stored easily. Instead we /// store only ParamId and MappingType and rely on the TUI to look up the /// value range when loading the data. /// #[derive(Serialize, Deserialize, Clone, Copy, Debug)] pub struct CtrlMapStorageEntry { id: ParamId, map_type: MappingType, } type CtrlHashMap = HashMap<u64, CtrlMapEntry>; type CtrlHashMapStorage = HashMap<u64, CtrlMapStorageEntry>; pub struct CtrlMap { map: Vec<CtrlHashMap> } impl CtrlMap { pub fn new() -> CtrlMap { // 36 sets of controller mappings (0-9, a-z) CtrlMap{map: vec!(CtrlHashMap::new(); 36)} } /// Reset the map, removing all controller assignments. pub fn reset(&mut self) { for m in &mut self.map { m.clear(); } } /// Add a new mapping entry for a controller. /// /// set: The selected controller map set /// controller: The controller number to add /// map_type: Type of value change (absolute or relative) /// parameter: The parameter changed with this controller /// val_range: The valid values for the parameter /// pub fn add_mapping(&mut self, set: usize, controller: u64, map_type: MappingType, parameter: ParamId, val_range: &'static ValueRange) { trace!("add_mapping: Set {}, ctrl {}, type {:?}, param {:?}, val range {:?}", set, controller, map_type, parameter, val_range); self.map[set].insert(controller, CtrlMapEntry{id: parameter, map_type, val_range}); } /// Delete all mappings for a parameter. /// /// Returns true if one or more mappings were deleted, false otherwise pub fn delete_mapping(&mut self, set: usize, parameter: ParamId) -> bool { trace!("delete_mapping: Set {}, param {:?}", set, parameter); let mut controller: u64; let mut found = false; loop { controller = 0; for (key, val) in self.map[set].iter() { if val.id == parameter { controller = *key; } } if controller > 0 { self.map[set].remove(&controller); found = true; } else { break; } } found } /// Update a value according to the controller value. /// /// Uses the parameter's val_range to translate the controller value into /// a valid parameter value. /// /// set: The selected controller map set /// controller: The controller number to look up /// value: New value of the controller /// sound: Currently active sound /// result: SynthParam that receives the changed value /// /// Return true if result was updated, false otherwise /// pub fn get_value(&self,
controller: u64, value: u64, sound: &SoundData) -> Result<SynthParam, ()> { // Get mapping if !self.map[set].contains_key(&controller) { return Err(()); } let mapping = &self.map[set][&controller]; let mut result = SynthParam::new_from(&mapping.id); match mapping.map_type { MappingType::Absolute => { // For absolute: Translate value let trans_val = mapping.val_range.translate_value(value); result.value = trans_val; } MappingType::Relative => { // For relative: Increase/ decrease value let sound_value = sound.get_value(&mapping.id); let delta = if value >= 64 { -1 } else { 1 }; result.value = mapping.val_range.add_value(sound_value, delta); } MappingType::None => panic!(), }; Ok(result) } // Load controller mappings from file pub fn load(&mut self, filename: &str) -> std::io::Result<()> { info!("Reading controller mapping from {}", filename); let file = File::open(filename)?; let mut reader = BufReader::new(file); self.reset(); let mut serialized = String::new(); reader.read_to_string(&mut serialized)?; let storage_map: Vec<CtrlHashMapStorage> = serde_json::from_str(&serialized).unwrap(); for (i, item) in storage_map.iter().enumerate() { for (key, value) in item { let val_range = MenuItem::get_val_range(value.id.function, value.id.parameter); self.map[i].insert(*key, CtrlMapEntry{id: value.id, map_type: value.map_type, val_range}); } } Ok(()) } // Store controller mappings to file pub fn save(&self, filename: &str) -> std::io::Result<()> { info!("Writing controller mapping to {}", filename); // Transfer data into serializable format let mut storage_map = vec!(CtrlHashMapStorage::new(); 36); for (i, item) in self.map.iter().enumerate() { for (key, value) in item { storage_map[i].insert(*key, CtrlMapStorageEntry{id: value.id, map_type: value.map_type}); } } let mut file = File::create(filename)?; let serialized = serde_json::to_string_pretty(&storage_map).unwrap(); file.write_all(serialized.as_bytes())?; Ok(()) } } // ---------------------------------------------- // Unit tests // ---------------------------------------------- #[cfg(test)] mod tests { use super::{CtrlMap, MappingType}; use super::super::Float; use super::super::{Parameter, ParamId, ParameterValue, MenuItem}; use super::super::{SoundData, SoundPatch}; use super::super::SynthParam; use std::cell::RefCell; use std::rc::Rc; struct TestContext { map: CtrlMap, sound: SoundPatch, sound_data: Rc<RefCell<SoundData>>, param_id: ParamId, synth_param: SynthParam, } impl TestContext { fn new() -> TestContext { let map = CtrlMap::new(); let sound = SoundPatch::new(); let sound_data = Rc::new(RefCell::new(sound.data)); let param_id = ParamId::new(Parameter::Oscillator, 1, Parameter::Level); let synth_param = SynthParam::new(Parameter::Oscillator, 1, Parameter::Level, ParameterValue::Float(0.0)); TestContext{map, sound, sound_data, param_id, synth_param} } pub fn add_controller(&mut self, ctrl_no: u64, ctrl_type: MappingType) { let val_range = MenuItem::get_val_range(self.param_id.function, self.param_id.parameter); self.map.add_mapping(1, ctrl_no, ctrl_type, self.param_id, val_range); } pub fn handle_controller(&mut self, ctrl_no: u64, value: u64) -> bool { let sound_data = &mut self.sound_data.borrow_mut(); match self.map.get_value(1, ctrl_no, value, sound_data) { Ok(result) => { sound_data.set_parameter(&result); true } Err(()) => false } } pub fn has_value(&mut self, value: Float) -> bool { let pval = self.sound_data.borrow().get_value(&self.param_id); if let ParameterValue::Float(x) = pval { println!("\nIs: {} Expected: {}", x, value); x == value } else { false } } pub fn delete_controller(&mut self) -> bool { self.map.delete_mapping(1, self.param_id) } } #[test] fn controller_without_mapping_returns_no_value() { let mut context = TestContext::new(); assert_eq!(context.handle_controller(1, 50), false); } #[test] fn absolute_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_absolute() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(0.0), true); } #[test] fn relative_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_relative() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Relative); // Increase value assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(51.0), true); // Decrease value assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.has_value(50.0), true); } #[test] fn mapping_can_be_deleted() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.delete_controller(), true); assert_eq!(context.handle_controller(1, 127), false); } #[test] fn nonexisting_mapping_isnt_deleted() { let mut context = TestContext::new(); assert_eq!(context.delete_controller(), false); } } // mod tests
set: usize,
random_line_split
ctrl_map.rs
//! Maps MIDI controllers to synth parameters. use super::{ParamId, MenuItem}; use super::SoundData; use super::SynthParam; use super::ValueRange; use log::{info, trace}; use serde::{Serialize, Deserialize}; use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] pub enum MappingType { None, Absolute, Relative } #[derive(Clone, Copy, Debug)] pub struct CtrlMapEntry { id: ParamId, map_type: MappingType, val_range: &'static ValueRange, } /// ValueRange contains a reference, so it can't be stored easily. Instead we /// store only ParamId and MappingType and rely on the TUI to look up the /// value range when loading the data. /// #[derive(Serialize, Deserialize, Clone, Copy, Debug)] pub struct CtrlMapStorageEntry { id: ParamId, map_type: MappingType, } type CtrlHashMap = HashMap<u64, CtrlMapEntry>; type CtrlHashMapStorage = HashMap<u64, CtrlMapStorageEntry>; pub struct CtrlMap { map: Vec<CtrlHashMap> } impl CtrlMap { pub fn new() -> CtrlMap { // 36 sets of controller mappings (0-9, a-z) CtrlMap{map: vec!(CtrlHashMap::new(); 36)} } /// Reset the map, removing all controller assignments. pub fn reset(&mut self) { for m in &mut self.map { m.clear(); } } /// Add a new mapping entry for a controller. /// /// set: The selected controller map set /// controller: The controller number to add /// map_type: Type of value change (absolute or relative) /// parameter: The parameter changed with this controller /// val_range: The valid values for the parameter /// pub fn add_mapping(&mut self, set: usize, controller: u64, map_type: MappingType, parameter: ParamId, val_range: &'static ValueRange) { trace!("add_mapping: Set {}, ctrl {}, type {:?}, param {:?}, val range {:?}", set, controller, map_type, parameter, val_range); self.map[set].insert(controller, CtrlMapEntry{id: parameter, map_type, val_range}); } /// Delete all mappings for a parameter. /// /// Returns true if one or more mappings were deleted, false otherwise pub fn delete_mapping(&mut self, set: usize, parameter: ParamId) -> bool { trace!("delete_mapping: Set {}, param {:?}", set, parameter); let mut controller: u64; let mut found = false; loop { controller = 0; for (key, val) in self.map[set].iter() { if val.id == parameter { controller = *key; } } if controller > 0 { self.map[set].remove(&controller); found = true; } else { break; } } found } /// Update a value according to the controller value. /// /// Uses the parameter's val_range to translate the controller value into /// a valid parameter value. /// /// set: The selected controller map set /// controller: The controller number to look up /// value: New value of the controller /// sound: Currently active sound /// result: SynthParam that receives the changed value /// /// Return true if result was updated, false otherwise /// pub fn get_value(&self, set: usize, controller: u64, value: u64, sound: &SoundData) -> Result<SynthParam, ()> { // Get mapping if !self.map[set].contains_key(&controller) { return Err(()); } let mapping = &self.map[set][&controller]; let mut result = SynthParam::new_from(&mapping.id); match mapping.map_type { MappingType::Absolute => { // For absolute: Translate value let trans_val = mapping.val_range.translate_value(value); result.value = trans_val; } MappingType::Relative => { // For relative: Increase/ decrease value let sound_value = sound.get_value(&mapping.id); let delta = if value >= 64 { -1 } else { 1 }; result.value = mapping.val_range.add_value(sound_value, delta); } MappingType::None => panic!(), }; Ok(result) } // Load controller mappings from file pub fn load(&mut self, filename: &str) -> std::io::Result<()> { info!("Reading controller mapping from {}", filename); let file = File::open(filename)?; let mut reader = BufReader::new(file); self.reset(); let mut serialized = String::new(); reader.read_to_string(&mut serialized)?; let storage_map: Vec<CtrlHashMapStorage> = serde_json::from_str(&serialized).unwrap(); for (i, item) in storage_map.iter().enumerate() { for (key, value) in item { let val_range = MenuItem::get_val_range(value.id.function, value.id.parameter); self.map[i].insert(*key, CtrlMapEntry{id: value.id, map_type: value.map_type, val_range}); } } Ok(()) } // Store controller mappings to file pub fn save(&self, filename: &str) -> std::io::Result<()> { info!("Writing controller mapping to {}", filename); // Transfer data into serializable format let mut storage_map = vec!(CtrlHashMapStorage::new(); 36); for (i, item) in self.map.iter().enumerate() { for (key, value) in item { storage_map[i].insert(*key, CtrlMapStorageEntry{id: value.id, map_type: value.map_type}); } } let mut file = File::create(filename)?; let serialized = serde_json::to_string_pretty(&storage_map).unwrap(); file.write_all(serialized.as_bytes())?; Ok(()) } } // ---------------------------------------------- // Unit tests // ---------------------------------------------- #[cfg(test)] mod tests { use super::{CtrlMap, MappingType}; use super::super::Float; use super::super::{Parameter, ParamId, ParameterValue, MenuItem}; use super::super::{SoundData, SoundPatch}; use super::super::SynthParam; use std::cell::RefCell; use std::rc::Rc; struct TestContext { map: CtrlMap, sound: SoundPatch, sound_data: Rc<RefCell<SoundData>>, param_id: ParamId, synth_param: SynthParam, } impl TestContext { fn new() -> TestContext { let map = CtrlMap::new(); let sound = SoundPatch::new(); let sound_data = Rc::new(RefCell::new(sound.data)); let param_id = ParamId::new(Parameter::Oscillator, 1, Parameter::Level); let synth_param = SynthParam::new(Parameter::Oscillator, 1, Parameter::Level, ParameterValue::Float(0.0)); TestContext{map, sound, sound_data, param_id, synth_param} } pub fn add_controller(&mut self, ctrl_no: u64, ctrl_type: MappingType) { let val_range = MenuItem::get_val_range(self.param_id.function, self.param_id.parameter); self.map.add_mapping(1, ctrl_no, ctrl_type, self.param_id, val_range); } pub fn handle_controller(&mut self, ctrl_no: u64, value: u64) -> bool { let sound_data = &mut self.sound_data.borrow_mut(); match self.map.get_value(1, ctrl_no, value, sound_data) { Ok(result) => { sound_data.set_parameter(&result); true } Err(()) => false } } pub fn has_value(&mut self, value: Float) -> bool { let pval = self.sound_data.borrow().get_value(&self.param_id); if let ParameterValue::Float(x) = pval { println!("\nIs: {} Expected: {}", x, value); x == value } else { false } } pub fn delete_controller(&mut self) -> bool { self.map.delete_mapping(1, self.param_id) } } #[test] fn controller_without_mapping_returns_no_value() { let mut context = TestContext::new(); assert_eq!(context.handle_controller(1, 50), false); } #[test] fn absolute_controller_can_be_added()
#[test] fn value_can_be_changed_absolute() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(0.0), true); } #[test] fn relative_controller_can_be_added() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 50), true); } #[test] fn value_can_be_changed_relative() { let mut context = TestContext::new(); assert_eq!(context.has_value(50.0), true); context.add_controller(1, MappingType::Relative); // Increase value assert_eq!(context.handle_controller(1, 0), true); assert_eq!(context.has_value(51.0), true); // Decrease value assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.has_value(50.0), true); } #[test] fn mapping_can_be_deleted() { let mut context = TestContext::new(); context.add_controller(1, MappingType::Relative); assert_eq!(context.handle_controller(1, 127), true); assert_eq!(context.delete_controller(), true); assert_eq!(context.handle_controller(1, 127), false); } #[test] fn nonexisting_mapping_isnt_deleted() { let mut context = TestContext::new(); assert_eq!(context.delete_controller(), false); } } // mod tests
{ let mut context = TestContext::new(); context.add_controller(1, MappingType::Absolute); assert_eq!(context.handle_controller(1, 50), true); }
identifier_body
random.rs
use alloc::boxed::Box; use std::f64::consts::PI; use std::num::Wrapping; use std::sync::Arc; use std::vec::Vec; use common::bytes::{Buf, Bytes}; use common::io::Readable; use common::{ceil_div, errors::*}; use executor::sync::Mutex; use file::LocalFile; use math::big::{BigUint, SecureBigUint}; use math::integer::Integer; use crate::chacha20::*; const MAX_BYTES_BEFORE_RESEED: usize = 1024 * 1024 * 1024; // 1GB lazy_static! { static ref GLOBAL_RNG_STATE: GlobalRng = GlobalRng::new(); } /// Gets a lazily initialized reference to a globally shared random number /// generator. /// /// This is seeded on the first random generation. /// /// The implementation can be assumed to be secure for cryptographic purposes /// but may not be very fast. /// /// TODO: We should disallow re-seeding this RNG. pub fn global_rng() -> GlobalRng { GLOBAL_RNG_STATE.clone() } /// Call me if you want a cheap but insecure RNG seeded by the current system /// time. pub fn clocked_rng() -> MersenneTwisterRng { let mut rng = MersenneTwisterRng::mt19937(); let seed = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .subsec_nanos(); rng.seed_u32(seed); rng } /// Generates secure random bytes suitable for cryptographic key generation. /// This will wait for sufficient entropy to accumulate in the system. /// /// Once done, the provided buffer will be filled with the random bytes to the /// end. pub async fn secure_random_bytes(buf: &mut [u8]) -> Result<()> { // See http://man7.org/linux/man-pages/man7/random.7.html // TODO: Reuse the file handle across calls. let mut f = LocalFile::open("/dev/random")?; f.read_exact(buf).await?; Ok(()) } /// Securely generates a random value in the range '[lower, upper)'. /// /// This is implemented to give every integer in the range the same probabiity /// of being output. /// /// NOTE: Both the 'lower' and 'upper' numbers should be publicly known for this /// to be secure. /// /// The output integer will have the same width as the 'upper' integer. pub async fn secure_random_range( lower: &SecureBigUint, upper: &SecureBigUint, ) -> Result<SecureBigUint> { if upper.byte_width() == 0 || upper <= lower { return Err(err_msg("Invalid upper/lower range")); } let mut buf = vec![]; buf.resize(upper.byte_width(), 0); let mut num_bytes = ceil_div(upper.value_bits(), 8); let msb_mask: u8 = { let r = upper.value_bits() % 8; if r == 0 { 0xff } else { !((1 << (8 - r)) - 1) } }; // TODO: Refactor out retrying. Instead shift to 0 loop { secure_random_bytes(&mut buf[0..num_bytes]).await?; buf[num_bytes - 1] &= msb_mask; let n = SecureBigUint::from_le_bytes(&buf); // TODO: This *must* be a secure comparison (which it isn't right now). if &n >= lower && &n < upper { return Ok(n); } } } pub trait Rng { fn seed_size(&self) -> usize; fn seed(&mut self, new_seed: &[u8]); fn generate_bytes(&mut self, output: &mut [u8]); } #[async_trait] pub trait SharedRng: 'static + Send + Sync { /// Number of bytes used to seed this RNG. fn seed_size(&self) -> usize; /// Should reset the state of the RNG based on the provided seed. /// Calling generate_bytes after calling reseed with the same seed should /// always produce the same result. async fn seed(&self, new_seed: &[u8]); async fn generate_bytes(&self, output: &mut [u8]); } #[derive(Clone)] pub struct GlobalRng { state: Arc<GlobalRngState>, } struct GlobalRngState { bytes_since_reseed: Mutex<usize>, rng: ChaCha20RNG, } impl GlobalRng { fn new() -> Self { Self { state: Arc::new(GlobalRngState { bytes_since_reseed: Mutex::new(std::usize::MAX), rng: ChaCha20RNG::new(), }), } } } #[async_trait] impl SharedRng for GlobalRng { fn seed_size(&self) -> usize { 0 } async fn seed(&self, _new_seed: &[u8]) { // Global RNG can't be manually reseeding panic!(); } async fn generate_bytes(&self, output: &mut [u8]) { { let mut counter = self.state.bytes_since_reseed.lock().await; if *counter > MAX_BYTES_BEFORE_RESEED { let mut new_seed = vec![0u8; self.state.rng.seed_size()]; secure_random_bytes(&mut new_seed).await.unwrap(); self.state.rng.seed(&new_seed).await; *counter = 0; } // NOTE: For now we ignore the case of a user requesting a quantity that // partially exceeds our max threshold. *counter += output.len(); } self.state.rng.generate_bytes(output).await } } #[async_trait] impl<R: Rng + Send + ?Sized + 'static> SharedRng for Mutex<R> { fn seed_size(&self) -> usize { todo!() // self.lock().await.seed_size() } async fn seed(&self, new_seed: &[u8]) { self.lock().await.seed(new_seed) } async fn generate_bytes(&self, output: &mut [u8]) { self.lock().await.generate_bytes(output) } } /// Sample random number generator based on ChaCha20 /// /// - During initialization and periodically afterwards, we (re-)generate the /// 256-bit key from a 'true random' source (/dev/random). /// - When a key is selected, we reset the nonce to 0. /// - The nonce is incremented by 1 for each block we encrypt. /// - The plaintext to be encrypted is the system time at key creation in /// nanoseconds. /// - All of the above are re-seeding in the background every 30 seconds. /// - Random bytes are generated by encrypting the plaintext with the current /// nonce and key. pub struct ChaCha20RNG { state: Mutex<ChaCha20RNGState>, } #[derive(Clone)] struct ChaCha20RNGState { key: [u8; CHACHA20_KEY_SIZE], nonce: u64, plaintext: [u8; CHACHA20_BLOCK_SIZE], } impl ChaCha20RNG { /// Creates a new instance of the rng with a fixed 'zero' seed. pub fn new() -> Self { Self { state: Mutex::new(ChaCha20RNGState { key: [0u8; CHACHA20_KEY_SIZE], nonce: 0, plaintext: [0u8; CHACHA20_BLOCK_SIZE], }), } } } #[async_trait] impl SharedRng for ChaCha20RNG { fn seed_size(&self) -> usize { CHACHA20_KEY_SIZE + CHACHA20_BLOCK_SIZE } async fn seed(&self, new_seed: &[u8]) { let mut state = self.state.lock().await; state.nonce = 0; state.key.copy_from_slice(&new_seed[0..CHACHA20_KEY_SIZE]); state .plaintext .copy_from_slice(&new_seed[CHACHA20_KEY_SIZE..]); } async fn generate_bytes(&self, mut output: &mut [u8]) { let state = { let mut guard = self.state.lock().await; let cur_state = guard.clone(); guard.nonce += 1; cur_state }; let mut nonce = [0u8; CHACHA20_NONCE_SIZE]; nonce[0..8].copy_from_slice(&state.nonce.to_ne_bytes()); let mut chacha = ChaCha20::new(&state.key, &nonce); while !output.is_empty() { let mut output_block = [0u8; CHACHA20_BLOCK_SIZE]; chacha.encrypt(&state.plaintext, &mut output_block); let n = std::cmp::min(output_block.len(), output.len()); output[0..n].copy_from_slice(&output_block[0..n]); output = &mut output[n..]; } } } #[async_trait] pub trait SharedRngExt { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]); async fn uniform<T: RngNumber>(&self) -> T; async fn between<T: RngNumber>(&self, min: T, max: T) -> T; } #[async_trait] impl<R: SharedRng + ?Sized> SharedRngExt for Arc<R> { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { self.as_ref().shuffle(elements).await } async fn uniform<T: RngNumber>(&self) -> T { self.as_ref().uniform().await } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { self.as_ref().between(min, max).await } } #[async_trait] impl<R: SharedRng + ?Sized> SharedRngExt for R { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>().await % elements.len(); elements.swap(i, j); } } async fn uniform<T: RngNumber>(&self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::uniform_buffer(buf) } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::between_buffer(buf, min, max) } } pub trait RngNumber: Send + Sync + 'static { type Buffer: Send + Sync + Sized + Default + AsMut<[u8]>; fn uniform_buffer(random: Self::Buffer) -> Self; fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self; } macro_rules! ensure_positive { ($value:ident, I) => { if $value < 0 { $value * -1 } else { $value } }; ($value:ident, U) => { $value }; } macro_rules! impl_rng_number_integer { ($num:ident, $type_prefix:ident) => { impl RngNumber for $num { type Buffer = [u8; std::mem::size_of::<$num>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = Self::uniform_buffer(random); // In rust (negative_number % positive_number) = negative_number num = ensure_positive!(num, $type_prefix); // Convert to [0, range) let range = max - min; num = num % range; // Convert to [min, max) num += min; num } } }; } impl_rng_number_integer!(u8, U); impl_rng_number_integer!(i8, I); impl_rng_number_integer!(u16, U); impl_rng_number_integer!(i16, I); impl_rng_number_integer!(u32, U); impl_rng_number_integer!(i32, I); impl_rng_number_integer!(u64, U); impl_rng_number_integer!(i64, I); impl_rng_number_integer!(usize, U); impl_rng_number_integer!(isize, I); macro_rules! impl_rng_number_float { ($float_type:ident, $int_type:ident, $fraction_bits:expr, $zero_exponent:expr) => { impl RngNumber for $float_type { type Buffer = [u8; std::mem::size_of::<$float_type>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(mut random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = $int_type::from_le_bytes(random); // Clear the sign and exponent bits. num &= (1 << $fraction_bits) - 1; // Set the exponent to '0'. So the number will be (1 + fraction) * 2^0 num |= $zero_exponent << $fraction_bits; random = num.to_le_bytes(); // This will in the range [0, 1). let f = Self::from_le_bytes(random) - 1.0; // Convert to [min, max). let range = max - min; f * range + min } } }; } impl_rng_number_float!(f32, u32, 23, 127); impl_rng_number_float!(f64, u64, 52, 1023); pub trait RngExt { fn shuffle<T>(&mut self, elements: &mut [T]); fn uniform<T: RngNumber>(&mut self) -> T; fn between<T: RngNumber>(&mut self, min: T, max: T) -> T; fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T; } impl<R: Rng + ?Sized> RngExt for R { fn shuffle<T>(&mut self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>() % elements.len(); elements.swap(i, j); } } /// Returns a completely random number anywhere in the range of the number /// type. Every number is equally probably of occuring. fn uniform<T: RngNumber>(&mut self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::uniform_buffer(buf) } /// Returns a uniform random number in the range [min, max). /// /// Limitations: /// - 'max' must be >= 'min'. /// - For signed integer types for N bits, 'max' - 'min' must fit in N-1 /// bits. fn between<T: RngNumber>(&mut self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::between_buffer(buf, min, max) } fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T { assert!(!elements.is_empty(), "Choosing from empty list"); let n = self.uniform::<usize>(); &elements[n % elements.len()] } } pub const MT_DEFAULT_SEED: u32 = 5489; pub struct MersenneTwisterRng { w: u32, n: usize, m: usize, r: u32, a: u32, // b: u32, c: u32, s: u32, t: u32, u: u32, d: u32, l: u32, f: u32, x: Vec<u32>, index: usize, } impl MersenneTwisterRng { // TODO: Add a simple time seeded implementation. pub fn mt19937() -> Self
pub fn seed_u32(&mut self, seed: u32) { self.x.resize(self.n, 0); self.index = self.n; self.x[0] = seed; for i in 1..self.n { self.x[i] = (self.x[i - 1] ^ (self.x[i - 1] >> (self.w - 2))) .wrapping_mul(self.f) .wrapping_add(i as u32); } } pub fn next_u32(&mut self) -> u32 { if self.x.is_empty() { self.seed_u32(MT_DEFAULT_SEED); } if self.index >= self.n { self.twist(); } let mut y = self.x[self.index]; y ^= (y >> self.u) & self.d; y ^= (y << self.s) & self.b; y ^= (y << self.t) & self.c; y ^= y >> self.l; self.index += 1; y } fn twist(&mut self) { let w_mask = 1u32.checked_shl(self.w).unwrap_or(0).wrapping_sub(1); let upper_mask = (w_mask << self.r) & w_mask; let lower_mask = (!upper_mask) & w_mask; self.index = 0; for i in 0..self.n { let x = (self.x[i] & upper_mask) | (self.x[(i + 1) % self.x.len()] & lower_mask); let mut x_a = x >> 1; if x & 1 != 0 { x_a = x_a ^ self.a; } self.x[i] = self.x[(i + self.m) % self.x.len()] ^ x_a; } } } impl Rng for MersenneTwisterRng { fn seed_size(&self) -> usize { std::mem::size_of::<u32>() } fn seed(&mut self, new_seed: &[u8]) { assert_eq!(new_seed.len(), std::mem::size_of::<u32>()); let seed_num = u32::from_le_bytes(*array_ref![new_seed, 0, 4]); self.seed_u32(seed_num); } fn generate_bytes(&mut self, output: &mut [u8]) { // NOTE: All of the 4's in here are std::mem::size_of::<u32>() let n = output.len() / 4; let r = output.len() % 4; for i in 0..n { *array_mut_ref![output, 4 * i, 4] = self.next_u32().to_le_bytes(); } if r != 0 { let v = self.next_u32().to_le_bytes(); let i = output.len() - r; output[i..].copy_from_slice(&v[0..r]); } } } pub struct FixedBytesRng { data: Bytes, } impl FixedBytesRng { pub fn new<T: Into<Bytes>>(data: T) -> Self { Self { data: data.into() } } } impl Rng for FixedBytesRng { fn seed_size(&self) -> usize { panic!(); } fn seed(&mut self, _new_seed: &[u8]) { panic!(); } fn generate_bytes(&mut self, output: &mut [u8]) { if output.len() > self.data.len() { panic!(); } output.copy_from_slice(&self.data[0..output.len()]); self.data.advance(output.len()); } } pub struct NormalDistribution { mean: f64, stddev: f64, next_number: Option<f64>, } impl NormalDistribution { pub fn new(mean: f64, stddev: f64) -> Self { Self { mean, stddev, next_number: None, } } /// Given two uniformly sampled random numbers in the range [0, 1], computes /// two independent random values with a normal/gaussian distribution /// with mean of 0 and standard deviation of 1. /// See https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform fn box_muller_transform(u1: f64, u2: f64) -> (f64, f64) { let theta = 2.0 * PI * u2; let (sin, cos) = theta.sin_cos(); let r = (-2.0 * u1.ln()).sqrt(); (r * sin, r * cos) } } pub trait NormalDistributionRngExt { fn next(&mut self, rng: &mut dyn Rng) -> f64; } impl NormalDistributionRngExt for NormalDistribution { fn next(&mut self, rng: &mut dyn Rng) -> f64 { if let Some(v) = self.next_number.take() { return v; } let u1 = rng.between(0.0, 1.0); let u2 = rng.between(0.0, 1.0); let (z1, z2) = Self::box_muller_transform(u1, u2); self.next_number = Some(z2); z1 } } #[cfg(test)] mod tests { use super::*; #[test] fn mersenne_twister_test() -> Result<()> { let mut rng = MersenneTwisterRng::mt19937(); rng.seed_u32(1234); let data = std::fs::read_to_string(project_path!("testdata/mt19937.txt"))?; for (i, line) in data.lines().enumerate() { let expected = line.parse::<u32>()?; assert_eq!(rng.next_u32(), expected, "Mismatch at index {}", i); } Ok(()) } #[test] fn between_inclusive_test() { let mut rng = MersenneTwisterRng::mt19937(); rng.seed_u32(1234); for _ in 0..100 { let f = rng.between::<f32>(0.0, 1.0); assert!(f >= 0.0 && f < 1.0); } for _ in 0..100 { let f = rng.between::<f64>(0.0, 0.25); assert!(f >= 0.0 && f < 0.25); } let min = 427; let max = 674; let num_iter = 20000000; let mut buckets = [0usize; 247]; for _ in 0..num_iter { let n = rng.between::<i32>(min, max); assert!(n >= min && n < max); buckets[(n - min) as usize] += 1; } for bucket in buckets { // Ideal value is num_iter / range = ~80971 // We'll accept a 1% deviation. assert!(bucket > 71254 && bucket < 81780, "Bucket is {}", bucket); } } }
{ Self { w: 32, n: 624, m: 397, r: 31, a: 0x9908B0DF, u: 11, d: 0xffffffff, s: 7, b: 0x9D2C5680, t: 15, c: 0xEFC60000, l: 18, f: 1812433253, x: vec![], index: 0, } }
identifier_body
random.rs
use alloc::boxed::Box; use std::f64::consts::PI; use std::num::Wrapping; use std::sync::Arc; use std::vec::Vec; use common::bytes::{Buf, Bytes}; use common::io::Readable; use common::{ceil_div, errors::*}; use executor::sync::Mutex; use file::LocalFile; use math::big::{BigUint, SecureBigUint}; use math::integer::Integer; use crate::chacha20::*; const MAX_BYTES_BEFORE_RESEED: usize = 1024 * 1024 * 1024; // 1GB lazy_static! { static ref GLOBAL_RNG_STATE: GlobalRng = GlobalRng::new(); } /// Gets a lazily initialized reference to a globally shared random number /// generator. /// /// This is seeded on the first random generation. /// /// The implementation can be assumed to be secure for cryptographic purposes /// but may not be very fast. /// /// TODO: We should disallow re-seeding this RNG. pub fn global_rng() -> GlobalRng { GLOBAL_RNG_STATE.clone() } /// Call me if you want a cheap but insecure RNG seeded by the current system /// time. pub fn clocked_rng() -> MersenneTwisterRng { let mut rng = MersenneTwisterRng::mt19937(); let seed = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .subsec_nanos(); rng.seed_u32(seed); rng } /// Generates secure random bytes suitable for cryptographic key generation. /// This will wait for sufficient entropy to accumulate in the system. /// /// Once done, the provided buffer will be filled with the random bytes to the /// end. pub async fn secure_random_bytes(buf: &mut [u8]) -> Result<()> { // See http://man7.org/linux/man-pages/man7/random.7.html // TODO: Reuse the file handle across calls. let mut f = LocalFile::open("/dev/random")?; f.read_exact(buf).await?; Ok(()) } /// Securely generates a random value in the range '[lower, upper)'. /// /// This is implemented to give every integer in the range the same probabiity /// of being output. /// /// NOTE: Both the 'lower' and 'upper' numbers should be publicly known for this /// to be secure. /// /// The output integer will have the same width as the 'upper' integer. pub async fn secure_random_range( lower: &SecureBigUint, upper: &SecureBigUint, ) -> Result<SecureBigUint> { if upper.byte_width() == 0 || upper <= lower { return Err(err_msg("Invalid upper/lower range")); } let mut buf = vec![]; buf.resize(upper.byte_width(), 0); let mut num_bytes = ceil_div(upper.value_bits(), 8); let msb_mask: u8 = { let r = upper.value_bits() % 8; if r == 0 { 0xff } else { !((1 << (8 - r)) - 1) } }; // TODO: Refactor out retrying. Instead shift to 0 loop { secure_random_bytes(&mut buf[0..num_bytes]).await?; buf[num_bytes - 1] &= msb_mask; let n = SecureBigUint::from_le_bytes(&buf); // TODO: This *must* be a secure comparison (which it isn't right now). if &n >= lower && &n < upper { return Ok(n); } } } pub trait Rng { fn seed_size(&self) -> usize; fn seed(&mut self, new_seed: &[u8]); fn generate_bytes(&mut self, output: &mut [u8]); } #[async_trait] pub trait SharedRng: 'static + Send + Sync { /// Number of bytes used to seed this RNG. fn seed_size(&self) -> usize; /// Should reset the state of the RNG based on the provided seed. /// Calling generate_bytes after calling reseed with the same seed should /// always produce the same result. async fn seed(&self, new_seed: &[u8]); async fn generate_bytes(&self, output: &mut [u8]); } #[derive(Clone)] pub struct GlobalRng { state: Arc<GlobalRngState>, } struct GlobalRngState { bytes_since_reseed: Mutex<usize>, rng: ChaCha20RNG, } impl GlobalRng { fn new() -> Self { Self { state: Arc::new(GlobalRngState { bytes_since_reseed: Mutex::new(std::usize::MAX), rng: ChaCha20RNG::new(), }), } } } #[async_trait] impl SharedRng for GlobalRng { fn seed_size(&self) -> usize { 0 } async fn seed(&self, _new_seed: &[u8]) { // Global RNG can't be manually reseeding panic!(); } async fn generate_bytes(&self, output: &mut [u8]) { { let mut counter = self.state.bytes_since_reseed.lock().await; if *counter > MAX_BYTES_BEFORE_RESEED { let mut new_seed = vec![0u8; self.state.rng.seed_size()]; secure_random_bytes(&mut new_seed).await.unwrap(); self.state.rng.seed(&new_seed).await; *counter = 0; } // NOTE: For now we ignore the case of a user requesting a quantity that // partially exceeds our max threshold. *counter += output.len(); } self.state.rng.generate_bytes(output).await } } #[async_trait] impl<R: Rng + Send + ?Sized + 'static> SharedRng for Mutex<R> { fn seed_size(&self) -> usize { todo!() // self.lock().await.seed_size() } async fn seed(&self, new_seed: &[u8]) { self.lock().await.seed(new_seed) } async fn generate_bytes(&self, output: &mut [u8]) { self.lock().await.generate_bytes(output) } } /// Sample random number generator based on ChaCha20 /// /// - During initialization and periodically afterwards, we (re-)generate the /// 256-bit key from a 'true random' source (/dev/random). /// - When a key is selected, we reset the nonce to 0. /// - The nonce is incremented by 1 for each block we encrypt. /// - The plaintext to be encrypted is the system time at key creation in /// nanoseconds. /// - All of the above are re-seeding in the background every 30 seconds. /// - Random bytes are generated by encrypting the plaintext with the current /// nonce and key. pub struct ChaCha20RNG { state: Mutex<ChaCha20RNGState>, } #[derive(Clone)] struct ChaCha20RNGState { key: [u8; CHACHA20_KEY_SIZE], nonce: u64, plaintext: [u8; CHACHA20_BLOCK_SIZE], } impl ChaCha20RNG { /// Creates a new instance of the rng with a fixed 'zero' seed. pub fn new() -> Self { Self { state: Mutex::new(ChaCha20RNGState { key: [0u8; CHACHA20_KEY_SIZE], nonce: 0, plaintext: [0u8; CHACHA20_BLOCK_SIZE], }), } } } #[async_trait] impl SharedRng for ChaCha20RNG { fn seed_size(&self) -> usize { CHACHA20_KEY_SIZE + CHACHA20_BLOCK_SIZE } async fn seed(&self, new_seed: &[u8]) { let mut state = self.state.lock().await; state.nonce = 0; state.key.copy_from_slice(&new_seed[0..CHACHA20_KEY_SIZE]); state .plaintext .copy_from_slice(&new_seed[CHACHA20_KEY_SIZE..]); } async fn generate_bytes(&self, mut output: &mut [u8]) { let state = { let mut guard = self.state.lock().await; let cur_state = guard.clone(); guard.nonce += 1; cur_state }; let mut nonce = [0u8; CHACHA20_NONCE_SIZE]; nonce[0..8].copy_from_slice(&state.nonce.to_ne_bytes()); let mut chacha = ChaCha20::new(&state.key, &nonce); while !output.is_empty() { let mut output_block = [0u8; CHACHA20_BLOCK_SIZE]; chacha.encrypt(&state.plaintext, &mut output_block); let n = std::cmp::min(output_block.len(), output.len()); output[0..n].copy_from_slice(&output_block[0..n]); output = &mut output[n..]; } } } #[async_trait] pub trait SharedRngExt { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]); async fn uniform<T: RngNumber>(&self) -> T; async fn between<T: RngNumber>(&self, min: T, max: T) -> T; } #[async_trait] impl<R: SharedRng + ?Sized> SharedRngExt for Arc<R> { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { self.as_ref().shuffle(elements).await } async fn uniform<T: RngNumber>(&self) -> T { self.as_ref().uniform().await } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { self.as_ref().between(min, max).await } } #[async_trait] impl<R: SharedRng + ?Sized> SharedRngExt for R { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>().await % elements.len(); elements.swap(i, j); } } async fn uniform<T: RngNumber>(&self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::uniform_buffer(buf) } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::between_buffer(buf, min, max) } } pub trait RngNumber: Send + Sync + 'static { type Buffer: Send + Sync + Sized + Default + AsMut<[u8]>; fn uniform_buffer(random: Self::Buffer) -> Self; fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self; } macro_rules! ensure_positive { ($value:ident, I) => { if $value < 0 { $value * -1 } else { $value } }; ($value:ident, U) => { $value }; } macro_rules! impl_rng_number_integer { ($num:ident, $type_prefix:ident) => { impl RngNumber for $num { type Buffer = [u8; std::mem::size_of::<$num>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = Self::uniform_buffer(random); // In rust (negative_number % positive_number) = negative_number num = ensure_positive!(num, $type_prefix); // Convert to [0, range) let range = max - min; num = num % range; // Convert to [min, max) num += min; num } } }; } impl_rng_number_integer!(u8, U); impl_rng_number_integer!(i8, I); impl_rng_number_integer!(u16, U); impl_rng_number_integer!(i16, I); impl_rng_number_integer!(u32, U); impl_rng_number_integer!(i32, I); impl_rng_number_integer!(u64, U); impl_rng_number_integer!(i64, I); impl_rng_number_integer!(usize, U); impl_rng_number_integer!(isize, I); macro_rules! impl_rng_number_float { ($float_type:ident, $int_type:ident, $fraction_bits:expr, $zero_exponent:expr) => { impl RngNumber for $float_type { type Buffer = [u8; std::mem::size_of::<$float_type>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(mut random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = $int_type::from_le_bytes(random); // Clear the sign and exponent bits. num &= (1 << $fraction_bits) - 1; // Set the exponent to '0'. So the number will be (1 + fraction) * 2^0 num |= $zero_exponent << $fraction_bits; random = num.to_le_bytes(); // This will in the range [0, 1). let f = Self::from_le_bytes(random) - 1.0; // Convert to [min, max). let range = max - min; f * range + min } } }; } impl_rng_number_float!(f32, u32, 23, 127); impl_rng_number_float!(f64, u64, 52, 1023); pub trait RngExt { fn shuffle<T>(&mut self, elements: &mut [T]); fn uniform<T: RngNumber>(&mut self) -> T; fn between<T: RngNumber>(&mut self, min: T, max: T) -> T; fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T; } impl<R: Rng + ?Sized> RngExt for R { fn shuffle<T>(&mut self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>() % elements.len(); elements.swap(i, j); } } /// Returns a completely random number anywhere in the range of the number /// type. Every number is equally probably of occuring. fn uniform<T: RngNumber>(&mut self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::uniform_buffer(buf) } /// Returns a uniform random number in the range [min, max). /// /// Limitations: /// - 'max' must be >= 'min'. /// - For signed integer types for N bits, 'max' - 'min' must fit in N-1 /// bits. fn between<T: RngNumber>(&mut self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::between_buffer(buf, min, max) } fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T { assert!(!elements.is_empty(), "Choosing from empty list"); let n = self.uniform::<usize>(); &elements[n % elements.len()] } } pub const MT_DEFAULT_SEED: u32 = 5489; pub struct MersenneTwisterRng { w: u32, n: usize, m: usize, r: u32, a: u32, // b: u32, c: u32, s: u32, t: u32, u: u32, d: u32, l: u32, f: u32, x: Vec<u32>, index: usize, } impl MersenneTwisterRng { // TODO: Add a simple time seeded implementation. pub fn mt19937() -> Self { Self { w: 32, n: 624, m: 397, r: 31, a: 0x9908B0DF, u: 11, d: 0xffffffff, s: 7, b: 0x9D2C5680, t: 15, c: 0xEFC60000, l: 18, f: 1812433253, x: vec![], index: 0, } } pub fn seed_u32(&mut self, seed: u32) { self.x.resize(self.n, 0); self.index = self.n; self.x[0] = seed; for i in 1..self.n { self.x[i] = (self.x[i - 1] ^ (self.x[i - 1] >> (self.w - 2))) .wrapping_mul(self.f) .wrapping_add(i as u32); } } pub fn next_u32(&mut self) -> u32 { if self.x.is_empty() { self.seed_u32(MT_DEFAULT_SEED); } if self.index >= self.n { self.twist(); } let mut y = self.x[self.index]; y ^= (y >> self.u) & self.d; y ^= (y << self.s) & self.b; y ^= (y << self.t) & self.c; y ^= y >> self.l; self.index += 1; y } fn twist(&mut self) { let w_mask = 1u32.checked_shl(self.w).unwrap_or(0).wrapping_sub(1); let upper_mask = (w_mask << self.r) & w_mask; let lower_mask = (!upper_mask) & w_mask; self.index = 0; for i in 0..self.n { let x = (self.x[i] & upper_mask) | (self.x[(i + 1) % self.x.len()] & lower_mask); let mut x_a = x >> 1; if x & 1 != 0 { x_a = x_a ^ self.a; } self.x[i] = self.x[(i + self.m) % self.x.len()] ^ x_a; } } } impl Rng for MersenneTwisterRng { fn seed_size(&self) -> usize { std::mem::size_of::<u32>() } fn seed(&mut self, new_seed: &[u8]) { assert_eq!(new_seed.len(), std::mem::size_of::<u32>()); let seed_num = u32::from_le_bytes(*array_ref![new_seed, 0, 4]); self.seed_u32(seed_num); } fn generate_bytes(&mut self, output: &mut [u8]) { // NOTE: All of the 4's in here are std::mem::size_of::<u32>() let n = output.len() / 4; let r = output.len() % 4; for i in 0..n { *array_mut_ref![output, 4 * i, 4] = self.next_u32().to_le_bytes(); } if r != 0 { let v = self.next_u32().to_le_bytes(); let i = output.len() - r; output[i..].copy_from_slice(&v[0..r]); } } } pub struct FixedBytesRng { data: Bytes, } impl FixedBytesRng { pub fn new<T: Into<Bytes>>(data: T) -> Self { Self { data: data.into() } } } impl Rng for FixedBytesRng { fn seed_size(&self) -> usize { panic!(); } fn seed(&mut self, _new_seed: &[u8]) { panic!(); } fn generate_bytes(&mut self, output: &mut [u8]) { if output.len() > self.data.len() { panic!(); } output.copy_from_slice(&self.data[0..output.len()]); self.data.advance(output.len()); } } pub struct NormalDistribution { mean: f64, stddev: f64, next_number: Option<f64>, } impl NormalDistribution { pub fn new(mean: f64, stddev: f64) -> Self { Self { mean, stddev, next_number: None, } } /// Given two uniformly sampled random numbers in the range [0, 1], computes /// two independent random values with a normal/gaussian distribution /// with mean of 0 and standard deviation of 1. /// See https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform fn box_muller_transform(u1: f64, u2: f64) -> (f64, f64) { let theta = 2.0 * PI * u2; let (sin, cos) = theta.sin_cos(); let r = (-2.0 * u1.ln()).sqrt(); (r * sin, r * cos) } } pub trait NormalDistributionRngExt { fn next(&mut self, rng: &mut dyn Rng) -> f64; } impl NormalDistributionRngExt for NormalDistribution { fn next(&mut self, rng: &mut dyn Rng) -> f64 { if let Some(v) = self.next_number.take() { return v; } let u1 = rng.between(0.0, 1.0); let u2 = rng.between(0.0, 1.0); let (z1, z2) = Self::box_muller_transform(u1, u2); self.next_number = Some(z2); z1 } } #[cfg(test)] mod tests { use super::*; #[test] fn mersenne_twister_test() -> Result<()> { let mut rng = MersenneTwisterRng::mt19937(); rng.seed_u32(1234); let data = std::fs::read_to_string(project_path!("testdata/mt19937.txt"))?; for (i, line) in data.lines().enumerate() { let expected = line.parse::<u32>()?; assert_eq!(rng.next_u32(), expected, "Mismatch at index {}", i); } Ok(()) } #[test] fn between_inclusive_test() { let mut rng = MersenneTwisterRng::mt19937(); rng.seed_u32(1234); for _ in 0..100 { let f = rng.between::<f32>(0.0, 1.0); assert!(f >= 0.0 && f < 1.0); } for _ in 0..100 { let f = rng.between::<f64>(0.0, 0.25); assert!(f >= 0.0 && f < 0.25); } let min = 427; let max = 674; let num_iter = 20000000; let mut buckets = [0usize; 247]; for _ in 0..num_iter { let n = rng.between::<i32>(min, max); assert!(n >= min && n < max); buckets[(n - min) as usize] += 1; } for bucket in buckets { // Ideal value is num_iter / range = ~80971 // We'll accept a 1% deviation.
} } }
assert!(bucket > 71254 && bucket < 81780, "Bucket is {}", bucket);
random_line_split
random.rs
use alloc::boxed::Box; use std::f64::consts::PI; use std::num::Wrapping; use std::sync::Arc; use std::vec::Vec; use common::bytes::{Buf, Bytes}; use common::io::Readable; use common::{ceil_div, errors::*}; use executor::sync::Mutex; use file::LocalFile; use math::big::{BigUint, SecureBigUint}; use math::integer::Integer; use crate::chacha20::*; const MAX_BYTES_BEFORE_RESEED: usize = 1024 * 1024 * 1024; // 1GB lazy_static! { static ref GLOBAL_RNG_STATE: GlobalRng = GlobalRng::new(); } /// Gets a lazily initialized reference to a globally shared random number /// generator. /// /// This is seeded on the first random generation. /// /// The implementation can be assumed to be secure for cryptographic purposes /// but may not be very fast. /// /// TODO: We should disallow re-seeding this RNG. pub fn global_rng() -> GlobalRng { GLOBAL_RNG_STATE.clone() } /// Call me if you want a cheap but insecure RNG seeded by the current system /// time. pub fn clocked_rng() -> MersenneTwisterRng { let mut rng = MersenneTwisterRng::mt19937(); let seed = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .subsec_nanos(); rng.seed_u32(seed); rng } /// Generates secure random bytes suitable for cryptographic key generation. /// This will wait for sufficient entropy to accumulate in the system. /// /// Once done, the provided buffer will be filled with the random bytes to the /// end. pub async fn secure_random_bytes(buf: &mut [u8]) -> Result<()> { // See http://man7.org/linux/man-pages/man7/random.7.html // TODO: Reuse the file handle across calls. let mut f = LocalFile::open("/dev/random")?; f.read_exact(buf).await?; Ok(()) } /// Securely generates a random value in the range '[lower, upper)'. /// /// This is implemented to give every integer in the range the same probabiity /// of being output. /// /// NOTE: Both the 'lower' and 'upper' numbers should be publicly known for this /// to be secure. /// /// The output integer will have the same width as the 'upper' integer. pub async fn secure_random_range( lower: &SecureBigUint, upper: &SecureBigUint, ) -> Result<SecureBigUint> { if upper.byte_width() == 0 || upper <= lower { return Err(err_msg("Invalid upper/lower range")); } let mut buf = vec![]; buf.resize(upper.byte_width(), 0); let mut num_bytes = ceil_div(upper.value_bits(), 8); let msb_mask: u8 = { let r = upper.value_bits() % 8; if r == 0 { 0xff } else { !((1 << (8 - r)) - 1) } }; // TODO: Refactor out retrying. Instead shift to 0 loop { secure_random_bytes(&mut buf[0..num_bytes]).await?; buf[num_bytes - 1] &= msb_mask; let n = SecureBigUint::from_le_bytes(&buf); // TODO: This *must* be a secure comparison (which it isn't right now). if &n >= lower && &n < upper { return Ok(n); } } } pub trait Rng { fn seed_size(&self) -> usize; fn seed(&mut self, new_seed: &[u8]); fn generate_bytes(&mut self, output: &mut [u8]); } #[async_trait] pub trait SharedRng: 'static + Send + Sync { /// Number of bytes used to seed this RNG. fn seed_size(&self) -> usize; /// Should reset the state of the RNG based on the provided seed. /// Calling generate_bytes after calling reseed with the same seed should /// always produce the same result. async fn seed(&self, new_seed: &[u8]); async fn generate_bytes(&self, output: &mut [u8]); } #[derive(Clone)] pub struct GlobalRng { state: Arc<GlobalRngState>, } struct GlobalRngState { bytes_since_reseed: Mutex<usize>, rng: ChaCha20RNG, } impl GlobalRng { fn new() -> Self { Self { state: Arc::new(GlobalRngState { bytes_since_reseed: Mutex::new(std::usize::MAX), rng: ChaCha20RNG::new(), }), } } } #[async_trait] impl SharedRng for GlobalRng { fn seed_size(&self) -> usize { 0 } async fn seed(&self, _new_seed: &[u8]) { // Global RNG can't be manually reseeding panic!(); } async fn generate_bytes(&self, output: &mut [u8]) { { let mut counter = self.state.bytes_since_reseed.lock().await; if *counter > MAX_BYTES_BEFORE_RESEED { let mut new_seed = vec![0u8; self.state.rng.seed_size()]; secure_random_bytes(&mut new_seed).await.unwrap(); self.state.rng.seed(&new_seed).await; *counter = 0; } // NOTE: For now we ignore the case of a user requesting a quantity that // partially exceeds our max threshold. *counter += output.len(); } self.state.rng.generate_bytes(output).await } } #[async_trait] impl<R: Rng + Send + ?Sized + 'static> SharedRng for Mutex<R> { fn seed_size(&self) -> usize { todo!() // self.lock().await.seed_size() } async fn seed(&self, new_seed: &[u8]) { self.lock().await.seed(new_seed) } async fn generate_bytes(&self, output: &mut [u8]) { self.lock().await.generate_bytes(output) } } /// Sample random number generator based on ChaCha20 /// /// - During initialization and periodically afterwards, we (re-)generate the /// 256-bit key from a 'true random' source (/dev/random). /// - When a key is selected, we reset the nonce to 0. /// - The nonce is incremented by 1 for each block we encrypt. /// - The plaintext to be encrypted is the system time at key creation in /// nanoseconds. /// - All of the above are re-seeding in the background every 30 seconds. /// - Random bytes are generated by encrypting the plaintext with the current /// nonce and key. pub struct ChaCha20RNG { state: Mutex<ChaCha20RNGState>, } #[derive(Clone)] struct ChaCha20RNGState { key: [u8; CHACHA20_KEY_SIZE], nonce: u64, plaintext: [u8; CHACHA20_BLOCK_SIZE], } impl ChaCha20RNG { /// Creates a new instance of the rng with a fixed 'zero' seed. pub fn
() -> Self { Self { state: Mutex::new(ChaCha20RNGState { key: [0u8; CHACHA20_KEY_SIZE], nonce: 0, plaintext: [0u8; CHACHA20_BLOCK_SIZE], }), } } } #[async_trait] impl SharedRng for ChaCha20RNG { fn seed_size(&self) -> usize { CHACHA20_KEY_SIZE + CHACHA20_BLOCK_SIZE } async fn seed(&self, new_seed: &[u8]) { let mut state = self.state.lock().await; state.nonce = 0; state.key.copy_from_slice(&new_seed[0..CHACHA20_KEY_SIZE]); state .plaintext .copy_from_slice(&new_seed[CHACHA20_KEY_SIZE..]); } async fn generate_bytes(&self, mut output: &mut [u8]) { let state = { let mut guard = self.state.lock().await; let cur_state = guard.clone(); guard.nonce += 1; cur_state }; let mut nonce = [0u8; CHACHA20_NONCE_SIZE]; nonce[0..8].copy_from_slice(&state.nonce.to_ne_bytes()); let mut chacha = ChaCha20::new(&state.key, &nonce); while !output.is_empty() { let mut output_block = [0u8; CHACHA20_BLOCK_SIZE]; chacha.encrypt(&state.plaintext, &mut output_block); let n = std::cmp::min(output_block.len(), output.len()); output[0..n].copy_from_slice(&output_block[0..n]); output = &mut output[n..]; } } } #[async_trait] pub trait SharedRngExt { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]); async fn uniform<T: RngNumber>(&self) -> T; async fn between<T: RngNumber>(&self, min: T, max: T) -> T; } #[async_trait] impl<R: SharedRng + ?Sized> SharedRngExt for Arc<R> { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { self.as_ref().shuffle(elements).await } async fn uniform<T: RngNumber>(&self) -> T { self.as_ref().uniform().await } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { self.as_ref().between(min, max).await } } #[async_trait] impl<R: SharedRng + ?Sized> SharedRngExt for R { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>().await % elements.len(); elements.swap(i, j); } } async fn uniform<T: RngNumber>(&self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::uniform_buffer(buf) } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::between_buffer(buf, min, max) } } pub trait RngNumber: Send + Sync + 'static { type Buffer: Send + Sync + Sized + Default + AsMut<[u8]>; fn uniform_buffer(random: Self::Buffer) -> Self; fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self; } macro_rules! ensure_positive { ($value:ident, I) => { if $value < 0 { $value * -1 } else { $value } }; ($value:ident, U) => { $value }; } macro_rules! impl_rng_number_integer { ($num:ident, $type_prefix:ident) => { impl RngNumber for $num { type Buffer = [u8; std::mem::size_of::<$num>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = Self::uniform_buffer(random); // In rust (negative_number % positive_number) = negative_number num = ensure_positive!(num, $type_prefix); // Convert to [0, range) let range = max - min; num = num % range; // Convert to [min, max) num += min; num } } }; } impl_rng_number_integer!(u8, U); impl_rng_number_integer!(i8, I); impl_rng_number_integer!(u16, U); impl_rng_number_integer!(i16, I); impl_rng_number_integer!(u32, U); impl_rng_number_integer!(i32, I); impl_rng_number_integer!(u64, U); impl_rng_number_integer!(i64, I); impl_rng_number_integer!(usize, U); impl_rng_number_integer!(isize, I); macro_rules! impl_rng_number_float { ($float_type:ident, $int_type:ident, $fraction_bits:expr, $zero_exponent:expr) => { impl RngNumber for $float_type { type Buffer = [u8; std::mem::size_of::<$float_type>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(mut random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = $int_type::from_le_bytes(random); // Clear the sign and exponent bits. num &= (1 << $fraction_bits) - 1; // Set the exponent to '0'. So the number will be (1 + fraction) * 2^0 num |= $zero_exponent << $fraction_bits; random = num.to_le_bytes(); // This will in the range [0, 1). let f = Self::from_le_bytes(random) - 1.0; // Convert to [min, max). let range = max - min; f * range + min } } }; } impl_rng_number_float!(f32, u32, 23, 127); impl_rng_number_float!(f64, u64, 52, 1023); pub trait RngExt { fn shuffle<T>(&mut self, elements: &mut [T]); fn uniform<T: RngNumber>(&mut self) -> T; fn between<T: RngNumber>(&mut self, min: T, max: T) -> T; fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T; } impl<R: Rng + ?Sized> RngExt for R { fn shuffle<T>(&mut self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>() % elements.len(); elements.swap(i, j); } } /// Returns a completely random number anywhere in the range of the number /// type. Every number is equally probably of occuring. fn uniform<T: RngNumber>(&mut self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::uniform_buffer(buf) } /// Returns a uniform random number in the range [min, max). /// /// Limitations: /// - 'max' must be >= 'min'. /// - For signed integer types for N bits, 'max' - 'min' must fit in N-1 /// bits. fn between<T: RngNumber>(&mut self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::between_buffer(buf, min, max) } fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T { assert!(!elements.is_empty(), "Choosing from empty list"); let n = self.uniform::<usize>(); &elements[n % elements.len()] } } pub const MT_DEFAULT_SEED: u32 = 5489; pub struct MersenneTwisterRng { w: u32, n: usize, m: usize, r: u32, a: u32, // b: u32, c: u32, s: u32, t: u32, u: u32, d: u32, l: u32, f: u32, x: Vec<u32>, index: usize, } impl MersenneTwisterRng { // TODO: Add a simple time seeded implementation. pub fn mt19937() -> Self { Self { w: 32, n: 624, m: 397, r: 31, a: 0x9908B0DF, u: 11, d: 0xffffffff, s: 7, b: 0x9D2C5680, t: 15, c: 0xEFC60000, l: 18, f: 1812433253, x: vec![], index: 0, } } pub fn seed_u32(&mut self, seed: u32) { self.x.resize(self.n, 0); self.index = self.n; self.x[0] = seed; for i in 1..self.n { self.x[i] = (self.x[i - 1] ^ (self.x[i - 1] >> (self.w - 2))) .wrapping_mul(self.f) .wrapping_add(i as u32); } } pub fn next_u32(&mut self) -> u32 { if self.x.is_empty() { self.seed_u32(MT_DEFAULT_SEED); } if self.index >= self.n { self.twist(); } let mut y = self.x[self.index]; y ^= (y >> self.u) & self.d; y ^= (y << self.s) & self.b; y ^= (y << self.t) & self.c; y ^= y >> self.l; self.index += 1; y } fn twist(&mut self) { let w_mask = 1u32.checked_shl(self.w).unwrap_or(0).wrapping_sub(1); let upper_mask = (w_mask << self.r) & w_mask; let lower_mask = (!upper_mask) & w_mask; self.index = 0; for i in 0..self.n { let x = (self.x[i] & upper_mask) | (self.x[(i + 1) % self.x.len()] & lower_mask); let mut x_a = x >> 1; if x & 1 != 0 { x_a = x_a ^ self.a; } self.x[i] = self.x[(i + self.m) % self.x.len()] ^ x_a; } } } impl Rng for MersenneTwisterRng { fn seed_size(&self) -> usize { std::mem::size_of::<u32>() } fn seed(&mut self, new_seed: &[u8]) { assert_eq!(new_seed.len(), std::mem::size_of::<u32>()); let seed_num = u32::from_le_bytes(*array_ref![new_seed, 0, 4]); self.seed_u32(seed_num); } fn generate_bytes(&mut self, output: &mut [u8]) { // NOTE: All of the 4's in here are std::mem::size_of::<u32>() let n = output.len() / 4; let r = output.len() % 4; for i in 0..n { *array_mut_ref![output, 4 * i, 4] = self.next_u32().to_le_bytes(); } if r != 0 { let v = self.next_u32().to_le_bytes(); let i = output.len() - r; output[i..].copy_from_slice(&v[0..r]); } } } pub struct FixedBytesRng { data: Bytes, } impl FixedBytesRng { pub fn new<T: Into<Bytes>>(data: T) -> Self { Self { data: data.into() } } } impl Rng for FixedBytesRng { fn seed_size(&self) -> usize { panic!(); } fn seed(&mut self, _new_seed: &[u8]) { panic!(); } fn generate_bytes(&mut self, output: &mut [u8]) { if output.len() > self.data.len() { panic!(); } output.copy_from_slice(&self.data[0..output.len()]); self.data.advance(output.len()); } } pub struct NormalDistribution { mean: f64, stddev: f64, next_number: Option<f64>, } impl NormalDistribution { pub fn new(mean: f64, stddev: f64) -> Self { Self { mean, stddev, next_number: None, } } /// Given two uniformly sampled random numbers in the range [0, 1], computes /// two independent random values with a normal/gaussian distribution /// with mean of 0 and standard deviation of 1. /// See https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform fn box_muller_transform(u1: f64, u2: f64) -> (f64, f64) { let theta = 2.0 * PI * u2; let (sin, cos) = theta.sin_cos(); let r = (-2.0 * u1.ln()).sqrt(); (r * sin, r * cos) } } pub trait NormalDistributionRngExt { fn next(&mut self, rng: &mut dyn Rng) -> f64; } impl NormalDistributionRngExt for NormalDistribution { fn next(&mut self, rng: &mut dyn Rng) -> f64 { if let Some(v) = self.next_number.take() { return v; } let u1 = rng.between(0.0, 1.0); let u2 = rng.between(0.0, 1.0); let (z1, z2) = Self::box_muller_transform(u1, u2); self.next_number = Some(z2); z1 } } #[cfg(test)] mod tests { use super::*; #[test] fn mersenne_twister_test() -> Result<()> { let mut rng = MersenneTwisterRng::mt19937(); rng.seed_u32(1234); let data = std::fs::read_to_string(project_path!("testdata/mt19937.txt"))?; for (i, line) in data.lines().enumerate() { let expected = line.parse::<u32>()?; assert_eq!(rng.next_u32(), expected, "Mismatch at index {}", i); } Ok(()) } #[test] fn between_inclusive_test() { let mut rng = MersenneTwisterRng::mt19937(); rng.seed_u32(1234); for _ in 0..100 { let f = rng.between::<f32>(0.0, 1.0); assert!(f >= 0.0 && f < 1.0); } for _ in 0..100 { let f = rng.between::<f64>(0.0, 0.25); assert!(f >= 0.0 && f < 0.25); } let min = 427; let max = 674; let num_iter = 20000000; let mut buckets = [0usize; 247]; for _ in 0..num_iter { let n = rng.between::<i32>(min, max); assert!(n >= min && n < max); buckets[(n - min) as usize] += 1; } for bucket in buckets { // Ideal value is num_iter / range = ~80971 // We'll accept a 1% deviation. assert!(bucket > 71254 && bucket < 81780, "Bucket is {}", bucket); } } }
new
identifier_name
random.rs
use alloc::boxed::Box; use std::f64::consts::PI; use std::num::Wrapping; use std::sync::Arc; use std::vec::Vec; use common::bytes::{Buf, Bytes}; use common::io::Readable; use common::{ceil_div, errors::*}; use executor::sync::Mutex; use file::LocalFile; use math::big::{BigUint, SecureBigUint}; use math::integer::Integer; use crate::chacha20::*; const MAX_BYTES_BEFORE_RESEED: usize = 1024 * 1024 * 1024; // 1GB lazy_static! { static ref GLOBAL_RNG_STATE: GlobalRng = GlobalRng::new(); } /// Gets a lazily initialized reference to a globally shared random number /// generator. /// /// This is seeded on the first random generation. /// /// The implementation can be assumed to be secure for cryptographic purposes /// but may not be very fast. /// /// TODO: We should disallow re-seeding this RNG. pub fn global_rng() -> GlobalRng { GLOBAL_RNG_STATE.clone() } /// Call me if you want a cheap but insecure RNG seeded by the current system /// time. pub fn clocked_rng() -> MersenneTwisterRng { let mut rng = MersenneTwisterRng::mt19937(); let seed = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .subsec_nanos(); rng.seed_u32(seed); rng } /// Generates secure random bytes suitable for cryptographic key generation. /// This will wait for sufficient entropy to accumulate in the system. /// /// Once done, the provided buffer will be filled with the random bytes to the /// end. pub async fn secure_random_bytes(buf: &mut [u8]) -> Result<()> { // See http://man7.org/linux/man-pages/man7/random.7.html // TODO: Reuse the file handle across calls. let mut f = LocalFile::open("/dev/random")?; f.read_exact(buf).await?; Ok(()) } /// Securely generates a random value in the range '[lower, upper)'. /// /// This is implemented to give every integer in the range the same probabiity /// of being output. /// /// NOTE: Both the 'lower' and 'upper' numbers should be publicly known for this /// to be secure. /// /// The output integer will have the same width as the 'upper' integer. pub async fn secure_random_range( lower: &SecureBigUint, upper: &SecureBigUint, ) -> Result<SecureBigUint> { if upper.byte_width() == 0 || upper <= lower
let mut buf = vec![]; buf.resize(upper.byte_width(), 0); let mut num_bytes = ceil_div(upper.value_bits(), 8); let msb_mask: u8 = { let r = upper.value_bits() % 8; if r == 0 { 0xff } else { !((1 << (8 - r)) - 1) } }; // TODO: Refactor out retrying. Instead shift to 0 loop { secure_random_bytes(&mut buf[0..num_bytes]).await?; buf[num_bytes - 1] &= msb_mask; let n = SecureBigUint::from_le_bytes(&buf); // TODO: This *must* be a secure comparison (which it isn't right now). if &n >= lower && &n < upper { return Ok(n); } } } pub trait Rng { fn seed_size(&self) -> usize; fn seed(&mut self, new_seed: &[u8]); fn generate_bytes(&mut self, output: &mut [u8]); } #[async_trait] pub trait SharedRng: 'static + Send + Sync { /// Number of bytes used to seed this RNG. fn seed_size(&self) -> usize; /// Should reset the state of the RNG based on the provided seed. /// Calling generate_bytes after calling reseed with the same seed should /// always produce the same result. async fn seed(&self, new_seed: &[u8]); async fn generate_bytes(&self, output: &mut [u8]); } #[derive(Clone)] pub struct GlobalRng { state: Arc<GlobalRngState>, } struct GlobalRngState { bytes_since_reseed: Mutex<usize>, rng: ChaCha20RNG, } impl GlobalRng { fn new() -> Self { Self { state: Arc::new(GlobalRngState { bytes_since_reseed: Mutex::new(std::usize::MAX), rng: ChaCha20RNG::new(), }), } } } #[async_trait] impl SharedRng for GlobalRng { fn seed_size(&self) -> usize { 0 } async fn seed(&self, _new_seed: &[u8]) { // Global RNG can't be manually reseeding panic!(); } async fn generate_bytes(&self, output: &mut [u8]) { { let mut counter = self.state.bytes_since_reseed.lock().await; if *counter > MAX_BYTES_BEFORE_RESEED { let mut new_seed = vec![0u8; self.state.rng.seed_size()]; secure_random_bytes(&mut new_seed).await.unwrap(); self.state.rng.seed(&new_seed).await; *counter = 0; } // NOTE: For now we ignore the case of a user requesting a quantity that // partially exceeds our max threshold. *counter += output.len(); } self.state.rng.generate_bytes(output).await } } #[async_trait] impl<R: Rng + Send + ?Sized + 'static> SharedRng for Mutex<R> { fn seed_size(&self) -> usize { todo!() // self.lock().await.seed_size() } async fn seed(&self, new_seed: &[u8]) { self.lock().await.seed(new_seed) } async fn generate_bytes(&self, output: &mut [u8]) { self.lock().await.generate_bytes(output) } } /// Sample random number generator based on ChaCha20 /// /// - During initialization and periodically afterwards, we (re-)generate the /// 256-bit key from a 'true random' source (/dev/random). /// - When a key is selected, we reset the nonce to 0. /// - The nonce is incremented by 1 for each block we encrypt. /// - The plaintext to be encrypted is the system time at key creation in /// nanoseconds. /// - All of the above are re-seeding in the background every 30 seconds. /// - Random bytes are generated by encrypting the plaintext with the current /// nonce and key. pub struct ChaCha20RNG { state: Mutex<ChaCha20RNGState>, } #[derive(Clone)] struct ChaCha20RNGState { key: [u8; CHACHA20_KEY_SIZE], nonce: u64, plaintext: [u8; CHACHA20_BLOCK_SIZE], } impl ChaCha20RNG { /// Creates a new instance of the rng with a fixed 'zero' seed. pub fn new() -> Self { Self { state: Mutex::new(ChaCha20RNGState { key: [0u8; CHACHA20_KEY_SIZE], nonce: 0, plaintext: [0u8; CHACHA20_BLOCK_SIZE], }), } } } #[async_trait] impl SharedRng for ChaCha20RNG { fn seed_size(&self) -> usize { CHACHA20_KEY_SIZE + CHACHA20_BLOCK_SIZE } async fn seed(&self, new_seed: &[u8]) { let mut state = self.state.lock().await; state.nonce = 0; state.key.copy_from_slice(&new_seed[0..CHACHA20_KEY_SIZE]); state .plaintext .copy_from_slice(&new_seed[CHACHA20_KEY_SIZE..]); } async fn generate_bytes(&self, mut output: &mut [u8]) { let state = { let mut guard = self.state.lock().await; let cur_state = guard.clone(); guard.nonce += 1; cur_state }; let mut nonce = [0u8; CHACHA20_NONCE_SIZE]; nonce[0..8].copy_from_slice(&state.nonce.to_ne_bytes()); let mut chacha = ChaCha20::new(&state.key, &nonce); while !output.is_empty() { let mut output_block = [0u8; CHACHA20_BLOCK_SIZE]; chacha.encrypt(&state.plaintext, &mut output_block); let n = std::cmp::min(output_block.len(), output.len()); output[0..n].copy_from_slice(&output_block[0..n]); output = &mut output[n..]; } } } #[async_trait] pub trait SharedRngExt { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]); async fn uniform<T: RngNumber>(&self) -> T; async fn between<T: RngNumber>(&self, min: T, max: T) -> T; } #[async_trait] impl<R: SharedRng + ?Sized> SharedRngExt for Arc<R> { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { self.as_ref().shuffle(elements).await } async fn uniform<T: RngNumber>(&self) -> T { self.as_ref().uniform().await } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { self.as_ref().between(min, max).await } } #[async_trait] impl<R: SharedRng + ?Sized> SharedRngExt for R { async fn shuffle<T: Send + Sync>(&self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>().await % elements.len(); elements.swap(i, j); } } async fn uniform<T: RngNumber>(&self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::uniform_buffer(buf) } async fn between<T: RngNumber>(&self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()).await; T::between_buffer(buf, min, max) } } pub trait RngNumber: Send + Sync + 'static { type Buffer: Send + Sync + Sized + Default + AsMut<[u8]>; fn uniform_buffer(random: Self::Buffer) -> Self; fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self; } macro_rules! ensure_positive { ($value:ident, I) => { if $value < 0 { $value * -1 } else { $value } }; ($value:ident, U) => { $value }; } macro_rules! impl_rng_number_integer { ($num:ident, $type_prefix:ident) => { impl RngNumber for $num { type Buffer = [u8; std::mem::size_of::<$num>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = Self::uniform_buffer(random); // In rust (negative_number % positive_number) = negative_number num = ensure_positive!(num, $type_prefix); // Convert to [0, range) let range = max - min; num = num % range; // Convert to [min, max) num += min; num } } }; } impl_rng_number_integer!(u8, U); impl_rng_number_integer!(i8, I); impl_rng_number_integer!(u16, U); impl_rng_number_integer!(i16, I); impl_rng_number_integer!(u32, U); impl_rng_number_integer!(i32, I); impl_rng_number_integer!(u64, U); impl_rng_number_integer!(i64, I); impl_rng_number_integer!(usize, U); impl_rng_number_integer!(isize, I); macro_rules! impl_rng_number_float { ($float_type:ident, $int_type:ident, $fraction_bits:expr, $zero_exponent:expr) => { impl RngNumber for $float_type { type Buffer = [u8; std::mem::size_of::<$float_type>()]; fn uniform_buffer(random: Self::Buffer) -> Self { Self::from_le_bytes(random) } fn between_buffer(mut random: Self::Buffer, min: Self, max: Self) -> Self { assert!(max >= min); let mut num = $int_type::from_le_bytes(random); // Clear the sign and exponent bits. num &= (1 << $fraction_bits) - 1; // Set the exponent to '0'. So the number will be (1 + fraction) * 2^0 num |= $zero_exponent << $fraction_bits; random = num.to_le_bytes(); // This will in the range [0, 1). let f = Self::from_le_bytes(random) - 1.0; // Convert to [min, max). let range = max - min; f * range + min } } }; } impl_rng_number_float!(f32, u32, 23, 127); impl_rng_number_float!(f64, u64, 52, 1023); pub trait RngExt { fn shuffle<T>(&mut self, elements: &mut [T]); fn uniform<T: RngNumber>(&mut self) -> T; fn between<T: RngNumber>(&mut self, min: T, max: T) -> T; fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T; } impl<R: Rng + ?Sized> RngExt for R { fn shuffle<T>(&mut self, elements: &mut [T]) { for i in 0..elements.len() { let j = self.uniform::<usize>() % elements.len(); elements.swap(i, j); } } /// Returns a completely random number anywhere in the range of the number /// type. Every number is equally probably of occuring. fn uniform<T: RngNumber>(&mut self) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::uniform_buffer(buf) } /// Returns a uniform random number in the range [min, max). /// /// Limitations: /// - 'max' must be >= 'min'. /// - For signed integer types for N bits, 'max' - 'min' must fit in N-1 /// bits. fn between<T: RngNumber>(&mut self, min: T, max: T) -> T { let mut buf = T::Buffer::default(); self.generate_bytes(buf.as_mut()); T::between_buffer(buf, min, max) } fn choose<'a, T>(&mut self, elements: &'a [T]) -> &'a T { assert!(!elements.is_empty(), "Choosing from empty list"); let n = self.uniform::<usize>(); &elements[n % elements.len()] } } pub const MT_DEFAULT_SEED: u32 = 5489; pub struct MersenneTwisterRng { w: u32, n: usize, m: usize, r: u32, a: u32, // b: u32, c: u32, s: u32, t: u32, u: u32, d: u32, l: u32, f: u32, x: Vec<u32>, index: usize, } impl MersenneTwisterRng { // TODO: Add a simple time seeded implementation. pub fn mt19937() -> Self { Self { w: 32, n: 624, m: 397, r: 31, a: 0x9908B0DF, u: 11, d: 0xffffffff, s: 7, b: 0x9D2C5680, t: 15, c: 0xEFC60000, l: 18, f: 1812433253, x: vec![], index: 0, } } pub fn seed_u32(&mut self, seed: u32) { self.x.resize(self.n, 0); self.index = self.n; self.x[0] = seed; for i in 1..self.n { self.x[i] = (self.x[i - 1] ^ (self.x[i - 1] >> (self.w - 2))) .wrapping_mul(self.f) .wrapping_add(i as u32); } } pub fn next_u32(&mut self) -> u32 { if self.x.is_empty() { self.seed_u32(MT_DEFAULT_SEED); } if self.index >= self.n { self.twist(); } let mut y = self.x[self.index]; y ^= (y >> self.u) & self.d; y ^= (y << self.s) & self.b; y ^= (y << self.t) & self.c; y ^= y >> self.l; self.index += 1; y } fn twist(&mut self) { let w_mask = 1u32.checked_shl(self.w).unwrap_or(0).wrapping_sub(1); let upper_mask = (w_mask << self.r) & w_mask; let lower_mask = (!upper_mask) & w_mask; self.index = 0; for i in 0..self.n { let x = (self.x[i] & upper_mask) | (self.x[(i + 1) % self.x.len()] & lower_mask); let mut x_a = x >> 1; if x & 1 != 0 { x_a = x_a ^ self.a; } self.x[i] = self.x[(i + self.m) % self.x.len()] ^ x_a; } } } impl Rng for MersenneTwisterRng { fn seed_size(&self) -> usize { std::mem::size_of::<u32>() } fn seed(&mut self, new_seed: &[u8]) { assert_eq!(new_seed.len(), std::mem::size_of::<u32>()); let seed_num = u32::from_le_bytes(*array_ref![new_seed, 0, 4]); self.seed_u32(seed_num); } fn generate_bytes(&mut self, output: &mut [u8]) { // NOTE: All of the 4's in here are std::mem::size_of::<u32>() let n = output.len() / 4; let r = output.len() % 4; for i in 0..n { *array_mut_ref![output, 4 * i, 4] = self.next_u32().to_le_bytes(); } if r != 0 { let v = self.next_u32().to_le_bytes(); let i = output.len() - r; output[i..].copy_from_slice(&v[0..r]); } } } pub struct FixedBytesRng { data: Bytes, } impl FixedBytesRng { pub fn new<T: Into<Bytes>>(data: T) -> Self { Self { data: data.into() } } } impl Rng for FixedBytesRng { fn seed_size(&self) -> usize { panic!(); } fn seed(&mut self, _new_seed: &[u8]) { panic!(); } fn generate_bytes(&mut self, output: &mut [u8]) { if output.len() > self.data.len() { panic!(); } output.copy_from_slice(&self.data[0..output.len()]); self.data.advance(output.len()); } } pub struct NormalDistribution { mean: f64, stddev: f64, next_number: Option<f64>, } impl NormalDistribution { pub fn new(mean: f64, stddev: f64) -> Self { Self { mean, stddev, next_number: None, } } /// Given two uniformly sampled random numbers in the range [0, 1], computes /// two independent random values with a normal/gaussian distribution /// with mean of 0 and standard deviation of 1. /// See https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform fn box_muller_transform(u1: f64, u2: f64) -> (f64, f64) { let theta = 2.0 * PI * u2; let (sin, cos) = theta.sin_cos(); let r = (-2.0 * u1.ln()).sqrt(); (r * sin, r * cos) } } pub trait NormalDistributionRngExt { fn next(&mut self, rng: &mut dyn Rng) -> f64; } impl NormalDistributionRngExt for NormalDistribution { fn next(&mut self, rng: &mut dyn Rng) -> f64 { if let Some(v) = self.next_number.take() { return v; } let u1 = rng.between(0.0, 1.0); let u2 = rng.between(0.0, 1.0); let (z1, z2) = Self::box_muller_transform(u1, u2); self.next_number = Some(z2); z1 } } #[cfg(test)] mod tests { use super::*; #[test] fn mersenne_twister_test() -> Result<()> { let mut rng = MersenneTwisterRng::mt19937(); rng.seed_u32(1234); let data = std::fs::read_to_string(project_path!("testdata/mt19937.txt"))?; for (i, line) in data.lines().enumerate() { let expected = line.parse::<u32>()?; assert_eq!(rng.next_u32(), expected, "Mismatch at index {}", i); } Ok(()) } #[test] fn between_inclusive_test() { let mut rng = MersenneTwisterRng::mt19937(); rng.seed_u32(1234); for _ in 0..100 { let f = rng.between::<f32>(0.0, 1.0); assert!(f >= 0.0 && f < 1.0); } for _ in 0..100 { let f = rng.between::<f64>(0.0, 0.25); assert!(f >= 0.0 && f < 0.25); } let min = 427; let max = 674; let num_iter = 20000000; let mut buckets = [0usize; 247]; for _ in 0..num_iter { let n = rng.between::<i32>(min, max); assert!(n >= min && n < max); buckets[(n - min) as usize] += 1; } for bucket in buckets { // Ideal value is num_iter / range = ~80971 // We'll accept a 1% deviation. assert!(bucket > 71254 && bucket < 81780, "Bucket is {}", bucket); } } }
{ return Err(err_msg("Invalid upper/lower range")); }
conditional_block
main.rs
use futures_util::future::Either; use futures_util::stream::StreamExt; use std::collections::{BTreeMap, HashMap}; use std::io::{self}; use structopt::StructOpt; use termion::raw::IntoRawMode; use tokio::prelude::*; use tui::backend::Backend; use tui::backend::TermionBackend; use tui::layout::{Constraint, Direction, Layout}; use tui::style::{Color, Modifier, Style}; use tui::widgets::{Block, Borders, Paragraph, Text, Widget}; use tui::Terminal; const DRAW_EVERY: std::time::Duration = std::time::Duration::from_millis(200); const WINDOW: std::time::Duration = std::time::Duration::from_secs(10); #[derive(Debug, StructOpt)] /// A live profile visualizer. /// /// Pipe the output of the appropriate `bpftrace` command into this program, and enjoy. /// Happy profiling! struct Opt { /// Treat input as a replay of a trace and emulate time accordingly. #[structopt(long)] replay: bool, } #[derive(Debug, Default)] struct
{ window: BTreeMap<usize, String>, } fn main() -> Result<(), io::Error> { let opt = Opt::from_args(); if termion::is_tty(&io::stdin().lock()) { eprintln!("Don't type input to this program, that's silly."); return Ok(()); } let stdout = io::stdout().into_raw_mode()?; let backend = TermionBackend::new(stdout); let mut terminal = Terminal::new(backend)?; let mut tids = BTreeMap::new(); let mut inframe = None; let mut stack = String::new(); terminal.hide_cursor()?; terminal.clear()?; terminal.draw(|mut f| { let chunks = Layout::default() .direction(Direction::Vertical) .margin(2) .constraints([Constraint::Percentage(100)].as_ref()) .split(f.size()); Block::default() .borders(Borders::ALL) .title("Common thread fan-out points") .title_style(Style::default().fg(Color::Magenta).modifier(Modifier::BOLD)) .render(&mut f, chunks[0]); })?; // a _super_ hacky way for us to get input from the TTY let tty = termion::get_tty()?; let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); std::thread::spawn(move || { use termion::input::TermRead; for key in tty.keys() { if let Err(_) = tx.send(key) { return; } } }); let mut rt = tokio::runtime::Runtime::new()?; rt.block_on(async move { let stdin = tokio::io::BufReader::new(tokio::io::stdin()); let lines = stdin.lines().map(Either::Left); let rx = rx.map(Either::Right); let mut input = futures_util::stream::select(lines, rx); let mut lastprint = 0; let mut lasttime = 0; while let Some(got) = input.next().await { match got { Either::Left(line) => { let line = line.unwrap(); if line.starts_with("Error") || line.starts_with("Attaching") { } else if !line.starts_with(' ') || line.is_empty() { if let Some((time, tid)) = inframe { // new frame starts, so finish the old one // skip empty stack frames if !stack.is_empty() { let nxt_stack = String::with_capacity(stack.capacity()); let mut stack = std::mem::replace(&mut stack, nxt_stack); // remove trailing ; let stackn = stack.len(); stack.truncate(stackn - 1); tids.entry(tid) .or_insert_with(Thread::default) .window .insert(time, stack); if opt.replay && lasttime != 0 && time - lasttime > 1_000_000 { tokio::time::delay_for(std::time::Duration::from_nanos( (time - lasttime) as u64, )) .await; } lasttime = time; if std::time::Duration::from_nanos((time - lastprint) as u64) > DRAW_EVERY { draw(&mut terminal, &mut tids)?; lastprint = time; } } inframe = None; } if !line.is_empty() { // read time + tid let mut fields = line.split_whitespace(); let time = fields .next() .expect("no time given for frame") .parse::<usize>() .expect("invalid time"); let tid = fields .next() .expect("no tid given for frame") .parse::<usize>() .expect("invalid tid"); inframe = Some((time, tid)); } } else { assert!(inframe.is_some()); stack.push_str(line.trim()); stack.push(';'); } } Either::Right(key) => { let key = key?; if let termion::event::Key::Char('q') = key { break; } } } } terminal.clear()?; Ok(()) }) } fn draw<B: Backend>( terminal: &mut Terminal<B>, threads: &mut BTreeMap<usize, Thread>, ) -> Result<(), io::Error> { // keep our window relatively short let mut latest = 0; for thread in threads.values() { if let Some(&last) = thread.window.keys().next_back() { latest = std::cmp::max(latest, last); } } if latest > WINDOW.as_nanos() as usize { for thread in threads.values_mut() { // trim to last 5 seconds thread.window = thread .window .split_off(&(latest - WINDOW.as_nanos() as usize)); } } // now only reading let threads = &*threads; let mut lines = Vec::new(); let mut hits = HashMap::new(); let mut maxes = BTreeMap::new(); for (_, thread) in threads { // add up across the window let mut max: Option<(&str, usize)> = None; for (&time, stack) in &thread.window { latest = std::cmp::max(latest, time); let mut at = stack.len(); while let Some(stack_start) = stack[..at].rfind(';') { at = stack_start; let stack = &stack[at + 1..]; let count = hits.entry(stack).or_insert(0); *count += 1; if let Some((_, max_count)) = max { if *count >= max_count { max = Some((stack, *count)); } } else { max = Some((stack, *count)); } } } if let Some((stack, count)) = max { let e = maxes.entry(stack).or_insert((0, 0)); e.0 += 1; e.1 += count; } hits.clear(); } if maxes.is_empty() { return Ok(()); } let max = *maxes.values().map(|(_, count)| count).max().unwrap() as f64; // sort by where most threads are let mut maxes: Vec<_> = maxes.into_iter().collect(); maxes.sort_by_key(|(_, (nthreads, _))| *nthreads); for (stack, (nthreads, count)) in maxes.iter().rev() { let count = *count; let nthreads = *nthreads; if stack.find(';').is_none() { // this thread just shares the root frame continue; } if count == 1 { // this thread only has one sample ever, let's reduce noise... continue; } let red = (128.0 * count as f64 / max) as u8; let color = Color::Rgb(255, 128 - red, 128 - red); if nthreads == 1 { lines.push(Text::styled( format!("A thread fanned out from here {} times\n", count), Style::default().modifier(Modifier::BOLD).fg(color), )); } else { lines.push(Text::styled( format!( "{} threads fanned out from here {} times\n", nthreads, count ), Style::default().modifier(Modifier::BOLD).fg(color), )); } for (i, frame) in stack.split(';').enumerate() { // https://github.com/alexcrichton/rustc-demangle/issues/34 let offset = &frame[frame.rfind('+').unwrap_or_else(|| frame.len())..]; let frame = rustc_demangle::demangle(&frame[..frame.rfind('+').unwrap_or_else(|| frame.len())]); if i == 0 { lines.push(Text::styled( format!(" {}{}\n", frame, offset), Style::default(), )); } else { lines.push(Text::styled( format!(" {}{}\n", frame, offset), Style::default().modifier(Modifier::DIM), )); } } lines.push(Text::raw("\n")); } terminal.draw(|mut f| { let chunks = Layout::default() .direction(Direction::Vertical) .margin(2) .constraints([Constraint::Percentage(100)].as_ref()) .split(f.size()); Paragraph::new(lines.iter()) .block( Block::default() .borders(Borders::ALL) .title("Common thread fan-out points") .title_style(Style::default().fg(Color::Magenta).modifier(Modifier::BOLD)), ) .render(&mut f, chunks[0]); })?; Ok(()) }
Thread
identifier_name
main.rs
use futures_util::future::Either; use futures_util::stream::StreamExt; use std::collections::{BTreeMap, HashMap}; use std::io::{self}; use structopt::StructOpt; use termion::raw::IntoRawMode; use tokio::prelude::*; use tui::backend::Backend; use tui::backend::TermionBackend; use tui::layout::{Constraint, Direction, Layout}; use tui::style::{Color, Modifier, Style}; use tui::widgets::{Block, Borders, Paragraph, Text, Widget}; use tui::Terminal; const DRAW_EVERY: std::time::Duration = std::time::Duration::from_millis(200); const WINDOW: std::time::Duration = std::time::Duration::from_secs(10); #[derive(Debug, StructOpt)] /// A live profile visualizer. /// /// Pipe the output of the appropriate `bpftrace` command into this program, and enjoy. /// Happy profiling! struct Opt { /// Treat input as a replay of a trace and emulate time accordingly. #[structopt(long)] replay: bool, } #[derive(Debug, Default)] struct Thread { window: BTreeMap<usize, String>, } fn main() -> Result<(), io::Error> { let opt = Opt::from_args(); if termion::is_tty(&io::stdin().lock()) { eprintln!("Don't type input to this program, that's silly."); return Ok(()); } let stdout = io::stdout().into_raw_mode()?; let backend = TermionBackend::new(stdout); let mut terminal = Terminal::new(backend)?; let mut tids = BTreeMap::new(); let mut inframe = None; let mut stack = String::new(); terminal.hide_cursor()?; terminal.clear()?; terminal.draw(|mut f| { let chunks = Layout::default() .direction(Direction::Vertical) .margin(2) .constraints([Constraint::Percentage(100)].as_ref()) .split(f.size()); Block::default() .borders(Borders::ALL) .title("Common thread fan-out points") .title_style(Style::default().fg(Color::Magenta).modifier(Modifier::BOLD)) .render(&mut f, chunks[0]); })?; // a _super_ hacky way for us to get input from the TTY let tty = termion::get_tty()?; let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); std::thread::spawn(move || { use termion::input::TermRead; for key in tty.keys() { if let Err(_) = tx.send(key) { return; } } }); let mut rt = tokio::runtime::Runtime::new()?; rt.block_on(async move { let stdin = tokio::io::BufReader::new(tokio::io::stdin()); let lines = stdin.lines().map(Either::Left); let rx = rx.map(Either::Right); let mut input = futures_util::stream::select(lines, rx); let mut lastprint = 0; let mut lasttime = 0; while let Some(got) = input.next().await { match got { Either::Left(line) => { let line = line.unwrap(); if line.starts_with("Error") || line.starts_with("Attaching") { } else if !line.starts_with(' ') || line.is_empty() { if let Some((time, tid)) = inframe { // new frame starts, so finish the old one // skip empty stack frames if !stack.is_empty() { let nxt_stack = String::with_capacity(stack.capacity()); let mut stack = std::mem::replace(&mut stack, nxt_stack); // remove trailing ; let stackn = stack.len(); stack.truncate(stackn - 1); tids.entry(tid) .or_insert_with(Thread::default) .window .insert(time, stack); if opt.replay && lasttime != 0 && time - lasttime > 1_000_000 { tokio::time::delay_for(std::time::Duration::from_nanos( (time - lasttime) as u64, )) .await; } lasttime = time; if std::time::Duration::from_nanos((time - lastprint) as u64) > DRAW_EVERY { draw(&mut terminal, &mut tids)?; lastprint = time; } } inframe = None; } if !line.is_empty() { // read time + tid let mut fields = line.split_whitespace(); let time = fields .next() .expect("no time given for frame") .parse::<usize>() .expect("invalid time"); let tid = fields .next() .expect("no tid given for frame") .parse::<usize>() .expect("invalid tid"); inframe = Some((time, tid)); } } else { assert!(inframe.is_some()); stack.push_str(line.trim()); stack.push(';'); } } Either::Right(key) => { let key = key?; if let termion::event::Key::Char('q') = key { break; } } } } terminal.clear()?; Ok(()) }) } fn draw<B: Backend>( terminal: &mut Terminal<B>, threads: &mut BTreeMap<usize, Thread>, ) -> Result<(), io::Error> { // keep our window relatively short let mut latest = 0; for thread in threads.values() { if let Some(&last) = thread.window.keys().next_back() { latest = std::cmp::max(latest, last); } } if latest > WINDOW.as_nanos() as usize { for thread in threads.values_mut() { // trim to last 5 seconds thread.window = thread .window .split_off(&(latest - WINDOW.as_nanos() as usize)); } } // now only reading let threads = &*threads; let mut lines = Vec::new(); let mut hits = HashMap::new(); let mut maxes = BTreeMap::new(); for (_, thread) in threads { // add up across the window let mut max: Option<(&str, usize)> = None; for (&time, stack) in &thread.window { latest = std::cmp::max(latest, time); let mut at = stack.len(); while let Some(stack_start) = stack[..at].rfind(';') { at = stack_start; let stack = &stack[at + 1..]; let count = hits.entry(stack).or_insert(0); *count += 1; if let Some((_, max_count)) = max { if *count >= max_count { max = Some((stack, *count)); } } else { max = Some((stack, *count)); } } } if let Some((stack, count)) = max { let e = maxes.entry(stack).or_insert((0, 0)); e.0 += 1; e.1 += count; } hits.clear(); } if maxes.is_empty() { return Ok(()); } let max = *maxes.values().map(|(_, count)| count).max().unwrap() as f64; // sort by where most threads are let mut maxes: Vec<_> = maxes.into_iter().collect(); maxes.sort_by_key(|(_, (nthreads, _))| *nthreads); for (stack, (nthreads, count)) in maxes.iter().rev() { let count = *count; let nthreads = *nthreads; if stack.find(';').is_none() { // this thread just shares the root frame continue; } if count == 1 { // this thread only has one sample ever, let's reduce noise... continue; } let red = (128.0 * count as f64 / max) as u8; let color = Color::Rgb(255, 128 - red, 128 - red); if nthreads == 1 { lines.push(Text::styled( format!("A thread fanned out from here {} times\n", count), Style::default().modifier(Modifier::BOLD).fg(color), )); } else { lines.push(Text::styled( format!( "{} threads fanned out from here {} times\n", nthreads, count ), Style::default().modifier(Modifier::BOLD).fg(color), )); } for (i, frame) in stack.split(';').enumerate() { // https://github.com/alexcrichton/rustc-demangle/issues/34 let offset = &frame[frame.rfind('+').unwrap_or_else(|| frame.len())..]; let frame = rustc_demangle::demangle(&frame[..frame.rfind('+').unwrap_or_else(|| frame.len())]); if i == 0 { lines.push(Text::styled( format!(" {}{}\n", frame, offset), Style::default(), ));
lines.push(Text::styled( format!(" {}{}\n", frame, offset), Style::default().modifier(Modifier::DIM), )); } } lines.push(Text::raw("\n")); } terminal.draw(|mut f| { let chunks = Layout::default() .direction(Direction::Vertical) .margin(2) .constraints([Constraint::Percentage(100)].as_ref()) .split(f.size()); Paragraph::new(lines.iter()) .block( Block::default() .borders(Borders::ALL) .title("Common thread fan-out points") .title_style(Style::default().fg(Color::Magenta).modifier(Modifier::BOLD)), ) .render(&mut f, chunks[0]); })?; Ok(()) }
} else {
random_line_split
main.rs
use futures_util::future::Either; use futures_util::stream::StreamExt; use std::collections::{BTreeMap, HashMap}; use std::io::{self}; use structopt::StructOpt; use termion::raw::IntoRawMode; use tokio::prelude::*; use tui::backend::Backend; use tui::backend::TermionBackend; use tui::layout::{Constraint, Direction, Layout}; use tui::style::{Color, Modifier, Style}; use tui::widgets::{Block, Borders, Paragraph, Text, Widget}; use tui::Terminal; const DRAW_EVERY: std::time::Duration = std::time::Duration::from_millis(200); const WINDOW: std::time::Duration = std::time::Duration::from_secs(10); #[derive(Debug, StructOpt)] /// A live profile visualizer. /// /// Pipe the output of the appropriate `bpftrace` command into this program, and enjoy. /// Happy profiling! struct Opt { /// Treat input as a replay of a trace and emulate time accordingly. #[structopt(long)] replay: bool, } #[derive(Debug, Default)] struct Thread { window: BTreeMap<usize, String>, } fn main() -> Result<(), io::Error> { let opt = Opt::from_args(); if termion::is_tty(&io::stdin().lock()) { eprintln!("Don't type input to this program, that's silly."); return Ok(()); } let stdout = io::stdout().into_raw_mode()?; let backend = TermionBackend::new(stdout); let mut terminal = Terminal::new(backend)?; let mut tids = BTreeMap::new(); let mut inframe = None; let mut stack = String::new(); terminal.hide_cursor()?; terminal.clear()?; terminal.draw(|mut f| { let chunks = Layout::default() .direction(Direction::Vertical) .margin(2) .constraints([Constraint::Percentage(100)].as_ref()) .split(f.size()); Block::default() .borders(Borders::ALL) .title("Common thread fan-out points") .title_style(Style::default().fg(Color::Magenta).modifier(Modifier::BOLD)) .render(&mut f, chunks[0]); })?; // a _super_ hacky way for us to get input from the TTY let tty = termion::get_tty()?; let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); std::thread::spawn(move || { use termion::input::TermRead; for key in tty.keys() { if let Err(_) = tx.send(key) { return; } } }); let mut rt = tokio::runtime::Runtime::new()?; rt.block_on(async move { let stdin = tokio::io::BufReader::new(tokio::io::stdin()); let lines = stdin.lines().map(Either::Left); let rx = rx.map(Either::Right); let mut input = futures_util::stream::select(lines, rx); let mut lastprint = 0; let mut lasttime = 0; while let Some(got) = input.next().await { match got { Either::Left(line) => { let line = line.unwrap(); if line.starts_with("Error") || line.starts_with("Attaching") { } else if !line.starts_with(' ') || line.is_empty() { if let Some((time, tid)) = inframe { // new frame starts, so finish the old one // skip empty stack frames if !stack.is_empty() { let nxt_stack = String::with_capacity(stack.capacity()); let mut stack = std::mem::replace(&mut stack, nxt_stack); // remove trailing ; let stackn = stack.len(); stack.truncate(stackn - 1); tids.entry(tid) .or_insert_with(Thread::default) .window .insert(time, stack); if opt.replay && lasttime != 0 && time - lasttime > 1_000_000 { tokio::time::delay_for(std::time::Duration::from_nanos( (time - lasttime) as u64, )) .await; } lasttime = time; if std::time::Duration::from_nanos((time - lastprint) as u64) > DRAW_EVERY { draw(&mut terminal, &mut tids)?; lastprint = time; } } inframe = None; } if !line.is_empty() { // read time + tid let mut fields = line.split_whitespace(); let time = fields .next() .expect("no time given for frame") .parse::<usize>() .expect("invalid time"); let tid = fields .next() .expect("no tid given for frame") .parse::<usize>() .expect("invalid tid"); inframe = Some((time, tid)); } } else
} Either::Right(key) => { let key = key?; if let termion::event::Key::Char('q') = key { break; } } } } terminal.clear()?; Ok(()) }) } fn draw<B: Backend>( terminal: &mut Terminal<B>, threads: &mut BTreeMap<usize, Thread>, ) -> Result<(), io::Error> { // keep our window relatively short let mut latest = 0; for thread in threads.values() { if let Some(&last) = thread.window.keys().next_back() { latest = std::cmp::max(latest, last); } } if latest > WINDOW.as_nanos() as usize { for thread in threads.values_mut() { // trim to last 5 seconds thread.window = thread .window .split_off(&(latest - WINDOW.as_nanos() as usize)); } } // now only reading let threads = &*threads; let mut lines = Vec::new(); let mut hits = HashMap::new(); let mut maxes = BTreeMap::new(); for (_, thread) in threads { // add up across the window let mut max: Option<(&str, usize)> = None; for (&time, stack) in &thread.window { latest = std::cmp::max(latest, time); let mut at = stack.len(); while let Some(stack_start) = stack[..at].rfind(';') { at = stack_start; let stack = &stack[at + 1..]; let count = hits.entry(stack).or_insert(0); *count += 1; if let Some((_, max_count)) = max { if *count >= max_count { max = Some((stack, *count)); } } else { max = Some((stack, *count)); } } } if let Some((stack, count)) = max { let e = maxes.entry(stack).or_insert((0, 0)); e.0 += 1; e.1 += count; } hits.clear(); } if maxes.is_empty() { return Ok(()); } let max = *maxes.values().map(|(_, count)| count).max().unwrap() as f64; // sort by where most threads are let mut maxes: Vec<_> = maxes.into_iter().collect(); maxes.sort_by_key(|(_, (nthreads, _))| *nthreads); for (stack, (nthreads, count)) in maxes.iter().rev() { let count = *count; let nthreads = *nthreads; if stack.find(';').is_none() { // this thread just shares the root frame continue; } if count == 1 { // this thread only has one sample ever, let's reduce noise... continue; } let red = (128.0 * count as f64 / max) as u8; let color = Color::Rgb(255, 128 - red, 128 - red); if nthreads == 1 { lines.push(Text::styled( format!("A thread fanned out from here {} times\n", count), Style::default().modifier(Modifier::BOLD).fg(color), )); } else { lines.push(Text::styled( format!( "{} threads fanned out from here {} times\n", nthreads, count ), Style::default().modifier(Modifier::BOLD).fg(color), )); } for (i, frame) in stack.split(';').enumerate() { // https://github.com/alexcrichton/rustc-demangle/issues/34 let offset = &frame[frame.rfind('+').unwrap_or_else(|| frame.len())..]; let frame = rustc_demangle::demangle(&frame[..frame.rfind('+').unwrap_or_else(|| frame.len())]); if i == 0 { lines.push(Text::styled( format!(" {}{}\n", frame, offset), Style::default(), )); } else { lines.push(Text::styled( format!(" {}{}\n", frame, offset), Style::default().modifier(Modifier::DIM), )); } } lines.push(Text::raw("\n")); } terminal.draw(|mut f| { let chunks = Layout::default() .direction(Direction::Vertical) .margin(2) .constraints([Constraint::Percentage(100)].as_ref()) .split(f.size()); Paragraph::new(lines.iter()) .block( Block::default() .borders(Borders::ALL) .title("Common thread fan-out points") .title_style(Style::default().fg(Color::Magenta).modifier(Modifier::BOLD)), ) .render(&mut f, chunks[0]); })?; Ok(()) }
{ assert!(inframe.is_some()); stack.push_str(line.trim()); stack.push(';'); }
conditional_block
main.rs
use futures_util::future::Either; use futures_util::stream::StreamExt; use std::collections::{BTreeMap, HashMap}; use std::io::{self}; use structopt::StructOpt; use termion::raw::IntoRawMode; use tokio::prelude::*; use tui::backend::Backend; use tui::backend::TermionBackend; use tui::layout::{Constraint, Direction, Layout}; use tui::style::{Color, Modifier, Style}; use tui::widgets::{Block, Borders, Paragraph, Text, Widget}; use tui::Terminal; const DRAW_EVERY: std::time::Duration = std::time::Duration::from_millis(200); const WINDOW: std::time::Duration = std::time::Duration::from_secs(10); #[derive(Debug, StructOpt)] /// A live profile visualizer. /// /// Pipe the output of the appropriate `bpftrace` command into this program, and enjoy. /// Happy profiling! struct Opt { /// Treat input as a replay of a trace and emulate time accordingly. #[structopt(long)] replay: bool, } #[derive(Debug, Default)] struct Thread { window: BTreeMap<usize, String>, } fn main() -> Result<(), io::Error>
fn draw<B: Backend>( terminal: &mut Terminal<B>, threads: &mut BTreeMap<usize, Thread>, ) -> Result<(), io::Error> { // keep our window relatively short let mut latest = 0; for thread in threads.values() { if let Some(&last) = thread.window.keys().next_back() { latest = std::cmp::max(latest, last); } } if latest > WINDOW.as_nanos() as usize { for thread in threads.values_mut() { // trim to last 5 seconds thread.window = thread .window .split_off(&(latest - WINDOW.as_nanos() as usize)); } } // now only reading let threads = &*threads; let mut lines = Vec::new(); let mut hits = HashMap::new(); let mut maxes = BTreeMap::new(); for (_, thread) in threads { // add up across the window let mut max: Option<(&str, usize)> = None; for (&time, stack) in &thread.window { latest = std::cmp::max(latest, time); let mut at = stack.len(); while let Some(stack_start) = stack[..at].rfind(';') { at = stack_start; let stack = &stack[at + 1..]; let count = hits.entry(stack).or_insert(0); *count += 1; if let Some((_, max_count)) = max { if *count >= max_count { max = Some((stack, *count)); } } else { max = Some((stack, *count)); } } } if let Some((stack, count)) = max { let e = maxes.entry(stack).or_insert((0, 0)); e.0 += 1; e.1 += count; } hits.clear(); } if maxes.is_empty() { return Ok(()); } let max = *maxes.values().map(|(_, count)| count).max().unwrap() as f64; // sort by where most threads are let mut maxes: Vec<_> = maxes.into_iter().collect(); maxes.sort_by_key(|(_, (nthreads, _))| *nthreads); for (stack, (nthreads, count)) in maxes.iter().rev() { let count = *count; let nthreads = *nthreads; if stack.find(';').is_none() { // this thread just shares the root frame continue; } if count == 1 { // this thread only has one sample ever, let's reduce noise... continue; } let red = (128.0 * count as f64 / max) as u8; let color = Color::Rgb(255, 128 - red, 128 - red); if nthreads == 1 { lines.push(Text::styled( format!("A thread fanned out from here {} times\n", count), Style::default().modifier(Modifier::BOLD).fg(color), )); } else { lines.push(Text::styled( format!( "{} threads fanned out from here {} times\n", nthreads, count ), Style::default().modifier(Modifier::BOLD).fg(color), )); } for (i, frame) in stack.split(';').enumerate() { // https://github.com/alexcrichton/rustc-demangle/issues/34 let offset = &frame[frame.rfind('+').unwrap_or_else(|| frame.len())..]; let frame = rustc_demangle::demangle(&frame[..frame.rfind('+').unwrap_or_else(|| frame.len())]); if i == 0 { lines.push(Text::styled( format!(" {}{}\n", frame, offset), Style::default(), )); } else { lines.push(Text::styled( format!(" {}{}\n", frame, offset), Style::default().modifier(Modifier::DIM), )); } } lines.push(Text::raw("\n")); } terminal.draw(|mut f| { let chunks = Layout::default() .direction(Direction::Vertical) .margin(2) .constraints([Constraint::Percentage(100)].as_ref()) .split(f.size()); Paragraph::new(lines.iter()) .block( Block::default() .borders(Borders::ALL) .title("Common thread fan-out points") .title_style(Style::default().fg(Color::Magenta).modifier(Modifier::BOLD)), ) .render(&mut f, chunks[0]); })?; Ok(()) }
{ let opt = Opt::from_args(); if termion::is_tty(&io::stdin().lock()) { eprintln!("Don't type input to this program, that's silly."); return Ok(()); } let stdout = io::stdout().into_raw_mode()?; let backend = TermionBackend::new(stdout); let mut terminal = Terminal::new(backend)?; let mut tids = BTreeMap::new(); let mut inframe = None; let mut stack = String::new(); terminal.hide_cursor()?; terminal.clear()?; terminal.draw(|mut f| { let chunks = Layout::default() .direction(Direction::Vertical) .margin(2) .constraints([Constraint::Percentage(100)].as_ref()) .split(f.size()); Block::default() .borders(Borders::ALL) .title("Common thread fan-out points") .title_style(Style::default().fg(Color::Magenta).modifier(Modifier::BOLD)) .render(&mut f, chunks[0]); })?; // a _super_ hacky way for us to get input from the TTY let tty = termion::get_tty()?; let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); std::thread::spawn(move || { use termion::input::TermRead; for key in tty.keys() { if let Err(_) = tx.send(key) { return; } } }); let mut rt = tokio::runtime::Runtime::new()?; rt.block_on(async move { let stdin = tokio::io::BufReader::new(tokio::io::stdin()); let lines = stdin.lines().map(Either::Left); let rx = rx.map(Either::Right); let mut input = futures_util::stream::select(lines, rx); let mut lastprint = 0; let mut lasttime = 0; while let Some(got) = input.next().await { match got { Either::Left(line) => { let line = line.unwrap(); if line.starts_with("Error") || line.starts_with("Attaching") { } else if !line.starts_with(' ') || line.is_empty() { if let Some((time, tid)) = inframe { // new frame starts, so finish the old one // skip empty stack frames if !stack.is_empty() { let nxt_stack = String::with_capacity(stack.capacity()); let mut stack = std::mem::replace(&mut stack, nxt_stack); // remove trailing ; let stackn = stack.len(); stack.truncate(stackn - 1); tids.entry(tid) .or_insert_with(Thread::default) .window .insert(time, stack); if opt.replay && lasttime != 0 && time - lasttime > 1_000_000 { tokio::time::delay_for(std::time::Duration::from_nanos( (time - lasttime) as u64, )) .await; } lasttime = time; if std::time::Duration::from_nanos((time - lastprint) as u64) > DRAW_EVERY { draw(&mut terminal, &mut tids)?; lastprint = time; } } inframe = None; } if !line.is_empty() { // read time + tid let mut fields = line.split_whitespace(); let time = fields .next() .expect("no time given for frame") .parse::<usize>() .expect("invalid time"); let tid = fields .next() .expect("no tid given for frame") .parse::<usize>() .expect("invalid tid"); inframe = Some((time, tid)); } } else { assert!(inframe.is_some()); stack.push_str(line.trim()); stack.push(';'); } } Either::Right(key) => { let key = key?; if let termion::event::Key::Char('q') = key { break; } } } } terminal.clear()?; Ok(()) }) }
identifier_body
sbot.py
#!/usr/bin/python import subprocess import os import sys import time import random from PIL import Image from PIL import ImageFile from pytesser import * import cv2 from adbInterface import adbInterface as adb os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' adbpath = '..\\platform-tools\\.\\adb' serial = "" ImageFile.LOAD_TRUNCATED_IMAGES = True soldRunes = 0 keptRunes = 0 totalRefills = 0 adb = adb() ### Sobre o funcionamento do bot ### # As vezes o bot nao limpa a variavel ref o que faz com que o texto antigo fique sendo exibido apos a tela de execucao do bot exemplo "Reward" # isso faz com que o bot execute a rotina de cliques def adbshell(command): return adb.adbshell(command) def adbpull(command): return adb.adbpull(command) def adbdevices(): return adb.adbdevices() def touchscreen_devices(): return adb.touchscreen_devices() def tap(x, y): command = "input tap " + str(x) + " " + str(y) command = str.encode(command) adbshell(command.decode('utf-8')) def screenCapture(): # perform a search in the sdcard of the device for the SummonerBot # folder. if we found it, we delete the file inside and capture a # new file. child = adbshell('ls sdcard') bFiles = child.stdout.read().split(b'\n') bFiles = list(filter(lambda x: x.find(b'SummonerBot\r') > -1, bFiles)) if len(bFiles) == 0: print("-- creating new folder --") adbshell('mkdir -m 777 /sdcard/SummonerBot') else: #print("-- comando do adb para remover capturas de tela --") adbshell('rm /sdcard/SummonerBot/capcha.jpg') #adbshell('rm /sdcard/SummonerBot/capcha_c.jpg') #adbshell('rm /sdcard/SummonerBot/capcha.png') adbshell('screencap -p /sdcard/SummonerBot/capcha.jpg') return "" def clearConsole(): os.system('cls') def runImageCheck(imageType): args = ["python.exe","classify_image.py","--image_file",".\dataset\\" + imageType + ".jpeg"] # print(args) return subprocess.Popen(args, shell=True, stdout=subprocess.PIPE) def sleepPrinter(timeEpoch): # print("sleeping for: " + str(timeEpoch) + " seconds") sleepCountdown(timeEpoch) def sleepCountdown(timeEpoch): last_sec = 0 for i in range(0,int(timeEpoch)): sys.stdout.write('\r' + str(int(timeEpoch)-i)+' ') sys.stdout.flush() time.sleep(1) last_sec = i if timeEpoch-float(last_sec+1) > 0: time.sleep(timeEpoch-float(last_sec+1)) # print("") sys.stdout.write('\r') sys.stdout.flush() # print("") # print("waiting reminder: " + str(timeEpoch-float(last_sec+1))) def tif2text(fileName): image_file = fileName text = "" try: im = Image.open(image_file + '.tif') text = image_to_string(im) text = image_file_to_string(image_file + '.tif') text = image_file_to_string(image_file + '.tif', graceful_errors=True) except IOError: print("Error converting tif to text") except errors.Tesser_General_Exception: print("Error converting tif to text in Tesseract") return text def convTIF2PNG(fileName): image_file = Image.open(fileName + '.tif').convert('L') image_file.save(fileName + '.jpg') def convPNG2TIF(fileName): # print("-- Nome da imagem salva como TIF --") #Exibindo o nome do arquivo salvo no formato TIF que sera usado como base para leita da tela pelo bot # print(fileName) # geralmente o nome das imagens salvas sao "capcha" e "capcha_c" respectivamente try: image_file = Image.open(fileName + '.jpg').convert('L') image_file.save(fileName + '.tif') except IOError: print("Error saving from jpg to tif") def checkSixStar(fileName): res = False im_gray = cv2.imread(fileName+".jpg", cv2.IMREAD_GRAYSCALE) thresh = 127 im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1] try: if im_bw is not None: res = im_bw[363][718] == im_bw[363][732] print("Found it to be a 6*? " + str(res)) except IOError: print("No picture found") return res def getScreenCapture(): screenCapture() # Pull image from the phone adbpull("/sdcard/SummonerBot/capcha.jpg") # adbpull("/sdcard/SummonerBot/capcha.png") # # convert to a working jpg file time.sleep(1) # try: # im = Image.open("capcha.png") # rgb_im = im.convert('RGB') # rgb_im.save('capcha.jpg') # except IOError: # print("Could not open file capcha.png") # return file name return "capcha" def crop(x,y,h,w,fileName): try: img = cv2.imread(fileName + '.jpg') if img is not None: crop_img = img[y:y+h, x:x+w] cv2.imwrite(fileName + "_c.jpg", crop_img) except IOError: print("Could not open file " + fileName) return fileName + "_c" def crop2Default(): try: img = cv2.imread('capcha_c.tif') if img is not None: crop_img = img[0, 0] cv2.imwrite("capcha_c.tif", crop_img) except IOError: print("Could not open file capcha_c.tif") try: img = cv2.imread('capcha_c.jpg') if img.all() != None: crop_img = img[0, 0] cv2.imwrite("capcha_c.jpg", crop_img) except IOError: print("Could not open file capcha_c.jpg") ### textos exibidos no final da dungeon de gigante ### # "eed more room in you" - exibido quando o inventario de runas esta cheio # "symbol that contains" - quando a recompensa eh simbolo do caos # "pieces of stones" - quando a recompensa eh pecas de runa # "Unknown Scroll" - quando a recompensa eh unknown scroll def performOCR(): # Metodo que fica sendo executado e faz a leitura da tela para o bot processar as informacoes time.sleep(2) # Adicionado um tempo de espera para o bot nao ler a tela muitas vezes seguidas global totalRefills fileN = getScreenCapture() convPNG2TIF(fileN) fullText = tif2text(fileN).split('\n') for text in fullText: if text.find("Not enough Energy") != -1: totalRefills += 1 return "need refill" if text.find("Revive") != -1: return "revive screen" if text.find("pieces of stones") != -1: return "pieces of stones screen" if text.find("symbol that contains") != -1: return "symbol that contains screen" if text.find("DEF") != -1 or text.find("ATK") != -1 or text.find("HP") != -1 or text.find("SPD") != -1 or text.find("CRI") != -1 or text.find("Resistance") != -1 or text.find("Accuracy") != -1: return "rune screen" if text.find("correct") != -1: return "correct" fileN = crop(800,350,300,450,fileN) convPNG2TIF(fileN) fullText = tif2text(fileN).split('\n') print("-- exibindo conteudo da variavel (fullText) utilizada no metodo performOCR --") print(fullText) # exibe a array com varios textos de leitura da tela for text in fullText: # caso o bot retorne reward ele executa o procedimento para verificar runa e continua e retorna a execucao para este metodo if text.find("Reward") != -1: return "reward" if text.find("Rewand") != -1: return "reward" if text.find("Rewamdi") != -1: return "reward" if text.find("Rewamd") != -1: return "reward" return "performed OCR reading" # (bug) Quando o bot entra neste metodo ele nao sai mais def refillEnergy(): print("\nClicked Refill\n") tap(random.randint(690,700),random.randint(600,700)) sleepPrinter(2) print("\nClicked recharge energy\n") tap(random.randint(690,700),random.randint(300,700)) sleepPrinter(2) print("\nClicked confirm buy\n") tap(random.randint(690,700),random.randint(600,700)) sleepPrinter(2) print("\nClicked purchase successful\n") tap(random.randint(840,1090),random.randint(600,700)) sleepPrinter(2) print("\nClicked close shop\n") tap(random.randint(850,1050),random.randint(880,980)) sleepPrinter(2) exitRefill() def exitRefill(): print("\nClicked Close Purchase\n") tap(random.randint(1760,1850),random.randint(75,140)) def keepOrSellRune(): i = 2 keep = True hasSpeedSub = False foundRare = False global soldRunes global keptRunes while i > 0: i-=1 performOCR() fileN = crop(1200,350,50,100,"capcha") # Rarity convPNG2TIF(fileN) try: img = cv2.imread('capcha_c.tif') if img.all() != None: cv2.imwrite("rarity.tif", img) except IOError: print("couldn't save with other name") fullText = tif2text("rarity").split('\n') print("Rarity:" + str(fullText)) rarity = "" for text in fullText: if text.find("Rare") != -1: # Sell rune if it's 5* and Rare. foundRare = True rarity = "Rare" if text.find("Hero") != -1: rarity = "Hero" if text.find("Legend") != -1: rarity = "Legend" if rarity == "" and i == 0: clickOther() return fileN = crop(600,350,300,600,"capcha") # Sub stats convPNG2TIF(fileN) try: img = cv2.imread('capcha_c.tif') if img.all() != None: cv2.imwrite("substats.tif", img) except IOError: print("couldn't save with other name") fullText = tif2text("substats").split('\n') print("Subststs:" + str(fullText)) for text in fullText: if text.find("SPD") != -1: # Keep rune if it has speed sub. hasSpeedSub = True sixStar = checkSixStar("capcha") print("found speed? " + str(hasSpeedSub)) print("found rare? " + str(foundRare)) print("found rarity? " + rarity) # print("Is 5* and has speed? " + str(sixStar)) if sixStar:
else: if rarity == "Legend": keep = True else: # keep = False if rarity == "Hero" and hasSpeedSub: keep = True else: keep = False print("keep? " + str(keep)) if keep == False: print("\nClicked sell rune\n") tap(random.randint(700,900),random.randint(820,920)) sleepPrinter(random.uniform(1,3)) print("\nClicked confirmed rune sell\n") tap(random.randint(850,880),random.randint(600,700)) soldRunes += 1 else: print("\nClicked keep rune\n") tap(random.randint(1030,1230),random.randint(820,920)) keptRunes += 1 def sayNo2Revives(): print("\nClicked no on revive\n") tap(random.randint(1050,1420),random.randint(650,750)) sleepPrinter(1) print("\nClicked Randomly\n") tap(random.randint(1340,1350),random.randint(440,450)) sleepPrinter(1) print("\nClicked Randomly\n") tap(random.randint(1300,1350),random.randint(440,450)) sleepPrinter(3) def clickOther(): # fileN = crop(580,250,100,600,"capcha") # Rarity # convPNG2TIF(fileN) # fullText = tif2text(fileN).split('\n') # print(fullText) # clickOthers = False # for text in fullText: # if ( text.find("Rare") == -1 ): # clickOthers = True # if ( text.find("Legend") == -1 ): # clickOthers = True # if ( text.find("Hero") == -1 ): # # if it doesn't have rarity, it's not a rune. # clickOthers = True # if clickOthers: print("it's not a rune!") print("\nClicked Get Symbol\\angelmon\\scrolls\n") tap(random.randint(950,960),random.randint(850,870)) sleepPrinter(random.uniform(1,3)) # return clickOthers def startBot(_SellRunes = False): SellRunes = _SellRunes i = 0 while True: i += 1 # print() print("-----------------------------------------------------------------------------------------") print("-- Stats --") print("Selling runes: " + str(SellRunes)) print("Number of runes sold: " + str(soldRunes)) print("Number of runes kept: " + str(keptRunes)) print("Total refills: " + str(totalRefills)) print("Total runs: " + str(i)) print("-----------------------------------------------------------------------------------------") crop2Default() # Reset capcha_c.tif file to avoid reading the same file next iteration getScreenCapture() print("\nClicked Start\n") tap(random.randint(1460,1780),random.randint(780,840)) # Click on start refilled = False loopCond = True mod = 0 while loopCond: ret = performOCR() if ret.find("need refill") != -1: #(bug) quando o bot entra na condicao de refil nao esta saindo mais refillEnergy() loopCond = False refilled = True if ret.find("revive screen") != -1: sayNo2Revives() refilled = True loopCond = False if ret.find("reward") != -1 or ret.find("rune screen") != -1: loopCond = False if ret.find("correct") != -1: return True if ret.find("pieces of stones screen") != -1 or ret.find("symbol that contains screen") != -1: clickOther() loopCond = False mod += 1 mod = mod %1024 print("-- exibindo o texto de leitura de tela --") sys.stdout.write(ret + " (execution number:" + str(mod) + ")\n") # exibe o texto "performed OCR reading" ou o texto que retornardo do metodo performOCR() sys.stdout.flush() print("\n") if refilled == False: print("\nClicked Randomly\n") tap(random.randint(1300,1350),random.randint(690,700)) sleepPrinter(1) print("\nClicked Randomly\n") tap(random.randint(1300,1350),random.randint(690,700)) sleepPrinter(3) # Click get other stuff if needed # clickOther() # Click keep rune if SellRunes: keepOrSellRune() else: print("\nClicked keep rune\n") tap(random.randint(1030,1230),random.randint(820,920)) sleepPrinter(random.uniform(2,3)) print("\nClicked Continue\n") tap(random.randint(800,850),random.randint(600,650)) sleepPrinter(random.uniform(1.5,2.5)) clearConsole() startBot(False) # keepOrSellRune() print("Finished")
if rarity == "Rare" and not hasSpeedSub: keep = False else: keep = True
conditional_block
sbot.py
#!/usr/bin/python import subprocess import os import sys import time import random from PIL import Image from PIL import ImageFile from pytesser import * import cv2 from adbInterface import adbInterface as adb os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' adbpath = '..\\platform-tools\\.\\adb' serial = "" ImageFile.LOAD_TRUNCATED_IMAGES = True soldRunes = 0 keptRunes = 0 totalRefills = 0 adb = adb() ### Sobre o funcionamento do bot ### # As vezes o bot nao limpa a variavel ref o que faz com que o texto antigo fique sendo exibido apos a tela de execucao do bot exemplo "Reward" # isso faz com que o bot execute a rotina de cliques def adbshell(command): return adb.adbshell(command) def adbpull(command):
def adbdevices(): return adb.adbdevices() def touchscreen_devices(): return adb.touchscreen_devices() def tap(x, y): command = "input tap " + str(x) + " " + str(y) command = str.encode(command) adbshell(command.decode('utf-8')) def screenCapture(): # perform a search in the sdcard of the device for the SummonerBot # folder. if we found it, we delete the file inside and capture a # new file. child = adbshell('ls sdcard') bFiles = child.stdout.read().split(b'\n') bFiles = list(filter(lambda x: x.find(b'SummonerBot\r') > -1, bFiles)) if len(bFiles) == 0: print("-- creating new folder --") adbshell('mkdir -m 777 /sdcard/SummonerBot') else: #print("-- comando do adb para remover capturas de tela --") adbshell('rm /sdcard/SummonerBot/capcha.jpg') #adbshell('rm /sdcard/SummonerBot/capcha_c.jpg') #adbshell('rm /sdcard/SummonerBot/capcha.png') adbshell('screencap -p /sdcard/SummonerBot/capcha.jpg') return "" def clearConsole(): os.system('cls') def runImageCheck(imageType): args = ["python.exe","classify_image.py","--image_file",".\dataset\\" + imageType + ".jpeg"] # print(args) return subprocess.Popen(args, shell=True, stdout=subprocess.PIPE) def sleepPrinter(timeEpoch): # print("sleeping for: " + str(timeEpoch) + " seconds") sleepCountdown(timeEpoch) def sleepCountdown(timeEpoch): last_sec = 0 for i in range(0,int(timeEpoch)): sys.stdout.write('\r' + str(int(timeEpoch)-i)+' ') sys.stdout.flush() time.sleep(1) last_sec = i if timeEpoch-float(last_sec+1) > 0: time.sleep(timeEpoch-float(last_sec+1)) # print("") sys.stdout.write('\r') sys.stdout.flush() # print("") # print("waiting reminder: " + str(timeEpoch-float(last_sec+1))) def tif2text(fileName): image_file = fileName text = "" try: im = Image.open(image_file + '.tif') text = image_to_string(im) text = image_file_to_string(image_file + '.tif') text = image_file_to_string(image_file + '.tif', graceful_errors=True) except IOError: print("Error converting tif to text") except errors.Tesser_General_Exception: print("Error converting tif to text in Tesseract") return text def convTIF2PNG(fileName): image_file = Image.open(fileName + '.tif').convert('L') image_file.save(fileName + '.jpg') def convPNG2TIF(fileName): # print("-- Nome da imagem salva como TIF --") #Exibindo o nome do arquivo salvo no formato TIF que sera usado como base para leita da tela pelo bot # print(fileName) # geralmente o nome das imagens salvas sao "capcha" e "capcha_c" respectivamente try: image_file = Image.open(fileName + '.jpg').convert('L') image_file.save(fileName + '.tif') except IOError: print("Error saving from jpg to tif") def checkSixStar(fileName): res = False im_gray = cv2.imread(fileName+".jpg", cv2.IMREAD_GRAYSCALE) thresh = 127 im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1] try: if im_bw is not None: res = im_bw[363][718] == im_bw[363][732] print("Found it to be a 6*? " + str(res)) except IOError: print("No picture found") return res def getScreenCapture(): screenCapture() # Pull image from the phone adbpull("/sdcard/SummonerBot/capcha.jpg") # adbpull("/sdcard/SummonerBot/capcha.png") # # convert to a working jpg file time.sleep(1) # try: # im = Image.open("capcha.png") # rgb_im = im.convert('RGB') # rgb_im.save('capcha.jpg') # except IOError: # print("Could not open file capcha.png") # return file name return "capcha" def crop(x,y,h,w,fileName): try: img = cv2.imread(fileName + '.jpg') if img is not None: crop_img = img[y:y+h, x:x+w] cv2.imwrite(fileName + "_c.jpg", crop_img) except IOError: print("Could not open file " + fileName) return fileName + "_c" def crop2Default(): try: img = cv2.imread('capcha_c.tif') if img is not None: crop_img = img[0, 0] cv2.imwrite("capcha_c.tif", crop_img) except IOError: print("Could not open file capcha_c.tif") try: img = cv2.imread('capcha_c.jpg') if img.all() != None: crop_img = img[0, 0] cv2.imwrite("capcha_c.jpg", crop_img) except IOError: print("Could not open file capcha_c.jpg") ### textos exibidos no final da dungeon de gigante ### # "eed more room in you" - exibido quando o inventario de runas esta cheio # "symbol that contains" - quando a recompensa eh simbolo do caos # "pieces of stones" - quando a recompensa eh pecas de runa # "Unknown Scroll" - quando a recompensa eh unknown scroll def performOCR(): # Metodo que fica sendo executado e faz a leitura da tela para o bot processar as informacoes time.sleep(2) # Adicionado um tempo de espera para o bot nao ler a tela muitas vezes seguidas global totalRefills fileN = getScreenCapture() convPNG2TIF(fileN) fullText = tif2text(fileN).split('\n') for text in fullText: if text.find("Not enough Energy") != -1: totalRefills += 1 return "need refill" if text.find("Revive") != -1: return "revive screen" if text.find("pieces of stones") != -1: return "pieces of stones screen" if text.find("symbol that contains") != -1: return "symbol that contains screen" if text.find("DEF") != -1 or text.find("ATK") != -1 or text.find("HP") != -1 or text.find("SPD") != -1 or text.find("CRI") != -1 or text.find("Resistance") != -1 or text.find("Accuracy") != -1: return "rune screen" if text.find("correct") != -1: return "correct" fileN = crop(800,350,300,450,fileN) convPNG2TIF(fileN) fullText = tif2text(fileN).split('\n') print("-- exibindo conteudo da variavel (fullText) utilizada no metodo performOCR --") print(fullText) # exibe a array com varios textos de leitura da tela for text in fullText: # caso o bot retorne reward ele executa o procedimento para verificar runa e continua e retorna a execucao para este metodo if text.find("Reward") != -1: return "reward" if text.find("Rewand") != -1: return "reward" if text.find("Rewamdi") != -1: return "reward" if text.find("Rewamd") != -1: return "reward" return "performed OCR reading" # (bug) Quando o bot entra neste metodo ele nao sai mais def refillEnergy(): print("\nClicked Refill\n") tap(random.randint(690,700),random.randint(600,700)) sleepPrinter(2) print("\nClicked recharge energy\n") tap(random.randint(690,700),random.randint(300,700)) sleepPrinter(2) print("\nClicked confirm buy\n") tap(random.randint(690,700),random.randint(600,700)) sleepPrinter(2) print("\nClicked purchase successful\n") tap(random.randint(840,1090),random.randint(600,700)) sleepPrinter(2) print("\nClicked close shop\n") tap(random.randint(850,1050),random.randint(880,980)) sleepPrinter(2) exitRefill() def exitRefill(): print("\nClicked Close Purchase\n") tap(random.randint(1760,1850),random.randint(75,140)) def keepOrSellRune(): i = 2 keep = True hasSpeedSub = False foundRare = False global soldRunes global keptRunes while i > 0: i-=1 performOCR() fileN = crop(1200,350,50,100,"capcha") # Rarity convPNG2TIF(fileN) try: img = cv2.imread('capcha_c.tif') if img.all() != None: cv2.imwrite("rarity.tif", img) except IOError: print("couldn't save with other name") fullText = tif2text("rarity").split('\n') print("Rarity:" + str(fullText)) rarity = "" for text in fullText: if text.find("Rare") != -1: # Sell rune if it's 5* and Rare. foundRare = True rarity = "Rare" if text.find("Hero") != -1: rarity = "Hero" if text.find("Legend") != -1: rarity = "Legend" if rarity == "" and i == 0: clickOther() return fileN = crop(600,350,300,600,"capcha") # Sub stats convPNG2TIF(fileN) try: img = cv2.imread('capcha_c.tif') if img.all() != None: cv2.imwrite("substats.tif", img) except IOError: print("couldn't save with other name") fullText = tif2text("substats").split('\n') print("Subststs:" + str(fullText)) for text in fullText: if text.find("SPD") != -1: # Keep rune if it has speed sub. hasSpeedSub = True sixStar = checkSixStar("capcha") print("found speed? " + str(hasSpeedSub)) print("found rare? " + str(foundRare)) print("found rarity? " + rarity) # print("Is 5* and has speed? " + str(sixStar)) if sixStar: if rarity == "Rare" and not hasSpeedSub: keep = False else: keep = True else: if rarity == "Legend": keep = True else: # keep = False if rarity == "Hero" and hasSpeedSub: keep = True else: keep = False print("keep? " + str(keep)) if keep == False: print("\nClicked sell rune\n") tap(random.randint(700,900),random.randint(820,920)) sleepPrinter(random.uniform(1,3)) print("\nClicked confirmed rune sell\n") tap(random.randint(850,880),random.randint(600,700)) soldRunes += 1 else: print("\nClicked keep rune\n") tap(random.randint(1030,1230),random.randint(820,920)) keptRunes += 1 def sayNo2Revives(): print("\nClicked no on revive\n") tap(random.randint(1050,1420),random.randint(650,750)) sleepPrinter(1) print("\nClicked Randomly\n") tap(random.randint(1340,1350),random.randint(440,450)) sleepPrinter(1) print("\nClicked Randomly\n") tap(random.randint(1300,1350),random.randint(440,450)) sleepPrinter(3) def clickOther(): # fileN = crop(580,250,100,600,"capcha") # Rarity # convPNG2TIF(fileN) # fullText = tif2text(fileN).split('\n') # print(fullText) # clickOthers = False # for text in fullText: # if ( text.find("Rare") == -1 ): # clickOthers = True # if ( text.find("Legend") == -1 ): # clickOthers = True # if ( text.find("Hero") == -1 ): # # if it doesn't have rarity, it's not a rune. # clickOthers = True # if clickOthers: print("it's not a rune!") print("\nClicked Get Symbol\\angelmon\\scrolls\n") tap(random.randint(950,960),random.randint(850,870)) sleepPrinter(random.uniform(1,3)) # return clickOthers def startBot(_SellRunes = False): SellRunes = _SellRunes i = 0 while True: i += 1 # print() print("-----------------------------------------------------------------------------------------") print("-- Stats --") print("Selling runes: " + str(SellRunes)) print("Number of runes sold: " + str(soldRunes)) print("Number of runes kept: " + str(keptRunes)) print("Total refills: " + str(totalRefills)) print("Total runs: " + str(i)) print("-----------------------------------------------------------------------------------------") crop2Default() # Reset capcha_c.tif file to avoid reading the same file next iteration getScreenCapture() print("\nClicked Start\n") tap(random.randint(1460,1780),random.randint(780,840)) # Click on start refilled = False loopCond = True mod = 0 while loopCond: ret = performOCR() if ret.find("need refill") != -1: #(bug) quando o bot entra na condicao de refil nao esta saindo mais refillEnergy() loopCond = False refilled = True if ret.find("revive screen") != -1: sayNo2Revives() refilled = True loopCond = False if ret.find("reward") != -1 or ret.find("rune screen") != -1: loopCond = False if ret.find("correct") != -1: return True if ret.find("pieces of stones screen") != -1 or ret.find("symbol that contains screen") != -1: clickOther() loopCond = False mod += 1 mod = mod %1024 print("-- exibindo o texto de leitura de tela --") sys.stdout.write(ret + " (execution number:" + str(mod) + ")\n") # exibe o texto "performed OCR reading" ou o texto que retornardo do metodo performOCR() sys.stdout.flush() print("\n") if refilled == False: print("\nClicked Randomly\n") tap(random.randint(1300,1350),random.randint(690,700)) sleepPrinter(1) print("\nClicked Randomly\n") tap(random.randint(1300,1350),random.randint(690,700)) sleepPrinter(3) # Click get other stuff if needed # clickOther() # Click keep rune if SellRunes: keepOrSellRune() else: print("\nClicked keep rune\n") tap(random.randint(1030,1230),random.randint(820,920)) sleepPrinter(random.uniform(2,3)) print("\nClicked Continue\n") tap(random.randint(800,850),random.randint(600,650)) sleepPrinter(random.uniform(1.5,2.5)) clearConsole() startBot(False) # keepOrSellRune() print("Finished")
return adb.adbpull(command)
identifier_body
sbot.py
#!/usr/bin/python import subprocess import os import sys import time import random from PIL import Image from PIL import ImageFile from pytesser import * import cv2 from adbInterface import adbInterface as adb os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' adbpath = '..\\platform-tools\\.\\adb' serial = "" ImageFile.LOAD_TRUNCATED_IMAGES = True soldRunes = 0 keptRunes = 0 totalRefills = 0 adb = adb() ### Sobre o funcionamento do bot ### # As vezes o bot nao limpa a variavel ref o que faz com que o texto antigo fique sendo exibido apos a tela de execucao do bot exemplo "Reward" # isso faz com que o bot execute a rotina de cliques def adbshell(command): return adb.adbshell(command) def adbpull(command): return adb.adbpull(command) def adbdevices(): return adb.adbdevices() def touchscreen_devices(): return adb.touchscreen_devices() def tap(x, y): command = "input tap " + str(x) + " " + str(y) command = str.encode(command) adbshell(command.decode('utf-8')) def screenCapture(): # perform a search in the sdcard of the device for the SummonerBot # folder. if we found it, we delete the file inside and capture a # new file. child = adbshell('ls sdcard') bFiles = child.stdout.read().split(b'\n') bFiles = list(filter(lambda x: x.find(b'SummonerBot\r') > -1, bFiles)) if len(bFiles) == 0: print("-- creating new folder --") adbshell('mkdir -m 777 /sdcard/SummonerBot') else: #print("-- comando do adb para remover capturas de tela --") adbshell('rm /sdcard/SummonerBot/capcha.jpg') #adbshell('rm /sdcard/SummonerBot/capcha_c.jpg') #adbshell('rm /sdcard/SummonerBot/capcha.png') adbshell('screencap -p /sdcard/SummonerBot/capcha.jpg') return "" def clearConsole(): os.system('cls') def runImageCheck(imageType): args = ["python.exe","classify_image.py","--image_file",".\dataset\\" + imageType + ".jpeg"] # print(args) return subprocess.Popen(args, shell=True, stdout=subprocess.PIPE) def sleepPrinter(timeEpoch): # print("sleeping for: " + str(timeEpoch) + " seconds") sleepCountdown(timeEpoch) def sleepCountdown(timeEpoch): last_sec = 0 for i in range(0,int(timeEpoch)): sys.stdout.write('\r' + str(int(timeEpoch)-i)+' ') sys.stdout.flush() time.sleep(1) last_sec = i if timeEpoch-float(last_sec+1) > 0: time.sleep(timeEpoch-float(last_sec+1)) # print("") sys.stdout.write('\r') sys.stdout.flush() # print("") # print("waiting reminder: " + str(timeEpoch-float(last_sec+1))) def tif2text(fileName): image_file = fileName text = "" try: im = Image.open(image_file + '.tif') text = image_to_string(im) text = image_file_to_string(image_file + '.tif') text = image_file_to_string(image_file + '.tif', graceful_errors=True) except IOError: print("Error converting tif to text") except errors.Tesser_General_Exception: print("Error converting tif to text in Tesseract") return text def convTIF2PNG(fileName): image_file = Image.open(fileName + '.tif').convert('L') image_file.save(fileName + '.jpg') def convPNG2TIF(fileName): # print("-- Nome da imagem salva como TIF --") #Exibindo o nome do arquivo salvo no formato TIF que sera usado como base para leita da tela pelo bot # print(fileName) # geralmente o nome das imagens salvas sao "capcha" e "capcha_c" respectivamente try: image_file = Image.open(fileName + '.jpg').convert('L') image_file.save(fileName + '.tif') except IOError: print("Error saving from jpg to tif") def checkSixStar(fileName): res = False im_gray = cv2.imread(fileName+".jpg", cv2.IMREAD_GRAYSCALE) thresh = 127 im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1] try: if im_bw is not None: res = im_bw[363][718] == im_bw[363][732] print("Found it to be a 6*? " + str(res)) except IOError: print("No picture found") return res def getScreenCapture(): screenCapture() # Pull image from the phone adbpull("/sdcard/SummonerBot/capcha.jpg") # adbpull("/sdcard/SummonerBot/capcha.png") # # convert to a working jpg file time.sleep(1) # try: # im = Image.open("capcha.png") # rgb_im = im.convert('RGB') # rgb_im.save('capcha.jpg') # except IOError: # print("Could not open file capcha.png") # return file name return "capcha" def crop(x,y,h,w,fileName): try: img = cv2.imread(fileName + '.jpg') if img is not None: crop_img = img[y:y+h, x:x+w] cv2.imwrite(fileName + "_c.jpg", crop_img) except IOError: print("Could not open file " + fileName) return fileName + "_c" def crop2Default(): try: img = cv2.imread('capcha_c.tif') if img is not None: crop_img = img[0, 0] cv2.imwrite("capcha_c.tif", crop_img) except IOError: print("Could not open file capcha_c.tif") try: img = cv2.imread('capcha_c.jpg') if img.all() != None: crop_img = img[0, 0] cv2.imwrite("capcha_c.jpg", crop_img) except IOError: print("Could not open file capcha_c.jpg") ### textos exibidos no final da dungeon de gigante ### # "eed more room in you" - exibido quando o inventario de runas esta cheio # "symbol that contains" - quando a recompensa eh simbolo do caos # "pieces of stones" - quando a recompensa eh pecas de runa # "Unknown Scroll" - quando a recompensa eh unknown scroll def performOCR(): # Metodo que fica sendo executado e faz a leitura da tela para o bot processar as informacoes time.sleep(2) # Adicionado um tempo de espera para o bot nao ler a tela muitas vezes seguidas global totalRefills fileN = getScreenCapture() convPNG2TIF(fileN) fullText = tif2text(fileN).split('\n') for text in fullText: if text.find("Not enough Energy") != -1: totalRefills += 1 return "need refill" if text.find("Revive") != -1: return "revive screen" if text.find("pieces of stones") != -1: return "pieces of stones screen" if text.find("symbol that contains") != -1: return "symbol that contains screen" if text.find("DEF") != -1 or text.find("ATK") != -1 or text.find("HP") != -1 or text.find("SPD") != -1 or text.find("CRI") != -1 or text.find("Resistance") != -1 or text.find("Accuracy") != -1: return "rune screen" if text.find("correct") != -1: return "correct" fileN = crop(800,350,300,450,fileN) convPNG2TIF(fileN) fullText = tif2text(fileN).split('\n') print("-- exibindo conteudo da variavel (fullText) utilizada no metodo performOCR --") print(fullText) # exibe a array com varios textos de leitura da tela for text in fullText: # caso o bot retorne reward ele executa o procedimento para verificar runa e continua e retorna a execucao para este metodo if text.find("Reward") != -1: return "reward" if text.find("Rewand") != -1: return "reward" if text.find("Rewamdi") != -1: return "reward" if text.find("Rewamd") != -1: return "reward" return "performed OCR reading" # (bug) Quando o bot entra neste metodo ele nao sai mais def refillEnergy(): print("\nClicked Refill\n") tap(random.randint(690,700),random.randint(600,700)) sleepPrinter(2) print("\nClicked recharge energy\n") tap(random.randint(690,700),random.randint(300,700)) sleepPrinter(2) print("\nClicked confirm buy\n") tap(random.randint(690,700),random.randint(600,700)) sleepPrinter(2) print("\nClicked purchase successful\n") tap(random.randint(840,1090),random.randint(600,700)) sleepPrinter(2) print("\nClicked close shop\n") tap(random.randint(850,1050),random.randint(880,980)) sleepPrinter(2) exitRefill() def exitRefill(): print("\nClicked Close Purchase\n") tap(random.randint(1760,1850),random.randint(75,140)) def
(): i = 2 keep = True hasSpeedSub = False foundRare = False global soldRunes global keptRunes while i > 0: i-=1 performOCR() fileN = crop(1200,350,50,100,"capcha") # Rarity convPNG2TIF(fileN) try: img = cv2.imread('capcha_c.tif') if img.all() != None: cv2.imwrite("rarity.tif", img) except IOError: print("couldn't save with other name") fullText = tif2text("rarity").split('\n') print("Rarity:" + str(fullText)) rarity = "" for text in fullText: if text.find("Rare") != -1: # Sell rune if it's 5* and Rare. foundRare = True rarity = "Rare" if text.find("Hero") != -1: rarity = "Hero" if text.find("Legend") != -1: rarity = "Legend" if rarity == "" and i == 0: clickOther() return fileN = crop(600,350,300,600,"capcha") # Sub stats convPNG2TIF(fileN) try: img = cv2.imread('capcha_c.tif') if img.all() != None: cv2.imwrite("substats.tif", img) except IOError: print("couldn't save with other name") fullText = tif2text("substats").split('\n') print("Subststs:" + str(fullText)) for text in fullText: if text.find("SPD") != -1: # Keep rune if it has speed sub. hasSpeedSub = True sixStar = checkSixStar("capcha") print("found speed? " + str(hasSpeedSub)) print("found rare? " + str(foundRare)) print("found rarity? " + rarity) # print("Is 5* and has speed? " + str(sixStar)) if sixStar: if rarity == "Rare" and not hasSpeedSub: keep = False else: keep = True else: if rarity == "Legend": keep = True else: # keep = False if rarity == "Hero" and hasSpeedSub: keep = True else: keep = False print("keep? " + str(keep)) if keep == False: print("\nClicked sell rune\n") tap(random.randint(700,900),random.randint(820,920)) sleepPrinter(random.uniform(1,3)) print("\nClicked confirmed rune sell\n") tap(random.randint(850,880),random.randint(600,700)) soldRunes += 1 else: print("\nClicked keep rune\n") tap(random.randint(1030,1230),random.randint(820,920)) keptRunes += 1 def sayNo2Revives(): print("\nClicked no on revive\n") tap(random.randint(1050,1420),random.randint(650,750)) sleepPrinter(1) print("\nClicked Randomly\n") tap(random.randint(1340,1350),random.randint(440,450)) sleepPrinter(1) print("\nClicked Randomly\n") tap(random.randint(1300,1350),random.randint(440,450)) sleepPrinter(3) def clickOther(): # fileN = crop(580,250,100,600,"capcha") # Rarity # convPNG2TIF(fileN) # fullText = tif2text(fileN).split('\n') # print(fullText) # clickOthers = False # for text in fullText: # if ( text.find("Rare") == -1 ): # clickOthers = True # if ( text.find("Legend") == -1 ): # clickOthers = True # if ( text.find("Hero") == -1 ): # # if it doesn't have rarity, it's not a rune. # clickOthers = True # if clickOthers: print("it's not a rune!") print("\nClicked Get Symbol\\angelmon\\scrolls\n") tap(random.randint(950,960),random.randint(850,870)) sleepPrinter(random.uniform(1,3)) # return clickOthers def startBot(_SellRunes = False): SellRunes = _SellRunes i = 0 while True: i += 1 # print() print("-----------------------------------------------------------------------------------------") print("-- Stats --") print("Selling runes: " + str(SellRunes)) print("Number of runes sold: " + str(soldRunes)) print("Number of runes kept: " + str(keptRunes)) print("Total refills: " + str(totalRefills)) print("Total runs: " + str(i)) print("-----------------------------------------------------------------------------------------") crop2Default() # Reset capcha_c.tif file to avoid reading the same file next iteration getScreenCapture() print("\nClicked Start\n") tap(random.randint(1460,1780),random.randint(780,840)) # Click on start refilled = False loopCond = True mod = 0 while loopCond: ret = performOCR() if ret.find("need refill") != -1: #(bug) quando o bot entra na condicao de refil nao esta saindo mais refillEnergy() loopCond = False refilled = True if ret.find("revive screen") != -1: sayNo2Revives() refilled = True loopCond = False if ret.find("reward") != -1 or ret.find("rune screen") != -1: loopCond = False if ret.find("correct") != -1: return True if ret.find("pieces of stones screen") != -1 or ret.find("symbol that contains screen") != -1: clickOther() loopCond = False mod += 1 mod = mod %1024 print("-- exibindo o texto de leitura de tela --") sys.stdout.write(ret + " (execution number:" + str(mod) + ")\n") # exibe o texto "performed OCR reading" ou o texto que retornardo do metodo performOCR() sys.stdout.flush() print("\n") if refilled == False: print("\nClicked Randomly\n") tap(random.randint(1300,1350),random.randint(690,700)) sleepPrinter(1) print("\nClicked Randomly\n") tap(random.randint(1300,1350),random.randint(690,700)) sleepPrinter(3) # Click get other stuff if needed # clickOther() # Click keep rune if SellRunes: keepOrSellRune() else: print("\nClicked keep rune\n") tap(random.randint(1030,1230),random.randint(820,920)) sleepPrinter(random.uniform(2,3)) print("\nClicked Continue\n") tap(random.randint(800,850),random.randint(600,650)) sleepPrinter(random.uniform(1.5,2.5)) clearConsole() startBot(False) # keepOrSellRune() print("Finished")
keepOrSellRune
identifier_name
sbot.py
#!/usr/bin/python import subprocess import os import sys import time import random from PIL import Image from PIL import ImageFile from pytesser import * import cv2 from adbInterface import adbInterface as adb os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' adbpath = '..\\platform-tools\\.\\adb' serial = "" ImageFile.LOAD_TRUNCATED_IMAGES = True soldRunes = 0 keptRunes = 0 totalRefills = 0 adb = adb() ### Sobre o funcionamento do bot ### # As vezes o bot nao limpa a variavel ref o que faz com que o texto antigo fique sendo exibido apos a tela de execucao do bot exemplo "Reward" # isso faz com que o bot execute a rotina de cliques def adbshell(command): return adb.adbshell(command) def adbpull(command): return adb.adbpull(command)
return adb.touchscreen_devices() def tap(x, y): command = "input tap " + str(x) + " " + str(y) command = str.encode(command) adbshell(command.decode('utf-8')) def screenCapture(): # perform a search in the sdcard of the device for the SummonerBot # folder. if we found it, we delete the file inside and capture a # new file. child = adbshell('ls sdcard') bFiles = child.stdout.read().split(b'\n') bFiles = list(filter(lambda x: x.find(b'SummonerBot\r') > -1, bFiles)) if len(bFiles) == 0: print("-- creating new folder --") adbshell('mkdir -m 777 /sdcard/SummonerBot') else: #print("-- comando do adb para remover capturas de tela --") adbshell('rm /sdcard/SummonerBot/capcha.jpg') #adbshell('rm /sdcard/SummonerBot/capcha_c.jpg') #adbshell('rm /sdcard/SummonerBot/capcha.png') adbshell('screencap -p /sdcard/SummonerBot/capcha.jpg') return "" def clearConsole(): os.system('cls') def runImageCheck(imageType): args = ["python.exe","classify_image.py","--image_file",".\dataset\\" + imageType + ".jpeg"] # print(args) return subprocess.Popen(args, shell=True, stdout=subprocess.PIPE) def sleepPrinter(timeEpoch): # print("sleeping for: " + str(timeEpoch) + " seconds") sleepCountdown(timeEpoch) def sleepCountdown(timeEpoch): last_sec = 0 for i in range(0,int(timeEpoch)): sys.stdout.write('\r' + str(int(timeEpoch)-i)+' ') sys.stdout.flush() time.sleep(1) last_sec = i if timeEpoch-float(last_sec+1) > 0: time.sleep(timeEpoch-float(last_sec+1)) # print("") sys.stdout.write('\r') sys.stdout.flush() # print("") # print("waiting reminder: " + str(timeEpoch-float(last_sec+1))) def tif2text(fileName): image_file = fileName text = "" try: im = Image.open(image_file + '.tif') text = image_to_string(im) text = image_file_to_string(image_file + '.tif') text = image_file_to_string(image_file + '.tif', graceful_errors=True) except IOError: print("Error converting tif to text") except errors.Tesser_General_Exception: print("Error converting tif to text in Tesseract") return text def convTIF2PNG(fileName): image_file = Image.open(fileName + '.tif').convert('L') image_file.save(fileName + '.jpg') def convPNG2TIF(fileName): # print("-- Nome da imagem salva como TIF --") #Exibindo o nome do arquivo salvo no formato TIF que sera usado como base para leita da tela pelo bot # print(fileName) # geralmente o nome das imagens salvas sao "capcha" e "capcha_c" respectivamente try: image_file = Image.open(fileName + '.jpg').convert('L') image_file.save(fileName + '.tif') except IOError: print("Error saving from jpg to tif") def checkSixStar(fileName): res = False im_gray = cv2.imread(fileName+".jpg", cv2.IMREAD_GRAYSCALE) thresh = 127 im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1] try: if im_bw is not None: res = im_bw[363][718] == im_bw[363][732] print("Found it to be a 6*? " + str(res)) except IOError: print("No picture found") return res def getScreenCapture(): screenCapture() # Pull image from the phone adbpull("/sdcard/SummonerBot/capcha.jpg") # adbpull("/sdcard/SummonerBot/capcha.png") # # convert to a working jpg file time.sleep(1) # try: # im = Image.open("capcha.png") # rgb_im = im.convert('RGB') # rgb_im.save('capcha.jpg') # except IOError: # print("Could not open file capcha.png") # return file name return "capcha" def crop(x,y,h,w,fileName): try: img = cv2.imread(fileName + '.jpg') if img is not None: crop_img = img[y:y+h, x:x+w] cv2.imwrite(fileName + "_c.jpg", crop_img) except IOError: print("Could not open file " + fileName) return fileName + "_c" def crop2Default(): try: img = cv2.imread('capcha_c.tif') if img is not None: crop_img = img[0, 0] cv2.imwrite("capcha_c.tif", crop_img) except IOError: print("Could not open file capcha_c.tif") try: img = cv2.imread('capcha_c.jpg') if img.all() != None: crop_img = img[0, 0] cv2.imwrite("capcha_c.jpg", crop_img) except IOError: print("Could not open file capcha_c.jpg") ### textos exibidos no final da dungeon de gigante ### # "eed more room in you" - exibido quando o inventario de runas esta cheio # "symbol that contains" - quando a recompensa eh simbolo do caos # "pieces of stones" - quando a recompensa eh pecas de runa # "Unknown Scroll" - quando a recompensa eh unknown scroll def performOCR(): # Metodo que fica sendo executado e faz a leitura da tela para o bot processar as informacoes time.sleep(2) # Adicionado um tempo de espera para o bot nao ler a tela muitas vezes seguidas global totalRefills fileN = getScreenCapture() convPNG2TIF(fileN) fullText = tif2text(fileN).split('\n') for text in fullText: if text.find("Not enough Energy") != -1: totalRefills += 1 return "need refill" if text.find("Revive") != -1: return "revive screen" if text.find("pieces of stones") != -1: return "pieces of stones screen" if text.find("symbol that contains") != -1: return "symbol that contains screen" if text.find("DEF") != -1 or text.find("ATK") != -1 or text.find("HP") != -1 or text.find("SPD") != -1 or text.find("CRI") != -1 or text.find("Resistance") != -1 or text.find("Accuracy") != -1: return "rune screen" if text.find("correct") != -1: return "correct" fileN = crop(800,350,300,450,fileN) convPNG2TIF(fileN) fullText = tif2text(fileN).split('\n') print("-- exibindo conteudo da variavel (fullText) utilizada no metodo performOCR --") print(fullText) # exibe a array com varios textos de leitura da tela for text in fullText: # caso o bot retorne reward ele executa o procedimento para verificar runa e continua e retorna a execucao para este metodo if text.find("Reward") != -1: return "reward" if text.find("Rewand") != -1: return "reward" if text.find("Rewamdi") != -1: return "reward" if text.find("Rewamd") != -1: return "reward" return "performed OCR reading" # (bug) Quando o bot entra neste metodo ele nao sai mais def refillEnergy(): print("\nClicked Refill\n") tap(random.randint(690,700),random.randint(600,700)) sleepPrinter(2) print("\nClicked recharge energy\n") tap(random.randint(690,700),random.randint(300,700)) sleepPrinter(2) print("\nClicked confirm buy\n") tap(random.randint(690,700),random.randint(600,700)) sleepPrinter(2) print("\nClicked purchase successful\n") tap(random.randint(840,1090),random.randint(600,700)) sleepPrinter(2) print("\nClicked close shop\n") tap(random.randint(850,1050),random.randint(880,980)) sleepPrinter(2) exitRefill() def exitRefill(): print("\nClicked Close Purchase\n") tap(random.randint(1760,1850),random.randint(75,140)) def keepOrSellRune(): i = 2 keep = True hasSpeedSub = False foundRare = False global soldRunes global keptRunes while i > 0: i-=1 performOCR() fileN = crop(1200,350,50,100,"capcha") # Rarity convPNG2TIF(fileN) try: img = cv2.imread('capcha_c.tif') if img.all() != None: cv2.imwrite("rarity.tif", img) except IOError: print("couldn't save with other name") fullText = tif2text("rarity").split('\n') print("Rarity:" + str(fullText)) rarity = "" for text in fullText: if text.find("Rare") != -1: # Sell rune if it's 5* and Rare. foundRare = True rarity = "Rare" if text.find("Hero") != -1: rarity = "Hero" if text.find("Legend") != -1: rarity = "Legend" if rarity == "" and i == 0: clickOther() return fileN = crop(600,350,300,600,"capcha") # Sub stats convPNG2TIF(fileN) try: img = cv2.imread('capcha_c.tif') if img.all() != None: cv2.imwrite("substats.tif", img) except IOError: print("couldn't save with other name") fullText = tif2text("substats").split('\n') print("Subststs:" + str(fullText)) for text in fullText: if text.find("SPD") != -1: # Keep rune if it has speed sub. hasSpeedSub = True sixStar = checkSixStar("capcha") print("found speed? " + str(hasSpeedSub)) print("found rare? " + str(foundRare)) print("found rarity? " + rarity) # print("Is 5* and has speed? " + str(sixStar)) if sixStar: if rarity == "Rare" and not hasSpeedSub: keep = False else: keep = True else: if rarity == "Legend": keep = True else: # keep = False if rarity == "Hero" and hasSpeedSub: keep = True else: keep = False print("keep? " + str(keep)) if keep == False: print("\nClicked sell rune\n") tap(random.randint(700,900),random.randint(820,920)) sleepPrinter(random.uniform(1,3)) print("\nClicked confirmed rune sell\n") tap(random.randint(850,880),random.randint(600,700)) soldRunes += 1 else: print("\nClicked keep rune\n") tap(random.randint(1030,1230),random.randint(820,920)) keptRunes += 1 def sayNo2Revives(): print("\nClicked no on revive\n") tap(random.randint(1050,1420),random.randint(650,750)) sleepPrinter(1) print("\nClicked Randomly\n") tap(random.randint(1340,1350),random.randint(440,450)) sleepPrinter(1) print("\nClicked Randomly\n") tap(random.randint(1300,1350),random.randint(440,450)) sleepPrinter(3) def clickOther(): # fileN = crop(580,250,100,600,"capcha") # Rarity # convPNG2TIF(fileN) # fullText = tif2text(fileN).split('\n') # print(fullText) # clickOthers = False # for text in fullText: # if ( text.find("Rare") == -1 ): # clickOthers = True # if ( text.find("Legend") == -1 ): # clickOthers = True # if ( text.find("Hero") == -1 ): # # if it doesn't have rarity, it's not a rune. # clickOthers = True # if clickOthers: print("it's not a rune!") print("\nClicked Get Symbol\\angelmon\\scrolls\n") tap(random.randint(950,960),random.randint(850,870)) sleepPrinter(random.uniform(1,3)) # return clickOthers def startBot(_SellRunes = False): SellRunes = _SellRunes i = 0 while True: i += 1 # print() print("-----------------------------------------------------------------------------------------") print("-- Stats --") print("Selling runes: " + str(SellRunes)) print("Number of runes sold: " + str(soldRunes)) print("Number of runes kept: " + str(keptRunes)) print("Total refills: " + str(totalRefills)) print("Total runs: " + str(i)) print("-----------------------------------------------------------------------------------------") crop2Default() # Reset capcha_c.tif file to avoid reading the same file next iteration getScreenCapture() print("\nClicked Start\n") tap(random.randint(1460,1780),random.randint(780,840)) # Click on start refilled = False loopCond = True mod = 0 while loopCond: ret = performOCR() if ret.find("need refill") != -1: #(bug) quando o bot entra na condicao de refil nao esta saindo mais refillEnergy() loopCond = False refilled = True if ret.find("revive screen") != -1: sayNo2Revives() refilled = True loopCond = False if ret.find("reward") != -1 or ret.find("rune screen") != -1: loopCond = False if ret.find("correct") != -1: return True if ret.find("pieces of stones screen") != -1 or ret.find("symbol that contains screen") != -1: clickOther() loopCond = False mod += 1 mod = mod %1024 print("-- exibindo o texto de leitura de tela --") sys.stdout.write(ret + " (execution number:" + str(mod) + ")\n") # exibe o texto "performed OCR reading" ou o texto que retornardo do metodo performOCR() sys.stdout.flush() print("\n") if refilled == False: print("\nClicked Randomly\n") tap(random.randint(1300,1350),random.randint(690,700)) sleepPrinter(1) print("\nClicked Randomly\n") tap(random.randint(1300,1350),random.randint(690,700)) sleepPrinter(3) # Click get other stuff if needed # clickOther() # Click keep rune if SellRunes: keepOrSellRune() else: print("\nClicked keep rune\n") tap(random.randint(1030,1230),random.randint(820,920)) sleepPrinter(random.uniform(2,3)) print("\nClicked Continue\n") tap(random.randint(800,850),random.randint(600,650)) sleepPrinter(random.uniform(1.5,2.5)) clearConsole() startBot(False) # keepOrSellRune() print("Finished")
def adbdevices(): return adb.adbdevices() def touchscreen_devices():
random_line_split
triggers.go
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package trigger import ( "context" "encoding/json" "errors" "fmt" "os" "strings" "text/tabwriter" "github.com/fnproject/fn_go/clientv2/fns" "github.com/jmoiron/jsonq" "github.com/fnproject/cli/client" "github.com/fnproject/cli/common" "github.com/fnproject/cli/objects/app" "github.com/fnproject/cli/objects/fn" fnclient "github.com/fnproject/fn_go/clientv2" apiTriggers "github.com/fnproject/fn_go/clientv2/triggers" models "github.com/fnproject/fn_go/modelsv2" "github.com/fnproject/fn_go/provider" "github.com/urfave/cli" ) type triggersCmd struct { provider provider.Provider client *fnclient.Fn } // TriggerFlags used to create/update triggers var TriggerFlags = []cli.Flag{ cli.StringFlag{ Name: "source,s", Usage: "trigger source", }, cli.StringFlag{ Name: "type, t", Usage: "Todo", }, cli.StringSliceFlag{ Name: "annotation", Usage: "fn annotation (can be specified multiple times)", }, } func (t *triggersCmd) create(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) app, err := app.GetAppByName(t.client, appName) if err != nil { return err } fn, err := fn.GetFnByName(t.client, app.ID, fnName) if err != nil { return err } trigger := &models.Trigger{ AppID: app.ID, FnID: fn.ID, } trigger.Name = triggerName if triggerType := c.String("type"); triggerType != "" { trigger.Type = triggerType } if triggerSource := c.String("source"); triggerSource != "" { trigger.Source = validateTriggerSource(triggerSource) } WithFlags(c, trigger) if trigger.Name == "" { return errors.New("triggerName path is missing") } return CreateTrigger(t.client, trigger) } func validateTriggerSource(ts string) string { if !strings.HasPrefix(ts, "/") { ts = "/" + ts } return ts } // CreateTrigger request func CreateTrigger(client *fnclient.Fn, trigger *models.Trigger) error { resp, err := client.Triggers.CreateTrigger(&apiTriggers.CreateTriggerParams{ Context: context.Background(), Body: trigger, }) if err != nil { switch e := err.(type) { case *apiTriggers.CreateTriggerBadRequest: fmt.Println(e) return fmt.Errorf("%s", e.Payload.Message) case *apiTriggers.CreateTriggerConflict: return fmt.Errorf("%s", e.Payload.Message) default: return err } } fmt.Println("Successfully created trigger:", resp.Payload.Name) endpoint := resp.Payload.Annotations["fnproject.io/trigger/httpEndpoint"] fmt.Println("Trigger Endpoint:", endpoint) return nil } func (t *triggersCmd)
(c *cli.Context) error { resTriggers, err := getTriggers(c, t.client) if err != nil { return err } fnName := c.Args().Get(1) w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0) if len(fnName) != 0 { fmt.Fprint(w, "NAME", "\t", "ID", "\t", "TYPE", "\t", "SOURCE", "\t", "ENDPOINT", "\n") for _, trigger := range resTriggers { endpoint := trigger.Annotations["fnproject.io/trigger/httpEndpoint"] fmt.Fprint(w, trigger.Name, "\t", trigger.ID, "\t", trigger.Type, "\t", trigger.Source, "\t", endpoint, "\n") } } else { fmt.Fprint(w, "FUNCTION", "\t", "NAME", "\t", "ID", "\t", "TYPE", "\t", "SOURCE", "\t", "ENDPOINT", "\n") for _, trigger := range resTriggers { endpoint := trigger.Annotations["fnproject.io/trigger/httpEndpoint"] resp, err := t.client.Fns.GetFn(&fns.GetFnParams{ FnID: trigger.FnID, Context: context.Background(), }) if err != nil { return err } fnName = resp.Payload.Name fmt.Fprint(w, fnName, "\t", trigger.Name, "\t", trigger.ID, "\t", trigger.Type, "\t", trigger.Source, "\t", endpoint, "\n") } } w.Flush() return nil } func getTriggers(c *cli.Context, client *fnclient.Fn) ([]*models.Trigger, error) { appName := c.Args().Get(0) fnName := c.Args().Get(1) var params *apiTriggers.ListTriggersParams app, err := app.GetAppByName(client, appName) if err != nil { return nil, err } if len(fnName) == 0 { params = &apiTriggers.ListTriggersParams{ Context: context.Background(), AppID: &app.ID, } } else { fn, err := fn.GetFnByName(client, app.ID, fnName) if err != nil { return nil, err } params = &apiTriggers.ListTriggersParams{ Context: context.Background(), AppID: &app.ID, FnID: &fn.ID, } } var resTriggers []*models.Trigger for { resp, err := client.Triggers.ListTriggers(params) if err != nil { return nil, err } n := c.Int64("n") resTriggers = append(resTriggers, resp.Payload.Items...) howManyMore := n - int64(len(resTriggers)+len(resp.Payload.Items)) if howManyMore <= 0 || resp.Payload.NextCursor == "" { break } params.Cursor = &resp.Payload.NextCursor } if len(resTriggers) == 0 { if len(fnName) == 0 { return nil, fmt.Errorf("no triggers found for app: %s", appName) } return nil, fmt.Errorf("no triggers found for function: %s", fnName) } return resTriggers, nil } // BashCompleteTriggers can be called from a BashComplete function // to provide function completion suggestions (Assumes the // current context already contains an app name and a function name // as the first 2 arguments. This should be confirmed before calling this) func BashCompleteTriggers(c *cli.Context) { provider, err := client.CurrentProvider() if err != nil { return } resp, err := getTriggers(c, provider.APIClientv2()) if err != nil { return } for _, t := range resp { fmt.Println(t.Name) } } func (t *triggersCmd) update(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) trigger, err := GetTrigger(t.client, appName, fnName, triggerName) if err != nil { return err } WithFlags(c, trigger) err = PutTrigger(t.client, trigger) if err != nil { return err } fmt.Println(appName, fnName, triggerName, "updated") return nil } // PutTrigger updates the provided trigger with new values func PutTrigger(t *fnclient.Fn, trigger *models.Trigger) error { _, err := t.Triggers.UpdateTrigger(&apiTriggers.UpdateTriggerParams{ Context: context.Background(), TriggerID: trigger.ID, Body: trigger, }) if err != nil { switch e := err.(type) { case *apiTriggers.UpdateTriggerBadRequest: return fmt.Errorf("%s", e.Payload.Message) default: return err } } return nil } func (t *triggersCmd) inspect(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) prop := c.Args().Get(3) trigger, err := GetTrigger(t.client, appName, fnName, triggerName) if err != nil { return err } if c.Bool("endpoint") { endpoint, ok := trigger.Annotations["fnproject.io/trigger/httpEndpoint"].(string) if !ok { return errors.New("missing or invalid http endpoint on trigger") } fmt.Println(endpoint) return nil } enc := json.NewEncoder(os.Stdout) enc.SetIndent("", "\t") if prop == "" { enc.Encode(trigger) return nil } data, err := json.Marshal(trigger) if err != nil { return fmt.Errorf("failed to inspect %s: %s", triggerName, err) } var inspect map[string]interface{} err = json.Unmarshal(data, &inspect) if err != nil { return fmt.Errorf("failed to inspect %s: %s", triggerName, err) } jq := jsonq.NewQuery(inspect) field, err := jq.Interface(strings.Split(prop, ".")...) if err != nil { return errors.New("failed to inspect %s field names") } enc.Encode(field) return nil } func (t *triggersCmd) delete(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) trigger, err := GetTrigger(t.client, appName, fnName, triggerName) if err != nil { return err } params := apiTriggers.NewDeleteTriggerParams() params.TriggerID = trigger.ID _, err = t.client.Triggers.DeleteTrigger(params) if err != nil { return err } fmt.Println(appName, fnName, triggerName, "deleted") return nil } // GetTrigger looks up a trigger using the provided client by app, function and trigger name func GetTrigger(client *fnclient.Fn, appName, fnName, triggerName string) (*models.Trigger, error) { app, err := app.GetAppByName(client, appName) if err != nil { return nil, err } fn, err := fn.GetFnByName(client, app.ID, fnName) if err != nil { return nil, err } trigger, err := GetTriggerByName(client, app.ID, fn.ID, triggerName) if err != nil { return nil, err } return trigger, nil } // GetTriggerByAppFnAndTriggerNames looks up a trigger using app, fn and trigger names func GetTriggerByAppFnAndTriggerNames(appName, fnName, triggerName string) (*models.Trigger, error) { provider, err := client.CurrentProvider() if err != nil { return nil, err } client := provider.APIClientv2() return GetTrigger(client, appName, fnName, triggerName) } // GetTriggerByName looks up a trigger using the provided client by app and function ID and trigger name func GetTriggerByName(client *fnclient.Fn, appID string, fnID string, triggerName string) (*models.Trigger, error) { triggerList, err := client.Triggers.ListTriggers(&apiTriggers.ListTriggersParams{ Context: context.Background(), AppID: &appID, FnID: &fnID, Name: &triggerName, }) if err != nil { return nil, err } if len(triggerList.Payload.Items) == 0 { return nil, NameNotFoundError{triggerName} } return triggerList.Payload.Items[0], nil } // WithFlags returns a trigger with the specified flags func WithFlags(c *cli.Context, t *models.Trigger) { if len(c.StringSlice("annotation")) > 0 { t.Annotations = common.ExtractAnnotations(c) } } // NameNotFoundError error for app not found when looked up by name type NameNotFoundError struct { Name string } func (n NameNotFoundError) Error() string { return fmt.Sprintf("trigger %s not found", n.Name) }
list
identifier_name
triggers.go
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package trigger import ( "context" "encoding/json" "errors" "fmt" "os" "strings" "text/tabwriter" "github.com/fnproject/fn_go/clientv2/fns" "github.com/jmoiron/jsonq" "github.com/fnproject/cli/client" "github.com/fnproject/cli/common" "github.com/fnproject/cli/objects/app" "github.com/fnproject/cli/objects/fn" fnclient "github.com/fnproject/fn_go/clientv2" apiTriggers "github.com/fnproject/fn_go/clientv2/triggers" models "github.com/fnproject/fn_go/modelsv2" "github.com/fnproject/fn_go/provider" "github.com/urfave/cli" ) type triggersCmd struct { provider provider.Provider client *fnclient.Fn } // TriggerFlags used to create/update triggers var TriggerFlags = []cli.Flag{ cli.StringFlag{ Name: "source,s", Usage: "trigger source", }, cli.StringFlag{ Name: "type, t", Usage: "Todo", }, cli.StringSliceFlag{ Name: "annotation", Usage: "fn annotation (can be specified multiple times)", }, } func (t *triggersCmd) create(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) app, err := app.GetAppByName(t.client, appName) if err != nil { return err } fn, err := fn.GetFnByName(t.client, app.ID, fnName) if err != nil { return err } trigger := &models.Trigger{ AppID: app.ID, FnID: fn.ID, } trigger.Name = triggerName if triggerType := c.String("type"); triggerType != "" { trigger.Type = triggerType } if triggerSource := c.String("source"); triggerSource != "" { trigger.Source = validateTriggerSource(triggerSource) } WithFlags(c, trigger) if trigger.Name == "" { return errors.New("triggerName path is missing") } return CreateTrigger(t.client, trigger) } func validateTriggerSource(ts string) string
// CreateTrigger request func CreateTrigger(client *fnclient.Fn, trigger *models.Trigger) error { resp, err := client.Triggers.CreateTrigger(&apiTriggers.CreateTriggerParams{ Context: context.Background(), Body: trigger, }) if err != nil { switch e := err.(type) { case *apiTriggers.CreateTriggerBadRequest: fmt.Println(e) return fmt.Errorf("%s", e.Payload.Message) case *apiTriggers.CreateTriggerConflict: return fmt.Errorf("%s", e.Payload.Message) default: return err } } fmt.Println("Successfully created trigger:", resp.Payload.Name) endpoint := resp.Payload.Annotations["fnproject.io/trigger/httpEndpoint"] fmt.Println("Trigger Endpoint:", endpoint) return nil } func (t *triggersCmd) list(c *cli.Context) error { resTriggers, err := getTriggers(c, t.client) if err != nil { return err } fnName := c.Args().Get(1) w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0) if len(fnName) != 0 { fmt.Fprint(w, "NAME", "\t", "ID", "\t", "TYPE", "\t", "SOURCE", "\t", "ENDPOINT", "\n") for _, trigger := range resTriggers { endpoint := trigger.Annotations["fnproject.io/trigger/httpEndpoint"] fmt.Fprint(w, trigger.Name, "\t", trigger.ID, "\t", trigger.Type, "\t", trigger.Source, "\t", endpoint, "\n") } } else { fmt.Fprint(w, "FUNCTION", "\t", "NAME", "\t", "ID", "\t", "TYPE", "\t", "SOURCE", "\t", "ENDPOINT", "\n") for _, trigger := range resTriggers { endpoint := trigger.Annotations["fnproject.io/trigger/httpEndpoint"] resp, err := t.client.Fns.GetFn(&fns.GetFnParams{ FnID: trigger.FnID, Context: context.Background(), }) if err != nil { return err } fnName = resp.Payload.Name fmt.Fprint(w, fnName, "\t", trigger.Name, "\t", trigger.ID, "\t", trigger.Type, "\t", trigger.Source, "\t", endpoint, "\n") } } w.Flush() return nil } func getTriggers(c *cli.Context, client *fnclient.Fn) ([]*models.Trigger, error) { appName := c.Args().Get(0) fnName := c.Args().Get(1) var params *apiTriggers.ListTriggersParams app, err := app.GetAppByName(client, appName) if err != nil { return nil, err } if len(fnName) == 0 { params = &apiTriggers.ListTriggersParams{ Context: context.Background(), AppID: &app.ID, } } else { fn, err := fn.GetFnByName(client, app.ID, fnName) if err != nil { return nil, err } params = &apiTriggers.ListTriggersParams{ Context: context.Background(), AppID: &app.ID, FnID: &fn.ID, } } var resTriggers []*models.Trigger for { resp, err := client.Triggers.ListTriggers(params) if err != nil { return nil, err } n := c.Int64("n") resTriggers = append(resTriggers, resp.Payload.Items...) howManyMore := n - int64(len(resTriggers)+len(resp.Payload.Items)) if howManyMore <= 0 || resp.Payload.NextCursor == "" { break } params.Cursor = &resp.Payload.NextCursor } if len(resTriggers) == 0 { if len(fnName) == 0 { return nil, fmt.Errorf("no triggers found for app: %s", appName) } return nil, fmt.Errorf("no triggers found for function: %s", fnName) } return resTriggers, nil } // BashCompleteTriggers can be called from a BashComplete function // to provide function completion suggestions (Assumes the // current context already contains an app name and a function name // as the first 2 arguments. This should be confirmed before calling this) func BashCompleteTriggers(c *cli.Context) { provider, err := client.CurrentProvider() if err != nil { return } resp, err := getTriggers(c, provider.APIClientv2()) if err != nil { return } for _, t := range resp { fmt.Println(t.Name) } } func (t *triggersCmd) update(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) trigger, err := GetTrigger(t.client, appName, fnName, triggerName) if err != nil { return err } WithFlags(c, trigger) err = PutTrigger(t.client, trigger) if err != nil { return err } fmt.Println(appName, fnName, triggerName, "updated") return nil } // PutTrigger updates the provided trigger with new values func PutTrigger(t *fnclient.Fn, trigger *models.Trigger) error { _, err := t.Triggers.UpdateTrigger(&apiTriggers.UpdateTriggerParams{ Context: context.Background(), TriggerID: trigger.ID, Body: trigger, }) if err != nil { switch e := err.(type) { case *apiTriggers.UpdateTriggerBadRequest: return fmt.Errorf("%s", e.Payload.Message) default: return err } } return nil } func (t *triggersCmd) inspect(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) prop := c.Args().Get(3) trigger, err := GetTrigger(t.client, appName, fnName, triggerName) if err != nil { return err } if c.Bool("endpoint") { endpoint, ok := trigger.Annotations["fnproject.io/trigger/httpEndpoint"].(string) if !ok { return errors.New("missing or invalid http endpoint on trigger") } fmt.Println(endpoint) return nil } enc := json.NewEncoder(os.Stdout) enc.SetIndent("", "\t") if prop == "" { enc.Encode(trigger) return nil } data, err := json.Marshal(trigger) if err != nil { return fmt.Errorf("failed to inspect %s: %s", triggerName, err) } var inspect map[string]interface{} err = json.Unmarshal(data, &inspect) if err != nil { return fmt.Errorf("failed to inspect %s: %s", triggerName, err) } jq := jsonq.NewQuery(inspect) field, err := jq.Interface(strings.Split(prop, ".")...) if err != nil { return errors.New("failed to inspect %s field names") } enc.Encode(field) return nil } func (t *triggersCmd) delete(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) trigger, err := GetTrigger(t.client, appName, fnName, triggerName) if err != nil { return err } params := apiTriggers.NewDeleteTriggerParams() params.TriggerID = trigger.ID _, err = t.client.Triggers.DeleteTrigger(params) if err != nil { return err } fmt.Println(appName, fnName, triggerName, "deleted") return nil } // GetTrigger looks up a trigger using the provided client by app, function and trigger name func GetTrigger(client *fnclient.Fn, appName, fnName, triggerName string) (*models.Trigger, error) { app, err := app.GetAppByName(client, appName) if err != nil { return nil, err } fn, err := fn.GetFnByName(client, app.ID, fnName) if err != nil { return nil, err } trigger, err := GetTriggerByName(client, app.ID, fn.ID, triggerName) if err != nil { return nil, err } return trigger, nil } // GetTriggerByAppFnAndTriggerNames looks up a trigger using app, fn and trigger names func GetTriggerByAppFnAndTriggerNames(appName, fnName, triggerName string) (*models.Trigger, error) { provider, err := client.CurrentProvider() if err != nil { return nil, err } client := provider.APIClientv2() return GetTrigger(client, appName, fnName, triggerName) } // GetTriggerByName looks up a trigger using the provided client by app and function ID and trigger name func GetTriggerByName(client *fnclient.Fn, appID string, fnID string, triggerName string) (*models.Trigger, error) { triggerList, err := client.Triggers.ListTriggers(&apiTriggers.ListTriggersParams{ Context: context.Background(), AppID: &appID, FnID: &fnID, Name: &triggerName, }) if err != nil { return nil, err } if len(triggerList.Payload.Items) == 0 { return nil, NameNotFoundError{triggerName} } return triggerList.Payload.Items[0], nil } // WithFlags returns a trigger with the specified flags func WithFlags(c *cli.Context, t *models.Trigger) { if len(c.StringSlice("annotation")) > 0 { t.Annotations = common.ExtractAnnotations(c) } } // NameNotFoundError error for app not found when looked up by name type NameNotFoundError struct { Name string } func (n NameNotFoundError) Error() string { return fmt.Sprintf("trigger %s not found", n.Name) }
{ if !strings.HasPrefix(ts, "/") { ts = "/" + ts } return ts }
identifier_body
triggers.go
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package trigger import ( "context" "encoding/json" "errors" "fmt" "os" "strings" "text/tabwriter" "github.com/fnproject/fn_go/clientv2/fns" "github.com/jmoiron/jsonq" "github.com/fnproject/cli/client" "github.com/fnproject/cli/common" "github.com/fnproject/cli/objects/app" "github.com/fnproject/cli/objects/fn" fnclient "github.com/fnproject/fn_go/clientv2" apiTriggers "github.com/fnproject/fn_go/clientv2/triggers" models "github.com/fnproject/fn_go/modelsv2" "github.com/fnproject/fn_go/provider" "github.com/urfave/cli" ) type triggersCmd struct { provider provider.Provider client *fnclient.Fn } // TriggerFlags used to create/update triggers var TriggerFlags = []cli.Flag{ cli.StringFlag{ Name: "source,s", Usage: "trigger source", }, cli.StringFlag{ Name: "type, t", Usage: "Todo", }, cli.StringSliceFlag{ Name: "annotation", Usage: "fn annotation (can be specified multiple times)", }, } func (t *triggersCmd) create(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) app, err := app.GetAppByName(t.client, appName) if err != nil { return err } fn, err := fn.GetFnByName(t.client, app.ID, fnName) if err != nil { return err } trigger := &models.Trigger{ AppID: app.ID, FnID: fn.ID, } trigger.Name = triggerName if triggerType := c.String("type"); triggerType != "" { trigger.Type = triggerType } if triggerSource := c.String("source"); triggerSource != "" { trigger.Source = validateTriggerSource(triggerSource) } WithFlags(c, trigger) if trigger.Name == "" { return errors.New("triggerName path is missing") } return CreateTrigger(t.client, trigger) } func validateTriggerSource(ts string) string { if !strings.HasPrefix(ts, "/") { ts = "/" + ts } return ts } // CreateTrigger request func CreateTrigger(client *fnclient.Fn, trigger *models.Trigger) error { resp, err := client.Triggers.CreateTrigger(&apiTriggers.CreateTriggerParams{ Context: context.Background(), Body: trigger, }) if err != nil { switch e := err.(type) { case *apiTriggers.CreateTriggerBadRequest: fmt.Println(e) return fmt.Errorf("%s", e.Payload.Message) case *apiTriggers.CreateTriggerConflict: return fmt.Errorf("%s", e.Payload.Message) default: return err } } fmt.Println("Successfully created trigger:", resp.Payload.Name) endpoint := resp.Payload.Annotations["fnproject.io/trigger/httpEndpoint"] fmt.Println("Trigger Endpoint:", endpoint) return nil } func (t *triggersCmd) list(c *cli.Context) error { resTriggers, err := getTriggers(c, t.client) if err != nil { return err } fnName := c.Args().Get(1) w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0) if len(fnName) != 0 { fmt.Fprint(w, "NAME", "\t", "ID", "\t", "TYPE", "\t", "SOURCE", "\t", "ENDPOINT", "\n") for _, trigger := range resTriggers { endpoint := trigger.Annotations["fnproject.io/trigger/httpEndpoint"] fmt.Fprint(w, trigger.Name, "\t", trigger.ID, "\t", trigger.Type, "\t", trigger.Source, "\t", endpoint, "\n") } } else { fmt.Fprint(w, "FUNCTION", "\t", "NAME", "\t", "ID", "\t", "TYPE", "\t", "SOURCE", "\t", "ENDPOINT", "\n") for _, trigger := range resTriggers { endpoint := trigger.Annotations["fnproject.io/trigger/httpEndpoint"] resp, err := t.client.Fns.GetFn(&fns.GetFnParams{ FnID: trigger.FnID, Context: context.Background(), }) if err != nil { return err } fnName = resp.Payload.Name fmt.Fprint(w, fnName, "\t", trigger.Name, "\t", trigger.ID, "\t", trigger.Type, "\t", trigger.Source, "\t", endpoint, "\n") } } w.Flush() return nil } func getTriggers(c *cli.Context, client *fnclient.Fn) ([]*models.Trigger, error) { appName := c.Args().Get(0) fnName := c.Args().Get(1) var params *apiTriggers.ListTriggersParams app, err := app.GetAppByName(client, appName) if err != nil { return nil, err } if len(fnName) == 0 { params = &apiTriggers.ListTriggersParams{ Context: context.Background(), AppID: &app.ID, } } else { fn, err := fn.GetFnByName(client, app.ID, fnName) if err != nil { return nil, err } params = &apiTriggers.ListTriggersParams{ Context: context.Background(), AppID: &app.ID, FnID: &fn.ID, } } var resTriggers []*models.Trigger for { resp, err := client.Triggers.ListTriggers(params) if err != nil { return nil, err } n := c.Int64("n") resTriggers = append(resTriggers, resp.Payload.Items...) howManyMore := n - int64(len(resTriggers)+len(resp.Payload.Items)) if howManyMore <= 0 || resp.Payload.NextCursor == "" { break } params.Cursor = &resp.Payload.NextCursor } if len(resTriggers) == 0 { if len(fnName) == 0 { return nil, fmt.Errorf("no triggers found for app: %s", appName) } return nil, fmt.Errorf("no triggers found for function: %s", fnName) } return resTriggers, nil } // BashCompleteTriggers can be called from a BashComplete function // to provide function completion suggestions (Assumes the // current context already contains an app name and a function name // as the first 2 arguments. This should be confirmed before calling this) func BashCompleteTriggers(c *cli.Context) { provider, err := client.CurrentProvider() if err != nil { return } resp, err := getTriggers(c, provider.APIClientv2()) if err != nil { return } for _, t := range resp { fmt.Println(t.Name) } } func (t *triggersCmd) update(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) trigger, err := GetTrigger(t.client, appName, fnName, triggerName) if err != nil { return err } WithFlags(c, trigger) err = PutTrigger(t.client, trigger) if err != nil { return err } fmt.Println(appName, fnName, triggerName, "updated") return nil } // PutTrigger updates the provided trigger with new values func PutTrigger(t *fnclient.Fn, trigger *models.Trigger) error { _, err := t.Triggers.UpdateTrigger(&apiTriggers.UpdateTriggerParams{ Context: context.Background(), TriggerID: trigger.ID, Body: trigger, }) if err != nil { switch e := err.(type) { case *apiTriggers.UpdateTriggerBadRequest: return fmt.Errorf("%s", e.Payload.Message) default: return err } } return nil } func (t *triggersCmd) inspect(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) prop := c.Args().Get(3) trigger, err := GetTrigger(t.client, appName, fnName, triggerName) if err != nil { return err } if c.Bool("endpoint") { endpoint, ok := trigger.Annotations["fnproject.io/trigger/httpEndpoint"].(string) if !ok { return errors.New("missing or invalid http endpoint on trigger") } fmt.Println(endpoint) return nil } enc := json.NewEncoder(os.Stdout) enc.SetIndent("", "\t") if prop == "" { enc.Encode(trigger) return nil } data, err := json.Marshal(trigger) if err != nil { return fmt.Errorf("failed to inspect %s: %s", triggerName, err) } var inspect map[string]interface{} err = json.Unmarshal(data, &inspect) if err != nil { return fmt.Errorf("failed to inspect %s: %s", triggerName, err) } jq := jsonq.NewQuery(inspect) field, err := jq.Interface(strings.Split(prop, ".")...) if err != nil { return errors.New("failed to inspect %s field names") } enc.Encode(field) return nil } func (t *triggersCmd) delete(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) trigger, err := GetTrigger(t.client, appName, fnName, triggerName) if err != nil { return err } params := apiTriggers.NewDeleteTriggerParams() params.TriggerID = trigger.ID _, err = t.client.Triggers.DeleteTrigger(params) if err != nil { return err } fmt.Println(appName, fnName, triggerName, "deleted") return nil } // GetTrigger looks up a trigger using the provided client by app, function and trigger name func GetTrigger(client *fnclient.Fn, appName, fnName, triggerName string) (*models.Trigger, error) { app, err := app.GetAppByName(client, appName) if err != nil
fn, err := fn.GetFnByName(client, app.ID, fnName) if err != nil { return nil, err } trigger, err := GetTriggerByName(client, app.ID, fn.ID, triggerName) if err != nil { return nil, err } return trigger, nil } // GetTriggerByAppFnAndTriggerNames looks up a trigger using app, fn and trigger names func GetTriggerByAppFnAndTriggerNames(appName, fnName, triggerName string) (*models.Trigger, error) { provider, err := client.CurrentProvider() if err != nil { return nil, err } client := provider.APIClientv2() return GetTrigger(client, appName, fnName, triggerName) } // GetTriggerByName looks up a trigger using the provided client by app and function ID and trigger name func GetTriggerByName(client *fnclient.Fn, appID string, fnID string, triggerName string) (*models.Trigger, error) { triggerList, err := client.Triggers.ListTriggers(&apiTriggers.ListTriggersParams{ Context: context.Background(), AppID: &appID, FnID: &fnID, Name: &triggerName, }) if err != nil { return nil, err } if len(triggerList.Payload.Items) == 0 { return nil, NameNotFoundError{triggerName} } return triggerList.Payload.Items[0], nil } // WithFlags returns a trigger with the specified flags func WithFlags(c *cli.Context, t *models.Trigger) { if len(c.StringSlice("annotation")) > 0 { t.Annotations = common.ExtractAnnotations(c) } } // NameNotFoundError error for app not found when looked up by name type NameNotFoundError struct { Name string } func (n NameNotFoundError) Error() string { return fmt.Sprintf("trigger %s not found", n.Name) }
{ return nil, err }
conditional_block
triggers.go
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package trigger import ( "context" "encoding/json" "errors" "fmt" "os" "strings" "text/tabwriter" "github.com/fnproject/fn_go/clientv2/fns" "github.com/jmoiron/jsonq" "github.com/fnproject/cli/client" "github.com/fnproject/cli/common" "github.com/fnproject/cli/objects/app" "github.com/fnproject/cli/objects/fn" fnclient "github.com/fnproject/fn_go/clientv2" apiTriggers "github.com/fnproject/fn_go/clientv2/triggers" models "github.com/fnproject/fn_go/modelsv2" "github.com/fnproject/fn_go/provider" "github.com/urfave/cli" ) type triggersCmd struct { provider provider.Provider client *fnclient.Fn } // TriggerFlags used to create/update triggers var TriggerFlags = []cli.Flag{ cli.StringFlag{ Name: "source,s", Usage: "trigger source", }, cli.StringFlag{ Name: "type, t", Usage: "Todo", }, cli.StringSliceFlag{ Name: "annotation", Usage: "fn annotation (can be specified multiple times)", }, } func (t *triggersCmd) create(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) app, err := app.GetAppByName(t.client, appName) if err != nil { return err } fn, err := fn.GetFnByName(t.client, app.ID, fnName) if err != nil { return err } trigger := &models.Trigger{ AppID: app.ID, FnID: fn.ID, } trigger.Name = triggerName if triggerType := c.String("type"); triggerType != "" { trigger.Type = triggerType } if triggerSource := c.String("source"); triggerSource != "" { trigger.Source = validateTriggerSource(triggerSource) } WithFlags(c, trigger) if trigger.Name == "" { return errors.New("triggerName path is missing") } return CreateTrigger(t.client, trigger) } func validateTriggerSource(ts string) string { if !strings.HasPrefix(ts, "/") { ts = "/" + ts } return ts } // CreateTrigger request func CreateTrigger(client *fnclient.Fn, trigger *models.Trigger) error { resp, err := client.Triggers.CreateTrigger(&apiTriggers.CreateTriggerParams{ Context: context.Background(), Body: trigger, }) if err != nil { switch e := err.(type) { case *apiTriggers.CreateTriggerBadRequest: fmt.Println(e) return fmt.Errorf("%s", e.Payload.Message) case *apiTriggers.CreateTriggerConflict: return fmt.Errorf("%s", e.Payload.Message) default: return err }
endpoint := resp.Payload.Annotations["fnproject.io/trigger/httpEndpoint"] fmt.Println("Trigger Endpoint:", endpoint) return nil } func (t *triggersCmd) list(c *cli.Context) error { resTriggers, err := getTriggers(c, t.client) if err != nil { return err } fnName := c.Args().Get(1) w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0) if len(fnName) != 0 { fmt.Fprint(w, "NAME", "\t", "ID", "\t", "TYPE", "\t", "SOURCE", "\t", "ENDPOINT", "\n") for _, trigger := range resTriggers { endpoint := trigger.Annotations["fnproject.io/trigger/httpEndpoint"] fmt.Fprint(w, trigger.Name, "\t", trigger.ID, "\t", trigger.Type, "\t", trigger.Source, "\t", endpoint, "\n") } } else { fmt.Fprint(w, "FUNCTION", "\t", "NAME", "\t", "ID", "\t", "TYPE", "\t", "SOURCE", "\t", "ENDPOINT", "\n") for _, trigger := range resTriggers { endpoint := trigger.Annotations["fnproject.io/trigger/httpEndpoint"] resp, err := t.client.Fns.GetFn(&fns.GetFnParams{ FnID: trigger.FnID, Context: context.Background(), }) if err != nil { return err } fnName = resp.Payload.Name fmt.Fprint(w, fnName, "\t", trigger.Name, "\t", trigger.ID, "\t", trigger.Type, "\t", trigger.Source, "\t", endpoint, "\n") } } w.Flush() return nil } func getTriggers(c *cli.Context, client *fnclient.Fn) ([]*models.Trigger, error) { appName := c.Args().Get(0) fnName := c.Args().Get(1) var params *apiTriggers.ListTriggersParams app, err := app.GetAppByName(client, appName) if err != nil { return nil, err } if len(fnName) == 0 { params = &apiTriggers.ListTriggersParams{ Context: context.Background(), AppID: &app.ID, } } else { fn, err := fn.GetFnByName(client, app.ID, fnName) if err != nil { return nil, err } params = &apiTriggers.ListTriggersParams{ Context: context.Background(), AppID: &app.ID, FnID: &fn.ID, } } var resTriggers []*models.Trigger for { resp, err := client.Triggers.ListTriggers(params) if err != nil { return nil, err } n := c.Int64("n") resTriggers = append(resTriggers, resp.Payload.Items...) howManyMore := n - int64(len(resTriggers)+len(resp.Payload.Items)) if howManyMore <= 0 || resp.Payload.NextCursor == "" { break } params.Cursor = &resp.Payload.NextCursor } if len(resTriggers) == 0 { if len(fnName) == 0 { return nil, fmt.Errorf("no triggers found for app: %s", appName) } return nil, fmt.Errorf("no triggers found for function: %s", fnName) } return resTriggers, nil } // BashCompleteTriggers can be called from a BashComplete function // to provide function completion suggestions (Assumes the // current context already contains an app name and a function name // as the first 2 arguments. This should be confirmed before calling this) func BashCompleteTriggers(c *cli.Context) { provider, err := client.CurrentProvider() if err != nil { return } resp, err := getTriggers(c, provider.APIClientv2()) if err != nil { return } for _, t := range resp { fmt.Println(t.Name) } } func (t *triggersCmd) update(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) trigger, err := GetTrigger(t.client, appName, fnName, triggerName) if err != nil { return err } WithFlags(c, trigger) err = PutTrigger(t.client, trigger) if err != nil { return err } fmt.Println(appName, fnName, triggerName, "updated") return nil } // PutTrigger updates the provided trigger with new values func PutTrigger(t *fnclient.Fn, trigger *models.Trigger) error { _, err := t.Triggers.UpdateTrigger(&apiTriggers.UpdateTriggerParams{ Context: context.Background(), TriggerID: trigger.ID, Body: trigger, }) if err != nil { switch e := err.(type) { case *apiTriggers.UpdateTriggerBadRequest: return fmt.Errorf("%s", e.Payload.Message) default: return err } } return nil } func (t *triggersCmd) inspect(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) prop := c.Args().Get(3) trigger, err := GetTrigger(t.client, appName, fnName, triggerName) if err != nil { return err } if c.Bool("endpoint") { endpoint, ok := trigger.Annotations["fnproject.io/trigger/httpEndpoint"].(string) if !ok { return errors.New("missing or invalid http endpoint on trigger") } fmt.Println(endpoint) return nil } enc := json.NewEncoder(os.Stdout) enc.SetIndent("", "\t") if prop == "" { enc.Encode(trigger) return nil } data, err := json.Marshal(trigger) if err != nil { return fmt.Errorf("failed to inspect %s: %s", triggerName, err) } var inspect map[string]interface{} err = json.Unmarshal(data, &inspect) if err != nil { return fmt.Errorf("failed to inspect %s: %s", triggerName, err) } jq := jsonq.NewQuery(inspect) field, err := jq.Interface(strings.Split(prop, ".")...) if err != nil { return errors.New("failed to inspect %s field names") } enc.Encode(field) return nil } func (t *triggersCmd) delete(c *cli.Context) error { appName := c.Args().Get(0) fnName := c.Args().Get(1) triggerName := c.Args().Get(2) trigger, err := GetTrigger(t.client, appName, fnName, triggerName) if err != nil { return err } params := apiTriggers.NewDeleteTriggerParams() params.TriggerID = trigger.ID _, err = t.client.Triggers.DeleteTrigger(params) if err != nil { return err } fmt.Println(appName, fnName, triggerName, "deleted") return nil } // GetTrigger looks up a trigger using the provided client by app, function and trigger name func GetTrigger(client *fnclient.Fn, appName, fnName, triggerName string) (*models.Trigger, error) { app, err := app.GetAppByName(client, appName) if err != nil { return nil, err } fn, err := fn.GetFnByName(client, app.ID, fnName) if err != nil { return nil, err } trigger, err := GetTriggerByName(client, app.ID, fn.ID, triggerName) if err != nil { return nil, err } return trigger, nil } // GetTriggerByAppFnAndTriggerNames looks up a trigger using app, fn and trigger names func GetTriggerByAppFnAndTriggerNames(appName, fnName, triggerName string) (*models.Trigger, error) { provider, err := client.CurrentProvider() if err != nil { return nil, err } client := provider.APIClientv2() return GetTrigger(client, appName, fnName, triggerName) } // GetTriggerByName looks up a trigger using the provided client by app and function ID and trigger name func GetTriggerByName(client *fnclient.Fn, appID string, fnID string, triggerName string) (*models.Trigger, error) { triggerList, err := client.Triggers.ListTriggers(&apiTriggers.ListTriggersParams{ Context: context.Background(), AppID: &appID, FnID: &fnID, Name: &triggerName, }) if err != nil { return nil, err } if len(triggerList.Payload.Items) == 0 { return nil, NameNotFoundError{triggerName} } return triggerList.Payload.Items[0], nil } // WithFlags returns a trigger with the specified flags func WithFlags(c *cli.Context, t *models.Trigger) { if len(c.StringSlice("annotation")) > 0 { t.Annotations = common.ExtractAnnotations(c) } } // NameNotFoundError error for app not found when looked up by name type NameNotFoundError struct { Name string } func (n NameNotFoundError) Error() string { return fmt.Sprintf("trigger %s not found", n.Name) }
} fmt.Println("Successfully created trigger:", resp.Payload.Name)
random_line_split
sql_utils.rs
//! Module for SQL Utility functions use diesel::prelude::*; use std::{ borrow::Cow, fs::File, io::BufReader, path::Path, }; use crate::error::IOErrorToError; use super::archive::import::{ detect_archive_type, import_ytdlr_json_archive, ArchiveType, ImportProgress, }; /// All migrations from "libytdlr/migrations" embedded into the binary pub const MIGRATIONS: diesel_migrations::EmbeddedMigrations = diesel_migrations::embed_migrations!(); /// Open a SQLite Connection for `sqlite_path` and apply sqlite migrations /// does not migrate archive formats, use [migrate_and_connect] instead pub fn sqlite_connect<P: AsRef<Path>>(sqlite_path: P) -> Result<SqliteConnection, crate::Error> { // having to convert the path to "str" because diesel (and underlying sqlite library) only accept strings return match sqlite_path.as_ref().to_str() { Some(path) => { let mut connection = SqliteConnection::establish(path)?; apply_sqlite_migrations(&mut connection)?; return Ok(connection); }, None => Err(crate::Error::other(format!("SQLite only accepts UTF-8 Paths, and given path failed to be converted to a string without being lossy, Path (converted lossy): \"{}\"", sqlite_path.as_ref().to_string_lossy()))), }; } /// Apply all (up) migrations to a SQLite Database #[inline] fn apply_sqlite_migrations(connection: &mut SqliteConnection) -> Result<(), crate::Error> { let applied = diesel_migrations::MigrationHarness::run_pending_migrations(connection, MIGRATIONS) .map_err(|err| return crate::Error::other(format!("Applying SQL Migrations Errored! Error:\n{err}")))?; debug!("Applied Migrations: {:?}", applied); return Ok(()); } /// Check if the input path is a sql database, if not migrate to sql and return new path and open connection /// Parameter `pgcb` will be used when migration will be applied /// /// This function is intended to be used over [`sqlite_connect`] in all non-test cases pub fn migrate_and_connect<S: FnMut(ImportProgress)>( archive_path: &Path, pgcb: S, ) -> Result<(Cow<Path>, SqliteConnection), crate::Error> { // early return in case the file does not actually exist if !archive_path.exists() { return Ok((archive_path.into(), sqlite_connect(archive_path)?)); } let migrate_to_path = { let mut tmp = archive_path.to_path_buf(); tmp.set_extension("db"); tmp }; // check if the "migrate-to" path already exists, and use that directly instead or error of already existing if migrate_to_path.exists() { if !migrate_to_path.is_file() { return Err(crate::Error::not_a_file( "Migrate-To Path exists but is not a file!", migrate_to_path, )); } let mut sqlite_path_reader = BufReader::new(File::open(&migrate_to_path).attach_path_err(&migrate_to_path)?); return Ok( match detect_archive_type(&mut sqlite_path_reader)? { ArchiveType::Unknown => return Err(crate::Error::other(format!("Migrate-To Path already exists, but is of unknown type! Path: \"{}\"", migrate_to_path.to_string_lossy()))), ArchiveType::JSON => return Err(crate::Error::other(format!("Migrate-To Path already exists and is a JSON archive, please rename it and retry the migration! Path: \"{}\"", migrate_to_path.to_string_lossy()))), ArchiveType::SQLite => { // this has to be done before, because the following ".into" call will move the value let connection = sqlite_connect(&migrate_to_path)?; (migrate_to_path.into(), connection) }, }, ); } let mut input_archive_reader = BufReader::new(File::open(archive_path).attach_path_err(archive_path)?); return Ok(match detect_archive_type(&mut input_archive_reader)? { ArchiveType::Unknown => { return Err(crate::Error::other( "Unknown Archive type to migrate, maybe try importing", )) }, ArchiveType::JSON => { debug!("Applying Migration from JSON to SQLite"); // handle case where the input path matches the changed path if migrate_to_path == archive_path { return Err(crate::Error::other( "Migration cannot be done: Input path matches output path (setting extension to \".db\")", )); } let mut connection = sqlite_connect(&migrate_to_path)?; import_ytdlr_json_archive(&mut input_archive_reader, &mut connection, pgcb)?; debug!("Migration from JSON to SQLite done"); (migrate_to_path.into(), connection) }, ArchiveType::SQLite => (archive_path.into(), sqlite_connect(archive_path)?), }); } #[cfg(test)] mod test { use super::*; use tempfile::{ Builder as TempBuilder, TempDir, }; fn create_connection() -> (SqliteConnection, TempDir) { let testdir = TempBuilder::new() .prefix("ytdl-test-sqlite-") .tempdir() .expect("Expected a temp dir to be created"); // chrono is used to create a different database for each thread let path = testdir.as_ref().join(format!("{}-sqlite.db", chrono::Utc::now())); // remove if already exists to have a clean test if path.exists() { std::fs::remove_file(&path).expect("Expected the file to be removed"); } return ( crate::main::sql_utils::sqlite_connect(&path).expect("Expected SQLite to successfully start"), testdir, ); } mod connect { use super::*; use std::{ ffi::OsString, os::unix::prelude::OsStringExt, }; #[test] fn test_connect() { let testdir = TempBuilder::new() .prefix("ytdl-test-sqliteConnect-") .tempdir() .expect("Expected a temp dir to be created"); let path = testdir.as_ref().join(format!("{}-sqlite.db", chrono::Utc::now())); std::fs::create_dir_all(path.parent().expect("Expected the file to have a parent")) .expect("expected the directory to be created"); let connection = sqlite_connect(path); assert!(connection.is_ok()); } // it seems like non-utf8 paths are a pain to create os-independently, so it is just linux where the following works #[cfg(target_os = "linux")] #[test] fn test_connect_notutf8() { let path = OsString::from_vec(vec![255]); let err = sqlite_connect(path); assert!(err.is_err()); // Not using "unwrap_err", because of https://github.com/diesel-rs/diesel/discussions/3124 let err = match err { Ok(_) => panic!("Expected a Error value"), Err(err) => err, }; // the following is only a "contains", because of the abitrary path that could be after it assert!(err.to_string().contains("SQLite only accepts UTF-8 Paths, and given path failed to be converted to a string without being lossy, Path (converted lossy):")); } } mod apply_sqlite_migrations { use super::*; #[test] fn test_all_migrations_applied() { let (mut connection, _tempdir) = create_connection(); let res = diesel_migrations::MigrationHarness::has_pending_migration(&mut connection, MIGRATIONS); assert!(res.is_ok()); let res = res.unwrap(); assert!(!res); } } mod migrate_and_connect { use std::{ ffi::OsStr, io::{ BufWriter, Write, }, ops::Deref, path::PathBuf, sync::RwLock, }; use super::*; fn gen_archive_path<P: AsRef<OsStr>>(extension: P) -> (PathBuf, TempDir) { let testdir = TempBuilder::new() .prefix("ytdl-test-sqliteMigrate-") .tempdir() .expect("Expected a temp dir to be created"); let mut path = testdir.as_ref().join(format!("{}-gen_archive", uuid::Uuid::new_v4())); path.set_extension(extension); println!("generated: {}", path.to_string_lossy()); // clear generated path clear_path(&path); { let mut migrate_to_path = path.clone(); migrate_to_path.set_extension("db"); // clear migrate_to_path clear_path(migrate_to_path); } return (path, testdir); } fn clear_path<P: AsRef<Path>>(path: P) { let path = path.as_ref(); if path.exists() { std::fs::remove_file(path).expect("Expected file to be removed"); } } fn create_dir_all_parent<P: AsRef<Path>>(path: P) { let path = path.as_ref(); std::fs::create_dir_all(path.parent().expect("Expected the file to have a parent")) .expect("expected the directory to be created"); } fn write_file_with_content<S: AsRef<str>, P: AsRef<OsStr>>(input: S, extension: P) -> (PathBuf, TempDir) { let (path, tempdir) = gen_archive_path(extension); create_dir_all_parent(&path); let mut file = BufWriter::new(std::fs::File::create(&path).expect("Expected file to be created")); file.write_all(input.as_ref().as_bytes()) .expect("Expected successfull file write"); return (path, tempdir); } /// Test utility function for easy callbacks fn callback_counter(c: &RwLock<Vec<ImportProgress>>) -> impl FnMut(ImportProgress) + '_
#[test] fn test_input_unknown_archive() { let string0 = " youtube ____________ youtube ------------ youtube aaaaaaaaaaaa soundcloud 0000000000 "; let (path, _tempdir) = write_file_with_content(string0, "unknown_ytdl"); let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_err()); let res = match res { Ok(_) => panic!("Expected a Error value"), Err(err) => err, }; assert!(res .to_string() .contains("Unknown Archive type to migrate, maybe try importing")); assert_eq!(0, pgcounter.read().expect("read failed").len()); } #[test] fn test_input_sqlite_archive() { let (path, _tempdir) = gen_archive_path("db_sqlite"); create_dir_all_parent(&path); { // create database file assert!(sqlite_connect(&path).is_ok()); } let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_ok()); let res = res.unwrap(); assert_eq!(&path, res.0.as_ref()); assert_eq!(0, pgcounter.read().expect("read failed").len()); } #[test] fn test_input_json_archive() { let string0 = r#" { "version": "0.1.0", "videos": [ { "id": "____________", "provider": "youtube", "dlFinished": true, "editAsked": true, "fileName": "someFile1.mp3" }, { "id": "------------", "provider": "youtube", "dlFinished": false, "editAsked": true, "fileName": "someFile2.mp3" }, { "id": "aaaaaaaaaaaa", "provider": "youtube", "dlFinished": true, "editAsked": false, "fileName": "someFile3.mp3" }, { "id": "0000000000", "provider": "soundcloud", "dlFinished": true, "editAsked": true, "fileName": "someFile4.mp3" } ] } "#; let (path, _tempdir) = write_file_with_content(string0, "json_json"); let expected_path = { let mut tmp = path.clone(); tmp.set_extension("db"); tmp }; clear_path(&expected_path); let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_ok()); let res = res.unwrap(); assert_eq!(&expected_path, res.0.as_ref()); assert_eq!( &vec![ ImportProgress::Starting, ImportProgress::SizeHint(4), // Size Hint of 4, because of a intermediate array length // index start at 0, thanks to json array index ImportProgress::Increase(1, 0), ImportProgress::Increase(1, 1), ImportProgress::Increase(1, 2), ImportProgress::Increase(1, 3), ImportProgress::Finished(4) ], pgcounter.read().expect("failed to read").deref() ); } #[test] fn test_to_existing_json() { let string0 = r#" { } "#; let (path, _tempdir) = write_file_with_content(string0, "db"); let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_err()); let res = match res { Ok(_) => panic!("Expected a Error value"), Err(err) => err, }; assert_eq!( res.to_string(), format!("Other: Migrate-To Path already exists and is a JSON archive, please rename it and retry the migration! Path: \"{}\"", path.to_string_lossy()) ); assert_eq!(0, pgcounter.read().expect("read failed").len()); } #[test] fn test_to_existing_unknown() { let string0 = " youtube ____________ youtube ------------ youtube aaaaaaaaaaaa soundcloud 0000000000 "; let (path, _tempdir) = write_file_with_content(string0, "db"); let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_err()); let res = match res { Ok(_) => panic!("Expected a Error value"), Err(err) => err, }; assert_eq!( res.to_string(), format!( "Other: Migrate-To Path already exists, but is of unknown type! Path: \"{}\"", path.to_string_lossy() ) ); assert_eq!(0, pgcounter.read().expect("read failed").len()); } #[test] fn test_to_existing_sqlite() { let (path, _tempdir) = gen_archive_path("db"); create_dir_all_parent(&path); { // create database file assert!(sqlite_connect(&path).is_ok()); } let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_ok()); let res = res.unwrap(); assert_eq!(&path, res.0.as_ref()); assert_eq!(0, pgcounter.read().expect("read failed").len()); } } }
{ return |imp| c.write().expect("write failed").push(imp); }
identifier_body
sql_utils.rs
//! Module for SQL Utility functions use diesel::prelude::*; use std::{ borrow::Cow, fs::File, io::BufReader, path::Path, }; use crate::error::IOErrorToError; use super::archive::import::{ detect_archive_type, import_ytdlr_json_archive, ArchiveType, ImportProgress, }; /// All migrations from "libytdlr/migrations" embedded into the binary pub const MIGRATIONS: diesel_migrations::EmbeddedMigrations = diesel_migrations::embed_migrations!(); /// Open a SQLite Connection for `sqlite_path` and apply sqlite migrations /// does not migrate archive formats, use [migrate_and_connect] instead pub fn sqlite_connect<P: AsRef<Path>>(sqlite_path: P) -> Result<SqliteConnection, crate::Error> { // having to convert the path to "str" because diesel (and underlying sqlite library) only accept strings return match sqlite_path.as_ref().to_str() { Some(path) => { let mut connection = SqliteConnection::establish(path)?; apply_sqlite_migrations(&mut connection)?; return Ok(connection); }, None => Err(crate::Error::other(format!("SQLite only accepts UTF-8 Paths, and given path failed to be converted to a string without being lossy, Path (converted lossy): \"{}\"", sqlite_path.as_ref().to_string_lossy()))), }; } /// Apply all (up) migrations to a SQLite Database #[inline] fn apply_sqlite_migrations(connection: &mut SqliteConnection) -> Result<(), crate::Error> { let applied = diesel_migrations::MigrationHarness::run_pending_migrations(connection, MIGRATIONS) .map_err(|err| return crate::Error::other(format!("Applying SQL Migrations Errored! Error:\n{err}")))?; debug!("Applied Migrations: {:?}", applied); return Ok(()); } /// Check if the input path is a sql database, if not migrate to sql and return new path and open connection /// Parameter `pgcb` will be used when migration will be applied /// /// This function is intended to be used over [`sqlite_connect`] in all non-test cases pub fn migrate_and_connect<S: FnMut(ImportProgress)>( archive_path: &Path, pgcb: S, ) -> Result<(Cow<Path>, SqliteConnection), crate::Error> { // early return in case the file does not actually exist if !archive_path.exists() { return Ok((archive_path.into(), sqlite_connect(archive_path)?)); } let migrate_to_path = { let mut tmp = archive_path.to_path_buf(); tmp.set_extension("db"); tmp }; // check if the "migrate-to" path already exists, and use that directly instead or error of already existing if migrate_to_path.exists() { if !migrate_to_path.is_file() { return Err(crate::Error::not_a_file( "Migrate-To Path exists but is not a file!", migrate_to_path, )); } let mut sqlite_path_reader = BufReader::new(File::open(&migrate_to_path).attach_path_err(&migrate_to_path)?); return Ok( match detect_archive_type(&mut sqlite_path_reader)? { ArchiveType::Unknown => return Err(crate::Error::other(format!("Migrate-To Path already exists, but is of unknown type! Path: \"{}\"", migrate_to_path.to_string_lossy()))), ArchiveType::JSON => return Err(crate::Error::other(format!("Migrate-To Path already exists and is a JSON archive, please rename it and retry the migration! Path: \"{}\"", migrate_to_path.to_string_lossy()))), ArchiveType::SQLite => { // this has to be done before, because the following ".into" call will move the value let connection = sqlite_connect(&migrate_to_path)?; (migrate_to_path.into(), connection) }, }, ); } let mut input_archive_reader = BufReader::new(File::open(archive_path).attach_path_err(archive_path)?); return Ok(match detect_archive_type(&mut input_archive_reader)? { ArchiveType::Unknown => { return Err(crate::Error::other( "Unknown Archive type to migrate, maybe try importing", )) }, ArchiveType::JSON => { debug!("Applying Migration from JSON to SQLite"); // handle case where the input path matches the changed path if migrate_to_path == archive_path { return Err(crate::Error::other( "Migration cannot be done: Input path matches output path (setting extension to \".db\")", )); } let mut connection = sqlite_connect(&migrate_to_path)?; import_ytdlr_json_archive(&mut input_archive_reader, &mut connection, pgcb)?; debug!("Migration from JSON to SQLite done"); (migrate_to_path.into(), connection) }, ArchiveType::SQLite => (archive_path.into(), sqlite_connect(archive_path)?), }); } #[cfg(test)] mod test { use super::*; use tempfile::{ Builder as TempBuilder, TempDir, }; fn create_connection() -> (SqliteConnection, TempDir) { let testdir = TempBuilder::new() .prefix("ytdl-test-sqlite-") .tempdir() .expect("Expected a temp dir to be created"); // chrono is used to create a different database for each thread let path = testdir.as_ref().join(format!("{}-sqlite.db", chrono::Utc::now())); // remove if already exists to have a clean test if path.exists() { std::fs::remove_file(&path).expect("Expected the file to be removed"); } return ( crate::main::sql_utils::sqlite_connect(&path).expect("Expected SQLite to successfully start"), testdir, ); } mod connect { use super::*; use std::{ ffi::OsString, os::unix::prelude::OsStringExt, }; #[test] fn test_connect() { let testdir = TempBuilder::new() .prefix("ytdl-test-sqliteConnect-") .tempdir() .expect("Expected a temp dir to be created"); let path = testdir.as_ref().join(format!("{}-sqlite.db", chrono::Utc::now())); std::fs::create_dir_all(path.parent().expect("Expected the file to have a parent")) .expect("expected the directory to be created"); let connection = sqlite_connect(path); assert!(connection.is_ok()); } // it seems like non-utf8 paths are a pain to create os-independently, so it is just linux where the following works #[cfg(target_os = "linux")] #[test] fn test_connect_notutf8() { let path = OsString::from_vec(vec![255]); let err = sqlite_connect(path); assert!(err.is_err()); // Not using "unwrap_err", because of https://github.com/diesel-rs/diesel/discussions/3124 let err = match err { Ok(_) => panic!("Expected a Error value"), Err(err) => err, }; // the following is only a "contains", because of the abitrary path that could be after it assert!(err.to_string().contains("SQLite only accepts UTF-8 Paths, and given path failed to be converted to a string without being lossy, Path (converted lossy):")); } } mod apply_sqlite_migrations { use super::*; #[test] fn test_all_migrations_applied() { let (mut connection, _tempdir) = create_connection(); let res = diesel_migrations::MigrationHarness::has_pending_migration(&mut connection, MIGRATIONS); assert!(res.is_ok()); let res = res.unwrap(); assert!(!res); } } mod migrate_and_connect { use std::{ ffi::OsStr, io::{ BufWriter, Write, }, ops::Deref, path::PathBuf, sync::RwLock, }; use super::*; fn gen_archive_path<P: AsRef<OsStr>>(extension: P) -> (PathBuf, TempDir) { let testdir = TempBuilder::new() .prefix("ytdl-test-sqliteMigrate-") .tempdir() .expect("Expected a temp dir to be created"); let mut path = testdir.as_ref().join(format!("{}-gen_archive", uuid::Uuid::new_v4())); path.set_extension(extension); println!("generated: {}", path.to_string_lossy()); // clear generated path clear_path(&path); { let mut migrate_to_path = path.clone(); migrate_to_path.set_extension("db"); // clear migrate_to_path clear_path(migrate_to_path); } return (path, testdir); } fn clear_path<P: AsRef<Path>>(path: P) { let path = path.as_ref(); if path.exists() { std::fs::remove_file(path).expect("Expected file to be removed"); } } fn create_dir_all_parent<P: AsRef<Path>>(path: P) { let path = path.as_ref(); std::fs::create_dir_all(path.parent().expect("Expected the file to have a parent")) .expect("expected the directory to be created"); } fn write_file_with_content<S: AsRef<str>, P: AsRef<OsStr>>(input: S, extension: P) -> (PathBuf, TempDir) { let (path, tempdir) = gen_archive_path(extension); create_dir_all_parent(&path); let mut file = BufWriter::new(std::fs::File::create(&path).expect("Expected file to be created")); file.write_all(input.as_ref().as_bytes()) .expect("Expected successfull file write"); return (path, tempdir); } /// Test utility function for easy callbacks fn callback_counter(c: &RwLock<Vec<ImportProgress>>) -> impl FnMut(ImportProgress) + '_ { return |imp| c.write().expect("write failed").push(imp); } #[test] fn test_input_unknown_archive() { let string0 = " youtube ____________ youtube ------------ youtube aaaaaaaaaaaa soundcloud 0000000000 "; let (path, _tempdir) = write_file_with_content(string0, "unknown_ytdl"); let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter));
assert!(res.is_err()); let res = match res { Ok(_) => panic!("Expected a Error value"), Err(err) => err, }; assert!(res .to_string() .contains("Unknown Archive type to migrate, maybe try importing")); assert_eq!(0, pgcounter.read().expect("read failed").len()); } #[test] fn test_input_sqlite_archive() { let (path, _tempdir) = gen_archive_path("db_sqlite"); create_dir_all_parent(&path); { // create database file assert!(sqlite_connect(&path).is_ok()); } let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_ok()); let res = res.unwrap(); assert_eq!(&path, res.0.as_ref()); assert_eq!(0, pgcounter.read().expect("read failed").len()); } #[test] fn test_input_json_archive() { let string0 = r#" { "version": "0.1.0", "videos": [ { "id": "____________", "provider": "youtube", "dlFinished": true, "editAsked": true, "fileName": "someFile1.mp3" }, { "id": "------------", "provider": "youtube", "dlFinished": false, "editAsked": true, "fileName": "someFile2.mp3" }, { "id": "aaaaaaaaaaaa", "provider": "youtube", "dlFinished": true, "editAsked": false, "fileName": "someFile3.mp3" }, { "id": "0000000000", "provider": "soundcloud", "dlFinished": true, "editAsked": true, "fileName": "someFile4.mp3" } ] } "#; let (path, _tempdir) = write_file_with_content(string0, "json_json"); let expected_path = { let mut tmp = path.clone(); tmp.set_extension("db"); tmp }; clear_path(&expected_path); let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_ok()); let res = res.unwrap(); assert_eq!(&expected_path, res.0.as_ref()); assert_eq!( &vec![ ImportProgress::Starting, ImportProgress::SizeHint(4), // Size Hint of 4, because of a intermediate array length // index start at 0, thanks to json array index ImportProgress::Increase(1, 0), ImportProgress::Increase(1, 1), ImportProgress::Increase(1, 2), ImportProgress::Increase(1, 3), ImportProgress::Finished(4) ], pgcounter.read().expect("failed to read").deref() ); } #[test] fn test_to_existing_json() { let string0 = r#" { } "#; let (path, _tempdir) = write_file_with_content(string0, "db"); let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_err()); let res = match res { Ok(_) => panic!("Expected a Error value"), Err(err) => err, }; assert_eq!( res.to_string(), format!("Other: Migrate-To Path already exists and is a JSON archive, please rename it and retry the migration! Path: \"{}\"", path.to_string_lossy()) ); assert_eq!(0, pgcounter.read().expect("read failed").len()); } #[test] fn test_to_existing_unknown() { let string0 = " youtube ____________ youtube ------------ youtube aaaaaaaaaaaa soundcloud 0000000000 "; let (path, _tempdir) = write_file_with_content(string0, "db"); let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_err()); let res = match res { Ok(_) => panic!("Expected a Error value"), Err(err) => err, }; assert_eq!( res.to_string(), format!( "Other: Migrate-To Path already exists, but is of unknown type! Path: \"{}\"", path.to_string_lossy() ) ); assert_eq!(0, pgcounter.read().expect("read failed").len()); } #[test] fn test_to_existing_sqlite() { let (path, _tempdir) = gen_archive_path("db"); create_dir_all_parent(&path); { // create database file assert!(sqlite_connect(&path).is_ok()); } let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_ok()); let res = res.unwrap(); assert_eq!(&path, res.0.as_ref()); assert_eq!(0, pgcounter.read().expect("read failed").len()); } } }
random_line_split
sql_utils.rs
//! Module for SQL Utility functions use diesel::prelude::*; use std::{ borrow::Cow, fs::File, io::BufReader, path::Path, }; use crate::error::IOErrorToError; use super::archive::import::{ detect_archive_type, import_ytdlr_json_archive, ArchiveType, ImportProgress, }; /// All migrations from "libytdlr/migrations" embedded into the binary pub const MIGRATIONS: diesel_migrations::EmbeddedMigrations = diesel_migrations::embed_migrations!(); /// Open a SQLite Connection for `sqlite_path` and apply sqlite migrations /// does not migrate archive formats, use [migrate_and_connect] instead pub fn sqlite_connect<P: AsRef<Path>>(sqlite_path: P) -> Result<SqliteConnection, crate::Error> { // having to convert the path to "str" because diesel (and underlying sqlite library) only accept strings return match sqlite_path.as_ref().to_str() { Some(path) => { let mut connection = SqliteConnection::establish(path)?; apply_sqlite_migrations(&mut connection)?; return Ok(connection); }, None => Err(crate::Error::other(format!("SQLite only accepts UTF-8 Paths, and given path failed to be converted to a string without being lossy, Path (converted lossy): \"{}\"", sqlite_path.as_ref().to_string_lossy()))), }; } /// Apply all (up) migrations to a SQLite Database #[inline] fn apply_sqlite_migrations(connection: &mut SqliteConnection) -> Result<(), crate::Error> { let applied = diesel_migrations::MigrationHarness::run_pending_migrations(connection, MIGRATIONS) .map_err(|err| return crate::Error::other(format!("Applying SQL Migrations Errored! Error:\n{err}")))?; debug!("Applied Migrations: {:?}", applied); return Ok(()); } /// Check if the input path is a sql database, if not migrate to sql and return new path and open connection /// Parameter `pgcb` will be used when migration will be applied /// /// This function is intended to be used over [`sqlite_connect`] in all non-test cases pub fn migrate_and_connect<S: FnMut(ImportProgress)>( archive_path: &Path, pgcb: S, ) -> Result<(Cow<Path>, SqliteConnection), crate::Error> { // early return in case the file does not actually exist if !archive_path.exists() { return Ok((archive_path.into(), sqlite_connect(archive_path)?)); } let migrate_to_path = { let mut tmp = archive_path.to_path_buf(); tmp.set_extension("db"); tmp }; // check if the "migrate-to" path already exists, and use that directly instead or error of already existing if migrate_to_path.exists() { if !migrate_to_path.is_file() { return Err(crate::Error::not_a_file( "Migrate-To Path exists but is not a file!", migrate_to_path, )); } let mut sqlite_path_reader = BufReader::new(File::open(&migrate_to_path).attach_path_err(&migrate_to_path)?); return Ok( match detect_archive_type(&mut sqlite_path_reader)? { ArchiveType::Unknown => return Err(crate::Error::other(format!("Migrate-To Path already exists, but is of unknown type! Path: \"{}\"", migrate_to_path.to_string_lossy()))), ArchiveType::JSON => return Err(crate::Error::other(format!("Migrate-To Path already exists and is a JSON archive, please rename it and retry the migration! Path: \"{}\"", migrate_to_path.to_string_lossy()))), ArchiveType::SQLite => { // this has to be done before, because the following ".into" call will move the value let connection = sqlite_connect(&migrate_to_path)?; (migrate_to_path.into(), connection) }, }, ); } let mut input_archive_reader = BufReader::new(File::open(archive_path).attach_path_err(archive_path)?); return Ok(match detect_archive_type(&mut input_archive_reader)? { ArchiveType::Unknown =>
, ArchiveType::JSON => { debug!("Applying Migration from JSON to SQLite"); // handle case where the input path matches the changed path if migrate_to_path == archive_path { return Err(crate::Error::other( "Migration cannot be done: Input path matches output path (setting extension to \".db\")", )); } let mut connection = sqlite_connect(&migrate_to_path)?; import_ytdlr_json_archive(&mut input_archive_reader, &mut connection, pgcb)?; debug!("Migration from JSON to SQLite done"); (migrate_to_path.into(), connection) }, ArchiveType::SQLite => (archive_path.into(), sqlite_connect(archive_path)?), }); } #[cfg(test)] mod test { use super::*; use tempfile::{ Builder as TempBuilder, TempDir, }; fn create_connection() -> (SqliteConnection, TempDir) { let testdir = TempBuilder::new() .prefix("ytdl-test-sqlite-") .tempdir() .expect("Expected a temp dir to be created"); // chrono is used to create a different database for each thread let path = testdir.as_ref().join(format!("{}-sqlite.db", chrono::Utc::now())); // remove if already exists to have a clean test if path.exists() { std::fs::remove_file(&path).expect("Expected the file to be removed"); } return ( crate::main::sql_utils::sqlite_connect(&path).expect("Expected SQLite to successfully start"), testdir, ); } mod connect { use super::*; use std::{ ffi::OsString, os::unix::prelude::OsStringExt, }; #[test] fn test_connect() { let testdir = TempBuilder::new() .prefix("ytdl-test-sqliteConnect-") .tempdir() .expect("Expected a temp dir to be created"); let path = testdir.as_ref().join(format!("{}-sqlite.db", chrono::Utc::now())); std::fs::create_dir_all(path.parent().expect("Expected the file to have a parent")) .expect("expected the directory to be created"); let connection = sqlite_connect(path); assert!(connection.is_ok()); } // it seems like non-utf8 paths are a pain to create os-independently, so it is just linux where the following works #[cfg(target_os = "linux")] #[test] fn test_connect_notutf8() { let path = OsString::from_vec(vec![255]); let err = sqlite_connect(path); assert!(err.is_err()); // Not using "unwrap_err", because of https://github.com/diesel-rs/diesel/discussions/3124 let err = match err { Ok(_) => panic!("Expected a Error value"), Err(err) => err, }; // the following is only a "contains", because of the abitrary path that could be after it assert!(err.to_string().contains("SQLite only accepts UTF-8 Paths, and given path failed to be converted to a string without being lossy, Path (converted lossy):")); } } mod apply_sqlite_migrations { use super::*; #[test] fn test_all_migrations_applied() { let (mut connection, _tempdir) = create_connection(); let res = diesel_migrations::MigrationHarness::has_pending_migration(&mut connection, MIGRATIONS); assert!(res.is_ok()); let res = res.unwrap(); assert!(!res); } } mod migrate_and_connect { use std::{ ffi::OsStr, io::{ BufWriter, Write, }, ops::Deref, path::PathBuf, sync::RwLock, }; use super::*; fn gen_archive_path<P: AsRef<OsStr>>(extension: P) -> (PathBuf, TempDir) { let testdir = TempBuilder::new() .prefix("ytdl-test-sqliteMigrate-") .tempdir() .expect("Expected a temp dir to be created"); let mut path = testdir.as_ref().join(format!("{}-gen_archive", uuid::Uuid::new_v4())); path.set_extension(extension); println!("generated: {}", path.to_string_lossy()); // clear generated path clear_path(&path); { let mut migrate_to_path = path.clone(); migrate_to_path.set_extension("db"); // clear migrate_to_path clear_path(migrate_to_path); } return (path, testdir); } fn clear_path<P: AsRef<Path>>(path: P) { let path = path.as_ref(); if path.exists() { std::fs::remove_file(path).expect("Expected file to be removed"); } } fn create_dir_all_parent<P: AsRef<Path>>(path: P) { let path = path.as_ref(); std::fs::create_dir_all(path.parent().expect("Expected the file to have a parent")) .expect("expected the directory to be created"); } fn write_file_with_content<S: AsRef<str>, P: AsRef<OsStr>>(input: S, extension: P) -> (PathBuf, TempDir) { let (path, tempdir) = gen_archive_path(extension); create_dir_all_parent(&path); let mut file = BufWriter::new(std::fs::File::create(&path).expect("Expected file to be created")); file.write_all(input.as_ref().as_bytes()) .expect("Expected successfull file write"); return (path, tempdir); } /// Test utility function for easy callbacks fn callback_counter(c: &RwLock<Vec<ImportProgress>>) -> impl FnMut(ImportProgress) + '_ { return |imp| c.write().expect("write failed").push(imp); } #[test] fn test_input_unknown_archive() { let string0 = " youtube ____________ youtube ------------ youtube aaaaaaaaaaaa soundcloud 0000000000 "; let (path, _tempdir) = write_file_with_content(string0, "unknown_ytdl"); let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_err()); let res = match res { Ok(_) => panic!("Expected a Error value"), Err(err) => err, }; assert!(res .to_string() .contains("Unknown Archive type to migrate, maybe try importing")); assert_eq!(0, pgcounter.read().expect("read failed").len()); } #[test] fn test_input_sqlite_archive() { let (path, _tempdir) = gen_archive_path("db_sqlite"); create_dir_all_parent(&path); { // create database file assert!(sqlite_connect(&path).is_ok()); } let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_ok()); let res = res.unwrap(); assert_eq!(&path, res.0.as_ref()); assert_eq!(0, pgcounter.read().expect("read failed").len()); } #[test] fn test_input_json_archive() { let string0 = r#" { "version": "0.1.0", "videos": [ { "id": "____________", "provider": "youtube", "dlFinished": true, "editAsked": true, "fileName": "someFile1.mp3" }, { "id": "------------", "provider": "youtube", "dlFinished": false, "editAsked": true, "fileName": "someFile2.mp3" }, { "id": "aaaaaaaaaaaa", "provider": "youtube", "dlFinished": true, "editAsked": false, "fileName": "someFile3.mp3" }, { "id": "0000000000", "provider": "soundcloud", "dlFinished": true, "editAsked": true, "fileName": "someFile4.mp3" } ] } "#; let (path, _tempdir) = write_file_with_content(string0, "json_json"); let expected_path = { let mut tmp = path.clone(); tmp.set_extension("db"); tmp }; clear_path(&expected_path); let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_ok()); let res = res.unwrap(); assert_eq!(&expected_path, res.0.as_ref()); assert_eq!( &vec![ ImportProgress::Starting, ImportProgress::SizeHint(4), // Size Hint of 4, because of a intermediate array length // index start at 0, thanks to json array index ImportProgress::Increase(1, 0), ImportProgress::Increase(1, 1), ImportProgress::Increase(1, 2), ImportProgress::Increase(1, 3), ImportProgress::Finished(4) ], pgcounter.read().expect("failed to read").deref() ); } #[test] fn test_to_existing_json() { let string0 = r#" { } "#; let (path, _tempdir) = write_file_with_content(string0, "db"); let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_err()); let res = match res { Ok(_) => panic!("Expected a Error value"), Err(err) => err, }; assert_eq!( res.to_string(), format!("Other: Migrate-To Path already exists and is a JSON archive, please rename it and retry the migration! Path: \"{}\"", path.to_string_lossy()) ); assert_eq!(0, pgcounter.read().expect("read failed").len()); } #[test] fn test_to_existing_unknown() { let string0 = " youtube ____________ youtube ------------ youtube aaaaaaaaaaaa soundcloud 0000000000 "; let (path, _tempdir) = write_file_with_content(string0, "db"); let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_err()); let res = match res { Ok(_) => panic!("Expected a Error value"), Err(err) => err, }; assert_eq!( res.to_string(), format!( "Other: Migrate-To Path already exists, but is of unknown type! Path: \"{}\"", path.to_string_lossy() ) ); assert_eq!(0, pgcounter.read().expect("read failed").len()); } #[test] fn test_to_existing_sqlite() { let (path, _tempdir) = gen_archive_path("db"); create_dir_all_parent(&path); { // create database file assert!(sqlite_connect(&path).is_ok()); } let pgcounter = RwLock::new(Vec::<ImportProgress>::new()); let res = migrate_and_connect(&path, callback_counter(&pgcounter)); assert!(res.is_ok()); let res = res.unwrap(); assert_eq!(&path, res.0.as_ref()); assert_eq!(0, pgcounter.read().expect("read failed").len()); } } }
{ return Err(crate::Error::other( "Unknown Archive type to migrate, maybe try importing", )) }
conditional_block