file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
keys.rs |
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);
| y { | identifier_name | |
keys.rs | " => 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, | random_line_split | |
lib.rs | = 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
} | conditional_block | |
lib.rs | "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 | };
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 | {
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 | identifier_body |
lib.rs | 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()); | random_line_split | |
lib.rs | 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 | identifier_name | |
controller.rs | _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) | out
}
/// returns current frame emulation pos in percents | random_line_split |
controller.rs | = 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( | {
self.events.clear();
} | identifier_body |
controller.rs | = 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( | {
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 | = 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 | io_contention_first | identifier_name |
storage.rs | _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 | {
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 | , 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 | &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 | {
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", | identifier_body |
storage.rs | // 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 | identifier_name | |
storage.rs | , 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 | 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 | Buf,
}
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 | 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 | get_tmp_dir | identifier_name |
lib.rs | 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_utf | {
return Err("Not a valid NPC ID".into());
} | conditional_block |
mmio.rs | 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"); | random_line_split | |
mmio.rs | ["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) }
} | identifier_body | |
mmio.rs | 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 | obj_palbank | identifier_name | |
domain_models.py | idPusher(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_rec | __init__ | identifier_name |
domain_models.py | 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 |
import re
import structlog | random_line_split | |
domain_models.py | idPusher(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 == | LOGGER.debug(
"OrcidPusher force delete", recid=self.recid, orcid=self.orcid
)
return True | conditional_block |
domain_models.py | .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 | identifier_body | |
lib.rs | lude::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(¬ification_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 = ();
| fmt | identifier_name |
lib.rs | lude::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(¬ification_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 = | {
self.current_future = Some(fut);
false
} | conditional_block |
lib.rs | 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(¬ification_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 | //!
//! [here]: https://github.com/ethereum/go-ethereum/wiki/RPC-PUB-SUB
extern crate futures;
extern crate jsonrpc_client_core; | random_line_split | |
boxed.rs |
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();
} | random_line_split | |
boxed.rs | // 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);
} | identifier_body | |
boxed.rs | ,
"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 | release | identifier_name |
boxed.rs | ,
"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(& | {
mprotect(self.ptr.as_ptr(), Prot::NoAccess);
self.prot.set(Prot::NoAccess);
} | conditional_block |
route.go | /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 | Create | identifier_name |
route.go | /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 | })
}
if route.Type == l3.Route_INTER_VRF && route.ViaVrfId != 0 {
dependencies = append(dependencies, kvs.Dependency{
Label: viaVrfTableDep, | random_line_split |
route.go | escriptor"
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) | {
return addr1 == addr2
} | conditional_block | |
route.go | /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,
) | 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 | {
// 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 | identifier_body |
models.py | 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 | try:
user = self.user
except ObjectDoesNotExist:
user = None
return "{0} ({1})".format(self.name, user) | identifier_body |
models.py | 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 | random_line_split | |
models.py | 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 | Device | identifier_name |
models.py | 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 | device_set = device_set.select_for_update() | conditional_block |
NetHandler.ts | ;
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.Msg | ,不能list两次role,所以每次都要断开重连
t | identifier_body |
NetHandler.ts | ;
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 | if (null != this.onDisconnectCallback) { | random_line_split |
NetHandler.ts | 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.Msg | rn;
}
this.work | conditional_block |
NetHandler.ts | 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.Msg | thi | identifier_name |
zsy_3pandas.py | 2['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 | r | identifier_name |
zsy_3pandas.py | 2['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汇总和计算描述统计(约简型)
| ies([x.min(), x.max()], index=['min', 'max'])
# print(f | identifier_body |
zsy_3pandas.py | 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)) | random_line_split | ||
movement.py |
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()
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)
| 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() | conditional_block |
movement.py | 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 | random_line_split | ||
movement.py | 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() | identifier_body | |
movement.py | (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 | identifier_name | |
model.py | 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 | random_line_split | |
model.py | 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 | '''
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 | 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 | __preprocess | identifier_name |
model.py | 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 | temp = sample | conditional_block |
mod.rs | };
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(),
| get_nonce | identifier_name |
mod.rs | };
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 | {
random_wait(random_wait_before_transaction_ms);
} | conditional_block |
mod.rs | };
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(),
| break;
}
}
client.client_api.close().unwrap(); | random_line_split |
app.py | ,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 | 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 | 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) | random_line_split | |
app.py | #集成分类器---简单投票分类器##################################
# 使用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(xx | vanoid ph | identifier_name |
app.py | 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, | 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 | .(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 | identifier_name | |
nargs.go | 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
}
}
} | conditional_block | |
nargs.go | 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(param | { a[i], a[j] = a[j], a[i] } | identifier_body |
nargs.go | Exprs(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
| random_line_split | |
raft.go | 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,
// | Start | identifier_name |
raft.go | 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,
| {
// 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 |
//
// 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 | {
//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 | // (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 | // 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 | 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")
}
}
| IsEmpty | identifier_name |
svc.go | 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")
}
| {
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 | 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 nil
}
| random_line_split |
svc.go | 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")
}
| {
switch err.(type) {
case *yaml.TypeError:
break
default:
return err
}
} | conditional_block |
lib.rs | 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 | get_value | identifier_name |
lib.rs | 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!( | }
let mut n = 0;
for e in self.lines.iter_mut() { | random_line_split |
lib.rs | ;
#[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 | {
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 | 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( | add_controller | identifier_name |
ctrl_map.rs | 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 | {
// 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 | , 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( | set: usize, | random_line_split |
ctrl_map.rs | 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 | {
let mut context = TestContext::new();
context.add_controller(1, MappingType::Absolute);
assert_eq!(context.handle_controller(1, 50), true);
} | identifier_body |
random.rs | 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,
} | identifier_body | |
random.rs | <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 | ::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 | new | identifier_name |
random.rs |
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
| {
return Err(err_msg("Invalid upper/lower range"));
} | conditional_block | |
main.rs | io::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"));
}
| Thread | identifier_name |
main.rs | io::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"));
}
| } else { | random_line_split |
main.rs | io::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"));
| {
assert!(inframe.is_some());
stack.push_str(line.trim());
stack.push(';');
} | conditional_block |
main.rs | io::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> | .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"));
}
| {
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() | identifier_body |
sbot.py | = 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 | conditional_block | |
sbot.py |
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, | return adb.adbpull(command) | identifier_body | |
sbot.py | Epoch)):
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 | keepOrSellRune | identifier_name |
sbot.py | 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 | def adbdevices():
return adb.adbdevices()
def touchscreen_devices():
| random_line_split | |
triggers.go | 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(). | list | identifier_name |
triggers.go | 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 | {
if !strings.HasPrefix(ts, "/") {
ts = "/" + ts
}
return ts
} | identifier_body |
triggers.go | 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 | {
return nil, err
} | conditional_block | |
triggers.go | "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(). | }
fmt.Println("Successfully created trigger:", resp.Payload.Name) | random_line_split |
sql_utils.rs | : &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::<Import | {
return |imp| c.write().expect("write failed").push(imp);
} | identifier_body |
sql_utils.rs | : &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 | random_line_split | |
sql_utils.rs | : &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::<Import | {
return Err(crate::Error::other(
"Unknown Archive type to migrate, maybe try importing",
))
} | conditional_block |
sql_utils.rs | : &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 | (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 | callback_counter | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.