file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
lib.rs
//! An Entity Component System for game development. //! //! Currently used for personal use (for a roguelike game), this library is highly unstable, and a WIP. #![allow(dead_code)] #![feature(append,drain)] use std::iter; use std::collections::HashMap; use std::ops::{Index, IndexMut}; use std::collections::hash_map::Entry::{Occupied, Vacant}; pub mod component_presence; pub mod family; pub mod builder; pub mod event; pub mod behavior; use family::{FamilyDataHolder, FamilyMap}; use event::{EventDataHolder}; pub use event::EventManager; pub use behavior::BehaviorManager; pub use behavior::Behavior; pub use component_presence::ComponentPresence; /// Type Entity is simply an ID used as indexes. pub type Entity = u32; /// The components macro defines all the structs and traits that manage /// the component part of the ECS. #[macro_export] macro_rules! components { ($data:ident: $([$access:ident, $ty:ty]),+ ) => { use $crate::component_presence::ComponentPresence; use $crate::component_presence::ComponentPresence::*; use $crate::{EntityDataHolder, Component, Entity, ComponentData}; use $crate::family::{FamilyMap}; use std::fmt; pub struct $data { pub components: Vec<&'static str>, pub families: Vec<&'static str>, $( pub $access: ComponentPresence<$ty>, )+ } impl $data { pub fn new_empty() -> $data { $data { components: Vec::new(), families: Vec::new(), $( $access: Lacks, )+ } } } impl fmt::Debug for $data { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut b = fmt.debug_struct("EntityData"); b.field("has components", &self.components); b.field("belongs to families", &self.families); /*$( if self.$access.has_it() { b.field(stringify!($access), &self.$access); } )+*/ b.finish() } } impl EntityDataHolder for $data { fn new() -> Self { $data::new_empty() } fn match_families(&self, families: &FamilyMap) -> Vec<&'static str> { let mut v: Vec<&str> = vec!(); // Tuple has the requirements/forbidden vectors for (family, tuple) in families { if $crate::family::matcher(tuple, &self.components) { v.push(family) } } v } fn set_families(&mut self, families: Vec<&'static str>) { self.families = families; } fn belongs_to_family(&self, family: &str) -> bool { self.families.contains(&family) } fn families(&self) -> Vec<&'static str> { self.families.clone() } } $( impl Component<$data> for $ty { fn add_to(self, ent: Entity, data: &mut ComponentData<$data>) { let ent_data: &mut $data = data.components.get_mut(&ent).expect("no entity"); ent_data.components.push(stringify!($access)); ent_data.$access = Has(self); } } )+ } } /// This is a marker trait to be used by the `components!` macro. /// /// This trait is implemented by `EntityData` which is a struct generated /// by the `components!` macro. /// /// `EntityData` will be of the form: /// /// ``` /// struct EntityData { /// component1: ComponentPresence<Component1>, /// component2: ComponentPresence<Component2>, /// //etc... /// } /// ``` /// /// So it will have one field per component defined in the call to `components!` /// You'll access these fields directly when indexing the `data` field of the `EntityManager` pub trait EntityDataHolder { fn new() -> Self; /// Takes a map of all the defined families, /// and returns the families that match this entity. fn match_families(&self, &FamilyMap) -> Vec<&'static str>; /// Sets the families this entity belongs to to `families` fn set_families(&mut self, Vec<&'static str>); fn belongs_to_family(&self, &'static str) -> bool; /// Gets the known families this ent belongs to. fn families(&self) -> Vec<&'static str>; } /// ComponentData knows which entities have which components. pub struct ComponentData<D: EntityDataHolder> { /// components holds the components owned by a certain entity. pub components: HashMap<Entity, D>, /// Family to list of entities. pub families: HashMap<&'static str, Vec<Entity>>, } /// This trait marks a struct as a component. (Automatically handled by macro `components!`) /// /// It should implement the `add_to` function, which is automatically generated /// by the `components!` macro. pub trait Component<D: EntityDataHolder> { /// Adds self to the specified entity. Called by the `EntityManager` fn add_to(self, ent: Entity, data: &mut ComponentData<D>); } impl<D: EntityDataHolder> ComponentData<D> { pub fn new() -> ComponentData<D> { ComponentData { components: HashMap::new(), families: HashMap::new(), } } pub fn get(&self, ent: &Entity) -> Option<&D> { self.components.get(ent) } pub fn get_mut(&mut self, ent: &Entity) -> Option<&mut D> { self.components.get_mut(ent) } pub fn create_component_data_for(&mut self, ent: Entity) { self.components.insert(ent, D::new()); } pub fn clear_family_data_for(&mut self, ent: Entity) { for family in self[ent].families() { self.remove_from_family(family, ent); debug_assert!(!self.families[family].contains(&ent)) } } pub fn delete_component_data_for(&mut self, ent: Entity) { self.clear_family_data_for(ent); self.components.remove(&ent); } fn remove_from_family(&mut self, family: &str, ent: Entity)
pub fn set_family_relation(&mut self, family: &'static str, ent: Entity) { match self.families.entry(family) { Vacant(entry) => {entry.insert(vec!(ent));}, Occupied(entry) => { let v = entry.into_mut(); if v.contains(&ent) { return; } v.push(ent); }, } } pub fn members_of(&self, family: &'static str) -> Vec<Entity> { match self.families.get(family) { Some(vec) => vec.clone(), None => vec!(), } } pub fn any_member_of(&self, family: &'static str) -> bool { !self.families.get(family).expect("no such family").is_empty() } } impl<D: EntityDataHolder> Index<Entity> for ComponentData<D> { type Output = D; fn index(&self, index: Entity) -> &D { &self.components.get(&index).expect(&format!("no entity {:?}", index)) } } impl<D: EntityDataHolder> IndexMut<Entity> for ComponentData<D> { fn index_mut(&mut self, index: Entity) -> &mut D { self.components.get_mut(&index).expect("no entity") } } /// The `EntityManager` type manages all the entities. /// /// It is in charge of creating and destroying entities. /// It also takes care of adding or removing components, through the `ComponentData` it contains. /// /// # Examples /// /// Creating a new manager, and adding some (predefined) components to a new entity. /// /// ``` /// let mut manager = EntityManager::new(); /// let ent = manager.new_entity(); /// manager.add_component_to(ent, Position{x: 1, y: 2}); /// ``` pub struct EntityManager<D: EntityDataHolder, F: FamilyDataHolder> { next_idx: usize, reusable_idxs: Vec<usize>, active: Vec<bool>, pub data: ComponentData<D>, /// Contains a list of all defined families, along with its requirements. families: F, } impl<D: EntityDataHolder, F: FamilyDataHolder> EntityManager<D, F> { /// Creates a new EntityManager pub fn new() -> EntityManager<D, F> { EntityManager{ next_idx: 0, reusable_idxs: vec!(), active: vec!(), data: ComponentData::new(), families: F::new(), } } /// Creates a new entity, assigning it an unused ID, returning that ID for further use. pub fn new_entity(&mut self) -> Entity { let idx = match self.reusable_idxs.pop() { None => { let idx = self.next_idx; self.next_idx += 1; idx } Some(idx) => idx, }; // Extend the vec if the idx is bigger. if self.active.len() <= idx { let padding = idx + 1 - self.active.len(); self.active.extend(iter::repeat(false).take(padding)); debug_assert!(self.active.len() == idx+1); } debug_assert!(!self.active[idx]); self.active[idx] = true; let ent = idx as Entity; self.data.create_component_data_for(ent); ent } /// Deletes the entity, removes all data related to it. /// /// Returns a list of events that were related to it, in case you need to do some clean up with them. pub fn delete_entity<Event>(&mut self, ent: Entity, events: &mut EventManager<Event>) -> Vec<Event> where Event: event::EventDataHolder { self.delete_entity_ignore_events(ent); events.clear_events_for(ent) } pub fn delete_entity_ignore_events(&mut self, ent: Entity) { let idx = ent as usize; assert!(self.active[idx]); self.reusable_idxs.push(idx); self.active[idx] = false; self.data.delete_component_data_for(ent); } pub fn build_ent<'a, A,B: EventDataHolder>(&'a mut self, ent: Entity, processor: &'a mut BehaviorManager<A,B>) -> EntityBuilder<D,A,B> { EntityBuilder::new(ent, processor, &mut self.data, self.families.all_families()) } /// Adds the specified component to the entity. pub fn add_component_to<A,B:EventDataHolder,C: Component<D>>(&mut self, e: Entity, c: C, processor: &mut BehaviorManager<A,B>) { //c.add_to(e, &mut self.data); self.build_ent(e, processor).add_component(c).finalize(); } } /// Used by `EntityManager` to add components to an Entity. /// /// An object of this type is obtained by calling `add_component` from an EntityManager pub struct EntityBuilder<'a, EntData: 'a + EntityDataHolder, T: 'a, Ev: event::EventDataHolder + 'a> { data: &'a mut ComponentData<EntData>, families: &'a FamilyMap, processor: &'a mut BehaviorManager<T,Ev>, ent: Entity, } impl<'a, EntData: 'a + EntityDataHolder, T, Ev: event::EventDataHolder> EntityBuilder<'a, EntData, T, Ev> { pub fn new(ent: Entity, processor: &'a mut BehaviorManager<T,Ev>, data: &'a mut ComponentData<EntData>, families: &'a FamilyMap) -> EntityBuilder<'a, EntData, T, Ev> { EntityBuilder { data: data, families: families, processor: processor, ent: ent, } } pub fn add_component<Comp: Component<EntData>>(self, comp: Comp) -> EntityBuilder<'a, EntData, T, Ev> { comp.add_to(self.ent, self.data); self } pub fn finalize(mut self) -> Entity { self.add_all_related_data(); self.ent } pub fn add_all_related_data(&mut self) { let mut families: Vec<&str> = self.data[self.ent].match_families(self.families); families.sort(); families.dedup(); // Clean up current component data, self.data.clear_family_data_for(self.ent); // Give the ComponentDataHolder information about this entities families. for family in families.iter() { self.data.set_family_relation(family, self.ent); } if !self.processor.valid_behaviors_for(families.clone()).is_empty() { self.processor.add_processable(self.ent); } // Give this EntityDataHolder a list of which families this entity has. self.data[self.ent].set_families(families); } } /* fn main() { println!("Hello, world!"); let mut manager = EntityManager::new(); let ent = manager.new_entity(); manager.add_component_to(ent, Position{x:1, y:2}); println!("pos: {:?}", manager.data[ent].position.x); manager.data[ent].position.x += 5; println!("pos: {:?}", manager.data[ent].position.x); println!("has glyph? {:?}", manager.data[ent].glyph.has_it()); } */
{ let mut idx: Option<usize> = None; { let vec = self.families.get_mut(family).expect("No such family"); let op = vec.iter().enumerate().find(|&(_,e)| *e == ent); idx = Some(op.expect("Entity not found in this family").0); } if let Some(idx) = idx { self.families.get_mut(family).unwrap().swap_remove(idx); } else { panic!("Entity not found for family"); } }
identifier_body
chat.py
#!/usr/bin/python #coding:utf8 #python 2.7.6 import threading import socket import time import os import sys import signal from readline import get_line_buffer BUFSIZE = 1024 BACKPORT = 7789 #状态监听端口 CHATPORT = 7788 #聊天信息发送窗口 class Cmd(): START = '>> ' INIT = '>> ' outmutex = threading.Lock() anoun = True @classmethod def output_with_rewrite(self, msg): if self.outmutex.acquire(1): sys.stdout.write('\r'+' '*(len(get_line_buffer())+len(self.START))+'\r') print msg sys.stdout.write(self.START+get_line_buffer()) sys.stdout.flush() self.outmutex.release() @classmethod def output(self, msg): if self.outmutex.acquire(1): print msg self.outmutex.release() @classmethod def set_start(self, start): self.START = start @classmethod def reset_start(self): self.START = self.INIT @classmethod def close_notice(self): self.anoun = False @classmethod def open_notice(self): self.anoun = True @classmethod def is_notice(self): return self.anoun class UserList(): def __init__(self):
(): def gettime(self): return time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time())) def getip(self): ip = os.popen("/sbin/ifconfig | grep 'inet addr' | awk '{print $2}'").read() ip = ip[ip.find(':')+1:ip.find('\n')] return ip def handlebc(self, data): data = data[5:] res = data.split('#opt:') return res def makebc(self, name, switch): data = 'name:%s#opt:%d' % (name, switch) return data def handlechat(self, data): msg = '\n' + self.gettime() + '\n' +'from '+ data + '\n' return msg def makechat(self, data, name): return name + ':' + data #后台监听类 class Back(threading.Thread): def __init__(self, user_list, name): threading.Thread.__init__(self) self.data = Data() self.user_list = user_list self.addrb = ('255.255.255.255', BACKPORT) self.addrl = ('', BACKPORT) self.name = name self.ip = self.data.getip() self.thread_stop = False def status(self, name, switch): if switch == 0: status = 'offline' elif switch == 1: status = 'online' #用来处理输入过程中被线程返回消息打乱的情况 Cmd.output_with_rewrite('[status]' + name + ' ' + status) def broadcast(self, switch): bsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) bsock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) data = self.data.makebc(self.name, switch) bsock.sendto(data, self.addrb) bsock.close() def response(self, addr, switch): rsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) data = self.data.makebc(self.name, switch) rsock.sendto(data, (addr, BACKPORT)) rsock.close() def check(self): self.user_list.clear() self.broadcast(1) def run(self): lsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) lsock.bind(self.addrl) self.broadcast(1) while not self.thread_stop: data, addr = lsock.recvfrom(BUFSIZE) datalist = self.data.handlebc(data) if datalist[1] == '0': if self.user_list.has_ip(addr[0]): if Cmd.is_notice(): self.status(datalist[0], 0) self.user_list.del_by_ip(addr[0]) elif datalist[1] == '1': if Cmd.is_notice() and datalist[0] != self.name: self.status(datalist[0], 1) self.user_list.add_user(datalist[0], addr[0]) elif datalist[1] == '2': if Cmd.is_notice() and datalist[0] != self.name: self.status(datalist[0], 1) self.user_list.add_user(datalist[0], addr[0]) lsock.close() def stop(self): self.broadcast(0) self.thread_stop = True #聊天类 class Listen(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.addr = ('', CHATPORT) self.name = socket.getfqdn(socket.gethostname()) self.data = Data() self.thread_stop = False def ack(self, addr):#to be added 用来确认消息报的接受 return def run(self): lsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) lsock.bind(self.addr) while not self.thread_stop: data, addr = lsock.recvfrom(BUFSIZE) msg = self.data.handlechat(data) Cmd.output_with_rewrite(msg) lsock.close() def stop(self): self.thread_stop = True #启动入口类 class Start(): def __init__(self, user_list, name): self.name = name self.user_list = user_list self.data = Data() self.listen = Listen() self.back = Back(user_list, self.name) print '******* iichats ********' print ' Written by Kevince \n' print 'This is ' + self.name print self.data.gettime()+'\n' #帮助信息 def helpinfo(self): helps = "use ':' to use options\n" + \ "\t:exit\t\t\texit iichats\n" + \ "\t:list\t\t\tlist online users\n" + \ "\t:quit\t\t\tquit the chat mode\n" + \ "\t:chat [hostname]\tchatting to someone\n" + \ "\t:set status [on|off]\tturn on/of status alarms\n" Cmd.output(helps) def refresh(self): out = '\n******Onlinelist******\n' users = self.user_list.get_users() for key in users: out += key + "\n" out += '**********************\n' Cmd.output(out) def cmd_exit(self): os.exit(1) def cmd_list(self): self.refresh() def cmd_set(self, params): if params[0] == 'status': if params[1] == 'on': Cmd.open_notice() elif params[1] == 'off': Cmd.close_notice() def cmd_help(self): self.helpinfo() def cmd_check(self): self.back.check() print 'checking the list...' time.sleep(3) self.refresh() def cmd_chat(self, name): if not self.user_list.has_name(name): Cmd.output('this host does not exist') return ('', True) addr = (self.user_list.get_ip(name), CHATPORT) Cmd.output('now chatting to ' + name+ \ " ,use ':quit' to quit CHAT mode") Cmd.set_start(name + Cmd.INIT) return (addr, False) def chatting(self): csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) Cmd.output("use ':help' to get help information") addr = '' in_chat = True while True: arg = raw_input(Cmd.START) if len(arg) < 1: continue if arg[0] == ':': args = arg[1:].rsplit() if args[0] == 'quit': if in_chat: addr = 0 in_chat = False Cmd.reset_start() elif args[0] == 'exit': self.cmd_exit() elif args[0] == 'list': self.cmd_list() elif args[0] == 'set': self.cmd_set(args[1:]) elif args[0] == 'help': self.cmd_help() elif args[0] == 'check': self.cmd_check() elif args[0] == 'chat': addr, err = self.cmd_chat(args[1]) if not err: in_chat = True else: Cmd.output("invalid input, use ':help' to get some info") else: if not in_chat: Cmd.output("you can CHAT to someone, or use ':help'") continue data = arg msg = self.data.makechat(data, self.name) csock.sendto(msg, addr) csock.close() def start(self): self.back.setDaemon(True) self.back.start() self.listen.setDaemon(True) self.listen.start() self.chatting() self.back.stop() self.listen.stop() sys.exit() def main(): if len(sys.argv) < 2: name = socket.getfqdn(socket.gethostname()) else: name = sys.argv[1] user_list = UserList() s = Start(user_list, name) s.start() if __name__ == '__main__': main()
self.users = {} self.ips = {} self.mutex = threading.Lock() def add_user(self, name, ip): if self.mutex.acquire(1): self.users[name] = ip self.ips[ip] = name self.mutex.release() def has_ip(self, ip): ret = False if self.mutex.acquire(1): ret = ip in self.ips self.mutex.release() return ret def get_ip(self, name): ip = '' if self.mutex.acquire(1): ip = self.users[name] self.mutex.release() return ip def has_name(self, name): ret = False if self.mutex.acquire(1): ret = name in self.users self.mutex.release() return ret def clear(self): if self.mutex.acquire(1): self.users.clear() self.ips.clear() self.mutex.release() def del_by_ip(self, ip): if self.mutex.acquire(1): del self.users[ips[ip]] del self.ips[ip] self.mutex.release() def get_users(self): users = [] if self.mutex.acquire(1): for key in self.users: users += [key] self.mutex.release() return users #数据处理类(消息封装、分解) class Data
identifier_body
chat.py
#!/usr/bin/python #coding:utf8 #python 2.7.6 import threading
import time import os import sys import signal from readline import get_line_buffer BUFSIZE = 1024 BACKPORT = 7789 #状态监听端口 CHATPORT = 7788 #聊天信息发送窗口 class Cmd(): START = '>> ' INIT = '>> ' outmutex = threading.Lock() anoun = True @classmethod def output_with_rewrite(self, msg): if self.outmutex.acquire(1): sys.stdout.write('\r'+' '*(len(get_line_buffer())+len(self.START))+'\r') print msg sys.stdout.write(self.START+get_line_buffer()) sys.stdout.flush() self.outmutex.release() @classmethod def output(self, msg): if self.outmutex.acquire(1): print msg self.outmutex.release() @classmethod def set_start(self, start): self.START = start @classmethod def reset_start(self): self.START = self.INIT @classmethod def close_notice(self): self.anoun = False @classmethod def open_notice(self): self.anoun = True @classmethod def is_notice(self): return self.anoun class UserList(): def __init__(self): self.users = {} self.ips = {} self.mutex = threading.Lock() def add_user(self, name, ip): if self.mutex.acquire(1): self.users[name] = ip self.ips[ip] = name self.mutex.release() def has_ip(self, ip): ret = False if self.mutex.acquire(1): ret = ip in self.ips self.mutex.release() return ret def get_ip(self, name): ip = '' if self.mutex.acquire(1): ip = self.users[name] self.mutex.release() return ip def has_name(self, name): ret = False if self.mutex.acquire(1): ret = name in self.users self.mutex.release() return ret def clear(self): if self.mutex.acquire(1): self.users.clear() self.ips.clear() self.mutex.release() def del_by_ip(self, ip): if self.mutex.acquire(1): del self.users[ips[ip]] del self.ips[ip] self.mutex.release() def get_users(self): users = [] if self.mutex.acquire(1): for key in self.users: users += [key] self.mutex.release() return users #数据处理类(消息封装、分解) class Data(): def gettime(self): return time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time())) def getip(self): ip = os.popen("/sbin/ifconfig | grep 'inet addr' | awk '{print $2}'").read() ip = ip[ip.find(':')+1:ip.find('\n')] return ip def handlebc(self, data): data = data[5:] res = data.split('#opt:') return res def makebc(self, name, switch): data = 'name:%s#opt:%d' % (name, switch) return data def handlechat(self, data): msg = '\n' + self.gettime() + '\n' +'from '+ data + '\n' return msg def makechat(self, data, name): return name + ':' + data #后台监听类 class Back(threading.Thread): def __init__(self, user_list, name): threading.Thread.__init__(self) self.data = Data() self.user_list = user_list self.addrb = ('255.255.255.255', BACKPORT) self.addrl = ('', BACKPORT) self.name = name self.ip = self.data.getip() self.thread_stop = False def status(self, name, switch): if switch == 0: status = 'offline' elif switch == 1: status = 'online' #用来处理输入过程中被线程返回消息打乱的情况 Cmd.output_with_rewrite('[status]' + name + ' ' + status) def broadcast(self, switch): bsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) bsock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) data = self.data.makebc(self.name, switch) bsock.sendto(data, self.addrb) bsock.close() def response(self, addr, switch): rsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) data = self.data.makebc(self.name, switch) rsock.sendto(data, (addr, BACKPORT)) rsock.close() def check(self): self.user_list.clear() self.broadcast(1) def run(self): lsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) lsock.bind(self.addrl) self.broadcast(1) while not self.thread_stop: data, addr = lsock.recvfrom(BUFSIZE) datalist = self.data.handlebc(data) if datalist[1] == '0': if self.user_list.has_ip(addr[0]): if Cmd.is_notice(): self.status(datalist[0], 0) self.user_list.del_by_ip(addr[0]) elif datalist[1] == '1': if Cmd.is_notice() and datalist[0] != self.name: self.status(datalist[0], 1) self.user_list.add_user(datalist[0], addr[0]) elif datalist[1] == '2': if Cmd.is_notice() and datalist[0] != self.name: self.status(datalist[0], 1) self.user_list.add_user(datalist[0], addr[0]) lsock.close() def stop(self): self.broadcast(0) self.thread_stop = True #聊天类 class Listen(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.addr = ('', CHATPORT) self.name = socket.getfqdn(socket.gethostname()) self.data = Data() self.thread_stop = False def ack(self, addr):#to be added 用来确认消息报的接受 return def run(self): lsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) lsock.bind(self.addr) while not self.thread_stop: data, addr = lsock.recvfrom(BUFSIZE) msg = self.data.handlechat(data) Cmd.output_with_rewrite(msg) lsock.close() def stop(self): self.thread_stop = True #启动入口类 class Start(): def __init__(self, user_list, name): self.name = name self.user_list = user_list self.data = Data() self.listen = Listen() self.back = Back(user_list, self.name) print '******* iichats ********' print ' Written by Kevince \n' print 'This is ' + self.name print self.data.gettime()+'\n' #帮助信息 def helpinfo(self): helps = "use ':' to use options\n" + \ "\t:exit\t\t\texit iichats\n" + \ "\t:list\t\t\tlist online users\n" + \ "\t:quit\t\t\tquit the chat mode\n" + \ "\t:chat [hostname]\tchatting to someone\n" + \ "\t:set status [on|off]\tturn on/of status alarms\n" Cmd.output(helps) def refresh(self): out = '\n******Onlinelist******\n' users = self.user_list.get_users() for key in users: out += key + "\n" out += '**********************\n' Cmd.output(out) def cmd_exit(self): os.exit(1) def cmd_list(self): self.refresh() def cmd_set(self, params): if params[0] == 'status': if params[1] == 'on': Cmd.open_notice() elif params[1] == 'off': Cmd.close_notice() def cmd_help(self): self.helpinfo() def cmd_check(self): self.back.check() print 'checking the list...' time.sleep(3) self.refresh() def cmd_chat(self, name): if not self.user_list.has_name(name): Cmd.output('this host does not exist') return ('', True) addr = (self.user_list.get_ip(name), CHATPORT) Cmd.output('now chatting to ' + name+ \ " ,use ':quit' to quit CHAT mode") Cmd.set_start(name + Cmd.INIT) return (addr, False) def chatting(self): csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) Cmd.output("use ':help' to get help information") addr = '' in_chat = True while True: arg = raw_input(Cmd.START) if len(arg) < 1: continue if arg[0] == ':': args = arg[1:].rsplit() if args[0] == 'quit': if in_chat: addr = 0 in_chat = False Cmd.reset_start() elif args[0] == 'exit': self.cmd_exit() elif args[0] == 'list': self.cmd_list() elif args[0] == 'set': self.cmd_set(args[1:]) elif args[0] == 'help': self.cmd_help() elif args[0] == 'check': self.cmd_check() elif args[0] == 'chat': addr, err = self.cmd_chat(args[1]) if not err: in_chat = True else: Cmd.output("invalid input, use ':help' to get some info") else: if not in_chat: Cmd.output("you can CHAT to someone, or use ':help'") continue data = arg msg = self.data.makechat(data, self.name) csock.sendto(msg, addr) csock.close() def start(self): self.back.setDaemon(True) self.back.start() self.listen.setDaemon(True) self.listen.start() self.chatting() self.back.stop() self.listen.stop() sys.exit() def main(): if len(sys.argv) < 2: name = socket.getfqdn(socket.gethostname()) else: name = sys.argv[1] user_list = UserList() s = Start(user_list, name) s.start() if __name__ == '__main__': main()
import socket
random_line_split
chat.py
#!/usr/bin/python #coding:utf8 #python 2.7.6 import threading import socket import time import os import sys import signal from readline import get_line_buffer BUFSIZE = 1024 BACKPORT = 7789 #状态监听端口 CHATPORT = 7788 #聊天信息发送窗口 class Cmd(): START = '>> ' INIT = '>> ' outmutex = threading.Lock() anoun = True @classmethod def output_with_rewrite(self, msg): if self.outmutex.acquire(1): sys.stdout.write('\r'+' '*(len(get_line_buffer())+len(self.START))+'\r') print msg sys.stdout.write(self.START+get_line_buffer()) sys.stdout.flush() self.outmutex.release() @classmethod def output(self, msg): if self.outmutex.acquire(1): print msg self.outmutex.release() @classmethod def set_start(self, start): self.START = start @classmethod def reset_start(self): self.START = self.INIT @classmethod def close_notice(self): self.anoun = False @classmethod def open_notice(self): self.anoun = True @classmethod def is_notice(self): return self.anoun class UserList(): def __init__(self): self.users = {} self.ips = {} self.mutex = threading.Lock() def add_user(self, name, ip): if self.mutex.acquire(1): self.users[name] = ip self.ips[ip] = name self.mutex.release() def has_ip(self, ip): ret = False if self.mutex.acquire(1): ret = ip in self.ips self.mutex.release() return ret def get_ip(self, name): ip = '' if self.mutex.acquire(1): ip = self.users[name] self.mutex.release() return ip def has_name(self, name): ret = False if self.mutex.acquire(1): ret = name in self.users self.mutex.release() return ret def clear(self): if self.mutex.acquire(1): self.users.clear() self.ips.clear() self.mutex.release() def del_by_ip(self, ip): if self.mutex.acquire(1): del self.users[ips[ip]] del self.ips[ip] self.mutex.release() def get_users(self): users = [] if self.mutex.acquire(1): for key in self.users: users += [key] self.mutex.release() return users #数据处理类(消息封装、分解) class Data(): def gettime(self): return time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time())) def getip(self): ip = os.popen("/sbin/ifconfig | grep 'inet addr' | awk '{print $2}'").read() ip = ip[ip.find(':')+1:ip.find('\n')] return ip def handlebc(self, data): data = data[5:] res = data.split('#opt:') return res def makebc(self, name, switch): data = 'name:%s#opt:%d' % (name, switch) return data def handlechat(self, data): msg = '\n' + self.gettime() + '\n' +'from '+ data + '\n' return msg def makechat(self, data, name): return name + ':' + data #后台监听类 class Back(threading.Thread): def __init__(self, user_list, name): threading.Thread.__init__(self) self.data = Data() self.user_list = user_list self.addrb = ('255.255.255.255', BACKPORT) self.addrl = ('', BACKPORT) self.name = name self.ip = self.data.getip() self.thread_stop = False def status(self, name, switch): if switch == 0: status = 'offline' elif switch == 1: status = 'online' #用来处理输入过程中被线程返回消息打乱的情况 Cmd.output_with_rewrite('[status]' + name + ' ' + status) def broadcast(self, switch): bsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) bsock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) data = self.data.makebc(self.name, switch) bsock.sendto(data, self.addrb) bsock.close() def response(self, addr, switch): rsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) data = self.data.makebc(self.name, switch) rsock.sendto(data, (addr, BACKPORT)) rsock.close() def check(self): self.user_list.clear() self.broadcast(1) def run(self): lsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) lsock.bind(self.addrl) self.broadcast(1) while not self.thread_stop: data, addr = lsock.recvfrom(BUFSIZE) datalist = self.data.handlebc(data) if datalist[1] == '0': if self.user_list.has_ip(addr[0]): if Cmd.is_notice(): self.status(datalist[0], 0) self.user_list.del_by_ip(addr[0]) elif datalist[1] == '1': if Cmd.is_notice() and datalist[0] != self.name: self.status(datalist[0], 1) self.user_list.add_user(datalist[0], addr[0]) elif datalist[1] == '2': if Cmd.is_notice() and datalist[0] != self.name: self.status(datalist[0], 1) self.user_list.add_user(datalist[0], addr[0]) lsock.close() def stop(self): self.broadcast(0) self.thread_stop = True #聊天类 class Listen(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.addr = ('', CHATPORT) self.name = socket.getfqdn(socket.gethostname()) self.data = Data() self.thread_stop = False def ack(self, addr):#to be added 用来确认消息报的接受 return def run(self): lsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) lsock.bind(self.addr) while not self.thread_stop: data, addr = lsock.recvfrom(BUFSIZE) msg = self.data.handlechat(data) Cmd.output_with_rewrite(msg) lsock.close() def stop(self): self.thread_stop = True #启动入口类 class Start(): def __init__(self, user_list, name): self.name = name self.user_list = user_list self.data = Data() self.listen = Listen() self.back = Back(user_list, self.name) print '******* iichats ********' print ' Written by Kevince \n' print 'This is ' + self.name print self.data.gettime()+'\n' #帮助信息 def helpinfo(self): helps = "use ':' to use options\n" + \ "\t:exit\t\t\texit iichats\n" + \ "\t:list\t\t\tlist online users\n" + \ "\t:quit\t\t\tquit the chat mode\n" + \ "\t:chat [hostname]\tchatting to someone\n" + \ "\t:set status [on|off]\tturn on/of status alarms\n" Cmd.output(helps) def refresh(self): out = '\n******Onlinelist******\n' users = self.user_list.get_users() for key in users: out += key + "\n" out += '**********************\n' Cmd.output(out) def cmd_exit(self): os.exit(1) def cmd_list(self): self.refresh() def cmd_set(self, params): if params[0] == 'status': if params[1] == 'on': Cmd.open_notice() elif params[1] == 'off': Cmd.close_notice() def cmd_help(self): self.helpinfo() def cmd_check(self): self.back.check() print 'checking the list...' time.sleep(3) self.refresh() def cmd_chat(self, name): if not self.user_list.has_name(name): Cmd.output('this host does not exist') return ('', True) addr = (self.user_list.get_ip(name), CHATPORT) Cmd.output('now chatting to ' + name+ \ " ,use ':quit' to quit CHAT mode") Cmd.set_start(name + Cmd.INIT) return (addr, False) def chatting(self): csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) Cmd.output("use ':help' to get help information") addr = '' in_chat = True while True: arg = raw_input(Cmd.START) if len(arg) < 1: continue if arg[0] == ':': args = arg[1:].rsplit()
f.listen.start() self.chatting() self.back.stop() self.listen.stop() sys.exit() def main(): if len(sys.argv) < 2: name = socket.getfqdn(socket.gethostname()) else: name = sys.argv[1] user_list = UserList() s = Start(user_list, name) s.start() if __name__ == '__main__': main()
if args[0] == 'quit': if in_chat: addr = 0 in_chat = False Cmd.reset_start() elif args[0] == 'exit': self.cmd_exit() elif args[0] == 'list': self.cmd_list() elif args[0] == 'set': self.cmd_set(args[1:]) elif args[0] == 'help': self.cmd_help() elif args[0] == 'check': self.cmd_check() elif args[0] == 'chat': addr, err = self.cmd_chat(args[1]) if not err: in_chat = True else: Cmd.output("invalid input, use ':help' to get some info") else: if not in_chat: Cmd.output("you can CHAT to someone, or use ':help'") continue data = arg msg = self.data.makechat(data, self.name) csock.sendto(msg, addr) csock.close() def start(self): self.back.setDaemon(True) self.back.start() self.listen.setDaemon(True) sel
conditional_block
chat.py
#!/usr/bin/python #coding:utf8 #python 2.7.6 import threading import socket import time import os import sys import signal from readline import get_line_buffer BUFSIZE = 1024 BACKPORT = 7789 #状态监听端口 CHATPORT = 7788 #聊天信息发送窗口 class Cmd(): START = '>> ' INIT = '>> ' outmutex = threading.Lock() anoun = True @classmethod def output_with_rewrite(self, msg): if self.outmutex.acquire(1): sys.stdout.write('\r'+' '*(len(get_line_buffer())+len(self.START))+'\r') print msg sys.stdout.write(self.START+get_line_buffer()) sys.stdout.flush() self.outmutex.release() @classmethod def output(self, msg): if self.outmutex.acquire(1): print msg self.outmutex.release() @classmethod def set_start(self, start): self.START = start @classmethod def reset_start(self): self.START = self.INIT @classmethod def close_notice(self): self.anoun = False @classmethod def open_notice(self): self.anoun = True @classmethod def is_notice(self): return self.anoun class UserList(): def __init__(self): self.users = {} self.ips = {} self.mutex = threading.Lock() def add_user(self, name, ip): if self.mutex.acquire(1): self.users[name] = ip self.ips[ip] = name self.mutex.release() def has_ip(self, ip): ret = False if self.mutex.acquire(1): ret = ip in self.ips self.mutex.release() return ret def get_ip(self, name): ip = '' if self.mutex.acquire(1): ip = self.users[name] self.mutex.release() return ip def has_name(self, name): ret = False if self.mutex.acquire(1): ret = name in self.users self.mutex.release() return ret def clear(self): if self.mutex.acquire(1): self.users.clear() self.ips.clear() self.mutex.release() def del_by_ip(self, ip): if self.mutex.acquire(1): del self.users[ips[ip]] del self.ips[ip] self.mutex.release() def get_users(self): users = [] if self.mutex.acquire(1): for key in self.users: users += [key] self.mutex.release() return users #数据处理类(消息封装、分解) class Data(): def gettime(self): return time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time())) def getip(self): ip = os.popen("/sbin/ifconfig | grep 'inet addr' | awk '{print $2}'").read() ip = ip[ip.find(':')+1:ip.find('\n')] return ip def handlebc(self, data): data = data[5:] res = data.split('#opt:') return res def makebc(self, name, switch): data = 'name:%s#opt:%d' % (name, switch) return data def handlechat(self, data): msg = '\n' + self.gettime() + '\n' +'from '+ data + '\n' return msg def makechat(self, data, name): return name + ':' + data #后台监听类 class Back(threading.Thread): def __init__(self, user_list, name): threading.Thread.__init__(self) self.data = Data() self.user_list = user_list self.addrb = ('255.255.255.255', BACKPORT) self.addrl = ('', BACKPORT) self.name = name self.ip = self.data.getip() self.thread_stop = False def status(self, name, switch): if switch == 0: status = 'offline' elif switch == 1: status = 'online' #用来处理输入过程中被线程返回消息打乱的情况 Cmd.output_with_rewrite('[status]' + name + ' ' + status) def broadcast(self, switch): bsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) bsock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) data = self.data.makebc(self.name, switch) bsock.sendto(data, self.addrb) bsock.close() def response(self, addr, switch): rsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) data = self.data.makebc(self.name, switch) rsock.sendto(data, (addr, BACKPORT)) rsock.close() def check(self): self.user_list.clear() self.broadcast(1) def run(self): lsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) lsock.bind(self.addrl) self.broadcast(1) while not self.thread_stop: data, addr = lsock.recvfrom(BUFSIZE) datalist = self.data.handlebc(data) if datalist[1] == '0': if self.user_list.has_ip(addr[0]): if Cmd.is_notice(): self.status(datalist[0], 0) self.user_list.del_by_ip(addr[0]) elif datalist[1] == '1': if Cmd.is_notice() and datalist[0] != self.name: self.status(datalist[0], 1) self.user_list.add_user(datalist[0], addr[0]) elif datalist[1] == '2': if Cmd.is_notice() and datalist[0] != self.name: self.status(datalist[0], 1) self.user_list.add_user(datalist[0], addr[0]) lsock.close() def stop(self): self.broadcast(0) self.thread_stop = True #聊天类 class Listen(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.addr = ('', CHATPORT) self.name = socket.getfqdn(socket.gethostname()) self.data = Data() self.thread_stop = False def ack(self, addr):#to be added 用来确认消息报的接受 return def run(self): lsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) lsock.bind(self.addr) while not self.thread_stop: data, addr = lsock.recvfrom(BUFSIZE) msg = self.data.handlechat(data) Cmd.output_with_rewrite(msg) lsock.close() def stop(self): self.thread_stop = True #启动入口类 class Start(): def __init__(self, user_list, name): self.name = name self.user_list = user_list self.data = Data() self.listen = Listen() self.back = Back(user_list, self.name) print '******* iichats ********' print ' Written by Kevince \n' print 'This is ' + self.name print self.data.gettime()+'\n' #帮助信息 def helpinfo(self): helps = "use ':' to use options\n" + \ "\t:exit\t\t\texit iichats\n" + \ "\t:list\t\t\tlist online users\n" + \ "\t:quit\t\t\tquit the chat mode\n" + \ "\t:chat [hostname]\tchatting to someone\n" + \ "\t:set status [on|off]\tturn on/of status alarms\n" Cmd.output(helps) def refresh(self): out = '\n******Onlinelist******\n' users = self.user_list.get_users() for key in users: out += key + "\n" out += '**********************\n' Cmd.output(out) def cmd_exit(self): os.exit(1) def cmd_list(self): self.refresh() def cmd_set(self, params): if params[0] == 'status': if params[1] == 'on': Cmd.open_notice() elif params[1] == 'off': Cmd.close_notice() def cmd_help(self): self.helpinfo() def cmd_check(self): self.back.check() print 'checking the list...' time.sleep(3) self.refresh() def cmd_chat(self, name): if not self.user_list.has_name(name): Cmd.output('this host does not exist') return ('', True)
r = (self.user_list.get_ip(name), CHATPORT) Cmd.output('now chatting to ' + name+ \ " ,use ':quit' to quit CHAT mode") Cmd.set_start(name + Cmd.INIT) return (addr, False) def chatting(self): csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) Cmd.output("use ':help' to get help information") addr = '' in_chat = True while True: arg = raw_input(Cmd.START) if len(arg) < 1: continue if arg[0] == ':': args = arg[1:].rsplit() if args[0] == 'quit': if in_chat: addr = 0 in_chat = False Cmd.reset_start() elif args[0] == 'exit': self.cmd_exit() elif args[0] == 'list': self.cmd_list() elif args[0] == 'set': self.cmd_set(args[1:]) elif args[0] == 'help': self.cmd_help() elif args[0] == 'check': self.cmd_check() elif args[0] == 'chat': addr, err = self.cmd_chat(args[1]) if not err: in_chat = True else: Cmd.output("invalid input, use ':help' to get some info") else: if not in_chat: Cmd.output("you can CHAT to someone, or use ':help'") continue data = arg msg = self.data.makechat(data, self.name) csock.sendto(msg, addr) csock.close() def start(self): self.back.setDaemon(True) self.back.start() self.listen.setDaemon(True) self.listen.start() self.chatting() self.back.stop() self.listen.stop() sys.exit() def main(): if len(sys.argv) < 2: name = socket.getfqdn(socket.gethostname()) else: name = sys.argv[1] user_list = UserList() s = Start(user_list, name) s.start() if __name__ == '__main__': main()
add
identifier_name
environment.go
/* Environments. */ /* * Copyright (c) 2013-2017, Jeremy Bingham (<jeremy@goiardi.gl>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Package environment provides... environments. They're like roles, but more // so, except without run lists. They're a convenient way to share many // attributes and cookbook version constraints among many servers. package environment import ( "database/sql" "fmt" "github.com/ctdk/goiardi/config" "github.com/ctdk/goiardi/cookbook" "github.com/ctdk/goiardi/datastore" "github.com/ctdk/goiardi/indexer" "github.com/ctdk/goiardi/util" "net/http" "sort" ) // ChefEnvironment is a collection of attributes and cookbook versions for // organizing how nodes are deployed. type ChefEnvironment struct { Name string `json:"name"` ChefType string `json:"chef_type"` JSONClass string `json:"json_class"` Description string `json:"description"` Default map[string]interface{} `json:"default_attributes"` Override map[string]interface{} `json:"override_attributes"` CookbookVersions map[string]string `json:"cookbook_versions"` } // New creates a new environment, returning an error if the environment already // exists or you try to create an environment named "_default". func New(name string) (*ChefEnvironment, util.Gerror) { if !util.ValidateEnvName(name) { err := util.Errorf("Field 'name' invalid") err.SetStatus(http.StatusBadRequest) return nil, err } var found bool if config.UsingDB() { var eerr error found, eerr = checkForEnvironmentSQL(datastore.Dbh, name) if eerr != nil { err := util.CastErr(eerr) err.SetStatus(http.StatusInternalServerError) return nil, err } } else { ds := datastore.New() _, found = ds.Get("env", name) } if found || name == "_default" { err := util.Errorf("Environment already exists") return nil, err } env := &ChefEnvironment{ Name: name, ChefType: "environment", JSONClass: "Chef::Environment", Default: map[string]interface{}{}, Override: map[string]interface{}{}, CookbookVersions: map[string]string{}, } return env, nil } // NewFromJSON creates a new environment from JSON uploaded to the server. func NewFromJSON(jsonEnv map[string]interface{}) (*ChefEnvironment, util.Gerror) { env, err := New(jsonEnv["name"].(string)) if err != nil { return nil, err } err = env.UpdateFromJSON(jsonEnv) if err != nil { return nil, err } return env, nil } // UpdateFromJSON updates an existing environment from JSON uploaded to the // server. func (e *ChefEnvironment) UpdateFromJSON(jsonEnv map[string]interface{}) util.Gerror { if e.Name != jsonEnv["name"].(string) { err := util.Errorf("Environment name %s and %s from JSON do not match", e.Name, jsonEnv["name"].(string)) return err } else if e.Name == "_default" { err := util.Errorf("The '_default' environment cannot be modified.") err.SetStatus(http.StatusMethodNotAllowed) return err } /* Validations */ validElements := []string{"name", "chef_type", "json_class", "description", "default_attributes", "override_attributes", "cookbook_versions"} ValidElem: for k := range jsonEnv { for _, i := range validElements { if k == i { continue ValidElem } } err := util.Errorf("Invalid key %s in request body", k) return err } var verr util.Gerror attrs := []string{"default_attributes", "override_attributes"} for _, a := range attrs { jsonEnv[a], verr = util.ValidateAttributes(a, jsonEnv[a]) if verr != nil { return verr } } jsonEnv["json_class"], verr = util.ValidateAsFieldString(jsonEnv["json_class"]) if verr != nil { if verr.Error() == "Field 'name' nil" { jsonEnv["json_class"] = e.JSONClass } else { return verr } } else { if jsonEnv["json_class"].(string) != "Chef::Environment" { verr = util.Errorf("Field 'json_class' invalid") return verr } } jsonEnv["chef_type"], verr = util.ValidateAsFieldString(jsonEnv["chef_type"]) if verr != nil { if verr.Error() == "Field 'name' nil" { jsonEnv["chef_type"] = e.ChefType } else { return verr } } else { if jsonEnv["chef_type"].(string) != "environment" { verr = util.Errorf("Field 'chef_type' invalid") return verr } } jsonEnv["cookbook_versions"], verr = util.ValidateAttributes("cookbook_versions", jsonEnv["cookbook_versions"]) if verr != nil { return verr } for k, v := range jsonEnv["cookbook_versions"].(map[string]interface{}) { if !util.ValidateEnvName(k) || k == "" { merr := util.Errorf("Cookbook name %s invalid", k) merr.SetStatus(http.StatusBadRequest) return merr } if v == nil { verr = util.Errorf("Invalid version number") return verr } _, verr = util.ValidateAsConstraint(v) if verr != nil { /* try validating as a version */ v, verr = util.ValidateAsVersion(v) if verr != nil { return verr } } } jsonEnv["description"], verr = util.ValidateAsString(jsonEnv["description"]) if verr != nil { if verr.Error() == "Field 'name' missing" { jsonEnv["description"] = "" } else { return verr } } e.ChefType = jsonEnv["chef_type"].(string) e.JSONClass = jsonEnv["json_class"].(string) e.Description = jsonEnv["description"].(string) e.Default = jsonEnv["default_attributes"].(map[string]interface{}) e.Override = jsonEnv["override_attributes"].(map[string]interface{}) /* clear out, then loop over the cookbook versions */ e.CookbookVersions = make(map[string]string, len(jsonEnv["cookbook_versions"].(map[string]interface{}))) for c, v := range jsonEnv["cookbook_versions"].(map[string]interface{}) { e.CookbookVersions[c] = v.(string) } return nil } // Get an environment. func Get(envName string) (*ChefEnvironment, util.Gerror) { if envName == "_default" { return defaultEnvironment(), nil } var env *ChefEnvironment var found bool if config.UsingDB() { var err error env, err = getEnvironmentSQL(envName) if err != nil { var gerr util.Gerror if err != sql.ErrNoRows { gerr = util.CastErr(err) gerr.SetStatus(http.StatusInternalServerError) return nil, gerr
found = true } } else { ds := datastore.New() var e interface{} e, found = ds.Get("env", envName) if e != nil { env = e.(*ChefEnvironment) } } if !found { err := util.Errorf("Cannot load environment %s", envName) err.SetStatus(http.StatusNotFound) return nil, err } return env, nil } // DoesExist checks if the environment in question exists or not func DoesExist(environmentName string) (bool, util.Gerror) { var found bool if config.UsingDB() { var cerr error found, cerr = checkForEnvironmentSQL(datastore.Dbh, environmentName) if cerr != nil { err := util.Errorf(cerr.Error()) err.SetStatus(http.StatusInternalServerError) return false, err } } else { ds := datastore.New() _, found = ds.Get("env", environmentName) } return found, nil } // GetMulti gets multiple environmets from a given slice of environment names. func GetMulti(envNames []string) ([]*ChefEnvironment, util.Gerror) { var envs []*ChefEnvironment if config.UsingDB() { var err error envs, err = getMultiSQL(envNames) if err != nil && err != sql.ErrNoRows { return nil, util.CastErr(err) } } else { envs = make([]*ChefEnvironment, 0, len(envNames)) for _, e := range envNames { eo, _ := Get(e) if eo != nil { envs = append(envs, eo) } } } return envs, nil } // MakeDefaultEnvironment creates the default environment on startup. func MakeDefaultEnvironment() { var de *ChefEnvironment if config.UsingDB() { // The default environment is pre-created in the db schema when // it's loaded. Re-indexing the default environment doesn't // hurt anything though, so just get the usual default env and // index it, not bothering with these other steps that are // easier to do with the in-memory mode. de = defaultEnvironment() } else { ds := datastore.New() // only create the new default environment if we don't already have one // saved if _, found := ds.Get("env", "_default"); found { return } de = defaultEnvironment() ds.Set("env", de.Name, de) } indexer.IndexObj(de) } func defaultEnvironment() *ChefEnvironment { return &ChefEnvironment{ Name: "_default", ChefType: "environment", JSONClass: "Chef::Environment", Description: "The default Chef environment", Default: map[string]interface{}{}, Override: map[string]interface{}{}, CookbookVersions: map[string]string{}, } } // Save the environment. Returns an error if you try to save the "_default" // environment. func (e *ChefEnvironment) Save() util.Gerror { if e.Name == "_default" { err := util.Errorf("The '_default' environment cannot be modified.") err.SetStatus(http.StatusMethodNotAllowed) return err } if config.Config.UseMySQL { err := e.saveEnvironmentMySQL() if err != nil { return err } } else if config.Config.UsePostgreSQL { err := e.saveEnvironmentPostgreSQL() if err != nil { return err } } else { ds := datastore.New() ds.Set("env", e.Name, e) } indexer.IndexObj(e) return nil } // Delete the environment, returning an error if you try to delete the // "_default" environment. func (e *ChefEnvironment) Delete() error { if e.Name == "_default" { err := fmt.Errorf("The '_default' environment cannot be modified.") return err } if config.UsingDB() { if err := e.deleteEnvironmentSQL(); err != nil { return nil } } else { ds := datastore.New() ds.Delete("env", e.Name) } indexer.DeleteItemFromCollection("environment", e.Name) return nil } // GetList gets a list of all environments on this server. func GetList() []string { var envList []string if config.UsingDB() { envList = getEnvironmentList() } else { ds := datastore.New() envList = ds.GetList("env") envList = append(envList, "_default") } return envList } // GetName returns the environment's name. func (e *ChefEnvironment) GetName() string { return e.Name } // URLType returns the base of an environment's URL. func (e *ChefEnvironment) URLType() string { return "environments" } func (e *ChefEnvironment) cookbookList() []*cookbook.Cookbook { return cookbook.AllCookbooks() } // AllCookbookHash returns a hash of the cookbooks and their versions available // to this environment. func (e *ChefEnvironment) AllCookbookHash(numVersions interface{}) map[string]interface{} { cbHash := make(map[string]interface{}) cbList := e.cookbookList() for _, cb := range cbList { if cb == nil { continue } cbHash[cb.Name] = cb.ConstrainedInfoHash(numVersions, e.CookbookVersions[cb.Name]) } return cbHash } // RecipeList gets a list of recipes available to this environment. func (e *ChefEnvironment) RecipeList() []string { recipeList := make(map[string]string) cbList := e.cookbookList() for _, cb := range cbList { if cb == nil { continue } cbv := cb.LatestConstrained(e.CookbookVersions[cb.Name]) if cbv == nil { continue } rlist, _ := cbv.RecipeList() for _, recipe := range rlist { recipeList[recipe] = recipe } } sortedRecipes := make([]string, len(recipeList)) i := 0 for k := range recipeList { sortedRecipes[i] = k i++ } sort.Strings(sortedRecipes) return sortedRecipes } /* Search indexing methods */ // DocID returns the environment's name. func (e *ChefEnvironment) DocID() string { return e.Name } // Index returns the environment's type so the indexer knows where it should go. func (e *ChefEnvironment) Index() string { return "environment" } // Flatten the environment so it's suitable for indexing. func (e *ChefEnvironment) Flatten() map[string]interface{} { return util.FlattenObj(e) } // AllEnvironments returns a slice of all environments on this server. func AllEnvironments() []*ChefEnvironment { var environments []*ChefEnvironment if config.UsingDB() { environments = allEnvironmentsSQL() } else { envList := GetList() for _, e := range envList { en, err := Get(e) if err != nil { continue } environments = append(environments, en) } } return environments }
} found = false } else {
random_line_split
environment.go
/* Environments. */ /* * Copyright (c) 2013-2017, Jeremy Bingham (<jeremy@goiardi.gl>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Package environment provides... environments. They're like roles, but more // so, except without run lists. They're a convenient way to share many // attributes and cookbook version constraints among many servers. package environment import ( "database/sql" "fmt" "github.com/ctdk/goiardi/config" "github.com/ctdk/goiardi/cookbook" "github.com/ctdk/goiardi/datastore" "github.com/ctdk/goiardi/indexer" "github.com/ctdk/goiardi/util" "net/http" "sort" ) // ChefEnvironment is a collection of attributes and cookbook versions for // organizing how nodes are deployed. type ChefEnvironment struct { Name string `json:"name"` ChefType string `json:"chef_type"` JSONClass string `json:"json_class"` Description string `json:"description"` Default map[string]interface{} `json:"default_attributes"` Override map[string]interface{} `json:"override_attributes"` CookbookVersions map[string]string `json:"cookbook_versions"` } // New creates a new environment, returning an error if the environment already // exists or you try to create an environment named "_default". func New(name string) (*ChefEnvironment, util.Gerror) { if !util.ValidateEnvName(name) { err := util.Errorf("Field 'name' invalid") err.SetStatus(http.StatusBadRequest) return nil, err } var found bool if config.UsingDB() { var eerr error found, eerr = checkForEnvironmentSQL(datastore.Dbh, name) if eerr != nil { err := util.CastErr(eerr) err.SetStatus(http.StatusInternalServerError) return nil, err } } else { ds := datastore.New() _, found = ds.Get("env", name) } if found || name == "_default" { err := util.Errorf("Environment already exists") return nil, err } env := &ChefEnvironment{ Name: name, ChefType: "environment", JSONClass: "Chef::Environment", Default: map[string]interface{}{}, Override: map[string]interface{}{}, CookbookVersions: map[string]string{}, } return env, nil } // NewFromJSON creates a new environment from JSON uploaded to the server. func NewFromJSON(jsonEnv map[string]interface{}) (*ChefEnvironment, util.Gerror) { env, err := New(jsonEnv["name"].(string)) if err != nil { return nil, err } err = env.UpdateFromJSON(jsonEnv) if err != nil { return nil, err } return env, nil } // UpdateFromJSON updates an existing environment from JSON uploaded to the // server. func (e *ChefEnvironment) UpdateFromJSON(jsonEnv map[string]interface{}) util.Gerror { if e.Name != jsonEnv["name"].(string) { err := util.Errorf("Environment name %s and %s from JSON do not match", e.Name, jsonEnv["name"].(string)) return err } else if e.Name == "_default" { err := util.Errorf("The '_default' environment cannot be modified.") err.SetStatus(http.StatusMethodNotAllowed) return err } /* Validations */ validElements := []string{"name", "chef_type", "json_class", "description", "default_attributes", "override_attributes", "cookbook_versions"} ValidElem: for k := range jsonEnv { for _, i := range validElements { if k == i { continue ValidElem } } err := util.Errorf("Invalid key %s in request body", k) return err } var verr util.Gerror attrs := []string{"default_attributes", "override_attributes"} for _, a := range attrs { jsonEnv[a], verr = util.ValidateAttributes(a, jsonEnv[a]) if verr != nil { return verr } } jsonEnv["json_class"], verr = util.ValidateAsFieldString(jsonEnv["json_class"]) if verr != nil { if verr.Error() == "Field 'name' nil" { jsonEnv["json_class"] = e.JSONClass } else { return verr } } else { if jsonEnv["json_class"].(string) != "Chef::Environment" { verr = util.Errorf("Field 'json_class' invalid") return verr } } jsonEnv["chef_type"], verr = util.ValidateAsFieldString(jsonEnv["chef_type"]) if verr != nil { if verr.Error() == "Field 'name' nil" { jsonEnv["chef_type"] = e.ChefType } else { return verr } } else { if jsonEnv["chef_type"].(string) != "environment" { verr = util.Errorf("Field 'chef_type' invalid") return verr } } jsonEnv["cookbook_versions"], verr = util.ValidateAttributes("cookbook_versions", jsonEnv["cookbook_versions"]) if verr != nil { return verr } for k, v := range jsonEnv["cookbook_versions"].(map[string]interface{}) { if !util.ValidateEnvName(k) || k == "" { merr := util.Errorf("Cookbook name %s invalid", k) merr.SetStatus(http.StatusBadRequest) return merr } if v == nil { verr = util.Errorf("Invalid version number") return verr } _, verr = util.ValidateAsConstraint(v) if verr != nil { /* try validating as a version */ v, verr = util.ValidateAsVersion(v) if verr != nil { return verr } } } jsonEnv["description"], verr = util.ValidateAsString(jsonEnv["description"]) if verr != nil { if verr.Error() == "Field 'name' missing" { jsonEnv["description"] = "" } else { return verr } } e.ChefType = jsonEnv["chef_type"].(string) e.JSONClass = jsonEnv["json_class"].(string) e.Description = jsonEnv["description"].(string) e.Default = jsonEnv["default_attributes"].(map[string]interface{}) e.Override = jsonEnv["override_attributes"].(map[string]interface{}) /* clear out, then loop over the cookbook versions */ e.CookbookVersions = make(map[string]string, len(jsonEnv["cookbook_versions"].(map[string]interface{}))) for c, v := range jsonEnv["cookbook_versions"].(map[string]interface{}) { e.CookbookVersions[c] = v.(string) } return nil } // Get an environment. func Get(envName string) (*ChefEnvironment, util.Gerror) { if envName == "_default" { return defaultEnvironment(), nil } var env *ChefEnvironment var found bool if config.UsingDB() { var err error env, err = getEnvironmentSQL(envName) if err != nil { var gerr util.Gerror if err != sql.ErrNoRows { gerr = util.CastErr(err) gerr.SetStatus(http.StatusInternalServerError) return nil, gerr } found = false } else { found = true } } else { ds := datastore.New() var e interface{} e, found = ds.Get("env", envName) if e != nil { env = e.(*ChefEnvironment) } } if !found { err := util.Errorf("Cannot load environment %s", envName) err.SetStatus(http.StatusNotFound) return nil, err } return env, nil } // DoesExist checks if the environment in question exists or not func DoesExist(environmentName string) (bool, util.Gerror) { var found bool if config.UsingDB() { var cerr error found, cerr = checkForEnvironmentSQL(datastore.Dbh, environmentName) if cerr != nil { err := util.Errorf(cerr.Error()) err.SetStatus(http.StatusInternalServerError) return false, err } } else { ds := datastore.New() _, found = ds.Get("env", environmentName) } return found, nil } // GetMulti gets multiple environmets from a given slice of environment names. func GetMulti(envNames []string) ([]*ChefEnvironment, util.Gerror) { var envs []*ChefEnvironment if config.UsingDB() { var err error envs, err = getMultiSQL(envNames) if err != nil && err != sql.ErrNoRows { return nil, util.CastErr(err) } } else { envs = make([]*ChefEnvironment, 0, len(envNames)) for _, e := range envNames { eo, _ := Get(e) if eo != nil { envs = append(envs, eo) } } } return envs, nil } // MakeDefaultEnvironment creates the default environment on startup. func MakeDefaultEnvironment() { var de *ChefEnvironment if config.UsingDB() { // The default environment is pre-created in the db schema when // it's loaded. Re-indexing the default environment doesn't // hurt anything though, so just get the usual default env and // index it, not bothering with these other steps that are // easier to do with the in-memory mode. de = defaultEnvironment() } else { ds := datastore.New() // only create the new default environment if we don't already have one // saved if _, found := ds.Get("env", "_default"); found { return } de = defaultEnvironment() ds.Set("env", de.Name, de) } indexer.IndexObj(de) } func defaultEnvironment() *ChefEnvironment { return &ChefEnvironment{ Name: "_default", ChefType: "environment", JSONClass: "Chef::Environment", Description: "The default Chef environment", Default: map[string]interface{}{}, Override: map[string]interface{}{}, CookbookVersions: map[string]string{}, } } // Save the environment. Returns an error if you try to save the "_default" // environment. func (e *ChefEnvironment) Save() util.Gerror { if e.Name == "_default" { err := util.Errorf("The '_default' environment cannot be modified.") err.SetStatus(http.StatusMethodNotAllowed) return err } if config.Config.UseMySQL { err := e.saveEnvironmentMySQL() if err != nil { return err } } else if config.Config.UsePostgreSQL { err := e.saveEnvironmentPostgreSQL() if err != nil { return err } } else { ds := datastore.New() ds.Set("env", e.Name, e) } indexer.IndexObj(e) return nil } // Delete the environment, returning an error if you try to delete the // "_default" environment. func (e *ChefEnvironment) Delete() error { if e.Name == "_default" { err := fmt.Errorf("The '_default' environment cannot be modified.") return err } if config.UsingDB() { if err := e.deleteEnvironmentSQL(); err != nil { return nil } } else { ds := datastore.New() ds.Delete("env", e.Name) } indexer.DeleteItemFromCollection("environment", e.Name) return nil } // GetList gets a list of all environments on this server. func GetList() []string { var envList []string if config.UsingDB() { envList = getEnvironmentList() } else { ds := datastore.New() envList = ds.GetList("env") envList = append(envList, "_default") } return envList } // GetName returns the environment's name. func (e *ChefEnvironment) GetName() string { return e.Name } // URLType returns the base of an environment's URL. func (e *ChefEnvironment) URLType() string { return "environments" } func (e *ChefEnvironment) cookbookList() []*cookbook.Cookbook { return cookbook.AllCookbooks() } // AllCookbookHash returns a hash of the cookbooks and their versions available // to this environment. func (e *ChefEnvironment) AllCookbookHash(numVersions interface{}) map[string]interface{} { cbHash := make(map[string]interface{}) cbList := e.cookbookList() for _, cb := range cbList { if cb == nil { continue } cbHash[cb.Name] = cb.ConstrainedInfoHash(numVersions, e.CookbookVersions[cb.Name]) } return cbHash } // RecipeList gets a list of recipes available to this environment. func (e *ChefEnvironment) RecipeList() []string { recipeList := make(map[string]string) cbList := e.cookbookList() for _, cb := range cbList { if cb == nil { continue } cbv := cb.LatestConstrained(e.CookbookVersions[cb.Name]) if cbv == nil { continue } rlist, _ := cbv.RecipeList() for _, recipe := range rlist { recipeList[recipe] = recipe } } sortedRecipes := make([]string, len(recipeList)) i := 0 for k := range recipeList { sortedRecipes[i] = k i++ } sort.Strings(sortedRecipes) return sortedRecipes } /* Search indexing methods */ // DocID returns the environment's name. func (e *ChefEnvironment) DocID() string { return e.Name } // Index returns the environment's type so the indexer knows where it should go. func (e *ChefEnvironment) Index() string { return "environment" } // Flatten the environment so it's suitable for indexing. func (e *ChefEnvironment) Flatten() map[string]interface{} { return util.FlattenObj(e) } // AllEnvironments returns a slice of all environments on this server. func
() []*ChefEnvironment { var environments []*ChefEnvironment if config.UsingDB() { environments = allEnvironmentsSQL() } else { envList := GetList() for _, e := range envList { en, err := Get(e) if err != nil { continue } environments = append(environments, en) } } return environments }
AllEnvironments
identifier_name
environment.go
/* Environments. */ /* * Copyright (c) 2013-2017, Jeremy Bingham (<jeremy@goiardi.gl>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Package environment provides... environments. They're like roles, but more // so, except without run lists. They're a convenient way to share many // attributes and cookbook version constraints among many servers. package environment import ( "database/sql" "fmt" "github.com/ctdk/goiardi/config" "github.com/ctdk/goiardi/cookbook" "github.com/ctdk/goiardi/datastore" "github.com/ctdk/goiardi/indexer" "github.com/ctdk/goiardi/util" "net/http" "sort" ) // ChefEnvironment is a collection of attributes and cookbook versions for // organizing how nodes are deployed. type ChefEnvironment struct { Name string `json:"name"` ChefType string `json:"chef_type"` JSONClass string `json:"json_class"` Description string `json:"description"` Default map[string]interface{} `json:"default_attributes"` Override map[string]interface{} `json:"override_attributes"` CookbookVersions map[string]string `json:"cookbook_versions"` } // New creates a new environment, returning an error if the environment already // exists or you try to create an environment named "_default". func New(name string) (*ChefEnvironment, util.Gerror) { if !util.ValidateEnvName(name) { err := util.Errorf("Field 'name' invalid") err.SetStatus(http.StatusBadRequest) return nil, err } var found bool if config.UsingDB() { var eerr error found, eerr = checkForEnvironmentSQL(datastore.Dbh, name) if eerr != nil { err := util.CastErr(eerr) err.SetStatus(http.StatusInternalServerError) return nil, err } } else { ds := datastore.New() _, found = ds.Get("env", name) } if found || name == "_default" { err := util.Errorf("Environment already exists") return nil, err } env := &ChefEnvironment{ Name: name, ChefType: "environment", JSONClass: "Chef::Environment", Default: map[string]interface{}{}, Override: map[string]interface{}{}, CookbookVersions: map[string]string{}, } return env, nil } // NewFromJSON creates a new environment from JSON uploaded to the server. func NewFromJSON(jsonEnv map[string]interface{}) (*ChefEnvironment, util.Gerror) { env, err := New(jsonEnv["name"].(string)) if err != nil { return nil, err } err = env.UpdateFromJSON(jsonEnv) if err != nil { return nil, err } return env, nil } // UpdateFromJSON updates an existing environment from JSON uploaded to the // server. func (e *ChefEnvironment) UpdateFromJSON(jsonEnv map[string]interface{}) util.Gerror { if e.Name != jsonEnv["name"].(string) { err := util.Errorf("Environment name %s and %s from JSON do not match", e.Name, jsonEnv["name"].(string)) return err } else if e.Name == "_default" { err := util.Errorf("The '_default' environment cannot be modified.") err.SetStatus(http.StatusMethodNotAllowed) return err } /* Validations */ validElements := []string{"name", "chef_type", "json_class", "description", "default_attributes", "override_attributes", "cookbook_versions"} ValidElem: for k := range jsonEnv { for _, i := range validElements { if k == i { continue ValidElem } } err := util.Errorf("Invalid key %s in request body", k) return err } var verr util.Gerror attrs := []string{"default_attributes", "override_attributes"} for _, a := range attrs { jsonEnv[a], verr = util.ValidateAttributes(a, jsonEnv[a]) if verr != nil { return verr } } jsonEnv["json_class"], verr = util.ValidateAsFieldString(jsonEnv["json_class"]) if verr != nil { if verr.Error() == "Field 'name' nil" { jsonEnv["json_class"] = e.JSONClass } else { return verr } } else { if jsonEnv["json_class"].(string) != "Chef::Environment" { verr = util.Errorf("Field 'json_class' invalid") return verr } } jsonEnv["chef_type"], verr = util.ValidateAsFieldString(jsonEnv["chef_type"]) if verr != nil { if verr.Error() == "Field 'name' nil" { jsonEnv["chef_type"] = e.ChefType } else { return verr } } else { if jsonEnv["chef_type"].(string) != "environment" { verr = util.Errorf("Field 'chef_type' invalid") return verr } } jsonEnv["cookbook_versions"], verr = util.ValidateAttributes("cookbook_versions", jsonEnv["cookbook_versions"]) if verr != nil { return verr } for k, v := range jsonEnv["cookbook_versions"].(map[string]interface{}) { if !util.ValidateEnvName(k) || k == "" { merr := util.Errorf("Cookbook name %s invalid", k) merr.SetStatus(http.StatusBadRequest) return merr } if v == nil { verr = util.Errorf("Invalid version number") return verr } _, verr = util.ValidateAsConstraint(v) if verr != nil { /* try validating as a version */ v, verr = util.ValidateAsVersion(v) if verr != nil { return verr } } } jsonEnv["description"], verr = util.ValidateAsString(jsonEnv["description"]) if verr != nil { if verr.Error() == "Field 'name' missing" { jsonEnv["description"] = "" } else { return verr } } e.ChefType = jsonEnv["chef_type"].(string) e.JSONClass = jsonEnv["json_class"].(string) e.Description = jsonEnv["description"].(string) e.Default = jsonEnv["default_attributes"].(map[string]interface{}) e.Override = jsonEnv["override_attributes"].(map[string]interface{}) /* clear out, then loop over the cookbook versions */ e.CookbookVersions = make(map[string]string, len(jsonEnv["cookbook_versions"].(map[string]interface{}))) for c, v := range jsonEnv["cookbook_versions"].(map[string]interface{}) { e.CookbookVersions[c] = v.(string) } return nil } // Get an environment. func Get(envName string) (*ChefEnvironment, util.Gerror) { if envName == "_default" { return defaultEnvironment(), nil } var env *ChefEnvironment var found bool if config.UsingDB() { var err error env, err = getEnvironmentSQL(envName) if err != nil
else { found = true } } else { ds := datastore.New() var e interface{} e, found = ds.Get("env", envName) if e != nil { env = e.(*ChefEnvironment) } } if !found { err := util.Errorf("Cannot load environment %s", envName) err.SetStatus(http.StatusNotFound) return nil, err } return env, nil } // DoesExist checks if the environment in question exists or not func DoesExist(environmentName string) (bool, util.Gerror) { var found bool if config.UsingDB() { var cerr error found, cerr = checkForEnvironmentSQL(datastore.Dbh, environmentName) if cerr != nil { err := util.Errorf(cerr.Error()) err.SetStatus(http.StatusInternalServerError) return false, err } } else { ds := datastore.New() _, found = ds.Get("env", environmentName) } return found, nil } // GetMulti gets multiple environmets from a given slice of environment names. func GetMulti(envNames []string) ([]*ChefEnvironment, util.Gerror) { var envs []*ChefEnvironment if config.UsingDB() { var err error envs, err = getMultiSQL(envNames) if err != nil && err != sql.ErrNoRows { return nil, util.CastErr(err) } } else { envs = make([]*ChefEnvironment, 0, len(envNames)) for _, e := range envNames { eo, _ := Get(e) if eo != nil { envs = append(envs, eo) } } } return envs, nil } // MakeDefaultEnvironment creates the default environment on startup. func MakeDefaultEnvironment() { var de *ChefEnvironment if config.UsingDB() { // The default environment is pre-created in the db schema when // it's loaded. Re-indexing the default environment doesn't // hurt anything though, so just get the usual default env and // index it, not bothering with these other steps that are // easier to do with the in-memory mode. de = defaultEnvironment() } else { ds := datastore.New() // only create the new default environment if we don't already have one // saved if _, found := ds.Get("env", "_default"); found { return } de = defaultEnvironment() ds.Set("env", de.Name, de) } indexer.IndexObj(de) } func defaultEnvironment() *ChefEnvironment { return &ChefEnvironment{ Name: "_default", ChefType: "environment", JSONClass: "Chef::Environment", Description: "The default Chef environment", Default: map[string]interface{}{}, Override: map[string]interface{}{}, CookbookVersions: map[string]string{}, } } // Save the environment. Returns an error if you try to save the "_default" // environment. func (e *ChefEnvironment) Save() util.Gerror { if e.Name == "_default" { err := util.Errorf("The '_default' environment cannot be modified.") err.SetStatus(http.StatusMethodNotAllowed) return err } if config.Config.UseMySQL { err := e.saveEnvironmentMySQL() if err != nil { return err } } else if config.Config.UsePostgreSQL { err := e.saveEnvironmentPostgreSQL() if err != nil { return err } } else { ds := datastore.New() ds.Set("env", e.Name, e) } indexer.IndexObj(e) return nil } // Delete the environment, returning an error if you try to delete the // "_default" environment. func (e *ChefEnvironment) Delete() error { if e.Name == "_default" { err := fmt.Errorf("The '_default' environment cannot be modified.") return err } if config.UsingDB() { if err := e.deleteEnvironmentSQL(); err != nil { return nil } } else { ds := datastore.New() ds.Delete("env", e.Name) } indexer.DeleteItemFromCollection("environment", e.Name) return nil } // GetList gets a list of all environments on this server. func GetList() []string { var envList []string if config.UsingDB() { envList = getEnvironmentList() } else { ds := datastore.New() envList = ds.GetList("env") envList = append(envList, "_default") } return envList } // GetName returns the environment's name. func (e *ChefEnvironment) GetName() string { return e.Name } // URLType returns the base of an environment's URL. func (e *ChefEnvironment) URLType() string { return "environments" } func (e *ChefEnvironment) cookbookList() []*cookbook.Cookbook { return cookbook.AllCookbooks() } // AllCookbookHash returns a hash of the cookbooks and their versions available // to this environment. func (e *ChefEnvironment) AllCookbookHash(numVersions interface{}) map[string]interface{} { cbHash := make(map[string]interface{}) cbList := e.cookbookList() for _, cb := range cbList { if cb == nil { continue } cbHash[cb.Name] = cb.ConstrainedInfoHash(numVersions, e.CookbookVersions[cb.Name]) } return cbHash } // RecipeList gets a list of recipes available to this environment. func (e *ChefEnvironment) RecipeList() []string { recipeList := make(map[string]string) cbList := e.cookbookList() for _, cb := range cbList { if cb == nil { continue } cbv := cb.LatestConstrained(e.CookbookVersions[cb.Name]) if cbv == nil { continue } rlist, _ := cbv.RecipeList() for _, recipe := range rlist { recipeList[recipe] = recipe } } sortedRecipes := make([]string, len(recipeList)) i := 0 for k := range recipeList { sortedRecipes[i] = k i++ } sort.Strings(sortedRecipes) return sortedRecipes } /* Search indexing methods */ // DocID returns the environment's name. func (e *ChefEnvironment) DocID() string { return e.Name } // Index returns the environment's type so the indexer knows where it should go. func (e *ChefEnvironment) Index() string { return "environment" } // Flatten the environment so it's suitable for indexing. func (e *ChefEnvironment) Flatten() map[string]interface{} { return util.FlattenObj(e) } // AllEnvironments returns a slice of all environments on this server. func AllEnvironments() []*ChefEnvironment { var environments []*ChefEnvironment if config.UsingDB() { environments = allEnvironmentsSQL() } else { envList := GetList() for _, e := range envList { en, err := Get(e) if err != nil { continue } environments = append(environments, en) } } return environments }
{ var gerr util.Gerror if err != sql.ErrNoRows { gerr = util.CastErr(err) gerr.SetStatus(http.StatusInternalServerError) return nil, gerr } found = false }
conditional_block
environment.go
/* Environments. */ /* * Copyright (c) 2013-2017, Jeremy Bingham (<jeremy@goiardi.gl>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Package environment provides... environments. They're like roles, but more // so, except without run lists. They're a convenient way to share many // attributes and cookbook version constraints among many servers. package environment import ( "database/sql" "fmt" "github.com/ctdk/goiardi/config" "github.com/ctdk/goiardi/cookbook" "github.com/ctdk/goiardi/datastore" "github.com/ctdk/goiardi/indexer" "github.com/ctdk/goiardi/util" "net/http" "sort" ) // ChefEnvironment is a collection of attributes and cookbook versions for // organizing how nodes are deployed. type ChefEnvironment struct { Name string `json:"name"` ChefType string `json:"chef_type"` JSONClass string `json:"json_class"` Description string `json:"description"` Default map[string]interface{} `json:"default_attributes"` Override map[string]interface{} `json:"override_attributes"` CookbookVersions map[string]string `json:"cookbook_versions"` } // New creates a new environment, returning an error if the environment already // exists or you try to create an environment named "_default". func New(name string) (*ChefEnvironment, util.Gerror) { if !util.ValidateEnvName(name) { err := util.Errorf("Field 'name' invalid") err.SetStatus(http.StatusBadRequest) return nil, err } var found bool if config.UsingDB() { var eerr error found, eerr = checkForEnvironmentSQL(datastore.Dbh, name) if eerr != nil { err := util.CastErr(eerr) err.SetStatus(http.StatusInternalServerError) return nil, err } } else { ds := datastore.New() _, found = ds.Get("env", name) } if found || name == "_default" { err := util.Errorf("Environment already exists") return nil, err } env := &ChefEnvironment{ Name: name, ChefType: "environment", JSONClass: "Chef::Environment", Default: map[string]interface{}{}, Override: map[string]interface{}{}, CookbookVersions: map[string]string{}, } return env, nil } // NewFromJSON creates a new environment from JSON uploaded to the server. func NewFromJSON(jsonEnv map[string]interface{}) (*ChefEnvironment, util.Gerror) { env, err := New(jsonEnv["name"].(string)) if err != nil { return nil, err } err = env.UpdateFromJSON(jsonEnv) if err != nil { return nil, err } return env, nil } // UpdateFromJSON updates an existing environment from JSON uploaded to the // server. func (e *ChefEnvironment) UpdateFromJSON(jsonEnv map[string]interface{}) util.Gerror { if e.Name != jsonEnv["name"].(string) { err := util.Errorf("Environment name %s and %s from JSON do not match", e.Name, jsonEnv["name"].(string)) return err } else if e.Name == "_default" { err := util.Errorf("The '_default' environment cannot be modified.") err.SetStatus(http.StatusMethodNotAllowed) return err } /* Validations */ validElements := []string{"name", "chef_type", "json_class", "description", "default_attributes", "override_attributes", "cookbook_versions"} ValidElem: for k := range jsonEnv { for _, i := range validElements { if k == i { continue ValidElem } } err := util.Errorf("Invalid key %s in request body", k) return err } var verr util.Gerror attrs := []string{"default_attributes", "override_attributes"} for _, a := range attrs { jsonEnv[a], verr = util.ValidateAttributes(a, jsonEnv[a]) if verr != nil { return verr } } jsonEnv["json_class"], verr = util.ValidateAsFieldString(jsonEnv["json_class"]) if verr != nil { if verr.Error() == "Field 'name' nil" { jsonEnv["json_class"] = e.JSONClass } else { return verr } } else { if jsonEnv["json_class"].(string) != "Chef::Environment" { verr = util.Errorf("Field 'json_class' invalid") return verr } } jsonEnv["chef_type"], verr = util.ValidateAsFieldString(jsonEnv["chef_type"]) if verr != nil { if verr.Error() == "Field 'name' nil" { jsonEnv["chef_type"] = e.ChefType } else { return verr } } else { if jsonEnv["chef_type"].(string) != "environment" { verr = util.Errorf("Field 'chef_type' invalid") return verr } } jsonEnv["cookbook_versions"], verr = util.ValidateAttributes("cookbook_versions", jsonEnv["cookbook_versions"]) if verr != nil { return verr } for k, v := range jsonEnv["cookbook_versions"].(map[string]interface{}) { if !util.ValidateEnvName(k) || k == "" { merr := util.Errorf("Cookbook name %s invalid", k) merr.SetStatus(http.StatusBadRequest) return merr } if v == nil { verr = util.Errorf("Invalid version number") return verr } _, verr = util.ValidateAsConstraint(v) if verr != nil { /* try validating as a version */ v, verr = util.ValidateAsVersion(v) if verr != nil { return verr } } } jsonEnv["description"], verr = util.ValidateAsString(jsonEnv["description"]) if verr != nil { if verr.Error() == "Field 'name' missing" { jsonEnv["description"] = "" } else { return verr } } e.ChefType = jsonEnv["chef_type"].(string) e.JSONClass = jsonEnv["json_class"].(string) e.Description = jsonEnv["description"].(string) e.Default = jsonEnv["default_attributes"].(map[string]interface{}) e.Override = jsonEnv["override_attributes"].(map[string]interface{}) /* clear out, then loop over the cookbook versions */ e.CookbookVersions = make(map[string]string, len(jsonEnv["cookbook_versions"].(map[string]interface{}))) for c, v := range jsonEnv["cookbook_versions"].(map[string]interface{}) { e.CookbookVersions[c] = v.(string) } return nil } // Get an environment. func Get(envName string) (*ChefEnvironment, util.Gerror) { if envName == "_default" { return defaultEnvironment(), nil } var env *ChefEnvironment var found bool if config.UsingDB() { var err error env, err = getEnvironmentSQL(envName) if err != nil { var gerr util.Gerror if err != sql.ErrNoRows { gerr = util.CastErr(err) gerr.SetStatus(http.StatusInternalServerError) return nil, gerr } found = false } else { found = true } } else { ds := datastore.New() var e interface{} e, found = ds.Get("env", envName) if e != nil { env = e.(*ChefEnvironment) } } if !found { err := util.Errorf("Cannot load environment %s", envName) err.SetStatus(http.StatusNotFound) return nil, err } return env, nil } // DoesExist checks if the environment in question exists or not func DoesExist(environmentName string) (bool, util.Gerror) { var found bool if config.UsingDB() { var cerr error found, cerr = checkForEnvironmentSQL(datastore.Dbh, environmentName) if cerr != nil { err := util.Errorf(cerr.Error()) err.SetStatus(http.StatusInternalServerError) return false, err } } else { ds := datastore.New() _, found = ds.Get("env", environmentName) } return found, nil } // GetMulti gets multiple environmets from a given slice of environment names. func GetMulti(envNames []string) ([]*ChefEnvironment, util.Gerror) { var envs []*ChefEnvironment if config.UsingDB() { var err error envs, err = getMultiSQL(envNames) if err != nil && err != sql.ErrNoRows { return nil, util.CastErr(err) } } else { envs = make([]*ChefEnvironment, 0, len(envNames)) for _, e := range envNames { eo, _ := Get(e) if eo != nil { envs = append(envs, eo) } } } return envs, nil } // MakeDefaultEnvironment creates the default environment on startup. func MakeDefaultEnvironment() { var de *ChefEnvironment if config.UsingDB() { // The default environment is pre-created in the db schema when // it's loaded. Re-indexing the default environment doesn't // hurt anything though, so just get the usual default env and // index it, not bothering with these other steps that are // easier to do with the in-memory mode. de = defaultEnvironment() } else { ds := datastore.New() // only create the new default environment if we don't already have one // saved if _, found := ds.Get("env", "_default"); found { return } de = defaultEnvironment() ds.Set("env", de.Name, de) } indexer.IndexObj(de) } func defaultEnvironment() *ChefEnvironment { return &ChefEnvironment{ Name: "_default", ChefType: "environment", JSONClass: "Chef::Environment", Description: "The default Chef environment", Default: map[string]interface{}{}, Override: map[string]interface{}{}, CookbookVersions: map[string]string{}, } } // Save the environment. Returns an error if you try to save the "_default" // environment. func (e *ChefEnvironment) Save() util.Gerror { if e.Name == "_default" { err := util.Errorf("The '_default' environment cannot be modified.") err.SetStatus(http.StatusMethodNotAllowed) return err } if config.Config.UseMySQL { err := e.saveEnvironmentMySQL() if err != nil { return err } } else if config.Config.UsePostgreSQL { err := e.saveEnvironmentPostgreSQL() if err != nil { return err } } else { ds := datastore.New() ds.Set("env", e.Name, e) } indexer.IndexObj(e) return nil } // Delete the environment, returning an error if you try to delete the // "_default" environment. func (e *ChefEnvironment) Delete() error { if e.Name == "_default" { err := fmt.Errorf("The '_default' environment cannot be modified.") return err } if config.UsingDB() { if err := e.deleteEnvironmentSQL(); err != nil { return nil } } else { ds := datastore.New() ds.Delete("env", e.Name) } indexer.DeleteItemFromCollection("environment", e.Name) return nil } // GetList gets a list of all environments on this server. func GetList() []string { var envList []string if config.UsingDB() { envList = getEnvironmentList() } else { ds := datastore.New() envList = ds.GetList("env") envList = append(envList, "_default") } return envList } // GetName returns the environment's name. func (e *ChefEnvironment) GetName() string { return e.Name } // URLType returns the base of an environment's URL. func (e *ChefEnvironment) URLType() string { return "environments" } func (e *ChefEnvironment) cookbookList() []*cookbook.Cookbook { return cookbook.AllCookbooks() } // AllCookbookHash returns a hash of the cookbooks and their versions available // to this environment. func (e *ChefEnvironment) AllCookbookHash(numVersions interface{}) map[string]interface{} { cbHash := make(map[string]interface{}) cbList := e.cookbookList() for _, cb := range cbList { if cb == nil { continue } cbHash[cb.Name] = cb.ConstrainedInfoHash(numVersions, e.CookbookVersions[cb.Name]) } return cbHash } // RecipeList gets a list of recipes available to this environment. func (e *ChefEnvironment) RecipeList() []string { recipeList := make(map[string]string) cbList := e.cookbookList() for _, cb := range cbList { if cb == nil { continue } cbv := cb.LatestConstrained(e.CookbookVersions[cb.Name]) if cbv == nil { continue } rlist, _ := cbv.RecipeList() for _, recipe := range rlist { recipeList[recipe] = recipe } } sortedRecipes := make([]string, len(recipeList)) i := 0 for k := range recipeList { sortedRecipes[i] = k i++ } sort.Strings(sortedRecipes) return sortedRecipes } /* Search indexing methods */ // DocID returns the environment's name. func (e *ChefEnvironment) DocID() string
// Index returns the environment's type so the indexer knows where it should go. func (e *ChefEnvironment) Index() string { return "environment" } // Flatten the environment so it's suitable for indexing. func (e *ChefEnvironment) Flatten() map[string]interface{} { return util.FlattenObj(e) } // AllEnvironments returns a slice of all environments on this server. func AllEnvironments() []*ChefEnvironment { var environments []*ChefEnvironment if config.UsingDB() { environments = allEnvironmentsSQL() } else { envList := GetList() for _, e := range envList { en, err := Get(e) if err != nil { continue } environments = append(environments, en) } } return environments }
{ return e.Name }
identifier_body
baconian.rs
//! Bacon's cipher, or the Baconian cipher, hides a secret message in plain sight rather than //! generating ciphertext (steganography). It was devised by Sir Francis Bacon in 1605. //! //! Each character of the plaintext message is encoded as a 5-bit binary character. //! These characters are then "hidden" in a decoy message through the use of font variation. //! This cipher is very easy to crack once the method of hiding is known. As such, this implementation includes //! the option to set whether the substitution is use_distinct_alphabet for the whole alphabet, //! or whether it follows the classical method of treating 'I' and 'J', and 'U' and 'V' as //! interchangeable characters - as would have been the case in Bacon's time. //! //! If no concealing text is given and the boilerplate of "Lorem ipsum..." is used, //! a plaintext message of up to ~50 characters may be hidden. //! use crate::common::cipher::Cipher; use lipsum::lipsum; use std::collections::HashMap; use std::string::String; // The default code length const CODE_LEN: usize = 5; // Code mappings: // * note: that str is preferred over char as it cannot be guaranteed that // there will be a single codepoint for a given character. lazy_static! { static ref CODE_MAP: HashMap<&'static str, &'static str> = hashmap! { "A" => "AAAAA", "B" => "AAAAB", "C" => "AAABA", "D" => "AAABB", "E" => "AABAA", "F" => "AABAB", "G" => "AABBA", "H" => "AABBB", "I" => "ABAAA", "J" => "ABAAB", "K" => "ABABA", "L" => "ABABB", "M" => "ABBAA", "N" => "ABBAB", "O" => "ABBBA", "P" => "ABBBB", "Q" => "BAAAA", "R" => "BAAAB", "S" => "BAABA", "T" => "BAABB", "U" => "BABAA", "V" => "BABAB", "W" => "BABBA", "X" => "BABBB", "Y" => "BBAAA", "Z" => "BBAAB" }; } // A mapping of alphabet to italic UTF-8 italic codes lazy_static! { static ref ITALIC_CODES: HashMap<&'static str, char> = hashmap!{ // Using Mathematical Italic "A" => '\u{1D434}', "B" => '\u{1D435}', "C" => '\u{1D436}', "D" => '\u{1D437}', "E" => '\u{1D438}', "F" => '\u{1D439}', "G" => '\u{1D43a}', "H" => '\u{1D43b}', "I" => '\u{1D43c}', "J" => '\u{1D43d}', "K" => '\u{1D43e}', "L" => '\u{1D43f}', "M" => '\u{1D440}', "N" => '\u{1D441}', "O" => '\u{1D442}', "P" => '\u{1D443}', "Q" => '\u{1D444}', "R" => '\u{1D445}', "S" => '\u{1D446}', "T" => '\u{1D447}', "U" => '\u{1D448}', "V" => '\u{1D449}', "W" => '\u{1D44a}', "X" => '\u{1D44b}', "Y" => '\u{1D44c}', "Z" => '\u{1D44d}', // Using Mathematical Sans-Serif Italic "a" => '\u{1D622}', "b" => '\u{1D623}', "c" => '\u{1D624}', "d" => '\u{1D625}', "e" => '\u{1D626}', "f" => '\u{1D627}', "g" => '\u{1D628}', "h" => '\u{1D629}', "i" => '\u{1D62a}', "j" => '\u{1D62b}', "k" => '\u{1D62c}', "l" => '\u{1D62d}', "m" => '\u{1D62e}', "n" => '\u{1D62f}', "o" => '\u{1D630}', "p" => '\u{1D631}', "q" => '\u{1D632}', "r" => '\u{1D633}', "s" => '\u{1D634}', "t" => '\u{1D635}', "u" => '\u{1D636}', "v" => '\u{1D637}', "w" => '\u{1D638}', "x" => '\u{1D639}', "y" => '\u{1D63a}', "z" => '\u{1D63b}' }; } /// Get the code for a given key (source character) fn get_code(use_distinct_alphabet: bool, key: &str) -> String { let mut code = String::new(); // Need to handle 'I'/'J' and 'U'/'V' // for traditional usage. let mut key_upper = key.to_uppercase(); if !use_distinct_alphabet { match key_upper.as_str() { "J" => key_upper = "I".to_string(), "U" => key_upper = "V".to_string(), _ => {} } } if CODE_MAP.contains_key(key_upper.as_str()) { code.push_str(CODE_MAP.get(key_upper.as_str()).unwrap()); } code } /// Gets the key (the source character) for a given cipher text code fn get_key(code: &str) -> String { let mut key = String::new(); for (_key, val) in CODE_MAP.iter() { if val == &code { key.push_str(_key); } } key } /// This struct is created by the `new()` method. See its documentation for more. pub struct Baconian { use_distinct_alphabet: bool, decoy_text: String, } impl Cipher for Baconian { type Key = (bool, Option<String>); type Algorithm = Baconian; /// Initialise a Baconian cipher /// /// The `key` tuple maps to the following: `(bool, Option<str>) = (use_distinct_alphabet, decoy_text)`. /// Where ... /// /// * The encoding will be use_distinct_alphabet for all alphabetical characters, or classical /// where I, J, U and V are mapped to the same value pairs /// * An optional decoy message that will will be used to hide the message - /// default is boilerplate "Lorem ipsum" text. /// fn new(key: (bool, Option<String>)) -> Baconian
/// Encrypt a message using the Baconian cipher /// /// * The message to be encrypted can only be ~18% of the decoy_text as each character /// of message is encoded by 5 encoding characters `AAAAA`, `AAAAB`, etc. /// * The italicised ciphertext is then hidden in a decoy text, where, for each 'B' /// in the ciphertext, the character is italicised in the decoy_text. /// /// # Examples /// Basic usage: /// /// ``` /// use cipher_crypt::{Cipher, Baconian}; /// /// let b = Baconian::new((false, None));; /// let message = "Hello"; /// let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘤𝘰n"; /// /// assert_eq!(cipher_text, b.encrypt(message).unwrap()); /// ``` fn encrypt(&self, message: &str) -> Result<String, &'static str> { let num_non_alphas = self .decoy_text .chars() .filter(|c| !c.is_alphabetic()) .count(); // Check whether the message fits in the decoy // Note: that non-alphabetical characters will be skipped. if (message.len() * CODE_LEN) > self.decoy_text.len() - num_non_alphas { return Err("Message too long for supplied decoy text."); } // Iterate through the message encoding each char (ignoring non-alphabetical chars) let secret: String = message .chars() .map(|c| get_code(self.use_distinct_alphabet, &c.to_string())) .collect(); let mut num_alphas = 0; let mut num_non_alphas = 0; for c in self.decoy_text.chars() { if num_alphas == secret.len() { break; } if c.is_alphabetic() { num_alphas += 1 } else { num_non_alphas += 1 }; } let decoy_slice: String = self .decoy_text .chars() .take(num_alphas + num_non_alphas) .collect(); // We now have an encoded message, `secret`, in which each character of of the // original plaintext is now represented by a 5-bit binary character, // "AAAAA", "ABABA" etc. // We now overlay the encoded text onto the decoy slice, and // where the binary 'B' is found the decoy slice char is swapped for an italic let mut decoy_msg = String::new(); let mut secret_iter = secret.chars(); for c in decoy_slice.chars() { if c.is_alphabetic() { if let Some(sc) = secret_iter.next() { if sc == 'B' { // match the binary 'B' and swap for italic let italic = *ITALIC_CODES.get(c.to_string().as_str()).unwrap(); decoy_msg.push(italic); } else { decoy_msg.push(c); } } } else { decoy_msg.push(c); } } Ok(decoy_msg) } /// Decrypt a message that was encrypted with the Baconian cipher /// /// # Examples /// Basic usage: /// /// ``` /// use cipher_crypt::{Cipher, Baconian}; /// /// let b = Baconian::new((false, None));; /// let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘯𝘦 t"; /// /// assert_eq!("HELLO", b.decrypt(cipher_text).unwrap()); /// ``` /// fn decrypt(&self, message: &str) -> Result<String, &'static str> { // The message is decoy text // Iterate through swapping any alphabetical chars found in the ITALIC_CODES // set to be 'B', else 'A', skip anything else. let ciphertext: String = message .chars() .filter(|c| c.is_alphabetic()) .map(|c| { if ITALIC_CODES.iter().any(|e| *e.1 == c) { 'B' } else { 'A' } }) .collect(); let mut plaintext = String::new(); let mut code = String::new(); for c in ciphertext.chars() { code.push(c); if code.len() == CODE_LEN { // If we have the right length code plaintext += &get_key(&code); code.clear(); } } Ok(plaintext) } } #[cfg(test)] mod tests { use super::*; #[test] fn encrypt_simple() { let b = Baconian::new((false, None)); let message = "Hello"; let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘤𝘰n"; assert_eq!(cipher_text, b.encrypt(message).unwrap()); } // Need to test that the traditional and use_distinct_alphabet codes give different results #[test] fn encrypt_trad_v_dist() { let b_trad = Baconian::new((false, None)); let b_dist = Baconian::new((true, None)); let message = "I JADE YOU VERVENT UNICORN"; assert_ne!( b_dist.encrypt(&message).unwrap(), b_trad.encrypt(message).unwrap() ); } #[test] fn encrypt_message_spaced() { let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let b = Baconian::new((false, Some(decoy_text))); let message = "Peace, Freedom 🗡️ and Liberty!"; let cipher_text = "T𝘩𝘦 𝘸𝘰rl𝘥\'s a bubble; an𝘥 the 𝘭ife o𝘧 m𝘢𝘯 les𝘴 th𝘢n a sp𝘢n. \ In hi𝘴 𝘤o𝘯𝘤𝘦pt𝘪𝘰n wretche𝘥; 𝘧r𝘰m th𝘦 𝘸o𝘮b 𝘴𝘰 t𝘰 the tomb: \ 𝐶ur𝘴t f𝘳om t𝘩𝘦 cr𝘢𝘥𝘭𝘦, and"; assert_eq!(cipher_text, b.encrypt(message).unwrap()); } // use_distinct_alphabet lexicon #[test] #[should_panic(expected = r#"Message too long for supplied decoy text."#)] fn encrypt_decoy_too_short() { let b = Baconian::new((false, None)); let message = "This is a long message that will be too long to encode using \ the default decoy text. In order to have a long message encoded you need a \ decoy text that is at least five times as long, plus the non-alphabeticals."; b.encrypt(message).unwrap(); } #[test] fn encrypt_with_use_distinct_alphabet_codeset() { let message = "Peace, Freedom 🗡️ and Liberty!"; let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let cipher_text = "T𝘩𝘦 𝘸𝘰rl𝘥's a bubble; an𝘥 the 𝘭ife o𝘧 m𝘢𝘯 les𝘴 th𝘢n a sp𝘢n. \ In hi𝘴 𝘤o𝘯𝘤𝘦pt𝘪𝘰n wretche𝘥; 𝘧r𝘰m th𝘦 𝘸o𝘮b 𝘴𝘰 t𝘰 the tomb: \ 𝐶ur𝘴t f𝘳om t𝘩𝘦 cr𝘢𝘥𝘭𝘦, and"; let b = Baconian::new((true, Some(decoy_text))); assert_eq!(cipher_text, b.encrypt(message).unwrap()); } #[test] fn decrypt_a_classic() { let cipher_text = String::from("Let's c𝘰mp𝘳𝘰𝘮is𝘦. 𝐻old off th𝘦 at𝘵a𝘤k"); let message = "ATTACK"; let decoy_text = String::from("Let's compromise. Hold off the attack"); let b = Baconian::new((true, Some(decoy_text))); assert_eq!(message, b.decrypt(&cipher_text).unwrap()); } #[test] fn decrypt_traditional() { let cipher_text = String::from( "T𝘩e wor𝘭d's a bubble; an𝘥 𝘵he 𝘭if𝘦 𝘰f man 𝘭𝘦𝘴s 𝘵h𝘢n 𝘢 𝘴p𝘢n. \ 𝐼n h𝘪s c𝘰nce𝘱𝘵i𝘰n 𝘸re𝘵che𝘥; 𝘧r𝘰𝘮 th𝘦 𝘸𝘰m𝘣 s𝘰 t𝘰 𝘵h𝘦 t𝘰mb: \ Curs𝘵 fr𝘰𝘮 𝘵h𝘦 cra𝘥l𝘦, 𝘢n𝘥", ); // Note: the substitution for 'I'/'J' and 'U'/'V' let message = "IIADEYOVVERVENTVNICORN"; let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let b = Baconian::new((false, Some(decoy_text))); assert_eq!(message, b.decrypt(&cipher_text).unwrap()); } }
{ Baconian { use_distinct_alphabet: key.0, decoy_text: key.1.unwrap_or_else(|| lipsum(160)), } }
identifier_body
baconian.rs
//! Bacon's cipher, or the Baconian cipher, hides a secret message in plain sight rather than //! generating ciphertext (steganography). It was devised by Sir Francis Bacon in 1605. //! //! Each character of the plaintext message is encoded as a 5-bit binary character. //! These characters are then "hidden" in a decoy message through the use of font variation. //! This cipher is very easy to crack once the method of hiding is known. As such, this implementation includes //! the option to set whether the substitution is use_distinct_alphabet for the whole alphabet, //! or whether it follows the classical method of treating 'I' and 'J', and 'U' and 'V' as //! interchangeable characters - as would have been the case in Bacon's time. //! //! If no concealing text is given and the boilerplate of "Lorem ipsum..." is used, //! a plaintext message of up to ~50 characters may be hidden. //! use crate::common::cipher::Cipher; use lipsum::lipsum; use std::collections::HashMap; use std::string::String; // The default code length const CODE_LEN: usize = 5; // Code mappings: // * note: that str is preferred over char as it cannot be guaranteed that // there will be a single codepoint for a given character. lazy_static! { static ref CODE_MAP: HashMap<&'static str, &'static str> = hashmap! { "A" => "AAAAA", "B" => "AAAAB", "C" => "AAABA", "D" => "AAABB", "E" => "AABAA", "F" => "AABAB", "G" => "AABBA", "H" => "AABBB", "I" => "ABAAA", "J" => "ABAAB", "K" => "ABABA", "L" => "ABABB", "M" => "ABBAA", "N" => "ABBAB", "O" => "ABBBA", "P" => "ABBBB", "Q" => "BAAAA", "R" => "BAAAB", "S" => "BAABA", "T" => "BAABB", "U" => "BABAA", "V" => "BABAB", "W" => "BABBA", "X" => "BABBB", "Y" => "BBAAA", "Z" => "BBAAB" }; } // A mapping of alphabet to italic UTF-8 italic codes lazy_static! { static ref ITALIC_CODES: HashMap<&'static str, char> = hashmap!{ // Using Mathematical Italic "A" => '\u{1D434}', "B" => '\u{1D435}', "C" => '\u{1D436}', "D" => '\u{1D437}', "E" => '\u{1D438}', "F" => '\u{1D439}', "G" => '\u{1D43a}', "H" => '\u{1D43b}', "I" => '\u{1D43c}', "J" => '\u{1D43d}', "K" => '\u{1D43e}', "L" => '\u{1D43f}', "M" => '\u{1D440}', "N" => '\u{1D441}', "O" => '\u{1D442}', "P" => '\u{1D443}', "Q" => '\u{1D444}', "R" => '\u{1D445}', "S" => '\u{1D446}', "T" => '\u{1D447}', "U" => '\u{1D448}', "V" => '\u{1D449}', "W" => '\u{1D44a}', "X" => '\u{1D44b}', "Y" => '\u{1D44c}', "Z" => '\u{1D44d}', // Using Mathematical Sans-Serif Italic "a" => '\u{1D622}', "b" => '\u{1D623}', "c" => '\u{1D624}', "d" => '\u{1D625}', "e" => '\u{1D626}', "f" => '\u{1D627}', "g" => '\u{1D628}', "h" => '\u{1D629}', "i" => '\u{1D62a}', "j" => '\u{1D62b}', "k" => '\u{1D62c}', "l" => '\u{1D62d}', "m" => '\u{1D62e}', "n" => '\u{1D62f}', "o" => '\u{1D630}', "p" => '\u{1D631}', "q" => '\u{1D632}', "r" => '\u{1D633}', "s" => '\u{1D634}', "t" => '\u{1D635}', "u" => '\u{1D636}', "v" => '\u{1D637}', "w" => '\u{1D638}', "x" => '\u{1D639}', "y" => '\u{1D63a}', "z" => '\u{1D63b}' }; } /// Get the code for a given key (source character) fn get_code(use_distinct_alphabet: bool, key: &str) -> String { let mut code = String::new(); // Need to handle 'I'/'J' and 'U'/'V' // for traditional usage. let mut key_upper = key.to_uppercase(); if !use_distinct_alphabet { match key_upper.as_str() { "J" => key_upper = "I".to_string(), "U" => key_upper = "V".to_string(), _ => {} } } if CODE_MAP.contains_key(key_upper.as_str()) { code.push_str(CODE_MAP.get(key_upper.as_str()).unwrap()); } code } /// Gets the key (the source character) for a given cipher text code fn get_key(code: &str) -> String { let mut key = String::new(); for (_key, val) in CODE_MAP.iter() { if val == &code { key.push_str(_key); } } key } /// This struct is created by the `new()` method. See its documentation for more. pub struct Baconian { use_distinct_alphabet: bool, decoy_text: String, } impl Cipher for Baconian { type Key = (bool, Option<String>); type Algorithm = Baconian; /// Initialise a Baconian cipher /// /// The `key` tuple maps to the following: `(bool, Option<str>) = (use_distinct_alphabet, decoy_text)`. /// Where ... /// /// * The encoding will be use_distinct_alphabet for all alphabetical characters, or classical /// where I, J, U and V are mapped to the same value pairs /// * An optional decoy message that will will be used to hide the message - /// default is boilerplate "Lorem ipsum" text. /// fn new(key: (bool, Option<String>)) -> Baconian { Baconian { use_distinct_alphabet: key.0, decoy_text: key.1.unwrap_or_else(|| lipsum(160)), } } /// Encrypt a message using the Baconian cipher /// /// * The message to be encrypted can only be ~18% of the decoy_text as each character /// of message is encoded by 5 encoding characters `AAAAA`, `AAAAB`, etc. /// * The italicised ciphertext is then hidden in a decoy text, where, for each 'B' /// in the ciphertext, the character is italicised in the decoy_text. /// /// # Examples /// Basic usage: /// /// ``` /// use cipher_crypt::{Cipher, Baconian}; /// /// let b = Baconian::new((false, None));; /// let message = "Hello"; /// let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘤𝘰n"; /// /// assert_eq!(cipher_text, b.encrypt(message).unwrap()); /// ``` fn encrypt(&self, message: &str) -> Result<String, &'static str> { let num_non_alphas = self .decoy_text .chars() .filter(|c| !c.is_alphabetic()) .count(); // Check whether the message fits in the decoy // Note: that non-alphabetical characters will be skipped. if (message.len() * CODE_LEN) > self.decoy_text.len() - num_non_alphas { return Err("Message too long for supplied decoy text."); } // Iterate through the message encoding each char (ignoring non-alphabetical chars) let secret: String = message .chars() .map(|c| get_code(self.use_distinct_alphabet, &c.to_string())) .collect(); let mut num_alphas = 0; let mut num_non_alphas = 0; for c in self.decoy_text.chars() { if num_alphas == secret.len() { break; } if c.is_alphabetic() { num_alphas += 1 } else { num_non_alphas += 1 }; } let decoy_slice: String = self .decoy_text .chars() .take(num_alphas + num_non_alphas) .collect(); // We now have an encoded message, `secret`, in which each character of of the // original plaintext is now represented by a 5-bit binary character, // "AAAAA", "ABABA" etc. // We now overlay the encoded text onto the decoy slice, and // where the binary 'B' is found the decoy slice char is swapped for an italic let mut decoy_msg = String::new(); let mut secret_iter = secret.chars(); for c in decoy_slice.chars() { if c.is_alphabetic() { if let Some(sc) = secret_iter.next() { if sc == 'B' { // match the binary 'B' and swap for italic let italic = *ITALIC_CODES.get(c.to_string().as_str()).unwrap(); decoy_msg.push(italic); } else { decoy_msg.push(c); } } } else { decoy_msg.push(c); } } Ok(decoy_msg) } /// Decrypt a message that was encrypted with the Baconian cipher /// /// # Examples /// Basic usage: /// /// ``` /// use cipher_crypt::{Cipher, Baconian}; /// /// let b = Baconian::new((false, None));; /// let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘯𝘦 t"; /// /// assert_eq!("HELLO", b.decrypt(cipher_text).unwrap()); /// ``` /// fn decrypt(&self, message: &str) -> Result<String, &'static str> { // The message is decoy text // Iterate through swapping any alphabetical chars found in the ITALIC_CODES // set to be 'B', else 'A', skip anything else. let ciphertext: String = message .chars() .filter(|c| c.is_alphabetic()) .map(|c| { if ITALIC_CODES.iter().any(|e| *e.1 == c) { 'B' } else { 'A' } }) .collect(); let mut plaintext = String::new(); let mut code = String::new(); for c in ciphertext.chars() { code.push(c); if code.len() == CODE_LEN { // If we have the right length code plaintext += &get_key(&code); code.clear(); } } Ok(plaintext) } } #[cfg(test)] mod tests { use super::*; #[test] fn encrypt_simple() { let b = Baconian::new((false, None)); let m
o"; let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘤𝘰n"; assert_eq!(cipher_text, b.encrypt(message).unwrap()); } // Need to test that the traditional and use_distinct_alphabet codes give different results #[test] fn encrypt_trad_v_dist() { let b_trad = Baconian::new((false, None)); let b_dist = Baconian::new((true, None)); let message = "I JADE YOU VERVENT UNICORN"; assert_ne!( b_dist.encrypt(&message).unwrap(), b_trad.encrypt(message).unwrap() ); } #[test] fn encrypt_message_spaced() { let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let b = Baconian::new((false, Some(decoy_text))); let message = "Peace, Freedom 🗡️ and Liberty!"; let cipher_text = "T𝘩𝘦 𝘸𝘰rl𝘥\'s a bubble; an𝘥 the 𝘭ife o𝘧 m𝘢𝘯 les𝘴 th𝘢n a sp𝘢n. \ In hi𝘴 𝘤o𝘯𝘤𝘦pt𝘪𝘰n wretche𝘥; 𝘧r𝘰m th𝘦 𝘸o𝘮b 𝘴𝘰 t𝘰 the tomb: \ 𝐶ur𝘴t f𝘳om t𝘩𝘦 cr𝘢𝘥𝘭𝘦, and"; assert_eq!(cipher_text, b.encrypt(message).unwrap()); } // use_distinct_alphabet lexicon #[test] #[should_panic(expected = r#"Message too long for supplied decoy text."#)] fn encrypt_decoy_too_short() { let b = Baconian::new((false, None)); let message = "This is a long message that will be too long to encode using \ the default decoy text. In order to have a long message encoded you need a \ decoy text that is at least five times as long, plus the non-alphabeticals."; b.encrypt(message).unwrap(); } #[test] fn encrypt_with_use_distinct_alphabet_codeset() { let message = "Peace, Freedom 🗡️ and Liberty!"; let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let cipher_text = "T𝘩𝘦 𝘸𝘰rl𝘥's a bubble; an𝘥 the 𝘭ife o𝘧 m𝘢𝘯 les𝘴 th𝘢n a sp𝘢n. \ In hi𝘴 𝘤o𝘯𝘤𝘦pt𝘪𝘰n wretche𝘥; 𝘧r𝘰m th𝘦 𝘸o𝘮b 𝘴𝘰 t𝘰 the tomb: \ 𝐶ur𝘴t f𝘳om t𝘩𝘦 cr𝘢𝘥𝘭𝘦, and"; let b = Baconian::new((true, Some(decoy_text))); assert_eq!(cipher_text, b.encrypt(message).unwrap()); } #[test] fn decrypt_a_classic() { let cipher_text = String::from("Let's c𝘰mp𝘳𝘰𝘮is𝘦. 𝐻old off th𝘦 at𝘵a𝘤k"); let message = "ATTACK"; let decoy_text = String::from("Let's compromise. Hold off the attack"); let b = Baconian::new((true, Some(decoy_text))); assert_eq!(message, b.decrypt(&cipher_text).unwrap()); } #[test] fn decrypt_traditional() { let cipher_text = String::from( "T𝘩e wor𝘭d's a bubble; an𝘥 𝘵he 𝘭if𝘦 𝘰f man 𝘭𝘦𝘴s 𝘵h𝘢n 𝘢 𝘴p𝘢n. \ 𝐼n h𝘪s c𝘰nce𝘱𝘵i𝘰n 𝘸re𝘵che𝘥; 𝘧r𝘰𝘮 th𝘦 𝘸𝘰m𝘣 s𝘰 t𝘰 𝘵h𝘦 t𝘰mb: \ Curs𝘵 fr𝘰𝘮 𝘵h𝘦 cra𝘥l𝘦, 𝘢n𝘥", ); // Note: the substitution for 'I'/'J' and 'U'/'V' let message = "IIADEYOVVERVENTVNICORN"; let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let b = Baconian::new((false, Some(decoy_text))); assert_eq!(message, b.decrypt(&cipher_text).unwrap()); } }
essage = "Hell
identifier_name
baconian.rs
//! Bacon's cipher, or the Baconian cipher, hides a secret message in plain sight rather than //! generating ciphertext (steganography). It was devised by Sir Francis Bacon in 1605. //! //! Each character of the plaintext message is encoded as a 5-bit binary character. //! These characters are then "hidden" in a decoy message through the use of font variation. //! This cipher is very easy to crack once the method of hiding is known. As such, this implementation includes //! the option to set whether the substitution is use_distinct_alphabet for the whole alphabet, //! or whether it follows the classical method of treating 'I' and 'J', and 'U' and 'V' as //! interchangeable characters - as would have been the case in Bacon's time. //! //! If no concealing text is given and the boilerplate of "Lorem ipsum..." is used, //! a plaintext message of up to ~50 characters may be hidden. //! use crate::common::cipher::Cipher; use lipsum::lipsum; use std::collections::HashMap; use std::string::String; // The default code length const CODE_LEN: usize = 5; // Code mappings: // * note: that str is preferred over char as it cannot be guaranteed that // there will be a single codepoint for a given character. lazy_static! { static ref CODE_MAP: HashMap<&'static str, &'static str> = hashmap! { "A" => "AAAAA", "B" => "AAAAB", "C" => "AAABA", "D" => "AAABB", "E" => "AABAA", "F" => "AABAB", "G" => "AABBA", "H" => "AABBB", "I" => "ABAAA", "J" => "ABAAB", "K" => "ABABA", "L" => "ABABB", "M" => "ABBAA", "N" => "ABBAB", "O" => "ABBBA", "P" => "ABBBB", "Q" => "BAAAA", "R" => "BAAAB", "S" => "BAABA", "T" => "BAABB", "U" => "BABAA", "V" => "BABAB", "W" => "BABBA", "X" => "BABBB", "Y" => "BBAAA", "Z" => "BBAAB" }; } // A mapping of alphabet to italic UTF-8 italic codes lazy_static! { static ref ITALIC_CODES: HashMap<&'static str, char> = hashmap!{ // Using Mathematical Italic "A" => '\u{1D434}', "B" => '\u{1D435}', "C" => '\u{1D436}', "D" => '\u{1D437}', "E" => '\u{1D438}', "F" => '\u{1D439}', "G" => '\u{1D43a}', "H" => '\u{1D43b}', "I" => '\u{1D43c}', "J" => '\u{1D43d}', "K" => '\u{1D43e}', "L" => '\u{1D43f}', "M" => '\u{1D440}', "N" => '\u{1D441}', "O" => '\u{1D442}', "P" => '\u{1D443}', "Q" => '\u{1D444}', "R" => '\u{1D445}', "S" => '\u{1D446}', "T" => '\u{1D447}', "U" => '\u{1D448}', "V" => '\u{1D449}', "W" => '\u{1D44a}', "X" => '\u{1D44b}', "Y" => '\u{1D44c}', "Z" => '\u{1D44d}', // Using Mathematical Sans-Serif Italic "a" => '\u{1D622}', "b" => '\u{1D623}', "c" => '\u{1D624}', "d" => '\u{1D625}', "e" => '\u{1D626}', "f" => '\u{1D627}', "g" => '\u{1D628}', "h" => '\u{1D629}', "i" => '\u{1D62a}', "j" => '\u{1D62b}', "k" => '\u{1D62c}', "l" => '\u{1D62d}', "m" => '\u{1D62e}', "n" => '\u{1D62f}', "o" => '\u{1D630}', "p" => '\u{1D631}', "q" => '\u{1D632}', "r" => '\u{1D633}', "s" => '\u{1D634}', "t" => '\u{1D635}', "u" => '\u{1D636}', "v" => '\u{1D637}', "w" => '\u{1D638}', "x" => '\u{1D639}', "y" => '\u{1D63a}', "z" => '\u{1D63b}' }; } /// Get the code for a given key (source character) fn get_code(use_distinct_alphabet: bool, key: &str) -> String { let mut code = String::new(); // Need to handle 'I'/'J' and 'U'/'V' // for traditional usage. let mut key_upper = key.to_uppercase(); if !use_distinct_alphabet { match key_upper.as_str() { "J" => key_upper = "I".to_string(), "U" => key_upper = "V".to_string(), _ => {} } } if CODE_MAP.contains_key(key_upper.as_str()) { code.push_str(CODE_MAP.get(key_upper.as_str()).unwrap()); } code } /// Gets the key (the source character) for a given cipher text code fn get_key(code: &str) -> String { let mut key = String::new(); for (_key, val) in CODE_MAP.iter() { if val == &code { key.push_str(_key); } } key } /// This struct is created by the `new()` method. See its documentation for more. pub struct Baconian { use_distinct_alphabet: bool, decoy_text: String, } impl Cipher for Baconian { type Key = (bool, Option<String>); type Algorithm = Baconian; /// Initialise a Baconian cipher /// /// The `key` tuple maps to the following: `(bool, Option<str>) = (use_distinct_alphabet, decoy_text)`. /// Where ... /// /// * The encoding will be use_distinct_alphabet for all alphabetical characters, or classical /// where I, J, U and V are mapped to the same value pairs /// * An optional decoy message that will will be used to hide the message - /// default is boilerplate "Lorem ipsum" text. /// fn new(key: (bool, Option<String>)) -> Baconian { Baconian { use_distinct_alphabet: key.0, decoy_text: key.1.unwrap_or_else(|| lipsum(160)), } } /// Encrypt a message using the Baconian cipher /// /// * The message to be encrypted can only be ~18% of the decoy_text as each character /// of message is encoded by 5 encoding characters `AAAAA`, `AAAAB`, etc. /// * The italicised ciphertext is then hidden in a decoy text, where, for each 'B' /// in the ciphertext, the character is italicised in the decoy_text. /// /// # Examples /// Basic usage: /// /// ``` /// use cipher_crypt::{Cipher, Baconian}; /// /// let b = Baconian::new((false, None));; /// let message = "Hello"; /// let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘤𝘰n"; /// /// assert_eq!(cipher_text, b.encrypt(message).unwrap()); /// ``` fn encrypt(&self, message: &str) -> Result<String, &'static str> { let num_non_alphas = self .decoy_text .chars() .filter(|c| !c.is_alphabetic()) .count(); // Check whether the message fits in the decoy // Note: that non-alphabetical characters will be skipped. if (message.len() * CODE_LEN) > self.decoy_text.len() - num_non_alphas { return Err("Message too long for supplied decoy text."); } // Iterate through the message encoding each char (ignoring non-alphabetical chars) let secret: String = message .chars() .map(|c| get_code(self.use_distinct_alphabet, &c.to_string())) .collect(); let mut num_alphas = 0; let mut num_non_alphas = 0; for c in self.decoy_text.chars() { if num_alphas == secret.len() { break; } if c.is_alphabetic() { num_alphas += 1 } else { num_non_alphas += 1 }; } let decoy_slice: String = self .decoy_text .chars() .take(num_alphas + num_non_alphas) .collect(); // We now have an encoded message, `secret`, in which each character of of the // original plaintext is now represented by a 5-bit binary character, // "AAAAA", "ABABA" etc. // We now overlay the encoded text onto the decoy slice, and // where the binary 'B' is found the decoy slice char is swapped for an italic let mut decoy_msg = String::new(); let mut secret_iter = secret.chars(); for c in decoy_slice.chars() { if c.is_alphabetic() { if let Some(sc) = secret_iter.next() { if sc == 'B' { // match the binary 'B' and swap for italic let italic = *ITALIC_CODES.get(c.to_string().as_str()).unwrap(); decoy_msg.push(italic); } else { decoy_msg.push(c); } } } else { decoy_msg.push(c); } } Ok(decoy_msg) } /// Decrypt a message that was encrypted with the Baconian cipher /// /// # Examples /// Basic usage: /// /// ``` /// use cipher_crypt::{Cipher, Baconian}; /// /// let b = Baconian::new((false, None));; /// let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘯𝘦 t"; /// /// assert_eq!("HELLO", b.decrypt(cipher_text).unwrap()); /// ``` /// fn decrypt(&self, message: &str) -> Result<String, &'static str> { // The message is decoy text // Iterate through swapping any alphabetical chars found in the ITALIC_CODES // set to be 'B', else 'A', skip anything else. let ciphertext: String = message .chars() .filter(|c| c.is_alphabetic()) .map(|c| { if ITALIC_CODES.iter().any(|e| *e.1 == c) { 'B' } else { 'A' } }) .collect(); let mut plaintext = String::new(); let mut code = String::new(); for c in ciphertext.chars() { code.push(c); if code.len() == CODE_LEN { // If we have the right length code plaintext += &get_key(&code); code.clear(); } } Ok(plaintext) } } #[cfg(test)] mod tests { use super::*; #[test] fn encrypt_simple() { let b = Baconian::new((false, None)); let message = "Hello"; let cipher_text = "Lo𝘳𝘦𝘮 ip𝘴um d𝘰l𝘰𝘳 s𝘪t 𝘢𝘮e𝘵, 𝘤𝘰n";
} // Need to test that the traditional and use_distinct_alphabet codes give different results #[test] fn encrypt_trad_v_dist() { let b_trad = Baconian::new((false, None)); let b_dist = Baconian::new((true, None)); let message = "I JADE YOU VERVENT UNICORN"; assert_ne!( b_dist.encrypt(&message).unwrap(), b_trad.encrypt(message).unwrap() ); } #[test] fn encrypt_message_spaced() { let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let b = Baconian::new((false, Some(decoy_text))); let message = "Peace, Freedom 🗡️ and Liberty!"; let cipher_text = "T𝘩𝘦 𝘸𝘰rl𝘥\'s a bubble; an𝘥 the 𝘭ife o𝘧 m𝘢𝘯 les𝘴 th𝘢n a sp𝘢n. \ In hi𝘴 𝘤o𝘯𝘤𝘦pt𝘪𝘰n wretche𝘥; 𝘧r𝘰m th𝘦 𝘸o𝘮b 𝘴𝘰 t𝘰 the tomb: \ 𝐶ur𝘴t f𝘳om t𝘩𝘦 cr𝘢𝘥𝘭𝘦, and"; assert_eq!(cipher_text, b.encrypt(message).unwrap()); } // use_distinct_alphabet lexicon #[test] #[should_panic(expected = r#"Message too long for supplied decoy text."#)] fn encrypt_decoy_too_short() { let b = Baconian::new((false, None)); let message = "This is a long message that will be too long to encode using \ the default decoy text. In order to have a long message encoded you need a \ decoy text that is at least five times as long, plus the non-alphabeticals."; b.encrypt(message).unwrap(); } #[test] fn encrypt_with_use_distinct_alphabet_codeset() { let message = "Peace, Freedom 🗡️ and Liberty!"; let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let cipher_text = "T𝘩𝘦 𝘸𝘰rl𝘥's a bubble; an𝘥 the 𝘭ife o𝘧 m𝘢𝘯 les𝘴 th𝘢n a sp𝘢n. \ In hi𝘴 𝘤o𝘯𝘤𝘦pt𝘪𝘰n wretche𝘥; 𝘧r𝘰m th𝘦 𝘸o𝘮b 𝘴𝘰 t𝘰 the tomb: \ 𝐶ur𝘴t f𝘳om t𝘩𝘦 cr𝘢𝘥𝘭𝘦, and"; let b = Baconian::new((true, Some(decoy_text))); assert_eq!(cipher_text, b.encrypt(message).unwrap()); } #[test] fn decrypt_a_classic() { let cipher_text = String::from("Let's c𝘰mp𝘳𝘰𝘮is𝘦. 𝐻old off th𝘦 at𝘵a𝘤k"); let message = "ATTACK"; let decoy_text = String::from("Let's compromise. Hold off the attack"); let b = Baconian::new((true, Some(decoy_text))); assert_eq!(message, b.decrypt(&cipher_text).unwrap()); } #[test] fn decrypt_traditional() { let cipher_text = String::from( "T𝘩e wor𝘭d's a bubble; an𝘥 𝘵he 𝘭if𝘦 𝘰f man 𝘭𝘦𝘴s 𝘵h𝘢n 𝘢 𝘴p𝘢n. \ 𝐼n h𝘪s c𝘰nce𝘱𝘵i𝘰n 𝘸re𝘵che𝘥; 𝘧r𝘰𝘮 th𝘦 𝘸𝘰m𝘣 s𝘰 t𝘰 𝘵h𝘦 t𝘰mb: \ Curs𝘵 fr𝘰𝘮 𝘵h𝘦 cra𝘥l𝘦, 𝘢n𝘥", ); // Note: the substitution for 'I'/'J' and 'U'/'V' let message = "IIADEYOVVERVENTVNICORN"; let decoy_text = String::from( // The Life of Man, verse 1 "The world's a bubble; and the life of man less than a span. \ In his conception wretched; from the womb so to the tomb: \ Curst from the cradle, and brought up to years, with cares and fears. \ Who then to frail mortality shall trust, \ But limns the water, or but writes in dust. \ Yet, since with sorrow here we live oppress'd, what life is best? \ Courts are but only superficial schools to dandle fools: \ The rural parts are turn'd into a den of savage men: \ And where's a city from all vice so free, \ But may be term'd the worst of all the three?", ); let b = Baconian::new((false, Some(decoy_text))); assert_eq!(message, b.decrypt(&cipher_text).unwrap()); } }
assert_eq!(cipher_text, b.encrypt(message).unwrap());
random_line_split
cifuzz_test.py
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests the functionality of the cifuzz module.""" import os import sys import tempfile import unittest from unittest import mock # pylint: disable=wrong-import-position INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(INFRA_DIR) OSS_FUZZ_DIR = os.path.dirname(INFRA_DIR) import cifuzz import test_helpers # NOTE: This integration test relies on # https://github.com/google/oss-fuzz/tree/master/projects/example project. EXAMPLE_PROJECT = 'example' # Location of files used for testing. TEST_FILES_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_files') # An example fuzzer that triggers an crash. # Binary is a copy of the example project's do_stuff_fuzzer and can be # generated by running "python3 infra/helper.py build_fuzzers example". EXAMPLE_CRASH_FUZZER = 'example_crash_fuzzer' # An example fuzzer that does not trigger a crash. # Binary is a modified version of example project's do_stuff_fuzzer. It is # created by removing the bug in my_api.cpp. EXAMPLE_NOCRASH_FUZZER = 'example_nocrash_fuzzer' # A fuzzer to be built in build_fuzzers integration tests. EXAMPLE_BUILD_FUZZER = 'do_stuff_fuzzer' # pylint: disable=no-self-use class BuildFuzzersTest(unittest.TestCase): """Unit tests for build_fuzzers.""" @mock.patch('build_specified_commit.detect_main_repo', return_value=('example.com', '/path')) @mock.patch('repo_manager._clone', return_value=None) @mock.patch('cifuzz.checkout_specified_commit') @mock.patch('helper.docker_run') def test_cifuzz_env_var(self, mocked_docker_run, _, __, ___): """Tests that the CIFUZZ env var is set.""" with tempfile.TemporaryDirectory() as tmp_dir: cifuzz.build_fuzzers(EXAMPLE_PROJECT, EXAMPLE_PROJECT, tmp_dir, pr_ref='refs/pull/1757/merge') docker_run_command = mocked_docker_run.call_args_list[0][0][0] def command_has_env_var_arg(command, env_var_arg): for idx, element in enumerate(command): if idx == 0: continue if element == env_var_arg and command[idx - 1] == '-e': return True return False self.assertTrue(command_has_env_var_arg(docker_run_command, 'CIFUZZ=True')) class InternalGithubBuilderTest(unittest.TestCase): """Tests for building OSS-Fuzz projects on GitHub actions.""" PROJECT_NAME = 'myproject' PROJECT_REPO_NAME = 'myproject' SANITIZER = 'address' COMMIT_SHA = 'fake' PR_REF = 'fake' def _create_builder(self, tmp_dir): """Creates an InternalGithubBuilder and returns it.""" return cifuzz.InternalGithubBuilder(self.PROJECT_NAME, self.PROJECT_REPO_NAME, tmp_dir, self.SANITIZER, self.COMMIT_SHA, self.PR_REF) @mock.patch('repo_manager._clone', side_effect=None) @mock.patch('cifuzz.checkout_specified_commit', side_effect=None) def test_correct_host_repo_path(self, _, __): """Tests that the correct self.host_repo_path is set by build_image_and_checkout_src. Specifically, we want the name of the directory the repo is in to match the name used in the docker image/container, so that it will replace the host's copy properly.""" image_repo_path = '/src/repo_dir' with tempfile.TemporaryDirectory() as tmp_dir, mock.patch( 'build_specified_commit.detect_main_repo', return_value=('inferred_url', image_repo_path)): builder = self._create_builder(tmp_dir) builder.build_image_and_checkout_src() self.assertEqual(os.path.basename(builder.host_repo_path), os.path.basename(image_repo_path)) @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), 'INTEGRATION_TESTS=1 not set') class BuildFuzzersIntegrationTest(unittest.TestCase): """Integration tests for build_fuzzers.""" def setUp(self): test_helpers.patch_environ(self) def test_external_project(self): """Tests building fuzzers from an external project.""" project_name = 'external-project' project_src_path = os.path.join(TEST_FILES_PATH, project_name) build_integration_path = os.path.join(project_src_path, 'oss-fuzz') with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers(project_name, project_name, tmp_dir, project_src_path=project_src_path, build_integration_path=build_integration_path)) self.assertTrue( os.path.exists(os.path.join(out_path, EXAMPLE_BUILD_FUZZER))) def test_valid_commit(self): """Tests building fuzzers with valid inputs.""" with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers( EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')) self.assertTrue( os.path.exists(os.path.join(out_path, EXAMPLE_BUILD_FUZZER))) def test_valid_pull_request(self): """Tests building fuzzers with valid pull request.""" with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers(EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, pr_ref='refs/pull/1757/merge')) self.assertTrue( os.path.exists(os.path.join(out_path, EXAMPLE_BUILD_FUZZER))) def test_invalid_pull_request(self): """Tests building fuzzers with invalid pull request.""" with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers(EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, pr_ref='ref-1/merge')) def test_invalid_project_name(self): """Tests building fuzzers with invalid project name.""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertFalse( cifuzz.build_fuzzers( 'not_a_valid_project', 'oss-fuzz', tmp_dir, commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')) def test_invalid_repo_name(self): """Tests building fuzzers with invalid repo name.""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertFalse( cifuzz.build_fuzzers( EXAMPLE_PROJECT, 'not-real-repo', tmp_dir, commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')) def test_invalid_commit_sha(self): """Tests building fuzzers with invalid commit SHA.""" with tempfile.TemporaryDirectory() as tmp_dir: with self.assertRaises(AssertionError): cifuzz.build_fuzzers(EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, commit_sha='') def test_invalid_workspace(self): """Tests building fuzzers with invalid workspace.""" self.assertFalse( cifuzz.build_fuzzers( EXAMPLE_PROJECT, 'oss-fuzz', 'not/a/dir', commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523', )) class CheckFuzzerBuildTest(unittest.TestCase): """Tests the check_fuzzer_build function in the cifuzz module.""" def test_correct_fuzzer_build(self): """Checks check_fuzzer_build function returns True for valid fuzzers.""" test_fuzzer_dir = os.path.join(TEST_FILES_PATH, 'out') self.assertTrue(cifuzz.check_fuzzer_build(test_fuzzer_dir)) def test_not_a_valid_fuzz_path(self): """Tests that False is returned when a bad path is given.""" self.assertFalse(cifuzz.check_fuzzer_build('not/a/valid/path')) def test_not_a_valid_fuzzer(self): """Checks a directory that exists but does not have fuzzers is False.""" self.assertFalse(cifuzz.check_fuzzer_build(TEST_FILES_PATH)) @mock.patch('helper.docker_run') def test_allow_broken_fuzz_targets_percentage(self, mocked_docker_run): """Tests that ALLOWED_BROKEN_TARGETS_PERCENTAGE is set when running docker if passed to check_fuzzer_build.""" mocked_docker_run.return_value = 0 test_fuzzer_dir = os.path.join(TEST_FILES_PATH, 'out') cifuzz.check_fuzzer_build(test_fuzzer_dir, allowed_broken_targets_percentage='0') self.assertIn('-e ALLOWED_BROKEN_TARGETS_PERCENTAGE=0', ' '.join(mocked_docker_run.call_args[0][0])) @unittest.skip('Test is too long to be run with presubmit.') class BuildSantizerIntegrationTest(unittest.TestCase): """Integration tests for the build_fuzzers. Note: This test relies on "curl" being an OSS-Fuzz project.""" def test_valid_project_curl_memory(self): """Tests that MSAN can be detected from project.yaml""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertTrue( cifuzz.build_fuzzers('curl', 'curl', tmp_dir, pr_ref='fake_pr', sanitizer='memory')) def test_valid_project_curl_undefined(self): """Test that UBSAN can be detected from project.yaml""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertTrue( cifuzz.build_fuzzers('curl', 'curl', tmp_dir, pr_ref='fake_pr', sanitizer='undefined')) if __name__ == '__main__':
unittest.main()
conditional_block
cifuzz_test.py
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests the functionality of the cifuzz module.""" import os import sys import tempfile import unittest from unittest import mock # pylint: disable=wrong-import-position INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(INFRA_DIR) OSS_FUZZ_DIR = os.path.dirname(INFRA_DIR) import cifuzz import test_helpers # NOTE: This integration test relies on # https://github.com/google/oss-fuzz/tree/master/projects/example project. EXAMPLE_PROJECT = 'example' # Location of files used for testing. TEST_FILES_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_files') # An example fuzzer that triggers an crash. # Binary is a copy of the example project's do_stuff_fuzzer and can be # generated by running "python3 infra/helper.py build_fuzzers example". EXAMPLE_CRASH_FUZZER = 'example_crash_fuzzer' # An example fuzzer that does not trigger a crash. # Binary is a modified version of example project's do_stuff_fuzzer. It is # created by removing the bug in my_api.cpp. EXAMPLE_NOCRASH_FUZZER = 'example_nocrash_fuzzer' # A fuzzer to be built in build_fuzzers integration tests. EXAMPLE_BUILD_FUZZER = 'do_stuff_fuzzer' # pylint: disable=no-self-use class BuildFuzzersTest(unittest.TestCase): """Unit tests for build_fuzzers.""" @mock.patch('build_specified_commit.detect_main_repo', return_value=('example.com', '/path')) @mock.patch('repo_manager._clone', return_value=None) @mock.patch('cifuzz.checkout_specified_commit') @mock.patch('helper.docker_run') def test_cifuzz_env_var(self, mocked_docker_run, _, __, ___): """Tests that the CIFUZZ env var is set.""" with tempfile.TemporaryDirectory() as tmp_dir: cifuzz.build_fuzzers(EXAMPLE_PROJECT, EXAMPLE_PROJECT, tmp_dir, pr_ref='refs/pull/1757/merge') docker_run_command = mocked_docker_run.call_args_list[0][0][0] def command_has_env_var_arg(command, env_var_arg): for idx, element in enumerate(command): if idx == 0: continue if element == env_var_arg and command[idx - 1] == '-e': return True return False self.assertTrue(command_has_env_var_arg(docker_run_command, 'CIFUZZ=True')) class InternalGithubBuilderTest(unittest.TestCase): """Tests for building OSS-Fuzz projects on GitHub actions.""" PROJECT_NAME = 'myproject' PROJECT_REPO_NAME = 'myproject' SANITIZER = 'address' COMMIT_SHA = 'fake' PR_REF = 'fake' def _create_builder(self, tmp_dir): """Creates an InternalGithubBuilder and returns it.""" return cifuzz.InternalGithubBuilder(self.PROJECT_NAME, self.PROJECT_REPO_NAME, tmp_dir, self.SANITIZER, self.COMMIT_SHA, self.PR_REF) @mock.patch('repo_manager._clone', side_effect=None) @mock.patch('cifuzz.checkout_specified_commit', side_effect=None) def test_correct_host_repo_path(self, _, __): """Tests that the correct self.host_repo_path is set by build_image_and_checkout_src. Specifically, we want the name of the directory the repo is in to match the name used in the docker image/container, so that it will replace the host's copy properly.""" image_repo_path = '/src/repo_dir' with tempfile.TemporaryDirectory() as tmp_dir, mock.patch( 'build_specified_commit.detect_main_repo', return_value=('inferred_url', image_repo_path)): builder = self._create_builder(tmp_dir) builder.build_image_and_checkout_src() self.assertEqual(os.path.basename(builder.host_repo_path), os.path.basename(image_repo_path)) @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), 'INTEGRATION_TESTS=1 not set') class BuildFuzzersIntegrationTest(unittest.TestCase): """Integration tests for build_fuzzers.""" def setUp(self): test_helpers.patch_environ(self) def test_external_project(self): """Tests building fuzzers from an external project.""" project_name = 'external-project' project_src_path = os.path.join(TEST_FILES_PATH, project_name) build_integration_path = os.path.join(project_src_path, 'oss-fuzz') with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers(project_name, project_name, tmp_dir, project_src_path=project_src_path, build_integration_path=build_integration_path)) self.assertTrue( os.path.exists(os.path.join(out_path, EXAMPLE_BUILD_FUZZER))) def test_valid_commit(self): """Tests building fuzzers with valid inputs.""" with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers( EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')) self.assertTrue( os.path.exists(os.path.join(out_path, EXAMPLE_BUILD_FUZZER))) def test_valid_pull_request(self): """Tests building fuzzers with valid pull request.""" with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers(EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, pr_ref='refs/pull/1757/merge')) self.assertTrue( os.path.exists(os.path.join(out_path, EXAMPLE_BUILD_FUZZER))) def test_invalid_pull_request(self): """Tests building fuzzers with invalid pull request.""" with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers(EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, pr_ref='ref-1/merge')) def test_invalid_project_name(self): """Tests building fuzzers with invalid project name.""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertFalse( cifuzz.build_fuzzers( 'not_a_valid_project', 'oss-fuzz', tmp_dir, commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')) def test_invalid_repo_name(self): """Tests building fuzzers with invalid repo name.""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertFalse( cifuzz.build_fuzzers( EXAMPLE_PROJECT, 'not-real-repo', tmp_dir, commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')) def test_invalid_commit_sha(self): """Tests building fuzzers with invalid commit SHA.""" with tempfile.TemporaryDirectory() as tmp_dir: with self.assertRaises(AssertionError): cifuzz.build_fuzzers(EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, commit_sha='') def test_invalid_workspace(self): """Tests building fuzzers with invalid workspace.""" self.assertFalse( cifuzz.build_fuzzers( EXAMPLE_PROJECT, 'oss-fuzz',
commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523', )) class CheckFuzzerBuildTest(unittest.TestCase): """Tests the check_fuzzer_build function in the cifuzz module.""" def test_correct_fuzzer_build(self): """Checks check_fuzzer_build function returns True for valid fuzzers.""" test_fuzzer_dir = os.path.join(TEST_FILES_PATH, 'out') self.assertTrue(cifuzz.check_fuzzer_build(test_fuzzer_dir)) def test_not_a_valid_fuzz_path(self): """Tests that False is returned when a bad path is given.""" self.assertFalse(cifuzz.check_fuzzer_build('not/a/valid/path')) def test_not_a_valid_fuzzer(self): """Checks a directory that exists but does not have fuzzers is False.""" self.assertFalse(cifuzz.check_fuzzer_build(TEST_FILES_PATH)) @mock.patch('helper.docker_run') def test_allow_broken_fuzz_targets_percentage(self, mocked_docker_run): """Tests that ALLOWED_BROKEN_TARGETS_PERCENTAGE is set when running docker if passed to check_fuzzer_build.""" mocked_docker_run.return_value = 0 test_fuzzer_dir = os.path.join(TEST_FILES_PATH, 'out') cifuzz.check_fuzzer_build(test_fuzzer_dir, allowed_broken_targets_percentage='0') self.assertIn('-e ALLOWED_BROKEN_TARGETS_PERCENTAGE=0', ' '.join(mocked_docker_run.call_args[0][0])) @unittest.skip('Test is too long to be run with presubmit.') class BuildSantizerIntegrationTest(unittest.TestCase): """Integration tests for the build_fuzzers. Note: This test relies on "curl" being an OSS-Fuzz project.""" def test_valid_project_curl_memory(self): """Tests that MSAN can be detected from project.yaml""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertTrue( cifuzz.build_fuzzers('curl', 'curl', tmp_dir, pr_ref='fake_pr', sanitizer='memory')) def test_valid_project_curl_undefined(self): """Test that UBSAN can be detected from project.yaml""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertTrue( cifuzz.build_fuzzers('curl', 'curl', tmp_dir, pr_ref='fake_pr', sanitizer='undefined')) if __name__ == '__main__': unittest.main()
'not/a/dir',
random_line_split
cifuzz_test.py
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests the functionality of the cifuzz module.""" import os import sys import tempfile import unittest from unittest import mock # pylint: disable=wrong-import-position INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(INFRA_DIR) OSS_FUZZ_DIR = os.path.dirname(INFRA_DIR) import cifuzz import test_helpers # NOTE: This integration test relies on # https://github.com/google/oss-fuzz/tree/master/projects/example project. EXAMPLE_PROJECT = 'example' # Location of files used for testing. TEST_FILES_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_files') # An example fuzzer that triggers an crash. # Binary is a copy of the example project's do_stuff_fuzzer and can be # generated by running "python3 infra/helper.py build_fuzzers example". EXAMPLE_CRASH_FUZZER = 'example_crash_fuzzer' # An example fuzzer that does not trigger a crash. # Binary is a modified version of example project's do_stuff_fuzzer. It is # created by removing the bug in my_api.cpp. EXAMPLE_NOCRASH_FUZZER = 'example_nocrash_fuzzer' # A fuzzer to be built in build_fuzzers integration tests. EXAMPLE_BUILD_FUZZER = 'do_stuff_fuzzer' # pylint: disable=no-self-use class BuildFuzzersTest(unittest.TestCase): """Unit tests for build_fuzzers.""" @mock.patch('build_specified_commit.detect_main_repo', return_value=('example.com', '/path')) @mock.patch('repo_manager._clone', return_value=None) @mock.patch('cifuzz.checkout_specified_commit') @mock.patch('helper.docker_run') def test_cifuzz_env_var(self, mocked_docker_run, _, __, ___): """Tests that the CIFUZZ env var is set.""" with tempfile.TemporaryDirectory() as tmp_dir: cifuzz.build_fuzzers(EXAMPLE_PROJECT, EXAMPLE_PROJECT, tmp_dir, pr_ref='refs/pull/1757/merge') docker_run_command = mocked_docker_run.call_args_list[0][0][0] def
(command, env_var_arg): for idx, element in enumerate(command): if idx == 0: continue if element == env_var_arg and command[idx - 1] == '-e': return True return False self.assertTrue(command_has_env_var_arg(docker_run_command, 'CIFUZZ=True')) class InternalGithubBuilderTest(unittest.TestCase): """Tests for building OSS-Fuzz projects on GitHub actions.""" PROJECT_NAME = 'myproject' PROJECT_REPO_NAME = 'myproject' SANITIZER = 'address' COMMIT_SHA = 'fake' PR_REF = 'fake' def _create_builder(self, tmp_dir): """Creates an InternalGithubBuilder and returns it.""" return cifuzz.InternalGithubBuilder(self.PROJECT_NAME, self.PROJECT_REPO_NAME, tmp_dir, self.SANITIZER, self.COMMIT_SHA, self.PR_REF) @mock.patch('repo_manager._clone', side_effect=None) @mock.patch('cifuzz.checkout_specified_commit', side_effect=None) def test_correct_host_repo_path(self, _, __): """Tests that the correct self.host_repo_path is set by build_image_and_checkout_src. Specifically, we want the name of the directory the repo is in to match the name used in the docker image/container, so that it will replace the host's copy properly.""" image_repo_path = '/src/repo_dir' with tempfile.TemporaryDirectory() as tmp_dir, mock.patch( 'build_specified_commit.detect_main_repo', return_value=('inferred_url', image_repo_path)): builder = self._create_builder(tmp_dir) builder.build_image_and_checkout_src() self.assertEqual(os.path.basename(builder.host_repo_path), os.path.basename(image_repo_path)) @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), 'INTEGRATION_TESTS=1 not set') class BuildFuzzersIntegrationTest(unittest.TestCase): """Integration tests for build_fuzzers.""" def setUp(self): test_helpers.patch_environ(self) def test_external_project(self): """Tests building fuzzers from an external project.""" project_name = 'external-project' project_src_path = os.path.join(TEST_FILES_PATH, project_name) build_integration_path = os.path.join(project_src_path, 'oss-fuzz') with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers(project_name, project_name, tmp_dir, project_src_path=project_src_path, build_integration_path=build_integration_path)) self.assertTrue( os.path.exists(os.path.join(out_path, EXAMPLE_BUILD_FUZZER))) def test_valid_commit(self): """Tests building fuzzers with valid inputs.""" with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers( EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')) self.assertTrue( os.path.exists(os.path.join(out_path, EXAMPLE_BUILD_FUZZER))) def test_valid_pull_request(self): """Tests building fuzzers with valid pull request.""" with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers(EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, pr_ref='refs/pull/1757/merge')) self.assertTrue( os.path.exists(os.path.join(out_path, EXAMPLE_BUILD_FUZZER))) def test_invalid_pull_request(self): """Tests building fuzzers with invalid pull request.""" with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers(EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, pr_ref='ref-1/merge')) def test_invalid_project_name(self): """Tests building fuzzers with invalid project name.""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertFalse( cifuzz.build_fuzzers( 'not_a_valid_project', 'oss-fuzz', tmp_dir, commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')) def test_invalid_repo_name(self): """Tests building fuzzers with invalid repo name.""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertFalse( cifuzz.build_fuzzers( EXAMPLE_PROJECT, 'not-real-repo', tmp_dir, commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')) def test_invalid_commit_sha(self): """Tests building fuzzers with invalid commit SHA.""" with tempfile.TemporaryDirectory() as tmp_dir: with self.assertRaises(AssertionError): cifuzz.build_fuzzers(EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, commit_sha='') def test_invalid_workspace(self): """Tests building fuzzers with invalid workspace.""" self.assertFalse( cifuzz.build_fuzzers( EXAMPLE_PROJECT, 'oss-fuzz', 'not/a/dir', commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523', )) class CheckFuzzerBuildTest(unittest.TestCase): """Tests the check_fuzzer_build function in the cifuzz module.""" def test_correct_fuzzer_build(self): """Checks check_fuzzer_build function returns True for valid fuzzers.""" test_fuzzer_dir = os.path.join(TEST_FILES_PATH, 'out') self.assertTrue(cifuzz.check_fuzzer_build(test_fuzzer_dir)) def test_not_a_valid_fuzz_path(self): """Tests that False is returned when a bad path is given.""" self.assertFalse(cifuzz.check_fuzzer_build('not/a/valid/path')) def test_not_a_valid_fuzzer(self): """Checks a directory that exists but does not have fuzzers is False.""" self.assertFalse(cifuzz.check_fuzzer_build(TEST_FILES_PATH)) @mock.patch('helper.docker_run') def test_allow_broken_fuzz_targets_percentage(self, mocked_docker_run): """Tests that ALLOWED_BROKEN_TARGETS_PERCENTAGE is set when running docker if passed to check_fuzzer_build.""" mocked_docker_run.return_value = 0 test_fuzzer_dir = os.path.join(TEST_FILES_PATH, 'out') cifuzz.check_fuzzer_build(test_fuzzer_dir, allowed_broken_targets_percentage='0') self.assertIn('-e ALLOWED_BROKEN_TARGETS_PERCENTAGE=0', ' '.join(mocked_docker_run.call_args[0][0])) @unittest.skip('Test is too long to be run with presubmit.') class BuildSantizerIntegrationTest(unittest.TestCase): """Integration tests for the build_fuzzers. Note: This test relies on "curl" being an OSS-Fuzz project.""" def test_valid_project_curl_memory(self): """Tests that MSAN can be detected from project.yaml""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertTrue( cifuzz.build_fuzzers('curl', 'curl', tmp_dir, pr_ref='fake_pr', sanitizer='memory')) def test_valid_project_curl_undefined(self): """Test that UBSAN can be detected from project.yaml""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertTrue( cifuzz.build_fuzzers('curl', 'curl', tmp_dir, pr_ref='fake_pr', sanitizer='undefined')) if __name__ == '__main__': unittest.main()
command_has_env_var_arg
identifier_name
cifuzz_test.py
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests the functionality of the cifuzz module.""" import os import sys import tempfile import unittest from unittest import mock # pylint: disable=wrong-import-position INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(INFRA_DIR) OSS_FUZZ_DIR = os.path.dirname(INFRA_DIR) import cifuzz import test_helpers # NOTE: This integration test relies on # https://github.com/google/oss-fuzz/tree/master/projects/example project. EXAMPLE_PROJECT = 'example' # Location of files used for testing. TEST_FILES_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_files') # An example fuzzer that triggers an crash. # Binary is a copy of the example project's do_stuff_fuzzer and can be # generated by running "python3 infra/helper.py build_fuzzers example". EXAMPLE_CRASH_FUZZER = 'example_crash_fuzzer' # An example fuzzer that does not trigger a crash. # Binary is a modified version of example project's do_stuff_fuzzer. It is # created by removing the bug in my_api.cpp. EXAMPLE_NOCRASH_FUZZER = 'example_nocrash_fuzzer' # A fuzzer to be built in build_fuzzers integration tests. EXAMPLE_BUILD_FUZZER = 'do_stuff_fuzzer' # pylint: disable=no-self-use class BuildFuzzersTest(unittest.TestCase): """Unit tests for build_fuzzers.""" @mock.patch('build_specified_commit.detect_main_repo', return_value=('example.com', '/path')) @mock.patch('repo_manager._clone', return_value=None) @mock.patch('cifuzz.checkout_specified_commit') @mock.patch('helper.docker_run') def test_cifuzz_env_var(self, mocked_docker_run, _, __, ___): """Tests that the CIFUZZ env var is set.""" with tempfile.TemporaryDirectory() as tmp_dir: cifuzz.build_fuzzers(EXAMPLE_PROJECT, EXAMPLE_PROJECT, tmp_dir, pr_ref='refs/pull/1757/merge') docker_run_command = mocked_docker_run.call_args_list[0][0][0] def command_has_env_var_arg(command, env_var_arg):
self.assertTrue(command_has_env_var_arg(docker_run_command, 'CIFUZZ=True')) class InternalGithubBuilderTest(unittest.TestCase): """Tests for building OSS-Fuzz projects on GitHub actions.""" PROJECT_NAME = 'myproject' PROJECT_REPO_NAME = 'myproject' SANITIZER = 'address' COMMIT_SHA = 'fake' PR_REF = 'fake' def _create_builder(self, tmp_dir): """Creates an InternalGithubBuilder and returns it.""" return cifuzz.InternalGithubBuilder(self.PROJECT_NAME, self.PROJECT_REPO_NAME, tmp_dir, self.SANITIZER, self.COMMIT_SHA, self.PR_REF) @mock.patch('repo_manager._clone', side_effect=None) @mock.patch('cifuzz.checkout_specified_commit', side_effect=None) def test_correct_host_repo_path(self, _, __): """Tests that the correct self.host_repo_path is set by build_image_and_checkout_src. Specifically, we want the name of the directory the repo is in to match the name used in the docker image/container, so that it will replace the host's copy properly.""" image_repo_path = '/src/repo_dir' with tempfile.TemporaryDirectory() as tmp_dir, mock.patch( 'build_specified_commit.detect_main_repo', return_value=('inferred_url', image_repo_path)): builder = self._create_builder(tmp_dir) builder.build_image_and_checkout_src() self.assertEqual(os.path.basename(builder.host_repo_path), os.path.basename(image_repo_path)) @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), 'INTEGRATION_TESTS=1 not set') class BuildFuzzersIntegrationTest(unittest.TestCase): """Integration tests for build_fuzzers.""" def setUp(self): test_helpers.patch_environ(self) def test_external_project(self): """Tests building fuzzers from an external project.""" project_name = 'external-project' project_src_path = os.path.join(TEST_FILES_PATH, project_name) build_integration_path = os.path.join(project_src_path, 'oss-fuzz') with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers(project_name, project_name, tmp_dir, project_src_path=project_src_path, build_integration_path=build_integration_path)) self.assertTrue( os.path.exists(os.path.join(out_path, EXAMPLE_BUILD_FUZZER))) def test_valid_commit(self): """Tests building fuzzers with valid inputs.""" with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers( EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')) self.assertTrue( os.path.exists(os.path.join(out_path, EXAMPLE_BUILD_FUZZER))) def test_valid_pull_request(self): """Tests building fuzzers with valid pull request.""" with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers(EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, pr_ref='refs/pull/1757/merge')) self.assertTrue( os.path.exists(os.path.join(out_path, EXAMPLE_BUILD_FUZZER))) def test_invalid_pull_request(self): """Tests building fuzzers with invalid pull request.""" with tempfile.TemporaryDirectory() as tmp_dir: out_path = os.path.join(tmp_dir, 'out') os.mkdir(out_path) self.assertTrue( cifuzz.build_fuzzers(EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, pr_ref='ref-1/merge')) def test_invalid_project_name(self): """Tests building fuzzers with invalid project name.""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertFalse( cifuzz.build_fuzzers( 'not_a_valid_project', 'oss-fuzz', tmp_dir, commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')) def test_invalid_repo_name(self): """Tests building fuzzers with invalid repo name.""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertFalse( cifuzz.build_fuzzers( EXAMPLE_PROJECT, 'not-real-repo', tmp_dir, commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')) def test_invalid_commit_sha(self): """Tests building fuzzers with invalid commit SHA.""" with tempfile.TemporaryDirectory() as tmp_dir: with self.assertRaises(AssertionError): cifuzz.build_fuzzers(EXAMPLE_PROJECT, 'oss-fuzz', tmp_dir, commit_sha='') def test_invalid_workspace(self): """Tests building fuzzers with invalid workspace.""" self.assertFalse( cifuzz.build_fuzzers( EXAMPLE_PROJECT, 'oss-fuzz', 'not/a/dir', commit_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523', )) class CheckFuzzerBuildTest(unittest.TestCase): """Tests the check_fuzzer_build function in the cifuzz module.""" def test_correct_fuzzer_build(self): """Checks check_fuzzer_build function returns True for valid fuzzers.""" test_fuzzer_dir = os.path.join(TEST_FILES_PATH, 'out') self.assertTrue(cifuzz.check_fuzzer_build(test_fuzzer_dir)) def test_not_a_valid_fuzz_path(self): """Tests that False is returned when a bad path is given.""" self.assertFalse(cifuzz.check_fuzzer_build('not/a/valid/path')) def test_not_a_valid_fuzzer(self): """Checks a directory that exists but does not have fuzzers is False.""" self.assertFalse(cifuzz.check_fuzzer_build(TEST_FILES_PATH)) @mock.patch('helper.docker_run') def test_allow_broken_fuzz_targets_percentage(self, mocked_docker_run): """Tests that ALLOWED_BROKEN_TARGETS_PERCENTAGE is set when running docker if passed to check_fuzzer_build.""" mocked_docker_run.return_value = 0 test_fuzzer_dir = os.path.join(TEST_FILES_PATH, 'out') cifuzz.check_fuzzer_build(test_fuzzer_dir, allowed_broken_targets_percentage='0') self.assertIn('-e ALLOWED_BROKEN_TARGETS_PERCENTAGE=0', ' '.join(mocked_docker_run.call_args[0][0])) @unittest.skip('Test is too long to be run with presubmit.') class BuildSantizerIntegrationTest(unittest.TestCase): """Integration tests for the build_fuzzers. Note: This test relies on "curl" being an OSS-Fuzz project.""" def test_valid_project_curl_memory(self): """Tests that MSAN can be detected from project.yaml""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertTrue( cifuzz.build_fuzzers('curl', 'curl', tmp_dir, pr_ref='fake_pr', sanitizer='memory')) def test_valid_project_curl_undefined(self): """Test that UBSAN can be detected from project.yaml""" with tempfile.TemporaryDirectory() as tmp_dir: self.assertTrue( cifuzz.build_fuzzers('curl', 'curl', tmp_dir, pr_ref='fake_pr', sanitizer='undefined')) if __name__ == '__main__': unittest.main()
for idx, element in enumerate(command): if idx == 0: continue if element == env_var_arg and command[idx - 1] == '-e': return True return False
identifier_body
recv_stream.rs
use std::{ future::Future, io, pin::Pin, task::{Context, Poll}, }; use bytes::Bytes; use proto::{Chunk, Chunks, ConnectionError, ReadableError, StreamId}; use thiserror::Error; use tokio::io::ReadBuf; use crate::{ connection::{ConnectionRef, UnknownStream}, VarInt, }; /// A stream that can only be used to receive data /// /// `stop(0)` is implicitly called on drop unless: /// - A variant of [`ReadError`] has been yielded by a read call /// - [`stop()`] was called explicitly /// /// # Closing a stream /// /// When a stream is expected to be closed gracefully the sender should call /// [`SendStream::finish`]. However there is no guarantee the connected [`RecvStream`] will /// receive the "finished" notification in the same QUIC frame as the last frame which /// carried data. /// /// Even if the application layer logic already knows it read all the data because it does /// its own framing, it should still read until it reaches the end of the [`RecvStream`]. /// Otherwise it risks inadvertently calling [`RecvStream::stop`] if it drops the stream. /// And calling [`RecvStream::stop`] could result in the connected [`SendStream::finish`] /// call failing with a [`WriteError::Stopped`] error. /// /// For example if exactly 10 bytes are to be read, you still need to explicitly read the /// end of the stream: /// /// ```no_run /// # use quinn::{SendStream, RecvStream}; /// # async fn func( /// # mut send_stream: SendStream, /// # mut recv_stream: RecvStream, /// # ) -> anyhow::Result<()> /// # { /// // In the sending task /// send_stream.write(&b"0123456789"[..]).await?; /// send_stream.finish().await?; /// /// // In the receiving task /// let mut buf = [0u8; 10]; /// let data = recv_stream.read_exact(&mut buf).await?; /// if recv_stream.read_to_end(0).await.is_err() { /// // Discard unexpected data and notify the peer to stop sending it /// let _ = recv_stream.stop(0u8.into()); /// } /// # Ok(()) /// # } /// ``` /// /// An alternative approach, used in HTTP/3, is to specify a particular error code used with `stop` /// that indicates graceful receiver-initiated stream shutdown, rather than a true error condition. /// /// [`RecvStream::read_chunk`] could be used instead which does not take ownership and /// allows using an explicit call to [`RecvStream::stop`] with a custom error code. /// /// [`ReadError`]: crate::ReadError /// [`stop()`]: RecvStream::stop /// [`SendStream::finish`]: crate::SendStream::finish /// [`WriteError::Stopped`]: crate::WriteError::Stopped #[derive(Debug)] pub struct RecvStream { conn: ConnectionRef, stream: StreamId, is_0rtt: bool, all_data_read: bool, reset: Option<VarInt>, } impl RecvStream { pub(crate) fn new(conn: ConnectionRef, stream: StreamId, is_0rtt: bool) -> Self { Self { conn, stream, is_0rtt, all_data_read: false, reset: None, } } /// Read data contiguously from the stream. /// /// Yields the number of bytes read into `buf` on success, or `None` if the stream was finished. pub async fn
(&mut self, buf: &mut [u8]) -> Result<Option<usize>, ReadError> { Read { stream: self, buf: ReadBuf::new(buf), } .await } /// Read an exact number of bytes contiguously from the stream. /// /// See [`read()`] for details. /// /// [`read()`]: RecvStream::read pub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), ReadExactError> { ReadExact { stream: self, buf: ReadBuf::new(buf), } .await } fn poll_read( &mut self, cx: &mut Context, buf: &mut ReadBuf<'_>, ) -> Poll<Result<(), ReadError>> { if buf.remaining() == 0 { return Poll::Ready(Ok(())); } self.poll_read_generic(cx, true, |chunks| { let mut read = false; loop { if buf.remaining() == 0 { // We know `read` is `true` because `buf.remaining()` was not 0 before return ReadStatus::Readable(()); } match chunks.next(buf.remaining()) { Ok(Some(chunk)) => { buf.put_slice(&chunk.bytes); read = true; } res => return (if read { Some(()) } else { None }, res.err()).into(), } } }) .map(|res| res.map(|_| ())) } /// Read the next segment of data /// /// Yields `None` if the stream was finished. Otherwise, yields a segment of data and its /// offset in the stream. If `ordered` is `true`, the chunk's offset will be immediately after /// the last data yielded by `read()` or `read_chunk()`. If `ordered` is `false`, segments may /// be received in any order, and the `Chunk`'s `offset` field can be used to determine /// ordering in the caller. Unordered reads are less prone to head-of-line blocking within a /// stream, but require the application to manage reassembling the original data. /// /// Slightly more efficient than `read` due to not copying. Chunk boundaries do not correspond /// to peer writes, and hence cannot be used as framing. pub async fn read_chunk( &mut self, max_length: usize, ordered: bool, ) -> Result<Option<Chunk>, ReadError> { ReadChunk { stream: self, max_length, ordered, } .await } /// Foundation of [`Self::read_chunk`] fn poll_read_chunk( &mut self, cx: &mut Context, max_length: usize, ordered: bool, ) -> Poll<Result<Option<Chunk>, ReadError>> { self.poll_read_generic(cx, ordered, |chunks| match chunks.next(max_length) { Ok(Some(chunk)) => ReadStatus::Readable(chunk), res => (None, res.err()).into(), }) } /// Read the next segments of data /// /// Fills `bufs` with the segments of data beginning immediately after the /// last data yielded by `read` or `read_chunk`, or `None` if the stream was /// finished. /// /// Slightly more efficient than `read` due to not copying. Chunk boundaries /// do not correspond to peer writes, and hence cannot be used as framing. pub async fn read_chunks(&mut self, bufs: &mut [Bytes]) -> Result<Option<usize>, ReadError> { ReadChunks { stream: self, bufs }.await } /// Foundation of [`Self::read_chunks`] fn poll_read_chunks( &mut self, cx: &mut Context, bufs: &mut [Bytes], ) -> Poll<Result<Option<usize>, ReadError>> { if bufs.is_empty() { return Poll::Ready(Ok(Some(0))); } self.poll_read_generic(cx, true, |chunks| { let mut read = 0; loop { if read >= bufs.len() { // We know `read > 0` because `bufs` cannot be empty here return ReadStatus::Readable(read); } match chunks.next(usize::MAX) { Ok(Some(chunk)) => { bufs[read] = chunk.bytes; read += 1; } res => return (if read == 0 { None } else { Some(read) }, res.err()).into(), } } }) } /// Convenience method to read all remaining data into a buffer /// /// Fails with [`ReadToEndError::TooLong`] on reading more than `size_limit` bytes, discarding /// all data read. Uses unordered reads to be more efficient than using `AsyncRead` would /// allow. `size_limit` should be set to limit worst-case memory use. /// /// If unordered reads have already been made, the resulting buffer may have gaps containing /// arbitrary data. /// /// [`ReadToEndError::TooLong`]: crate::ReadToEndError::TooLong pub async fn read_to_end(&mut self, size_limit: usize) -> Result<Vec<u8>, ReadToEndError> { ReadToEnd { stream: self, size_limit, read: Vec::new(), start: u64::max_value(), end: 0, } .await } /// Stop accepting data /// /// Discards unread data and notifies the peer to stop transmitting. Once stopped, further /// attempts to operate on a stream will yield `UnknownStream` errors. pub fn stop(&mut self, error_code: VarInt) -> Result<(), UnknownStream> { let mut conn = self.conn.state.lock("RecvStream::stop"); if self.is_0rtt && conn.check_0rtt().is_err() { return Ok(()); } conn.inner.recv_stream(self.stream).stop(error_code)?; conn.wake(); self.all_data_read = true; Ok(()) } /// Check if this stream has been opened during 0-RTT. /// /// In which case any non-idempotent request should be considered dangerous at the application /// level. Because read data is subject to replay attacks. pub fn is_0rtt(&self) -> bool { self.is_0rtt } /// Get the identity of this stream pub fn id(&self) -> StreamId { self.stream } /// Handle common logic related to reading out of a receive stream /// /// This takes an `FnMut` closure that takes care of the actual reading process, matching /// the detailed read semantics for the calling function with a particular return type. /// The closure can read from the passed `&mut Chunks` and has to return the status after /// reading: the amount of data read, and the status after the final read call. fn poll_read_generic<T, U>( &mut self, cx: &mut Context, ordered: bool, mut read_fn: T, ) -> Poll<Result<Option<U>, ReadError>> where T: FnMut(&mut Chunks) -> ReadStatus<U>, { use proto::ReadError::*; if self.all_data_read { return Poll::Ready(Ok(None)); } let mut conn = self.conn.state.lock("RecvStream::poll_read"); if self.is_0rtt { conn.check_0rtt().map_err(|()| ReadError::ZeroRttRejected)?; } // If we stored an error during a previous call, return it now. This can happen if a // `read_fn` both wants to return data and also returns an error in its final stream status. let status = match self.reset.take() { Some(code) => ReadStatus::Failed(None, Reset(code)), None => { let mut recv = conn.inner.recv_stream(self.stream); let mut chunks = recv.read(ordered)?; let status = read_fn(&mut chunks); if chunks.finalize().should_transmit() { conn.wake(); } status } }; match status { ReadStatus::Readable(read) => Poll::Ready(Ok(Some(read))), ReadStatus::Finished(read) => { self.all_data_read = true; Poll::Ready(Ok(read)) } ReadStatus::Failed(read, Blocked) => match read { Some(val) => Poll::Ready(Ok(Some(val))), None => { if let Some(ref x) = conn.error { return Poll::Ready(Err(ReadError::ConnectionLost(x.clone()))); } conn.blocked_readers.insert(self.stream, cx.waker().clone()); Poll::Pending } }, ReadStatus::Failed(read, Reset(error_code)) => match read { None => { self.all_data_read = true; Poll::Ready(Err(ReadError::Reset(error_code))) } done => { self.reset = Some(error_code); Poll::Ready(Ok(done)) } }, } } } enum ReadStatus<T> { Readable(T), Finished(Option<T>), Failed(Option<T>, proto::ReadError), } impl<T> From<(Option<T>, Option<proto::ReadError>)> for ReadStatus<T> { fn from(status: (Option<T>, Option<proto::ReadError>)) -> Self { match status { (read, None) => Self::Finished(read), (read, Some(e)) => Self::Failed(read, e), } } } /// Future produced by [`RecvStream::read_to_end()`]. /// /// [`RecvStream::read_to_end()`]: crate::RecvStream::read_to_end #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadToEnd<'a> { stream: &'a mut RecvStream, read: Vec<(Bytes, u64)>, start: u64, end: u64, size_limit: usize, } impl Future for ReadToEnd<'_> { type Output = Result<Vec<u8>, ReadToEndError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { loop { match ready!(self.stream.poll_read_chunk(cx, usize::MAX, false))? { Some(chunk) => { self.start = self.start.min(chunk.offset); let end = chunk.bytes.len() as u64 + chunk.offset; if (end - self.start) > self.size_limit as u64 { return Poll::Ready(Err(ReadToEndError::TooLong)); } self.end = self.end.max(end); self.read.push((chunk.bytes, chunk.offset)); } None => { if self.end == 0 { // Never received anything return Poll::Ready(Ok(Vec::new())); } let start = self.start; let mut buffer = vec![0; (self.end - start) as usize]; for (data, offset) in self.read.drain(..) { let offset = (offset - start) as usize; buffer[offset..offset + data.len()].copy_from_slice(&data); } return Poll::Ready(Ok(buffer)); } } } } } /// Errors from [`RecvStream::read_to_end`] #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadToEndError { /// An error occurred during reading #[error("read error: {0}")] Read(#[from] ReadError), /// The stream is larger than the user-supplied limit #[error("stream too long")] TooLong, } #[cfg(feature = "futures-io")] impl futures_io::AsyncRead for RecvStream { fn poll_read( self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8], ) -> Poll<io::Result<usize>> { let mut buf = ReadBuf::new(buf); ready!(RecvStream::poll_read(self.get_mut(), cx, &mut buf))?; Poll::Ready(Ok(buf.filled().len())) } } impl tokio::io::AsyncRead for RecvStream { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { ready!(Self::poll_read(self.get_mut(), cx, buf))?; Poll::Ready(Ok(())) } } impl Drop for RecvStream { fn drop(&mut self) { let mut conn = self.conn.state.lock("RecvStream::drop"); // clean up any previously registered wakers conn.blocked_readers.remove(&self.stream); if conn.error.is_some() || (self.is_0rtt && conn.check_0rtt().is_err()) { return; } if !self.all_data_read { // Ignore UnknownStream errors let _ = conn.inner.recv_stream(self.stream).stop(0u32.into()); conn.wake(); } } } /// Errors that arise from reading from a stream. #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadError { /// The peer abandoned transmitting data on this stream /// /// Carries an application-defined error code. #[error("stream reset by peer: error {0}")] Reset(VarInt), /// The connection was lost #[error("connection lost")] ConnectionLost(#[from] ConnectionError), /// The stream has already been stopped, finished, or reset #[error("unknown stream")] UnknownStream, /// Attempted an ordered read following an unordered read /// /// Performing an unordered read allows discontinuities to arise in the receive buffer of a /// stream which cannot be recovered, making further ordered reads impossible. #[error("ordered read after unordered read")] IllegalOrderedRead, /// This was a 0-RTT stream and the server rejected it /// /// Can only occur on clients for 0-RTT streams, which can be opened using /// [`Connecting::into_0rtt()`]. /// /// [`Connecting::into_0rtt()`]: crate::Connecting::into_0rtt() #[error("0-RTT rejected")] ZeroRttRejected, } impl From<ReadableError> for ReadError { fn from(e: ReadableError) -> Self { match e { ReadableError::UnknownStream => Self::UnknownStream, ReadableError::IllegalOrderedRead => Self::IllegalOrderedRead, } } } impl From<ReadError> for io::Error { fn from(x: ReadError) -> Self { use self::ReadError::*; let kind = match x { Reset { .. } | ZeroRttRejected => io::ErrorKind::ConnectionReset, ConnectionLost(_) | UnknownStream => io::ErrorKind::NotConnected, IllegalOrderedRead => io::ErrorKind::InvalidInput, }; Self::new(kind, x) } } /// Future produced by [`RecvStream::read()`]. /// /// [`RecvStream::read()`]: crate::RecvStream::read #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct Read<'a> { stream: &'a mut RecvStream, buf: ReadBuf<'a>, } impl<'a> Future for Read<'a> { type Output = Result<Option<usize>, ReadError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let this = self.get_mut(); ready!(this.stream.poll_read(cx, &mut this.buf))?; match this.buf.filled().len() { 0 if this.buf.capacity() != 0 => Poll::Ready(Ok(None)), n => Poll::Ready(Ok(Some(n))), } } } /// Future produced by [`RecvStream::read_exact()`]. /// /// [`RecvStream::read_exact()`]: crate::RecvStream::read_exact #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadExact<'a> { stream: &'a mut RecvStream, buf: ReadBuf<'a>, } impl<'a> Future for ReadExact<'a> { type Output = Result<(), ReadExactError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let this = self.get_mut(); let mut remaining = this.buf.remaining(); while remaining > 0 { ready!(this.stream.poll_read(cx, &mut this.buf))?; let new = this.buf.remaining(); if new == remaining { return Poll::Ready(Err(ReadExactError::FinishedEarly)); } remaining = new; } Poll::Ready(Ok(())) } } /// Errors that arise from reading from a stream. #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadExactError { /// The stream finished before all bytes were read #[error("stream finished early")] FinishedEarly, /// A read error occurred #[error(transparent)] ReadError(#[from] ReadError), } /// Future produced by [`RecvStream::read_chunk()`]. /// /// [`RecvStream::read_chunk()`]: crate::RecvStream::read_chunk #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadChunk<'a> { stream: &'a mut RecvStream, max_length: usize, ordered: bool, } impl<'a> Future for ReadChunk<'a> { type Output = Result<Option<Chunk>, ReadError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let (max_length, ordered) = (self.max_length, self.ordered); self.stream.poll_read_chunk(cx, max_length, ordered) } } /// Future produced by [`RecvStream::read_chunks()`]. /// /// [`RecvStream::read_chunks()`]: crate::RecvStream::read_chunks #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadChunks<'a> { stream: &'a mut RecvStream, bufs: &'a mut [Bytes], } impl<'a> Future for ReadChunks<'a> { type Output = Result<Option<usize>, ReadError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let this = self.get_mut(); this.stream.poll_read_chunks(cx, this.bufs) } }
read
identifier_name
recv_stream.rs
use std::{ future::Future, io, pin::Pin, task::{Context, Poll}, }; use bytes::Bytes; use proto::{Chunk, Chunks, ConnectionError, ReadableError, StreamId}; use thiserror::Error; use tokio::io::ReadBuf; use crate::{ connection::{ConnectionRef, UnknownStream}, VarInt, }; /// A stream that can only be used to receive data /// /// `stop(0)` is implicitly called on drop unless: /// - A variant of [`ReadError`] has been yielded by a read call /// - [`stop()`] was called explicitly /// /// # Closing a stream /// /// When a stream is expected to be closed gracefully the sender should call /// [`SendStream::finish`]. However there is no guarantee the connected [`RecvStream`] will /// receive the "finished" notification in the same QUIC frame as the last frame which /// carried data. /// /// Even if the application layer logic already knows it read all the data because it does /// its own framing, it should still read until it reaches the end of the [`RecvStream`]. /// Otherwise it risks inadvertently calling [`RecvStream::stop`] if it drops the stream. /// And calling [`RecvStream::stop`] could result in the connected [`SendStream::finish`] /// call failing with a [`WriteError::Stopped`] error. /// /// For example if exactly 10 bytes are to be read, you still need to explicitly read the /// end of the stream: /// /// ```no_run /// # use quinn::{SendStream, RecvStream}; /// # async fn func( /// # mut send_stream: SendStream, /// # mut recv_stream: RecvStream, /// # ) -> anyhow::Result<()> /// # { /// // In the sending task /// send_stream.write(&b"0123456789"[..]).await?; /// send_stream.finish().await?; /// /// // In the receiving task /// let mut buf = [0u8; 10]; /// let data = recv_stream.read_exact(&mut buf).await?; /// if recv_stream.read_to_end(0).await.is_err() { /// // Discard unexpected data and notify the peer to stop sending it /// let _ = recv_stream.stop(0u8.into()); /// } /// # Ok(()) /// # } /// ``` /// /// An alternative approach, used in HTTP/3, is to specify a particular error code used with `stop` /// that indicates graceful receiver-initiated stream shutdown, rather than a true error condition. /// /// [`RecvStream::read_chunk`] could be used instead which does not take ownership and /// allows using an explicit call to [`RecvStream::stop`] with a custom error code. /// /// [`ReadError`]: crate::ReadError /// [`stop()`]: RecvStream::stop /// [`SendStream::finish`]: crate::SendStream::finish /// [`WriteError::Stopped`]: crate::WriteError::Stopped #[derive(Debug)] pub struct RecvStream { conn: ConnectionRef, stream: StreamId, is_0rtt: bool, all_data_read: bool, reset: Option<VarInt>, } impl RecvStream { pub(crate) fn new(conn: ConnectionRef, stream: StreamId, is_0rtt: bool) -> Self { Self { conn, stream, is_0rtt, all_data_read: false, reset: None, } } /// Read data contiguously from the stream. /// /// Yields the number of bytes read into `buf` on success, or `None` if the stream was finished. pub async fn read(&mut self, buf: &mut [u8]) -> Result<Option<usize>, ReadError> { Read { stream: self, buf: ReadBuf::new(buf), } .await } /// Read an exact number of bytes contiguously from the stream. /// /// See [`read()`] for details. /// /// [`read()`]: RecvStream::read pub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), ReadExactError> { ReadExact { stream: self, buf: ReadBuf::new(buf), } .await } fn poll_read( &mut self, cx: &mut Context, buf: &mut ReadBuf<'_>, ) -> Poll<Result<(), ReadError>> { if buf.remaining() == 0 { return Poll::Ready(Ok(())); } self.poll_read_generic(cx, true, |chunks| { let mut read = false; loop { if buf.remaining() == 0 { // We know `read` is `true` because `buf.remaining()` was not 0 before return ReadStatus::Readable(()); } match chunks.next(buf.remaining()) { Ok(Some(chunk)) => { buf.put_slice(&chunk.bytes); read = true; } res => return (if read { Some(()) } else { None }, res.err()).into(), } } }) .map(|res| res.map(|_| ())) } /// Read the next segment of data /// /// Yields `None` if the stream was finished. Otherwise, yields a segment of data and its /// offset in the stream. If `ordered` is `true`, the chunk's offset will be immediately after /// the last data yielded by `read()` or `read_chunk()`. If `ordered` is `false`, segments may /// be received in any order, and the `Chunk`'s `offset` field can be used to determine /// ordering in the caller. Unordered reads are less prone to head-of-line blocking within a /// stream, but require the application to manage reassembling the original data. /// /// Slightly more efficient than `read` due to not copying. Chunk boundaries do not correspond /// to peer writes, and hence cannot be used as framing. pub async fn read_chunk( &mut self, max_length: usize, ordered: bool, ) -> Result<Option<Chunk>, ReadError> { ReadChunk { stream: self, max_length, ordered, } .await } /// Foundation of [`Self::read_chunk`] fn poll_read_chunk( &mut self, cx: &mut Context, max_length: usize, ordered: bool, ) -> Poll<Result<Option<Chunk>, ReadError>> { self.poll_read_generic(cx, ordered, |chunks| match chunks.next(max_length) { Ok(Some(chunk)) => ReadStatus::Readable(chunk), res => (None, res.err()).into(), }) } /// Read the next segments of data /// /// Fills `bufs` with the segments of data beginning immediately after the /// last data yielded by `read` or `read_chunk`, or `None` if the stream was /// finished. /// /// Slightly more efficient than `read` due to not copying. Chunk boundaries /// do not correspond to peer writes, and hence cannot be used as framing. pub async fn read_chunks(&mut self, bufs: &mut [Bytes]) -> Result<Option<usize>, ReadError> { ReadChunks { stream: self, bufs }.await } /// Foundation of [`Self::read_chunks`] fn poll_read_chunks( &mut self, cx: &mut Context, bufs: &mut [Bytes], ) -> Poll<Result<Option<usize>, ReadError>> { if bufs.is_empty() { return Poll::Ready(Ok(Some(0))); } self.poll_read_generic(cx, true, |chunks| { let mut read = 0; loop { if read >= bufs.len() { // We know `read > 0` because `bufs` cannot be empty here return ReadStatus::Readable(read); } match chunks.next(usize::MAX) { Ok(Some(chunk)) => { bufs[read] = chunk.bytes; read += 1; } res => return (if read == 0 { None } else { Some(read) }, res.err()).into(), } } }) } /// Convenience method to read all remaining data into a buffer /// /// Fails with [`ReadToEndError::TooLong`] on reading more than `size_limit` bytes, discarding /// all data read. Uses unordered reads to be more efficient than using `AsyncRead` would /// allow. `size_limit` should be set to limit worst-case memory use. /// /// If unordered reads have already been made, the resulting buffer may have gaps containing /// arbitrary data. /// /// [`ReadToEndError::TooLong`]: crate::ReadToEndError::TooLong pub async fn read_to_end(&mut self, size_limit: usize) -> Result<Vec<u8>, ReadToEndError> { ReadToEnd { stream: self, size_limit, read: Vec::new(), start: u64::max_value(), end: 0, } .await } /// Stop accepting data /// /// Discards unread data and notifies the peer to stop transmitting. Once stopped, further /// attempts to operate on a stream will yield `UnknownStream` errors. pub fn stop(&mut self, error_code: VarInt) -> Result<(), UnknownStream> { let mut conn = self.conn.state.lock("RecvStream::stop"); if self.is_0rtt && conn.check_0rtt().is_err() { return Ok(()); } conn.inner.recv_stream(self.stream).stop(error_code)?; conn.wake(); self.all_data_read = true; Ok(()) } /// Check if this stream has been opened during 0-RTT. /// /// In which case any non-idempotent request should be considered dangerous at the application /// level. Because read data is subject to replay attacks. pub fn is_0rtt(&self) -> bool { self.is_0rtt } /// Get the identity of this stream pub fn id(&self) -> StreamId { self.stream } /// Handle common logic related to reading out of a receive stream /// /// This takes an `FnMut` closure that takes care of the actual reading process, matching /// the detailed read semantics for the calling function with a particular return type. /// The closure can read from the passed `&mut Chunks` and has to return the status after /// reading: the amount of data read, and the status after the final read call. fn poll_read_generic<T, U>( &mut self, cx: &mut Context, ordered: bool, mut read_fn: T, ) -> Poll<Result<Option<U>, ReadError>> where T: FnMut(&mut Chunks) -> ReadStatus<U>, { use proto::ReadError::*; if self.all_data_read { return Poll::Ready(Ok(None)); } let mut conn = self.conn.state.lock("RecvStream::poll_read"); if self.is_0rtt { conn.check_0rtt().map_err(|()| ReadError::ZeroRttRejected)?; } // If we stored an error during a previous call, return it now. This can happen if a // `read_fn` both wants to return data and also returns an error in its final stream status. let status = match self.reset.take() { Some(code) => ReadStatus::Failed(None, Reset(code)), None => { let mut recv = conn.inner.recv_stream(self.stream); let mut chunks = recv.read(ordered)?; let status = read_fn(&mut chunks); if chunks.finalize().should_transmit() { conn.wake(); } status } }; match status { ReadStatus::Readable(read) => Poll::Ready(Ok(Some(read))), ReadStatus::Finished(read) => { self.all_data_read = true; Poll::Ready(Ok(read)) } ReadStatus::Failed(read, Blocked) => match read { Some(val) => Poll::Ready(Ok(Some(val))), None => { if let Some(ref x) = conn.error { return Poll::Ready(Err(ReadError::ConnectionLost(x.clone()))); } conn.blocked_readers.insert(self.stream, cx.waker().clone()); Poll::Pending } }, ReadStatus::Failed(read, Reset(error_code)) => match read { None => { self.all_data_read = true; Poll::Ready(Err(ReadError::Reset(error_code))) } done => { self.reset = Some(error_code); Poll::Ready(Ok(done)) } }, } } } enum ReadStatus<T> { Readable(T), Finished(Option<T>), Failed(Option<T>, proto::ReadError), } impl<T> From<(Option<T>, Option<proto::ReadError>)> for ReadStatus<T> { fn from(status: (Option<T>, Option<proto::ReadError>)) -> Self { match status { (read, None) => Self::Finished(read), (read, Some(e)) => Self::Failed(read, e), } } } /// Future produced by [`RecvStream::read_to_end()`]. /// /// [`RecvStream::read_to_end()`]: crate::RecvStream::read_to_end #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadToEnd<'a> { stream: &'a mut RecvStream, read: Vec<(Bytes, u64)>, start: u64, end: u64, size_limit: usize, } impl Future for ReadToEnd<'_> { type Output = Result<Vec<u8>, ReadToEndError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { loop { match ready!(self.stream.poll_read_chunk(cx, usize::MAX, false))? { Some(chunk) => { self.start = self.start.min(chunk.offset); let end = chunk.bytes.len() as u64 + chunk.offset; if (end - self.start) > self.size_limit as u64 { return Poll::Ready(Err(ReadToEndError::TooLong)); } self.end = self.end.max(end); self.read.push((chunk.bytes, chunk.offset)); } None => { if self.end == 0 { // Never received anything return Poll::Ready(Ok(Vec::new())); } let start = self.start; let mut buffer = vec![0; (self.end - start) as usize]; for (data, offset) in self.read.drain(..) { let offset = (offset - start) as usize; buffer[offset..offset + data.len()].copy_from_slice(&data); } return Poll::Ready(Ok(buffer)); } } } } } /// Errors from [`RecvStream::read_to_end`] #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadToEndError { /// An error occurred during reading #[error("read error: {0}")] Read(#[from] ReadError), /// The stream is larger than the user-supplied limit #[error("stream too long")] TooLong, } #[cfg(feature = "futures-io")] impl futures_io::AsyncRead for RecvStream { fn poll_read( self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8], ) -> Poll<io::Result<usize>> { let mut buf = ReadBuf::new(buf); ready!(RecvStream::poll_read(self.get_mut(), cx, &mut buf))?; Poll::Ready(Ok(buf.filled().len())) } } impl tokio::io::AsyncRead for RecvStream { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { ready!(Self::poll_read(self.get_mut(), cx, buf))?; Poll::Ready(Ok(())) } } impl Drop for RecvStream { fn drop(&mut self) { let mut conn = self.conn.state.lock("RecvStream::drop"); // clean up any previously registered wakers conn.blocked_readers.remove(&self.stream); if conn.error.is_some() || (self.is_0rtt && conn.check_0rtt().is_err()) { return; } if !self.all_data_read { // Ignore UnknownStream errors let _ = conn.inner.recv_stream(self.stream).stop(0u32.into()); conn.wake(); } } } /// Errors that arise from reading from a stream. #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadError { /// The peer abandoned transmitting data on this stream /// /// Carries an application-defined error code. #[error("stream reset by peer: error {0}")] Reset(VarInt), /// The connection was lost
UnknownStream, /// Attempted an ordered read following an unordered read /// /// Performing an unordered read allows discontinuities to arise in the receive buffer of a /// stream which cannot be recovered, making further ordered reads impossible. #[error("ordered read after unordered read")] IllegalOrderedRead, /// This was a 0-RTT stream and the server rejected it /// /// Can only occur on clients for 0-RTT streams, which can be opened using /// [`Connecting::into_0rtt()`]. /// /// [`Connecting::into_0rtt()`]: crate::Connecting::into_0rtt() #[error("0-RTT rejected")] ZeroRttRejected, } impl From<ReadableError> for ReadError { fn from(e: ReadableError) -> Self { match e { ReadableError::UnknownStream => Self::UnknownStream, ReadableError::IllegalOrderedRead => Self::IllegalOrderedRead, } } } impl From<ReadError> for io::Error { fn from(x: ReadError) -> Self { use self::ReadError::*; let kind = match x { Reset { .. } | ZeroRttRejected => io::ErrorKind::ConnectionReset, ConnectionLost(_) | UnknownStream => io::ErrorKind::NotConnected, IllegalOrderedRead => io::ErrorKind::InvalidInput, }; Self::new(kind, x) } } /// Future produced by [`RecvStream::read()`]. /// /// [`RecvStream::read()`]: crate::RecvStream::read #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct Read<'a> { stream: &'a mut RecvStream, buf: ReadBuf<'a>, } impl<'a> Future for Read<'a> { type Output = Result<Option<usize>, ReadError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let this = self.get_mut(); ready!(this.stream.poll_read(cx, &mut this.buf))?; match this.buf.filled().len() { 0 if this.buf.capacity() != 0 => Poll::Ready(Ok(None)), n => Poll::Ready(Ok(Some(n))), } } } /// Future produced by [`RecvStream::read_exact()`]. /// /// [`RecvStream::read_exact()`]: crate::RecvStream::read_exact #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadExact<'a> { stream: &'a mut RecvStream, buf: ReadBuf<'a>, } impl<'a> Future for ReadExact<'a> { type Output = Result<(), ReadExactError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let this = self.get_mut(); let mut remaining = this.buf.remaining(); while remaining > 0 { ready!(this.stream.poll_read(cx, &mut this.buf))?; let new = this.buf.remaining(); if new == remaining { return Poll::Ready(Err(ReadExactError::FinishedEarly)); } remaining = new; } Poll::Ready(Ok(())) } } /// Errors that arise from reading from a stream. #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadExactError { /// The stream finished before all bytes were read #[error("stream finished early")] FinishedEarly, /// A read error occurred #[error(transparent)] ReadError(#[from] ReadError), } /// Future produced by [`RecvStream::read_chunk()`]. /// /// [`RecvStream::read_chunk()`]: crate::RecvStream::read_chunk #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadChunk<'a> { stream: &'a mut RecvStream, max_length: usize, ordered: bool, } impl<'a> Future for ReadChunk<'a> { type Output = Result<Option<Chunk>, ReadError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let (max_length, ordered) = (self.max_length, self.ordered); self.stream.poll_read_chunk(cx, max_length, ordered) } } /// Future produced by [`RecvStream::read_chunks()`]. /// /// [`RecvStream::read_chunks()`]: crate::RecvStream::read_chunks #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadChunks<'a> { stream: &'a mut RecvStream, bufs: &'a mut [Bytes], } impl<'a> Future for ReadChunks<'a> { type Output = Result<Option<usize>, ReadError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let this = self.get_mut(); this.stream.poll_read_chunks(cx, this.bufs) } }
#[error("connection lost")] ConnectionLost(#[from] ConnectionError), /// The stream has already been stopped, finished, or reset #[error("unknown stream")]
random_line_split
recv_stream.rs
use std::{ future::Future, io, pin::Pin, task::{Context, Poll}, }; use bytes::Bytes; use proto::{Chunk, Chunks, ConnectionError, ReadableError, StreamId}; use thiserror::Error; use tokio::io::ReadBuf; use crate::{ connection::{ConnectionRef, UnknownStream}, VarInt, }; /// A stream that can only be used to receive data /// /// `stop(0)` is implicitly called on drop unless: /// - A variant of [`ReadError`] has been yielded by a read call /// - [`stop()`] was called explicitly /// /// # Closing a stream /// /// When a stream is expected to be closed gracefully the sender should call /// [`SendStream::finish`]. However there is no guarantee the connected [`RecvStream`] will /// receive the "finished" notification in the same QUIC frame as the last frame which /// carried data. /// /// Even if the application layer logic already knows it read all the data because it does /// its own framing, it should still read until it reaches the end of the [`RecvStream`]. /// Otherwise it risks inadvertently calling [`RecvStream::stop`] if it drops the stream. /// And calling [`RecvStream::stop`] could result in the connected [`SendStream::finish`] /// call failing with a [`WriteError::Stopped`] error. /// /// For example if exactly 10 bytes are to be read, you still need to explicitly read the /// end of the stream: /// /// ```no_run /// # use quinn::{SendStream, RecvStream}; /// # async fn func( /// # mut send_stream: SendStream, /// # mut recv_stream: RecvStream, /// # ) -> anyhow::Result<()> /// # { /// // In the sending task /// send_stream.write(&b"0123456789"[..]).await?; /// send_stream.finish().await?; /// /// // In the receiving task /// let mut buf = [0u8; 10]; /// let data = recv_stream.read_exact(&mut buf).await?; /// if recv_stream.read_to_end(0).await.is_err() { /// // Discard unexpected data and notify the peer to stop sending it /// let _ = recv_stream.stop(0u8.into()); /// } /// # Ok(()) /// # } /// ``` /// /// An alternative approach, used in HTTP/3, is to specify a particular error code used with `stop` /// that indicates graceful receiver-initiated stream shutdown, rather than a true error condition. /// /// [`RecvStream::read_chunk`] could be used instead which does not take ownership and /// allows using an explicit call to [`RecvStream::stop`] with a custom error code. /// /// [`ReadError`]: crate::ReadError /// [`stop()`]: RecvStream::stop /// [`SendStream::finish`]: crate::SendStream::finish /// [`WriteError::Stopped`]: crate::WriteError::Stopped #[derive(Debug)] pub struct RecvStream { conn: ConnectionRef, stream: StreamId, is_0rtt: bool, all_data_read: bool, reset: Option<VarInt>, } impl RecvStream { pub(crate) fn new(conn: ConnectionRef, stream: StreamId, is_0rtt: bool) -> Self { Self { conn, stream, is_0rtt, all_data_read: false, reset: None, } } /// Read data contiguously from the stream. /// /// Yields the number of bytes read into `buf` on success, or `None` if the stream was finished. pub async fn read(&mut self, buf: &mut [u8]) -> Result<Option<usize>, ReadError> { Read { stream: self, buf: ReadBuf::new(buf), } .await } /// Read an exact number of bytes contiguously from the stream. /// /// See [`read()`] for details. /// /// [`read()`]: RecvStream::read pub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), ReadExactError> { ReadExact { stream: self, buf: ReadBuf::new(buf), } .await } fn poll_read( &mut self, cx: &mut Context, buf: &mut ReadBuf<'_>, ) -> Poll<Result<(), ReadError>> { if buf.remaining() == 0 { return Poll::Ready(Ok(())); } self.poll_read_generic(cx, true, |chunks| { let mut read = false; loop { if buf.remaining() == 0 { // We know `read` is `true` because `buf.remaining()` was not 0 before return ReadStatus::Readable(()); } match chunks.next(buf.remaining()) { Ok(Some(chunk)) => { buf.put_slice(&chunk.bytes); read = true; } res => return (if read { Some(()) } else { None }, res.err()).into(), } } }) .map(|res| res.map(|_| ())) } /// Read the next segment of data /// /// Yields `None` if the stream was finished. Otherwise, yields a segment of data and its /// offset in the stream. If `ordered` is `true`, the chunk's offset will be immediately after /// the last data yielded by `read()` or `read_chunk()`. If `ordered` is `false`, segments may /// be received in any order, and the `Chunk`'s `offset` field can be used to determine /// ordering in the caller. Unordered reads are less prone to head-of-line blocking within a /// stream, but require the application to manage reassembling the original data. /// /// Slightly more efficient than `read` due to not copying. Chunk boundaries do not correspond /// to peer writes, and hence cannot be used as framing. pub async fn read_chunk( &mut self, max_length: usize, ordered: bool, ) -> Result<Option<Chunk>, ReadError> { ReadChunk { stream: self, max_length, ordered, } .await } /// Foundation of [`Self::read_chunk`] fn poll_read_chunk( &mut self, cx: &mut Context, max_length: usize, ordered: bool, ) -> Poll<Result<Option<Chunk>, ReadError>> { self.poll_read_generic(cx, ordered, |chunks| match chunks.next(max_length) { Ok(Some(chunk)) => ReadStatus::Readable(chunk), res => (None, res.err()).into(), }) } /// Read the next segments of data /// /// Fills `bufs` with the segments of data beginning immediately after the /// last data yielded by `read` or `read_chunk`, or `None` if the stream was /// finished. /// /// Slightly more efficient than `read` due to not copying. Chunk boundaries /// do not correspond to peer writes, and hence cannot be used as framing. pub async fn read_chunks(&mut self, bufs: &mut [Bytes]) -> Result<Option<usize>, ReadError> { ReadChunks { stream: self, bufs }.await } /// Foundation of [`Self::read_chunks`] fn poll_read_chunks( &mut self, cx: &mut Context, bufs: &mut [Bytes], ) -> Poll<Result<Option<usize>, ReadError>> { if bufs.is_empty() { return Poll::Ready(Ok(Some(0))); } self.poll_read_generic(cx, true, |chunks| { let mut read = 0; loop { if read >= bufs.len() { // We know `read > 0` because `bufs` cannot be empty here return ReadStatus::Readable(read); } match chunks.next(usize::MAX) { Ok(Some(chunk)) => { bufs[read] = chunk.bytes; read += 1; } res => return (if read == 0 { None } else { Some(read) }, res.err()).into(), } } }) } /// Convenience method to read all remaining data into a buffer /// /// Fails with [`ReadToEndError::TooLong`] on reading more than `size_limit` bytes, discarding /// all data read. Uses unordered reads to be more efficient than using `AsyncRead` would /// allow. `size_limit` should be set to limit worst-case memory use. /// /// If unordered reads have already been made, the resulting buffer may have gaps containing /// arbitrary data. /// /// [`ReadToEndError::TooLong`]: crate::ReadToEndError::TooLong pub async fn read_to_end(&mut self, size_limit: usize) -> Result<Vec<u8>, ReadToEndError> { ReadToEnd { stream: self, size_limit, read: Vec::new(), start: u64::max_value(), end: 0, } .await } /// Stop accepting data /// /// Discards unread data and notifies the peer to stop transmitting. Once stopped, further /// attempts to operate on a stream will yield `UnknownStream` errors. pub fn stop(&mut self, error_code: VarInt) -> Result<(), UnknownStream> { let mut conn = self.conn.state.lock("RecvStream::stop"); if self.is_0rtt && conn.check_0rtt().is_err() { return Ok(()); } conn.inner.recv_stream(self.stream).stop(error_code)?; conn.wake(); self.all_data_read = true; Ok(()) } /// Check if this stream has been opened during 0-RTT. /// /// In which case any non-idempotent request should be considered dangerous at the application /// level. Because read data is subject to replay attacks. pub fn is_0rtt(&self) -> bool { self.is_0rtt } /// Get the identity of this stream pub fn id(&self) -> StreamId { self.stream } /// Handle common logic related to reading out of a receive stream /// /// This takes an `FnMut` closure that takes care of the actual reading process, matching /// the detailed read semantics for the calling function with a particular return type. /// The closure can read from the passed `&mut Chunks` and has to return the status after /// reading: the amount of data read, and the status after the final read call. fn poll_read_generic<T, U>( &mut self, cx: &mut Context, ordered: bool, mut read_fn: T, ) -> Poll<Result<Option<U>, ReadError>> where T: FnMut(&mut Chunks) -> ReadStatus<U>, { use proto::ReadError::*; if self.all_data_read { return Poll::Ready(Ok(None)); } let mut conn = self.conn.state.lock("RecvStream::poll_read"); if self.is_0rtt { conn.check_0rtt().map_err(|()| ReadError::ZeroRttRejected)?; } // If we stored an error during a previous call, return it now. This can happen if a // `read_fn` both wants to return data and also returns an error in its final stream status. let status = match self.reset.take() { Some(code) => ReadStatus::Failed(None, Reset(code)), None => { let mut recv = conn.inner.recv_stream(self.stream); let mut chunks = recv.read(ordered)?; let status = read_fn(&mut chunks); if chunks.finalize().should_transmit() { conn.wake(); } status } }; match status { ReadStatus::Readable(read) => Poll::Ready(Ok(Some(read))), ReadStatus::Finished(read) => { self.all_data_read = true; Poll::Ready(Ok(read)) } ReadStatus::Failed(read, Blocked) => match read { Some(val) => Poll::Ready(Ok(Some(val))), None => { if let Some(ref x) = conn.error { return Poll::Ready(Err(ReadError::ConnectionLost(x.clone()))); } conn.blocked_readers.insert(self.stream, cx.waker().clone()); Poll::Pending } }, ReadStatus::Failed(read, Reset(error_code)) => match read { None => { self.all_data_read = true; Poll::Ready(Err(ReadError::Reset(error_code))) } done => { self.reset = Some(error_code); Poll::Ready(Ok(done)) } }, } } } enum ReadStatus<T> { Readable(T), Finished(Option<T>), Failed(Option<T>, proto::ReadError), } impl<T> From<(Option<T>, Option<proto::ReadError>)> for ReadStatus<T> { fn from(status: (Option<T>, Option<proto::ReadError>)) -> Self { match status { (read, None) => Self::Finished(read), (read, Some(e)) => Self::Failed(read, e), } } } /// Future produced by [`RecvStream::read_to_end()`]. /// /// [`RecvStream::read_to_end()`]: crate::RecvStream::read_to_end #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadToEnd<'a> { stream: &'a mut RecvStream, read: Vec<(Bytes, u64)>, start: u64, end: u64, size_limit: usize, } impl Future for ReadToEnd<'_> { type Output = Result<Vec<u8>, ReadToEndError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { loop { match ready!(self.stream.poll_read_chunk(cx, usize::MAX, false))? { Some(chunk) => { self.start = self.start.min(chunk.offset); let end = chunk.bytes.len() as u64 + chunk.offset; if (end - self.start) > self.size_limit as u64 { return Poll::Ready(Err(ReadToEndError::TooLong)); } self.end = self.end.max(end); self.read.push((chunk.bytes, chunk.offset)); } None => { if self.end == 0 { // Never received anything return Poll::Ready(Ok(Vec::new())); } let start = self.start; let mut buffer = vec![0; (self.end - start) as usize]; for (data, offset) in self.read.drain(..) { let offset = (offset - start) as usize; buffer[offset..offset + data.len()].copy_from_slice(&data); } return Poll::Ready(Ok(buffer)); } } } } } /// Errors from [`RecvStream::read_to_end`] #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadToEndError { /// An error occurred during reading #[error("read error: {0}")] Read(#[from] ReadError), /// The stream is larger than the user-supplied limit #[error("stream too long")] TooLong, } #[cfg(feature = "futures-io")] impl futures_io::AsyncRead for RecvStream { fn poll_read( self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8], ) -> Poll<io::Result<usize>> { let mut buf = ReadBuf::new(buf); ready!(RecvStream::poll_read(self.get_mut(), cx, &mut buf))?; Poll::Ready(Ok(buf.filled().len())) } } impl tokio::io::AsyncRead for RecvStream { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { ready!(Self::poll_read(self.get_mut(), cx, buf))?; Poll::Ready(Ok(())) } } impl Drop for RecvStream { fn drop(&mut self) { let mut conn = self.conn.state.lock("RecvStream::drop"); // clean up any previously registered wakers conn.blocked_readers.remove(&self.stream); if conn.error.is_some() || (self.is_0rtt && conn.check_0rtt().is_err()) { return; } if !self.all_data_read { // Ignore UnknownStream errors let _ = conn.inner.recv_stream(self.stream).stop(0u32.into()); conn.wake(); } } } /// Errors that arise from reading from a stream. #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadError { /// The peer abandoned transmitting data on this stream /// /// Carries an application-defined error code. #[error("stream reset by peer: error {0}")] Reset(VarInt), /// The connection was lost #[error("connection lost")] ConnectionLost(#[from] ConnectionError), /// The stream has already been stopped, finished, or reset #[error("unknown stream")] UnknownStream, /// Attempted an ordered read following an unordered read /// /// Performing an unordered read allows discontinuities to arise in the receive buffer of a /// stream which cannot be recovered, making further ordered reads impossible. #[error("ordered read after unordered read")] IllegalOrderedRead, /// This was a 0-RTT stream and the server rejected it /// /// Can only occur on clients for 0-RTT streams, which can be opened using /// [`Connecting::into_0rtt()`]. /// /// [`Connecting::into_0rtt()`]: crate::Connecting::into_0rtt() #[error("0-RTT rejected")] ZeroRttRejected, } impl From<ReadableError> for ReadError { fn from(e: ReadableError) -> Self { match e { ReadableError::UnknownStream => Self::UnknownStream, ReadableError::IllegalOrderedRead => Self::IllegalOrderedRead, } } } impl From<ReadError> for io::Error { fn from(x: ReadError) -> Self { use self::ReadError::*; let kind = match x { Reset { .. } | ZeroRttRejected => io::ErrorKind::ConnectionReset, ConnectionLost(_) | UnknownStream => io::ErrorKind::NotConnected, IllegalOrderedRead => io::ErrorKind::InvalidInput, }; Self::new(kind, x) } } /// Future produced by [`RecvStream::read()`]. /// /// [`RecvStream::read()`]: crate::RecvStream::read #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct Read<'a> { stream: &'a mut RecvStream, buf: ReadBuf<'a>, } impl<'a> Future for Read<'a> { type Output = Result<Option<usize>, ReadError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output>
} /// Future produced by [`RecvStream::read_exact()`]. /// /// [`RecvStream::read_exact()`]: crate::RecvStream::read_exact #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadExact<'a> { stream: &'a mut RecvStream, buf: ReadBuf<'a>, } impl<'a> Future for ReadExact<'a> { type Output = Result<(), ReadExactError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let this = self.get_mut(); let mut remaining = this.buf.remaining(); while remaining > 0 { ready!(this.stream.poll_read(cx, &mut this.buf))?; let new = this.buf.remaining(); if new == remaining { return Poll::Ready(Err(ReadExactError::FinishedEarly)); } remaining = new; } Poll::Ready(Ok(())) } } /// Errors that arise from reading from a stream. #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum ReadExactError { /// The stream finished before all bytes were read #[error("stream finished early")] FinishedEarly, /// A read error occurred #[error(transparent)] ReadError(#[from] ReadError), } /// Future produced by [`RecvStream::read_chunk()`]. /// /// [`RecvStream::read_chunk()`]: crate::RecvStream::read_chunk #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadChunk<'a> { stream: &'a mut RecvStream, max_length: usize, ordered: bool, } impl<'a> Future for ReadChunk<'a> { type Output = Result<Option<Chunk>, ReadError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let (max_length, ordered) = (self.max_length, self.ordered); self.stream.poll_read_chunk(cx, max_length, ordered) } } /// Future produced by [`RecvStream::read_chunks()`]. /// /// [`RecvStream::read_chunks()`]: crate::RecvStream::read_chunks #[must_use = "futures/streams/sinks do nothing unless you `.await` or poll them"] struct ReadChunks<'a> { stream: &'a mut RecvStream, bufs: &'a mut [Bytes], } impl<'a> Future for ReadChunks<'a> { type Output = Result<Option<usize>, ReadError>; fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { let this = self.get_mut(); this.stream.poll_read_chunks(cx, this.bufs) } }
{ let this = self.get_mut(); ready!(this.stream.poll_read(cx, &mut this.buf))?; match this.buf.filled().len() { 0 if this.buf.capacity() != 0 => Poll::Ready(Ok(None)), n => Poll::Ready(Ok(Some(n))), } }
identifier_body
conf.rs
use crate::ecies; use crate::hash256::Hash256; use crate::keys::{public_to_slice, sign, slice_to_public}; use crate::messages::{Message, NodeKey, Version, PROTOCOL_VERSION, NODE_NONE}; use crate::util::secs_since; use secp256k1::{ecdh, Secp256k1, PublicKey, SecretKey}; use std::str::FromStr; use std::time::UNIX_EPOCH; use structopt::StructOpt; use tiny_keccak::Keccak; #[derive(StructOpt,Debug)] /// Sender information. pub struct Wallet { #[structopt(long)] /// Public address of sender to be used as input. /// pub in_address: String, #[structopt(long)] /// input UTXO amount /// pub in_amount: f64, #[structopt(long, parse(try_from_str="Hash256::decode"))] /// OutPoint transaction id. /// pub outpoint_hash: Hash256, #[structopt(long)] /// OutPoint vout index. /// pub outpoint_index: u32, #[structopt(long)] /// Private key to sign sender input. /// /// Supported format: WIF (Wallet Import Format) - base56check encoded string. /// /// > bitcoin-cli -regtest dumpprivkey "address" /// pub secret: String, #[structopt(long)] /// Public addrss to be used as output for change. /// /// > bitcoin-cli -regtest getnewaddress /// pub out_address: String, #[structopt(long)] /// Change from input transaction. /// Amout that should be returned to new sender address and don't burned or spent for writing data. /// pub change: f64, } #[derive(StructOpt, Debug)] /// Eth node info pub struct EthWallet { #[structopt(long)] /// Node public key /// pub pub_key: HexData, #[structopt(long, required_unless="crypto")] /// Secret key. Having this key drastically improve the performance. /// pub secret: Option<String>, #[structopt(long, required_unless="secret")] /// Crypto part of privkey file. /// Generating private key on ETH will take a lot of time (for undiscovered yet reason), /// so if you have it from another sources just provide the secret key /// pub crypto: Option<String>, #[structopt(long)] /// Secret key password /// pub password: String, #[structopt(long)] /// Public addrss to be used as output. /// pub out_address: String, /// Transfered value /// #[structopt(long)] pub value: u128, /// Gas paid up front for transaction execution /// #[structopt(long, default_value="21000")] pub gas: u128, /// Gas price /// #[structopt(long, default_value="1000000000")] pub gas_price: u128, } /// Initial encryption configuration #[derive(Clone)] pub struct EncOpt { pub node_public: PublicKey, pub node_secret: SecretKey, pub msg_secret: SecretKey, pub enc_version: Vec<u8>, pub nonce: Hash256, } pub trait Sender { fn change(&self) -> f64 {0.0} fn secret(&self) -> Option<String> {None} fn crypto(&self) -> Option<String> {None} fn pub_key(&self) -> Vec<u8> {vec![]} fn password(&self) -> String {String::new()} fn in_amount(&self) -> f64 {0.0} fn in_address(&self) -> String {String::new()} fn out_address(&self) -> String; fn outpoint_hash(&self) -> Hash256 {Hash256::default()} fn outpoint_index(&self) -> u32 {0} fn gas(&self) -> u128 {0} fn gas_price(&self) -> u128 {0} fn value(&self) -> u128 {0} fn encryption_conf(&self) -> Option<EncOpt> { None } fn version(&self, cfg: &Option<EncOpt>) -> Message; } impl Sender for Wallet { fn in_address(&self) -> String {return self.in_address.clone();} fn out_address(&self) -> String {return self.out_address.clone();} fn outpoint_hash(&self) -> Hash256 {return self.outpoint_hash;} fn outpoint_index(&self) -> u32 {return self.outpoint_index;} fn change(&self) -> f64 {return self.change;} fn in_amount(&self) -> f64 {return self.in_amount;} fn secret(&self) -> Option<String> {return Some(self.secret.clone());} fn version(&self, _cfg: &Option<EncOpt>) -> Message { let version = Version { version: PROTOCOL_VERSION, services: NODE_NONE, timestamp: secs_since(UNIX_EPOCH) as i64, user_agent: "umbrella".to_string(), ..Default::default() }; Message::Version(version) } } impl Sender for EthWallet { fn pub_key(&self) -> Vec<u8> {self.pub_key.0.clone()} fn secret(&self) -> Option<String> {self.secret.clone()} fn crypto(&self) -> Option<String> {self.crypto.clone()} fn password(&self) -> String {self.password.clone()} fn out_address(&self) -> String {self.out_address.clone()} fn gas(&self) -> u128 {self.gas} fn
(&self) -> u128 {self.value} fn gas_price(&self) -> u128 {self.gas_price} fn encryption_conf(&self) -> Option<EncOpt> { let mut rng = rand::thread_rng(); let pub_key:PublicKey = slice_to_public(&self.pub_key.0).unwrap(); let nonce: Hash256 = Hash256::random(); let secp = Secp256k1::new(); let (node_secret, node_public) = secp.generate_keypair(&mut rng); let (msg, msg_secret) = encrypt_node_version(pub_key, node_public, node_secret, nonce); Some(EncOpt { node_public: node_public, node_secret: node_secret, msg_secret: msg_secret, enc_version: msg, nonce: nonce, }) } fn version(&self, cfg: &Option<EncOpt>) -> Message { let version = NodeKey { version: cfg.as_ref().unwrap().enc_version.clone(), }; Message::NodeKey(version) } } /// Probably a part of version message with encryption support /// fn encrypt_node_version(pub_key:PublicKey , node_public:PublicKey , node_secret:SecretKey , nonce: Hash256) -> (Vec<u8>, SecretKey) { let mut rng = rand::thread_rng(); let secp = Secp256k1::new(); let mut version = [0u8;194]; //sig + public + 2*h256 + 1 version[193] = 0x0; let (sig, rest) = version.split_at_mut(65); let (version_pub, rest) = rest.split_at_mut(32); let (node_pub, rest) = rest.split_at_mut(64); let (data_nonce, _) = rest.split_at_mut(32); let (sec1, pub1) = secp.generate_keypair(&mut rng); let pub1 = public_to_slice(&pub1); let sec1 = SecretKey::from_slice(&sec1[..32]).unwrap(); let shr = &ecdh::shared_secret_point(&pub_key, &node_secret)[..32]; let xor = Hash256::from_slice(&shr) ^ nonce; //signature sig.copy_from_slice(&sign(&sec1, &xor)); Keccak::keccak256(&pub1, version_pub); node_pub.copy_from_slice(&public_to_slice(&node_public)); data_nonce.copy_from_slice(nonce.as_bytes()); (ecies::encrypt(&pub_key, &[], &version).unwrap(), sec1) } #[derive(Debug)] pub struct HexData(pub Vec<u8>); impl FromStr for HexData { type Err = hex::FromHexError; fn from_str(s: &str) -> Result<Self, Self::Err> { hex::decode(s).map(HexData) } } #[derive(StructOpt, Debug)] pub struct Data { #[structopt(long)] /// Public address to pay for data storage. /// /// > bitcoin-cli -regtest getnewaddress /// pub dust_address: String, #[structopt(long, default_value="0.0001")] /// Amount to pay for data storage. /// pub dust_amount: f64, #[structopt(long)] /// Data to be incuded in output. /// pub data: HexData, } #[derive(StructOpt, Debug)] /// Network configuration. /// pub enum Network { #[structopt(name="bch", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash main network BCH{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bch-test", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash test network BCHTest{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bch-reg", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash Regtest network BCHReg{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="eth", raw(setting="structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Ethereum network Eth{ #[structopt(flatten)] sender: EthWallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bsv", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin SV Regtest network BSV{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bsv-reg", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin SV Regtest network BSVReg{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, } impl Network { pub fn network(&self) -> crate::network::Network { match *self { Network::BCH{..} => crate::network::Network::Mainnet, Network::BCHTest{..}=> crate::network::Network::Testnet, Network::BCHReg{..} => crate::network::Network::Regtest, Network::Eth{..} => crate::network::Network::Ethereum, Network::BSV{..} => crate::network::Network::BsvMainnet, Network::BSVReg{..} => crate::network::Network::BsvRegtest, } } } #[derive(StructOpt, Debug)] #[structopt(name="umbrella", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Make a note on transaction within a network selected by <SUBCOMMAND>. /// /// Run `help <SUBCOMMAND>` for [OPTIONS] description. pub struct Opt { #[structopt(subcommand)] pub network: Network, /// Silence all output #[structopt(short = "q", long = "quiet")] pub quiet: bool, } impl Opt { pub fn sender(&self) -> &dyn Sender { match &self.network { Network::BCH {sender, ..} => sender, Network::BCHTest{sender, ..} => sender, Network::BCHReg {sender, ..} => sender, Network::Eth {sender, ..} => sender, Network::BSV {sender, ..} => sender, Network::BSVReg {sender, ..} => sender, } } pub fn data(&self) -> &Data{ match &self.network { Network::BCH {sender:_, data} => data, Network::BCHTest{sender:_, data} => data, Network::BCHReg {sender:_, data} => data, Network::Eth {sender:_, data} => data, Network::BSV {sender:_, data} => data, Network::BSVReg {sender:_, data} => data, } } } #[cfg(test)] mod tests { use super::*; #[ignore] #[test] fn help_network() { Opt::from_iter(&["umbrella", "help", "bch-reg"]); } }
value
identifier_name
conf.rs
use crate::ecies; use crate::hash256::Hash256; use crate::keys::{public_to_slice, sign, slice_to_public}; use crate::messages::{Message, NodeKey, Version, PROTOCOL_VERSION, NODE_NONE}; use crate::util::secs_since; use secp256k1::{ecdh, Secp256k1, PublicKey, SecretKey}; use std::str::FromStr; use std::time::UNIX_EPOCH; use structopt::StructOpt; use tiny_keccak::Keccak; #[derive(StructOpt,Debug)] /// Sender information. pub struct Wallet { #[structopt(long)] /// Public address of sender to be used as input. /// pub in_address: String, #[structopt(long)] /// input UTXO amount /// pub in_amount: f64, #[structopt(long, parse(try_from_str="Hash256::decode"))] /// OutPoint transaction id. /// pub outpoint_hash: Hash256, #[structopt(long)] /// OutPoint vout index. /// pub outpoint_index: u32, #[structopt(long)] /// Private key to sign sender input. /// /// Supported format: WIF (Wallet Import Format) - base56check encoded string. /// /// > bitcoin-cli -regtest dumpprivkey "address" /// pub secret: String, #[structopt(long)] /// Public addrss to be used as output for change. /// /// > bitcoin-cli -regtest getnewaddress /// pub out_address: String, #[structopt(long)] /// Change from input transaction. /// Amout that should be returned to new sender address and don't burned or spent for writing data. /// pub change: f64, } #[derive(StructOpt, Debug)] /// Eth node info pub struct EthWallet { #[structopt(long)] /// Node public key /// pub pub_key: HexData, #[structopt(long, required_unless="crypto")] /// Secret key. Having this key drastically improve the performance. /// pub secret: Option<String>, #[structopt(long, required_unless="secret")] /// Crypto part of privkey file. /// Generating private key on ETH will take a lot of time (for undiscovered yet reason), /// so if you have it from another sources just provide the secret key /// pub crypto: Option<String>, #[structopt(long)] /// Secret key password /// pub password: String, #[structopt(long)] /// Public addrss to be used as output. /// pub out_address: String, /// Transfered value /// #[structopt(long)] pub value: u128, /// Gas paid up front for transaction execution /// #[structopt(long, default_value="21000")] pub gas: u128, /// Gas price /// #[structopt(long, default_value="1000000000")] pub gas_price: u128, } /// Initial encryption configuration #[derive(Clone)] pub struct EncOpt { pub node_public: PublicKey, pub node_secret: SecretKey, pub msg_secret: SecretKey, pub enc_version: Vec<u8>, pub nonce: Hash256, } pub trait Sender { fn change(&self) -> f64 {0.0} fn secret(&self) -> Option<String> {None} fn crypto(&self) -> Option<String> {None} fn pub_key(&self) -> Vec<u8> {vec![]} fn password(&self) -> String {String::new()} fn in_amount(&self) -> f64 {0.0} fn in_address(&self) -> String {String::new()} fn out_address(&self) -> String; fn outpoint_hash(&self) -> Hash256 {Hash256::default()} fn outpoint_index(&self) -> u32 {0} fn gas(&self) -> u128 {0} fn gas_price(&self) -> u128 {0} fn value(&self) -> u128 {0} fn encryption_conf(&self) -> Option<EncOpt> { None } fn version(&self, cfg: &Option<EncOpt>) -> Message; } impl Sender for Wallet { fn in_address(&self) -> String {return self.in_address.clone();} fn out_address(&self) -> String {return self.out_address.clone();} fn outpoint_hash(&self) -> Hash256 {return self.outpoint_hash;} fn outpoint_index(&self) -> u32 {return self.outpoint_index;} fn change(&self) -> f64 {return self.change;} fn in_amount(&self) -> f64 {return self.in_amount;} fn secret(&self) -> Option<String> {return Some(self.secret.clone());} fn version(&self, _cfg: &Option<EncOpt>) -> Message { let version = Version { version: PROTOCOL_VERSION, services: NODE_NONE, timestamp: secs_since(UNIX_EPOCH) as i64, user_agent: "umbrella".to_string(), ..Default::default() }; Message::Version(version) } } impl Sender for EthWallet { fn pub_key(&self) -> Vec<u8> {self.pub_key.0.clone()}
fn gas(&self) -> u128 {self.gas} fn value(&self) -> u128 {self.value} fn gas_price(&self) -> u128 {self.gas_price} fn encryption_conf(&self) -> Option<EncOpt> { let mut rng = rand::thread_rng(); let pub_key:PublicKey = slice_to_public(&self.pub_key.0).unwrap(); let nonce: Hash256 = Hash256::random(); let secp = Secp256k1::new(); let (node_secret, node_public) = secp.generate_keypair(&mut rng); let (msg, msg_secret) = encrypt_node_version(pub_key, node_public, node_secret, nonce); Some(EncOpt { node_public: node_public, node_secret: node_secret, msg_secret: msg_secret, enc_version: msg, nonce: nonce, }) } fn version(&self, cfg: &Option<EncOpt>) -> Message { let version = NodeKey { version: cfg.as_ref().unwrap().enc_version.clone(), }; Message::NodeKey(version) } } /// Probably a part of version message with encryption support /// fn encrypt_node_version(pub_key:PublicKey , node_public:PublicKey , node_secret:SecretKey , nonce: Hash256) -> (Vec<u8>, SecretKey) { let mut rng = rand::thread_rng(); let secp = Secp256k1::new(); let mut version = [0u8;194]; //sig + public + 2*h256 + 1 version[193] = 0x0; let (sig, rest) = version.split_at_mut(65); let (version_pub, rest) = rest.split_at_mut(32); let (node_pub, rest) = rest.split_at_mut(64); let (data_nonce, _) = rest.split_at_mut(32); let (sec1, pub1) = secp.generate_keypair(&mut rng); let pub1 = public_to_slice(&pub1); let sec1 = SecretKey::from_slice(&sec1[..32]).unwrap(); let shr = &ecdh::shared_secret_point(&pub_key, &node_secret)[..32]; let xor = Hash256::from_slice(&shr) ^ nonce; //signature sig.copy_from_slice(&sign(&sec1, &xor)); Keccak::keccak256(&pub1, version_pub); node_pub.copy_from_slice(&public_to_slice(&node_public)); data_nonce.copy_from_slice(nonce.as_bytes()); (ecies::encrypt(&pub_key, &[], &version).unwrap(), sec1) } #[derive(Debug)] pub struct HexData(pub Vec<u8>); impl FromStr for HexData { type Err = hex::FromHexError; fn from_str(s: &str) -> Result<Self, Self::Err> { hex::decode(s).map(HexData) } } #[derive(StructOpt, Debug)] pub struct Data { #[structopt(long)] /// Public address to pay for data storage. /// /// > bitcoin-cli -regtest getnewaddress /// pub dust_address: String, #[structopt(long, default_value="0.0001")] /// Amount to pay for data storage. /// pub dust_amount: f64, #[structopt(long)] /// Data to be incuded in output. /// pub data: HexData, } #[derive(StructOpt, Debug)] /// Network configuration. /// pub enum Network { #[structopt(name="bch", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash main network BCH{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bch-test", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash test network BCHTest{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bch-reg", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash Regtest network BCHReg{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="eth", raw(setting="structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Ethereum network Eth{ #[structopt(flatten)] sender: EthWallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bsv", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin SV Regtest network BSV{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bsv-reg", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin SV Regtest network BSVReg{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, } impl Network { pub fn network(&self) -> crate::network::Network { match *self { Network::BCH{..} => crate::network::Network::Mainnet, Network::BCHTest{..}=> crate::network::Network::Testnet, Network::BCHReg{..} => crate::network::Network::Regtest, Network::Eth{..} => crate::network::Network::Ethereum, Network::BSV{..} => crate::network::Network::BsvMainnet, Network::BSVReg{..} => crate::network::Network::BsvRegtest, } } } #[derive(StructOpt, Debug)] #[structopt(name="umbrella", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Make a note on transaction within a network selected by <SUBCOMMAND>. /// /// Run `help <SUBCOMMAND>` for [OPTIONS] description. pub struct Opt { #[structopt(subcommand)] pub network: Network, /// Silence all output #[structopt(short = "q", long = "quiet")] pub quiet: bool, } impl Opt { pub fn sender(&self) -> &dyn Sender { match &self.network { Network::BCH {sender, ..} => sender, Network::BCHTest{sender, ..} => sender, Network::BCHReg {sender, ..} => sender, Network::Eth {sender, ..} => sender, Network::BSV {sender, ..} => sender, Network::BSVReg {sender, ..} => sender, } } pub fn data(&self) -> &Data{ match &self.network { Network::BCH {sender:_, data} => data, Network::BCHTest{sender:_, data} => data, Network::BCHReg {sender:_, data} => data, Network::Eth {sender:_, data} => data, Network::BSV {sender:_, data} => data, Network::BSVReg {sender:_, data} => data, } } } #[cfg(test)] mod tests { use super::*; #[ignore] #[test] fn help_network() { Opt::from_iter(&["umbrella", "help", "bch-reg"]); } }
fn secret(&self) -> Option<String> {self.secret.clone()} fn crypto(&self) -> Option<String> {self.crypto.clone()} fn password(&self) -> String {self.password.clone()} fn out_address(&self) -> String {self.out_address.clone()}
random_line_split
conf.rs
use crate::ecies; use crate::hash256::Hash256; use crate::keys::{public_to_slice, sign, slice_to_public}; use crate::messages::{Message, NodeKey, Version, PROTOCOL_VERSION, NODE_NONE}; use crate::util::secs_since; use secp256k1::{ecdh, Secp256k1, PublicKey, SecretKey}; use std::str::FromStr; use std::time::UNIX_EPOCH; use structopt::StructOpt; use tiny_keccak::Keccak; #[derive(StructOpt,Debug)] /// Sender information. pub struct Wallet { #[structopt(long)] /// Public address of sender to be used as input. /// pub in_address: String, #[structopt(long)] /// input UTXO amount /// pub in_amount: f64, #[structopt(long, parse(try_from_str="Hash256::decode"))] /// OutPoint transaction id. /// pub outpoint_hash: Hash256, #[structopt(long)] /// OutPoint vout index. /// pub outpoint_index: u32, #[structopt(long)] /// Private key to sign sender input. /// /// Supported format: WIF (Wallet Import Format) - base56check encoded string. /// /// > bitcoin-cli -regtest dumpprivkey "address" /// pub secret: String, #[structopt(long)] /// Public addrss to be used as output for change. /// /// > bitcoin-cli -regtest getnewaddress /// pub out_address: String, #[structopt(long)] /// Change from input transaction. /// Amout that should be returned to new sender address and don't burned or spent for writing data. /// pub change: f64, } #[derive(StructOpt, Debug)] /// Eth node info pub struct EthWallet { #[structopt(long)] /// Node public key /// pub pub_key: HexData, #[structopt(long, required_unless="crypto")] /// Secret key. Having this key drastically improve the performance. /// pub secret: Option<String>, #[structopt(long, required_unless="secret")] /// Crypto part of privkey file. /// Generating private key on ETH will take a lot of time (for undiscovered yet reason), /// so if you have it from another sources just provide the secret key /// pub crypto: Option<String>, #[structopt(long)] /// Secret key password /// pub password: String, #[structopt(long)] /// Public addrss to be used as output. /// pub out_address: String, /// Transfered value /// #[structopt(long)] pub value: u128, /// Gas paid up front for transaction execution /// #[structopt(long, default_value="21000")] pub gas: u128, /// Gas price /// #[structopt(long, default_value="1000000000")] pub gas_price: u128, } /// Initial encryption configuration #[derive(Clone)] pub struct EncOpt { pub node_public: PublicKey, pub node_secret: SecretKey, pub msg_secret: SecretKey, pub enc_version: Vec<u8>, pub nonce: Hash256, } pub trait Sender { fn change(&self) -> f64 {0.0} fn secret(&self) -> Option<String> {None} fn crypto(&self) -> Option<String> {None} fn pub_key(&self) -> Vec<u8> {vec![]} fn password(&self) -> String {String::new()} fn in_amount(&self) -> f64 {0.0} fn in_address(&self) -> String {String::new()} fn out_address(&self) -> String; fn outpoint_hash(&self) -> Hash256 {Hash256::default()} fn outpoint_index(&self) -> u32 {0} fn gas(&self) -> u128 {0} fn gas_price(&self) -> u128 {0} fn value(&self) -> u128
fn encryption_conf(&self) -> Option<EncOpt> { None } fn version(&self, cfg: &Option<EncOpt>) -> Message; } impl Sender for Wallet { fn in_address(&self) -> String {return self.in_address.clone();} fn out_address(&self) -> String {return self.out_address.clone();} fn outpoint_hash(&self) -> Hash256 {return self.outpoint_hash;} fn outpoint_index(&self) -> u32 {return self.outpoint_index;} fn change(&self) -> f64 {return self.change;} fn in_amount(&self) -> f64 {return self.in_amount;} fn secret(&self) -> Option<String> {return Some(self.secret.clone());} fn version(&self, _cfg: &Option<EncOpt>) -> Message { let version = Version { version: PROTOCOL_VERSION, services: NODE_NONE, timestamp: secs_since(UNIX_EPOCH) as i64, user_agent: "umbrella".to_string(), ..Default::default() }; Message::Version(version) } } impl Sender for EthWallet { fn pub_key(&self) -> Vec<u8> {self.pub_key.0.clone()} fn secret(&self) -> Option<String> {self.secret.clone()} fn crypto(&self) -> Option<String> {self.crypto.clone()} fn password(&self) -> String {self.password.clone()} fn out_address(&self) -> String {self.out_address.clone()} fn gas(&self) -> u128 {self.gas} fn value(&self) -> u128 {self.value} fn gas_price(&self) -> u128 {self.gas_price} fn encryption_conf(&self) -> Option<EncOpt> { let mut rng = rand::thread_rng(); let pub_key:PublicKey = slice_to_public(&self.pub_key.0).unwrap(); let nonce: Hash256 = Hash256::random(); let secp = Secp256k1::new(); let (node_secret, node_public) = secp.generate_keypair(&mut rng); let (msg, msg_secret) = encrypt_node_version(pub_key, node_public, node_secret, nonce); Some(EncOpt { node_public: node_public, node_secret: node_secret, msg_secret: msg_secret, enc_version: msg, nonce: nonce, }) } fn version(&self, cfg: &Option<EncOpt>) -> Message { let version = NodeKey { version: cfg.as_ref().unwrap().enc_version.clone(), }; Message::NodeKey(version) } } /// Probably a part of version message with encryption support /// fn encrypt_node_version(pub_key:PublicKey , node_public:PublicKey , node_secret:SecretKey , nonce: Hash256) -> (Vec<u8>, SecretKey) { let mut rng = rand::thread_rng(); let secp = Secp256k1::new(); let mut version = [0u8;194]; //sig + public + 2*h256 + 1 version[193] = 0x0; let (sig, rest) = version.split_at_mut(65); let (version_pub, rest) = rest.split_at_mut(32); let (node_pub, rest) = rest.split_at_mut(64); let (data_nonce, _) = rest.split_at_mut(32); let (sec1, pub1) = secp.generate_keypair(&mut rng); let pub1 = public_to_slice(&pub1); let sec1 = SecretKey::from_slice(&sec1[..32]).unwrap(); let shr = &ecdh::shared_secret_point(&pub_key, &node_secret)[..32]; let xor = Hash256::from_slice(&shr) ^ nonce; //signature sig.copy_from_slice(&sign(&sec1, &xor)); Keccak::keccak256(&pub1, version_pub); node_pub.copy_from_slice(&public_to_slice(&node_public)); data_nonce.copy_from_slice(nonce.as_bytes()); (ecies::encrypt(&pub_key, &[], &version).unwrap(), sec1) } #[derive(Debug)] pub struct HexData(pub Vec<u8>); impl FromStr for HexData { type Err = hex::FromHexError; fn from_str(s: &str) -> Result<Self, Self::Err> { hex::decode(s).map(HexData) } } #[derive(StructOpt, Debug)] pub struct Data { #[structopt(long)] /// Public address to pay for data storage. /// /// > bitcoin-cli -regtest getnewaddress /// pub dust_address: String, #[structopt(long, default_value="0.0001")] /// Amount to pay for data storage. /// pub dust_amount: f64, #[structopt(long)] /// Data to be incuded in output. /// pub data: HexData, } #[derive(StructOpt, Debug)] /// Network configuration. /// pub enum Network { #[structopt(name="bch", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash main network BCH{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bch-test", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash test network BCHTest{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bch-reg", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin Cash Regtest network BCHReg{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="eth", raw(setting="structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Ethereum network Eth{ #[structopt(flatten)] sender: EthWallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bsv", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin SV Regtest network BSV{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, #[structopt(name="bsv-reg", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Operate on Bitcoin SV Regtest network BSVReg{ #[structopt(flatten)] sender: Wallet, #[structopt(flatten)] data: Data, }, } impl Network { pub fn network(&self) -> crate::network::Network { match *self { Network::BCH{..} => crate::network::Network::Mainnet, Network::BCHTest{..}=> crate::network::Network::Testnet, Network::BCHReg{..} => crate::network::Network::Regtest, Network::Eth{..} => crate::network::Network::Ethereum, Network::BSV{..} => crate::network::Network::BsvMainnet, Network::BSVReg{..} => crate::network::Network::BsvRegtest, } } } #[derive(StructOpt, Debug)] #[structopt(name="umbrella", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] /// Make a note on transaction within a network selected by <SUBCOMMAND>. /// /// Run `help <SUBCOMMAND>` for [OPTIONS] description. pub struct Opt { #[structopt(subcommand)] pub network: Network, /// Silence all output #[structopt(short = "q", long = "quiet")] pub quiet: bool, } impl Opt { pub fn sender(&self) -> &dyn Sender { match &self.network { Network::BCH {sender, ..} => sender, Network::BCHTest{sender, ..} => sender, Network::BCHReg {sender, ..} => sender, Network::Eth {sender, ..} => sender, Network::BSV {sender, ..} => sender, Network::BSVReg {sender, ..} => sender, } } pub fn data(&self) -> &Data{ match &self.network { Network::BCH {sender:_, data} => data, Network::BCHTest{sender:_, data} => data, Network::BCHReg {sender:_, data} => data, Network::Eth {sender:_, data} => data, Network::BSV {sender:_, data} => data, Network::BSVReg {sender:_, data} => data, } } } #[cfg(test)] mod tests { use super::*; #[ignore] #[test] fn help_network() { Opt::from_iter(&["umbrella", "help", "bch-reg"]); } }
{0}
identifier_body
connection.go
// Copyright 2014-2021 Aerospike, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package aerospike import ( "compress/zlib" "crypto/tls" "io" "net" "runtime" "strconv" "sync" "sync/atomic" "time" "github.com/aerospike/aerospike-client-go/logger" "github.com/aerospike/aerospike-client-go/types" ) // DefaultBufferSize specifies the initial size of the connection buffer when it is created. // If not big enough (as big as the average record), it will be reallocated to size again // which will be more expensive. var DefaultBufferSize = 64 * 1024 // 64 KiB // bufPool reuses the data buffers to remove pressure from // the allocator and the GC during connection churns. var bufPool = sync.Pool{ New: func() interface{} { return make([]byte, DefaultBufferSize) }, } // Connection represents a connection with a timeout. type Connection struct { node *Node // timeouts socketTimeout time.Duration deadline time.Time // duration after which connection is considered idle idleTimeout time.Duration idleDeadline time.Time // connection object conn net.Conn // to avoid having a buffer pool and contention dataBuffer []byte compressed bool inflater io.ReadCloser // inflater may consume more bytes than required. // LimitReader is used to avoid that problem. limitReader *io.LimitedReader closer sync.Once } // makes sure that the connection is closed eventually, even if it is not consumed func connectionFinalizer(c *Connection) { c.Close() } func errToTimeoutErr(conn *Connection, err error) error { switch e := err.(type) { case net.Error: if e.Timeout() { if conn != nil && conn.node != nil { atomic.AddInt64(&conn.node.stats.ConnectionsTimeoutErrors, 1) } } return types.ErrTimeout case types.AerospikeError: if e.ResultCode() == types.TIMEOUT { if conn != nil && conn.node != nil { atomic.AddInt64(&conn.node.stats.ConnectionsTimeoutErrors, 1) } } return e default: if conn != nil && conn.node != nil { atomic.AddInt64(&conn.node.stats.ConnectionsOtherErrors, 1) } return err } } // newConnection creates a connection on the network and returns the pointer // A minimum timeout of 2 seconds will always be applied. // If the connection is not established in the specified timeout, // an error will be returned func newConnection(address string, timeout time.Duration) (*Connection, error) { newConn := &Connection{dataBuffer: bufPool.Get().([]byte)} runtime.SetFinalizer(newConn, connectionFinalizer) // don't wait indefinitely if timeout == 0 { timeout = 5 * time.Second } conn, err := net.DialTimeout("tcp", address, timeout) if err != nil { logger.Logger.Debug("Connection to address `%s` failed to establish with error: %s", address, err.Error()) return nil, errToTimeoutErr(nil, err) } newConn.conn = conn newConn.limitReader = &io.LimitedReader{R: conn, N: 0} // set timeout at the last possible moment if err := newConn.SetTimeout(time.Now().Add(timeout), timeout); err != nil { newConn.Close() return nil, err } return newConn, nil } // NewConnection creates a TLS connection on the network and returns the pointer. // A minimum timeout of 2 seconds will always be applied. // If the connection is not established in the specified timeout, // an error will be returned func NewConnection(policy *ClientPolicy, host *Host) (*Connection, error) { address := net.JoinHostPort(host.Name, strconv.Itoa(host.Port)) conn, err := newConnection(address, policy.Timeout) if err != nil { return nil, err } if policy.TlsConfig == nil { return conn, nil } // Use version dependent clone function to clone the config tlsConfig := cloneTLSConfig(policy.TlsConfig) tlsConfig.ServerName = host.TLSName sconn := tls.Client(conn.conn, tlsConfig) if err := sconn.Handshake(); err != nil { if cerr := sconn.Close(); cerr != nil { logger.Logger.Debug("Closing connection after handshake error failed: %s", cerr.Error()) } return nil, err } if host.TLSName != "" && !tlsConfig.InsecureSkipVerify { if err := sconn.VerifyHostname(host.TLSName); err != nil { if cerr := sconn.Close(); cerr != nil { logger.Logger.Debug("Closing connection after VerifyHostName error failed: %s", cerr.Error()) } logger.Logger.Error("Connection to address `%s` failed to establish with error: %s", address, err.Error()) return nil, errToTimeoutErr(nil, err) } } conn.conn = sconn return conn, nil } // Write writes the slice to the connection buffer. func (ctn *Connection) Write(buf []byte) (total int, err error) { // make sure all bytes are written // Don't worry about the loop, timeout has been set elsewhere length := len(buf) for total < length { var r int if err = ctn.updateDeadline(); err != nil { break } r, err = ctn.conn.Write(buf[total:]) total += r if err != nil { break } } // If all bytes are written, ignore any potential error // The error will bubble up on the next network io if it matters. if total == len(buf) { return total, nil } if ctn.node != nil { ctn.node.incrErrorCount() atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // the line should happen before .Close() err = errToTimeoutErr(ctn, err) ctn.Close() return total, err } // Read reads from connection buffer to the provided slice. func (ctn *Connection) Read(buf []byte, length int) (total int, err error) { // if all bytes are not read, retry until successful // Don't worry about the loop; we've already set the timeout elsewhere for total < length { var r int if err = ctn.updateDeadline(); err != nil { break } if !ctn.compressed { r, err = ctn.conn.Read(buf[total:length]) } else { r, err = ctn.inflater.Read(buf[total:length]) if err == io.EOF && total+r == length { ctn.compressed = false err = ctn.inflater.Close() } } total += r if err != nil { break } } if total == length { // If all required bytes are read, ignore any potential error. // The error will bubble up on the next network io if it matters. return total, nil } if ctn.node != nil { ctn.node.incrErrorCount() atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // the line should happen before .Close() err = errToTimeoutErr(ctn, err) ctn.Close() return total, err } // IsConnected returns true if the connection is not closed yet. func (ctn *Connection) IsConnected() bool { return ctn.conn != nil } // updateDeadline sets connection timeout for both read and write operations. // this function is called before each read and write operation. If deadline has passed, // the function will return a TIMEOUT error. func (ctn *Connection) updateDeadline() error { now := time.Now() var socketDeadline time.Time if ctn.deadline.IsZero() { if ctn.socketTimeout > 0 { socketDeadline = now.Add(ctn.socketTimeout) } } else { if now.After(ctn.deadline) { return types.NewAerospikeError(types.TIMEOUT) } if ctn.socketTimeout == 0 { socketDeadline = ctn.deadline } else { tDeadline := now.Add(ctn.socketTimeout) if tDeadline.After(ctn.deadline) { socketDeadline = ctn.deadline } else { socketDeadline = tDeadline } } // floor to a millisecond to avoid too short timeouts if socketDeadline.Sub(now) < time.Millisecond { socketDeadline = now.Add(time.Millisecond) } } if err := ctn.conn.SetDeadline(socketDeadline); err != nil { if ctn.node != nil { atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } return err } return nil } // SetTimeout sets connection timeout for both read and write operations. func (ctn *Connection) SetTimeout(deadline time.Time, socketTimeout time.Duration) error { ctn.deadline = deadline ctn.socketTimeout = socketTimeout return nil } // Close closes the connection func (ctn *Connection) Close() { ctn.closer.Do(func() { if ctn != nil && ctn.conn != nil { // deregister if ctn.node != nil { ctn.node.connectionCount.DecrementAndGet() atomic.AddInt64(&ctn.node.stats.ConnectionsClosed, 1) } if err := ctn.conn.Close(); err != nil { logger.Logger.Warn(err.Error()) } ctn.conn = nil // put the data buffer back in the pool in case it gets used again if len(ctn.dataBuffer) >= DefaultBufferSize && len(ctn.dataBuffer) <= MaxBufferSize { bufPool.Put(ctn.dataBuffer) } ctn.dataBuffer = nil ctn.node = nil } }) } // Authenticate will send authentication information to the server. // Notice: This method does not support external authentication mechanisms like LDAP. // This method is deprecated and will be removed in the future. func (ctn *Connection) Authenticate(user string, password string) error { // need to authenticate if user != "" { hashedPass, err := hashPassword(password) if err != nil { return err } return ctn.authenticateFast(user, hashedPass) } return nil } // authenticateFast will send authentication information to the server. func (ctn *Connection) authenticateFast(user string, hashedPass []byte) error { // need to authenticate if len(user) > 0 { command := newLoginCommand(ctn.dataBuffer) if err := command.authenticateInternal(ctn, user, hashedPass); err != nil { if ctn.node != nil { atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // Socket not authenticated. Do not put back into pool. ctn.Close() return err } } return nil } // Login will send authentication information to the server. func (ctn *Connection) login(policy *ClientPolicy, hashedPassword []byte, sessionToken []byte) error { // need to authenticate if policy.RequiresAuthentication() { switch policy.AuthMode { case AuthModeExternal: var err error command := newLoginCommand(ctn.dataBuffer) if sessionToken == nil { err = command.login(policy, ctn, hashedPassword) } else { err = command.authenticateViaToken(policy, ctn, sessionToken) } if err != nil { if ctn.node != nil { atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // Socket not authenticated. Do not put back into pool. ctn.Close() return err } if ctn.node != nil && command.SessionToken != nil { ctn.node._sessionToken.Store(command.SessionToken) ctn.node._sessionExpiration.Store(command.SessionExpiration) } return nil case AuthModeInternal: return ctn.authenticateFast(policy.User, hashedPassword) } } return nil } // Login will send authentication information to the server. // This function is provided for using the connection in conjunction with external libraries. // The password will be hashed everytime, which is a slow operation. func (ctn *Connection) Login(policy *ClientPolicy) error { if !policy.RequiresAuthentication() { return nil } hashedPassword, err := hashPassword(policy.Password) if err != nil { return err } return ctn.login(policy, hashedPassword, nil) } // setIdleTimeout sets the idle timeout for the connection. func (ctn *Connection) setIdleTimeout(timeout time.Duration) { ctn.idleTimeout = timeout } // isIdle returns true if the connection has reached the idle deadline. func (ctn *Connection) isIdle() bool { return ctn.idleTimeout > 0 && time.Now().After(ctn.idleDeadline) } // refresh extends the idle deadline of the connection. func (ctn *Connection) refresh() { ctn.idleDeadline = time.Now().Add(ctn.idleTimeout) if ctn.inflater != nil { ctn.inflater.Close() } ctn.compressed = false ctn.inflater = nil } // initInflater sets up the zlib inflater to read compressed data from the connection func (ctn *Connection)
(enabled bool, length int) error { ctn.compressed = enabled ctn.inflater = nil if ctn.compressed { ctn.limitReader.N = int64(length) r, err := zlib.NewReader(ctn.limitReader) if err != nil { return err } ctn.inflater = r } return nil }
initInflater
identifier_name
connection.go
// Copyright 2014-2021 Aerospike, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package aerospike import ( "compress/zlib" "crypto/tls" "io" "net" "runtime" "strconv" "sync" "sync/atomic" "time" "github.com/aerospike/aerospike-client-go/logger" "github.com/aerospike/aerospike-client-go/types" ) // DefaultBufferSize specifies the initial size of the connection buffer when it is created. // If not big enough (as big as the average record), it will be reallocated to size again // which will be more expensive. var DefaultBufferSize = 64 * 1024 // 64 KiB // bufPool reuses the data buffers to remove pressure from // the allocator and the GC during connection churns. var bufPool = sync.Pool{ New: func() interface{} { return make([]byte, DefaultBufferSize) }, } // Connection represents a connection with a timeout. type Connection struct { node *Node // timeouts socketTimeout time.Duration deadline time.Time // duration after which connection is considered idle idleTimeout time.Duration idleDeadline time.Time // connection object conn net.Conn // to avoid having a buffer pool and contention dataBuffer []byte compressed bool inflater io.ReadCloser // inflater may consume more bytes than required. // LimitReader is used to avoid that problem. limitReader *io.LimitedReader closer sync.Once } // makes sure that the connection is closed eventually, even if it is not consumed func connectionFinalizer(c *Connection) { c.Close() } func errToTimeoutErr(conn *Connection, err error) error { switch e := err.(type) { case net.Error: if e.Timeout() { if conn != nil && conn.node != nil { atomic.AddInt64(&conn.node.stats.ConnectionsTimeoutErrors, 1) } } return types.ErrTimeout case types.AerospikeError: if e.ResultCode() == types.TIMEOUT { if conn != nil && conn.node != nil { atomic.AddInt64(&conn.node.stats.ConnectionsTimeoutErrors, 1) } } return e default: if conn != nil && conn.node != nil { atomic.AddInt64(&conn.node.stats.ConnectionsOtherErrors, 1) } return err } } // newConnection creates a connection on the network and returns the pointer // A minimum timeout of 2 seconds will always be applied. // If the connection is not established in the specified timeout, // an error will be returned func newConnection(address string, timeout time.Duration) (*Connection, error) { newConn := &Connection{dataBuffer: bufPool.Get().([]byte)} runtime.SetFinalizer(newConn, connectionFinalizer) // don't wait indefinitely if timeout == 0 { timeout = 5 * time.Second } conn, err := net.DialTimeout("tcp", address, timeout) if err != nil { logger.Logger.Debug("Connection to address `%s` failed to establish with error: %s", address, err.Error()) return nil, errToTimeoutErr(nil, err) } newConn.conn = conn newConn.limitReader = &io.LimitedReader{R: conn, N: 0} // set timeout at the last possible moment if err := newConn.SetTimeout(time.Now().Add(timeout), timeout); err != nil { newConn.Close() return nil, err } return newConn, nil } // NewConnection creates a TLS connection on the network and returns the pointer. // A minimum timeout of 2 seconds will always be applied. // If the connection is not established in the specified timeout, // an error will be returned func NewConnection(policy *ClientPolicy, host *Host) (*Connection, error) { address := net.JoinHostPort(host.Name, strconv.Itoa(host.Port)) conn, err := newConnection(address, policy.Timeout) if err != nil { return nil, err } if policy.TlsConfig == nil { return conn, nil } // Use version dependent clone function to clone the config tlsConfig := cloneTLSConfig(policy.TlsConfig) tlsConfig.ServerName = host.TLSName sconn := tls.Client(conn.conn, tlsConfig) if err := sconn.Handshake(); err != nil { if cerr := sconn.Close(); cerr != nil { logger.Logger.Debug("Closing connection after handshake error failed: %s", cerr.Error()) } return nil, err } if host.TLSName != "" && !tlsConfig.InsecureSkipVerify { if err := sconn.VerifyHostname(host.TLSName); err != nil { if cerr := sconn.Close(); cerr != nil { logger.Logger.Debug("Closing connection after VerifyHostName error failed: %s", cerr.Error()) } logger.Logger.Error("Connection to address `%s` failed to establish with error: %s", address, err.Error()) return nil, errToTimeoutErr(nil, err) } } conn.conn = sconn return conn, nil } // Write writes the slice to the connection buffer. func (ctn *Connection) Write(buf []byte) (total int, err error) { // make sure all bytes are written // Don't worry about the loop, timeout has been set elsewhere length := len(buf) for total < length { var r int if err = ctn.updateDeadline(); err != nil { break } r, err = ctn.conn.Write(buf[total:]) total += r if err != nil { break } } // If all bytes are written, ignore any potential error // The error will bubble up on the next network io if it matters. if total == len(buf) { return total, nil } if ctn.node != nil { ctn.node.incrErrorCount() atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // the line should happen before .Close() err = errToTimeoutErr(ctn, err) ctn.Close() return total, err } // Read reads from connection buffer to the provided slice. func (ctn *Connection) Read(buf []byte, length int) (total int, err error) { // if all bytes are not read, retry until successful // Don't worry about the loop; we've already set the timeout elsewhere for total < length { var r int if err = ctn.updateDeadline(); err != nil { break } if !ctn.compressed { r, err = ctn.conn.Read(buf[total:length]) } else { r, err = ctn.inflater.Read(buf[total:length]) if err == io.EOF && total+r == length { ctn.compressed = false err = ctn.inflater.Close() } } total += r if err != nil { break } } if total == length { // If all required bytes are read, ignore any potential error. // The error will bubble up on the next network io if it matters. return total, nil } if ctn.node != nil { ctn.node.incrErrorCount() atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // the line should happen before .Close() err = errToTimeoutErr(ctn, err) ctn.Close() return total, err } // IsConnected returns true if the connection is not closed yet. func (ctn *Connection) IsConnected() bool {
// the function will return a TIMEOUT error. func (ctn *Connection) updateDeadline() error { now := time.Now() var socketDeadline time.Time if ctn.deadline.IsZero() { if ctn.socketTimeout > 0 { socketDeadline = now.Add(ctn.socketTimeout) } } else { if now.After(ctn.deadline) { return types.NewAerospikeError(types.TIMEOUT) } if ctn.socketTimeout == 0 { socketDeadline = ctn.deadline } else { tDeadline := now.Add(ctn.socketTimeout) if tDeadline.After(ctn.deadline) { socketDeadline = ctn.deadline } else { socketDeadline = tDeadline } } // floor to a millisecond to avoid too short timeouts if socketDeadline.Sub(now) < time.Millisecond { socketDeadline = now.Add(time.Millisecond) } } if err := ctn.conn.SetDeadline(socketDeadline); err != nil { if ctn.node != nil { atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } return err } return nil } // SetTimeout sets connection timeout for both read and write operations. func (ctn *Connection) SetTimeout(deadline time.Time, socketTimeout time.Duration) error { ctn.deadline = deadline ctn.socketTimeout = socketTimeout return nil } // Close closes the connection func (ctn *Connection) Close() { ctn.closer.Do(func() { if ctn != nil && ctn.conn != nil { // deregister if ctn.node != nil { ctn.node.connectionCount.DecrementAndGet() atomic.AddInt64(&ctn.node.stats.ConnectionsClosed, 1) } if err := ctn.conn.Close(); err != nil { logger.Logger.Warn(err.Error()) } ctn.conn = nil // put the data buffer back in the pool in case it gets used again if len(ctn.dataBuffer) >= DefaultBufferSize && len(ctn.dataBuffer) <= MaxBufferSize { bufPool.Put(ctn.dataBuffer) } ctn.dataBuffer = nil ctn.node = nil } }) } // Authenticate will send authentication information to the server. // Notice: This method does not support external authentication mechanisms like LDAP. // This method is deprecated and will be removed in the future. func (ctn *Connection) Authenticate(user string, password string) error { // need to authenticate if user != "" { hashedPass, err := hashPassword(password) if err != nil { return err } return ctn.authenticateFast(user, hashedPass) } return nil } // authenticateFast will send authentication information to the server. func (ctn *Connection) authenticateFast(user string, hashedPass []byte) error { // need to authenticate if len(user) > 0 { command := newLoginCommand(ctn.dataBuffer) if err := command.authenticateInternal(ctn, user, hashedPass); err != nil { if ctn.node != nil { atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // Socket not authenticated. Do not put back into pool. ctn.Close() return err } } return nil } // Login will send authentication information to the server. func (ctn *Connection) login(policy *ClientPolicy, hashedPassword []byte, sessionToken []byte) error { // need to authenticate if policy.RequiresAuthentication() { switch policy.AuthMode { case AuthModeExternal: var err error command := newLoginCommand(ctn.dataBuffer) if sessionToken == nil { err = command.login(policy, ctn, hashedPassword) } else { err = command.authenticateViaToken(policy, ctn, sessionToken) } if err != nil { if ctn.node != nil { atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // Socket not authenticated. Do not put back into pool. ctn.Close() return err } if ctn.node != nil && command.SessionToken != nil { ctn.node._sessionToken.Store(command.SessionToken) ctn.node._sessionExpiration.Store(command.SessionExpiration) } return nil case AuthModeInternal: return ctn.authenticateFast(policy.User, hashedPassword) } } return nil } // Login will send authentication information to the server. // This function is provided for using the connection in conjunction with external libraries. // The password will be hashed everytime, which is a slow operation. func (ctn *Connection) Login(policy *ClientPolicy) error { if !policy.RequiresAuthentication() { return nil } hashedPassword, err := hashPassword(policy.Password) if err != nil { return err } return ctn.login(policy, hashedPassword, nil) } // setIdleTimeout sets the idle timeout for the connection. func (ctn *Connection) setIdleTimeout(timeout time.Duration) { ctn.idleTimeout = timeout } // isIdle returns true if the connection has reached the idle deadline. func (ctn *Connection) isIdle() bool { return ctn.idleTimeout > 0 && time.Now().After(ctn.idleDeadline) } // refresh extends the idle deadline of the connection. func (ctn *Connection) refresh() { ctn.idleDeadline = time.Now().Add(ctn.idleTimeout) if ctn.inflater != nil { ctn.inflater.Close() } ctn.compressed = false ctn.inflater = nil } // initInflater sets up the zlib inflater to read compressed data from the connection func (ctn *Connection) initInflater(enabled bool, length int) error { ctn.compressed = enabled ctn.inflater = nil if ctn.compressed { ctn.limitReader.N = int64(length) r, err := zlib.NewReader(ctn.limitReader) if err != nil { return err } ctn.inflater = r } return nil }
return ctn.conn != nil } // updateDeadline sets connection timeout for both read and write operations. // this function is called before each read and write operation. If deadline has passed,
random_line_split
connection.go
// Copyright 2014-2021 Aerospike, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package aerospike import ( "compress/zlib" "crypto/tls" "io" "net" "runtime" "strconv" "sync" "sync/atomic" "time" "github.com/aerospike/aerospike-client-go/logger" "github.com/aerospike/aerospike-client-go/types" ) // DefaultBufferSize specifies the initial size of the connection buffer when it is created. // If not big enough (as big as the average record), it will be reallocated to size again // which will be more expensive. var DefaultBufferSize = 64 * 1024 // 64 KiB // bufPool reuses the data buffers to remove pressure from // the allocator and the GC during connection churns. var bufPool = sync.Pool{ New: func() interface{} { return make([]byte, DefaultBufferSize) }, } // Connection represents a connection with a timeout. type Connection struct { node *Node // timeouts socketTimeout time.Duration deadline time.Time // duration after which connection is considered idle idleTimeout time.Duration idleDeadline time.Time // connection object conn net.Conn // to avoid having a buffer pool and contention dataBuffer []byte compressed bool inflater io.ReadCloser // inflater may consume more bytes than required. // LimitReader is used to avoid that problem. limitReader *io.LimitedReader closer sync.Once } // makes sure that the connection is closed eventually, even if it is not consumed func connectionFinalizer(c *Connection) { c.Close() } func errToTimeoutErr(conn *Connection, err error) error { switch e := err.(type) { case net.Error: if e.Timeout() { if conn != nil && conn.node != nil { atomic.AddInt64(&conn.node.stats.ConnectionsTimeoutErrors, 1) } } return types.ErrTimeout case types.AerospikeError: if e.ResultCode() == types.TIMEOUT { if conn != nil && conn.node != nil { atomic.AddInt64(&conn.node.stats.ConnectionsTimeoutErrors, 1) } } return e default: if conn != nil && conn.node != nil { atomic.AddInt64(&conn.node.stats.ConnectionsOtherErrors, 1) } return err } } // newConnection creates a connection on the network and returns the pointer // A minimum timeout of 2 seconds will always be applied. // If the connection is not established in the specified timeout, // an error will be returned func newConnection(address string, timeout time.Duration) (*Connection, error) { newConn := &Connection{dataBuffer: bufPool.Get().([]byte)} runtime.SetFinalizer(newConn, connectionFinalizer) // don't wait indefinitely if timeout == 0 { timeout = 5 * time.Second } conn, err := net.DialTimeout("tcp", address, timeout) if err != nil { logger.Logger.Debug("Connection to address `%s` failed to establish with error: %s", address, err.Error()) return nil, errToTimeoutErr(nil, err) } newConn.conn = conn newConn.limitReader = &io.LimitedReader{R: conn, N: 0} // set timeout at the last possible moment if err := newConn.SetTimeout(time.Now().Add(timeout), timeout); err != nil { newConn.Close() return nil, err } return newConn, nil } // NewConnection creates a TLS connection on the network and returns the pointer. // A minimum timeout of 2 seconds will always be applied. // If the connection is not established in the specified timeout, // an error will be returned func NewConnection(policy *ClientPolicy, host *Host) (*Connection, error) { address := net.JoinHostPort(host.Name, strconv.Itoa(host.Port)) conn, err := newConnection(address, policy.Timeout) if err != nil { return nil, err } if policy.TlsConfig == nil { return conn, nil } // Use version dependent clone function to clone the config tlsConfig := cloneTLSConfig(policy.TlsConfig) tlsConfig.ServerName = host.TLSName sconn := tls.Client(conn.conn, tlsConfig) if err := sconn.Handshake(); err != nil { if cerr := sconn.Close(); cerr != nil { logger.Logger.Debug("Closing connection after handshake error failed: %s", cerr.Error()) } return nil, err } if host.TLSName != "" && !tlsConfig.InsecureSkipVerify { if err := sconn.VerifyHostname(host.TLSName); err != nil { if cerr := sconn.Close(); cerr != nil { logger.Logger.Debug("Closing connection after VerifyHostName error failed: %s", cerr.Error()) } logger.Logger.Error("Connection to address `%s` failed to establish with error: %s", address, err.Error()) return nil, errToTimeoutErr(nil, err) } } conn.conn = sconn return conn, nil } // Write writes the slice to the connection buffer. func (ctn *Connection) Write(buf []byte) (total int, err error) { // make sure all bytes are written // Don't worry about the loop, timeout has been set elsewhere length := len(buf) for total < length { var r int if err = ctn.updateDeadline(); err != nil { break } r, err = ctn.conn.Write(buf[total:]) total += r if err != nil { break } } // If all bytes are written, ignore any potential error // The error will bubble up on the next network io if it matters. if total == len(buf) { return total, nil } if ctn.node != nil { ctn.node.incrErrorCount() atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // the line should happen before .Close() err = errToTimeoutErr(ctn, err) ctn.Close() return total, err } // Read reads from connection buffer to the provided slice. func (ctn *Connection) Read(buf []byte, length int) (total int, err error) { // if all bytes are not read, retry until successful // Don't worry about the loop; we've already set the timeout elsewhere for total < length { var r int if err = ctn.updateDeadline(); err != nil { break } if !ctn.compressed { r, err = ctn.conn.Read(buf[total:length]) } else { r, err = ctn.inflater.Read(buf[total:length]) if err == io.EOF && total+r == length { ctn.compressed = false err = ctn.inflater.Close() } } total += r if err != nil { break } } if total == length { // If all required bytes are read, ignore any potential error. // The error will bubble up on the next network io if it matters. return total, nil } if ctn.node != nil { ctn.node.incrErrorCount() atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // the line should happen before .Close() err = errToTimeoutErr(ctn, err) ctn.Close() return total, err } // IsConnected returns true if the connection is not closed yet. func (ctn *Connection) IsConnected() bool { return ctn.conn != nil } // updateDeadline sets connection timeout for both read and write operations. // this function is called before each read and write operation. If deadline has passed, // the function will return a TIMEOUT error. func (ctn *Connection) updateDeadline() error { now := time.Now() var socketDeadline time.Time if ctn.deadline.IsZero() { if ctn.socketTimeout > 0 { socketDeadline = now.Add(ctn.socketTimeout) } } else { if now.After(ctn.deadline) { return types.NewAerospikeError(types.TIMEOUT) } if ctn.socketTimeout == 0 { socketDeadline = ctn.deadline } else { tDeadline := now.Add(ctn.socketTimeout) if tDeadline.After(ctn.deadline) { socketDeadline = ctn.deadline } else { socketDeadline = tDeadline } } // floor to a millisecond to avoid too short timeouts if socketDeadline.Sub(now) < time.Millisecond
} if err := ctn.conn.SetDeadline(socketDeadline); err != nil { if ctn.node != nil { atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } return err } return nil } // SetTimeout sets connection timeout for both read and write operations. func (ctn *Connection) SetTimeout(deadline time.Time, socketTimeout time.Duration) error { ctn.deadline = deadline ctn.socketTimeout = socketTimeout return nil } // Close closes the connection func (ctn *Connection) Close() { ctn.closer.Do(func() { if ctn != nil && ctn.conn != nil { // deregister if ctn.node != nil { ctn.node.connectionCount.DecrementAndGet() atomic.AddInt64(&ctn.node.stats.ConnectionsClosed, 1) } if err := ctn.conn.Close(); err != nil { logger.Logger.Warn(err.Error()) } ctn.conn = nil // put the data buffer back in the pool in case it gets used again if len(ctn.dataBuffer) >= DefaultBufferSize && len(ctn.dataBuffer) <= MaxBufferSize { bufPool.Put(ctn.dataBuffer) } ctn.dataBuffer = nil ctn.node = nil } }) } // Authenticate will send authentication information to the server. // Notice: This method does not support external authentication mechanisms like LDAP. // This method is deprecated and will be removed in the future. func (ctn *Connection) Authenticate(user string, password string) error { // need to authenticate if user != "" { hashedPass, err := hashPassword(password) if err != nil { return err } return ctn.authenticateFast(user, hashedPass) } return nil } // authenticateFast will send authentication information to the server. func (ctn *Connection) authenticateFast(user string, hashedPass []byte) error { // need to authenticate if len(user) > 0 { command := newLoginCommand(ctn.dataBuffer) if err := command.authenticateInternal(ctn, user, hashedPass); err != nil { if ctn.node != nil { atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // Socket not authenticated. Do not put back into pool. ctn.Close() return err } } return nil } // Login will send authentication information to the server. func (ctn *Connection) login(policy *ClientPolicy, hashedPassword []byte, sessionToken []byte) error { // need to authenticate if policy.RequiresAuthentication() { switch policy.AuthMode { case AuthModeExternal: var err error command := newLoginCommand(ctn.dataBuffer) if sessionToken == nil { err = command.login(policy, ctn, hashedPassword) } else { err = command.authenticateViaToken(policy, ctn, sessionToken) } if err != nil { if ctn.node != nil { atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // Socket not authenticated. Do not put back into pool. ctn.Close() return err } if ctn.node != nil && command.SessionToken != nil { ctn.node._sessionToken.Store(command.SessionToken) ctn.node._sessionExpiration.Store(command.SessionExpiration) } return nil case AuthModeInternal: return ctn.authenticateFast(policy.User, hashedPassword) } } return nil } // Login will send authentication information to the server. // This function is provided for using the connection in conjunction with external libraries. // The password will be hashed everytime, which is a slow operation. func (ctn *Connection) Login(policy *ClientPolicy) error { if !policy.RequiresAuthentication() { return nil } hashedPassword, err := hashPassword(policy.Password) if err != nil { return err } return ctn.login(policy, hashedPassword, nil) } // setIdleTimeout sets the idle timeout for the connection. func (ctn *Connection) setIdleTimeout(timeout time.Duration) { ctn.idleTimeout = timeout } // isIdle returns true if the connection has reached the idle deadline. func (ctn *Connection) isIdle() bool { return ctn.idleTimeout > 0 && time.Now().After(ctn.idleDeadline) } // refresh extends the idle deadline of the connection. func (ctn *Connection) refresh() { ctn.idleDeadline = time.Now().Add(ctn.idleTimeout) if ctn.inflater != nil { ctn.inflater.Close() } ctn.compressed = false ctn.inflater = nil } // initInflater sets up the zlib inflater to read compressed data from the connection func (ctn *Connection) initInflater(enabled bool, length int) error { ctn.compressed = enabled ctn.inflater = nil if ctn.compressed { ctn.limitReader.N = int64(length) r, err := zlib.NewReader(ctn.limitReader) if err != nil { return err } ctn.inflater = r } return nil }
{ socketDeadline = now.Add(time.Millisecond) }
conditional_block
connection.go
// Copyright 2014-2021 Aerospike, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package aerospike import ( "compress/zlib" "crypto/tls" "io" "net" "runtime" "strconv" "sync" "sync/atomic" "time" "github.com/aerospike/aerospike-client-go/logger" "github.com/aerospike/aerospike-client-go/types" ) // DefaultBufferSize specifies the initial size of the connection buffer when it is created. // If not big enough (as big as the average record), it will be reallocated to size again // which will be more expensive. var DefaultBufferSize = 64 * 1024 // 64 KiB // bufPool reuses the data buffers to remove pressure from // the allocator and the GC during connection churns. var bufPool = sync.Pool{ New: func() interface{} { return make([]byte, DefaultBufferSize) }, } // Connection represents a connection with a timeout. type Connection struct { node *Node // timeouts socketTimeout time.Duration deadline time.Time // duration after which connection is considered idle idleTimeout time.Duration idleDeadline time.Time // connection object conn net.Conn // to avoid having a buffer pool and contention dataBuffer []byte compressed bool inflater io.ReadCloser // inflater may consume more bytes than required. // LimitReader is used to avoid that problem. limitReader *io.LimitedReader closer sync.Once } // makes sure that the connection is closed eventually, even if it is not consumed func connectionFinalizer(c *Connection) { c.Close() } func errToTimeoutErr(conn *Connection, err error) error { switch e := err.(type) { case net.Error: if e.Timeout() { if conn != nil && conn.node != nil { atomic.AddInt64(&conn.node.stats.ConnectionsTimeoutErrors, 1) } } return types.ErrTimeout case types.AerospikeError: if e.ResultCode() == types.TIMEOUT { if conn != nil && conn.node != nil { atomic.AddInt64(&conn.node.stats.ConnectionsTimeoutErrors, 1) } } return e default: if conn != nil && conn.node != nil { atomic.AddInt64(&conn.node.stats.ConnectionsOtherErrors, 1) } return err } } // newConnection creates a connection on the network and returns the pointer // A minimum timeout of 2 seconds will always be applied. // If the connection is not established in the specified timeout, // an error will be returned func newConnection(address string, timeout time.Duration) (*Connection, error)
// NewConnection creates a TLS connection on the network and returns the pointer. // A minimum timeout of 2 seconds will always be applied. // If the connection is not established in the specified timeout, // an error will be returned func NewConnection(policy *ClientPolicy, host *Host) (*Connection, error) { address := net.JoinHostPort(host.Name, strconv.Itoa(host.Port)) conn, err := newConnection(address, policy.Timeout) if err != nil { return nil, err } if policy.TlsConfig == nil { return conn, nil } // Use version dependent clone function to clone the config tlsConfig := cloneTLSConfig(policy.TlsConfig) tlsConfig.ServerName = host.TLSName sconn := tls.Client(conn.conn, tlsConfig) if err := sconn.Handshake(); err != nil { if cerr := sconn.Close(); cerr != nil { logger.Logger.Debug("Closing connection after handshake error failed: %s", cerr.Error()) } return nil, err } if host.TLSName != "" && !tlsConfig.InsecureSkipVerify { if err := sconn.VerifyHostname(host.TLSName); err != nil { if cerr := sconn.Close(); cerr != nil { logger.Logger.Debug("Closing connection after VerifyHostName error failed: %s", cerr.Error()) } logger.Logger.Error("Connection to address `%s` failed to establish with error: %s", address, err.Error()) return nil, errToTimeoutErr(nil, err) } } conn.conn = sconn return conn, nil } // Write writes the slice to the connection buffer. func (ctn *Connection) Write(buf []byte) (total int, err error) { // make sure all bytes are written // Don't worry about the loop, timeout has been set elsewhere length := len(buf) for total < length { var r int if err = ctn.updateDeadline(); err != nil { break } r, err = ctn.conn.Write(buf[total:]) total += r if err != nil { break } } // If all bytes are written, ignore any potential error // The error will bubble up on the next network io if it matters. if total == len(buf) { return total, nil } if ctn.node != nil { ctn.node.incrErrorCount() atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // the line should happen before .Close() err = errToTimeoutErr(ctn, err) ctn.Close() return total, err } // Read reads from connection buffer to the provided slice. func (ctn *Connection) Read(buf []byte, length int) (total int, err error) { // if all bytes are not read, retry until successful // Don't worry about the loop; we've already set the timeout elsewhere for total < length { var r int if err = ctn.updateDeadline(); err != nil { break } if !ctn.compressed { r, err = ctn.conn.Read(buf[total:length]) } else { r, err = ctn.inflater.Read(buf[total:length]) if err == io.EOF && total+r == length { ctn.compressed = false err = ctn.inflater.Close() } } total += r if err != nil { break } } if total == length { // If all required bytes are read, ignore any potential error. // The error will bubble up on the next network io if it matters. return total, nil } if ctn.node != nil { ctn.node.incrErrorCount() atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // the line should happen before .Close() err = errToTimeoutErr(ctn, err) ctn.Close() return total, err } // IsConnected returns true if the connection is not closed yet. func (ctn *Connection) IsConnected() bool { return ctn.conn != nil } // updateDeadline sets connection timeout for both read and write operations. // this function is called before each read and write operation. If deadline has passed, // the function will return a TIMEOUT error. func (ctn *Connection) updateDeadline() error { now := time.Now() var socketDeadline time.Time if ctn.deadline.IsZero() { if ctn.socketTimeout > 0 { socketDeadline = now.Add(ctn.socketTimeout) } } else { if now.After(ctn.deadline) { return types.NewAerospikeError(types.TIMEOUT) } if ctn.socketTimeout == 0 { socketDeadline = ctn.deadline } else { tDeadline := now.Add(ctn.socketTimeout) if tDeadline.After(ctn.deadline) { socketDeadline = ctn.deadline } else { socketDeadline = tDeadline } } // floor to a millisecond to avoid too short timeouts if socketDeadline.Sub(now) < time.Millisecond { socketDeadline = now.Add(time.Millisecond) } } if err := ctn.conn.SetDeadline(socketDeadline); err != nil { if ctn.node != nil { atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } return err } return nil } // SetTimeout sets connection timeout for both read and write operations. func (ctn *Connection) SetTimeout(deadline time.Time, socketTimeout time.Duration) error { ctn.deadline = deadline ctn.socketTimeout = socketTimeout return nil } // Close closes the connection func (ctn *Connection) Close() { ctn.closer.Do(func() { if ctn != nil && ctn.conn != nil { // deregister if ctn.node != nil { ctn.node.connectionCount.DecrementAndGet() atomic.AddInt64(&ctn.node.stats.ConnectionsClosed, 1) } if err := ctn.conn.Close(); err != nil { logger.Logger.Warn(err.Error()) } ctn.conn = nil // put the data buffer back in the pool in case it gets used again if len(ctn.dataBuffer) >= DefaultBufferSize && len(ctn.dataBuffer) <= MaxBufferSize { bufPool.Put(ctn.dataBuffer) } ctn.dataBuffer = nil ctn.node = nil } }) } // Authenticate will send authentication information to the server. // Notice: This method does not support external authentication mechanisms like LDAP. // This method is deprecated and will be removed in the future. func (ctn *Connection) Authenticate(user string, password string) error { // need to authenticate if user != "" { hashedPass, err := hashPassword(password) if err != nil { return err } return ctn.authenticateFast(user, hashedPass) } return nil } // authenticateFast will send authentication information to the server. func (ctn *Connection) authenticateFast(user string, hashedPass []byte) error { // need to authenticate if len(user) > 0 { command := newLoginCommand(ctn.dataBuffer) if err := command.authenticateInternal(ctn, user, hashedPass); err != nil { if ctn.node != nil { atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // Socket not authenticated. Do not put back into pool. ctn.Close() return err } } return nil } // Login will send authentication information to the server. func (ctn *Connection) login(policy *ClientPolicy, hashedPassword []byte, sessionToken []byte) error { // need to authenticate if policy.RequiresAuthentication() { switch policy.AuthMode { case AuthModeExternal: var err error command := newLoginCommand(ctn.dataBuffer) if sessionToken == nil { err = command.login(policy, ctn, hashedPassword) } else { err = command.authenticateViaToken(policy, ctn, sessionToken) } if err != nil { if ctn.node != nil { atomic.AddInt64(&ctn.node.stats.ConnectionsFailed, 1) } // Socket not authenticated. Do not put back into pool. ctn.Close() return err } if ctn.node != nil && command.SessionToken != nil { ctn.node._sessionToken.Store(command.SessionToken) ctn.node._sessionExpiration.Store(command.SessionExpiration) } return nil case AuthModeInternal: return ctn.authenticateFast(policy.User, hashedPassword) } } return nil } // Login will send authentication information to the server. // This function is provided for using the connection in conjunction with external libraries. // The password will be hashed everytime, which is a slow operation. func (ctn *Connection) Login(policy *ClientPolicy) error { if !policy.RequiresAuthentication() { return nil } hashedPassword, err := hashPassword(policy.Password) if err != nil { return err } return ctn.login(policy, hashedPassword, nil) } // setIdleTimeout sets the idle timeout for the connection. func (ctn *Connection) setIdleTimeout(timeout time.Duration) { ctn.idleTimeout = timeout } // isIdle returns true if the connection has reached the idle deadline. func (ctn *Connection) isIdle() bool { return ctn.idleTimeout > 0 && time.Now().After(ctn.idleDeadline) } // refresh extends the idle deadline of the connection. func (ctn *Connection) refresh() { ctn.idleDeadline = time.Now().Add(ctn.idleTimeout) if ctn.inflater != nil { ctn.inflater.Close() } ctn.compressed = false ctn.inflater = nil } // initInflater sets up the zlib inflater to read compressed data from the connection func (ctn *Connection) initInflater(enabled bool, length int) error { ctn.compressed = enabled ctn.inflater = nil if ctn.compressed { ctn.limitReader.N = int64(length) r, err := zlib.NewReader(ctn.limitReader) if err != nil { return err } ctn.inflater = r } return nil }
{ newConn := &Connection{dataBuffer: bufPool.Get().([]byte)} runtime.SetFinalizer(newConn, connectionFinalizer) // don't wait indefinitely if timeout == 0 { timeout = 5 * time.Second } conn, err := net.DialTimeout("tcp", address, timeout) if err != nil { logger.Logger.Debug("Connection to address `%s` failed to establish with error: %s", address, err.Error()) return nil, errToTimeoutErr(nil, err) } newConn.conn = conn newConn.limitReader = &io.LimitedReader{R: conn, N: 0} // set timeout at the last possible moment if err := newConn.SetTimeout(time.Now().Add(timeout), timeout); err != nil { newConn.Close() return nil, err } return newConn, nil }
identifier_body
main.rs
use std::cell::Cell; fn main() { variable_bindings(); functions(); primitive_types(); comments(); if_(); loops(); ownership(); reference_and_borrowing(); lifetimes(); mutability(); struct_(); enums(); match_(); patterns(); method_syntax(); vectors(); strings(); generics(); traits(); drop(); if_let(); trait_objects(); closures(); } fn variable_bindings() { // Variable bindings let x = 5; println!("{}", x); // Patterns let (x, y) = (2, 3); println!("{}, {}", x, y); // Type annotation let y: u32 = 10; println!("{}", y); // Mutability let mut x = 10; println!("x is {} before mutation", x); x = 5; println!("x is {} after mutation", x); // Initializing bindings // The following won't compile because x is not initialized. // let x: i32; // println!("{}", x); // Scope and shadowing { println!("x is {} inside the scope, before shadowing", x); let x: u16 = 121; println!("x is {} inside the scope", x); } println!("x is {} outside the scope", x); // Here the variable is no longer mutable let x = x; println!("x is {}", x); } fn functions() { addition(50, 100); println!("{} plus one is {}", 10, add_by_one(10)); // Expression vs statements // expression returns a value, statements don't // This is an declaration statement // let x = 10; // The evaluation of "x = 10" is empty tuple () // Expression statement turns express to statments. println!("{} is even? {}", 3, is_even(3)); // Function pointers let f: fn(i32) -> i32 = add_by_one; println!("Using function pointers {}", f(10)); } fn addition(x: i32, y: i32) { println!("{} + {} = {}", x, y, x + y); } fn add_by_one(x: i32) -> i32 { x + 1 } fn is_even(i: i32) -> bool { if i % 2 == 0 { return true; } false } // Can be used as any type fn diverges() -> ! { loop {}; } fn
() { // Booleans let x: bool = false; println!("x is {}", x); // char, supports Unicode let x: char = 'A'; println!("x is {}", x); // Numeric values // signed and fixed size let x: i8 = -12; println!("x is {}", x); // unsigned and fixed size let x: u8 = 12; println!("x is {}", x); // variable size (depending on underlying machine size) let x: usize = 1200; println!("x is {}", x); // floating point let x = 1.0; println!("x is {}", x); // Arrays (fixed sized) let a: [u8; 3] = [1, 2, 3]; println!("a[0] is {}", a[0]); // shorthand initialization let a = [100; 20]; println!("a[0] is {}", a[0]); println!("length of a is {}", a.len()); // Slices let complete = &a[..]; println!("length of complete is {}", complete.len()); let some: &[u32] = &a[5..10]; println!("length of some is {}", some.len()); // str // Is an unsized type // Tuples // Ordered list of fixed size let mut x: (i32, &str) = (1, "hello"); let y = (2, "hellos"); x = y; // accessing values in tuple with destructuring let let (number, word) = x; println!("There are {} {}.", number, word); // single element tuple (0,); // Tuple indexing println!("There are {} {}.", x.0, x.1); } /// # Doc comments here /// /// Markdown is supported fn comments() { //! # This documents the containing element //! instead of the following element (0,); // This is a line comment. } fn if_() { let x = 5; if x == 5 { println!("x is five!"); } else if x == 6 { println!("x is six!"); } else { println!("x is not five or six :("); } // if is an expression let y = if x == 6 { 10 } else { 20 }; println!("y is {}", y); } fn loops() { // loop // indefinite loop loop { break; } // while let mut x = 0; while x < 2 { println!("x is now {} in while loop", x); x += 1; } // for // for var in expression { code } for x in 0..5 { println!("x is now {} in for loop", x); } // Enumerate for (i, j) in (5..10).enumerate() { println!("i is {} and j is {}", i, j); } // Ending iteration early // break let mut x = 5; loop { x += x - 3; println!("x is {}", x); if x % 5 == 0 { break; } } // continue for x in 0..10 { if x % 2 == 0 { continue; } println!("x is {}", x); } // Loop labels 'outer: for x in 0..6 { 'inner: for y in 0..6 { if x % 2 == 0 { continue 'outer }; if y % 2 == 0 { continue 'inner }; println!("x is {} and y is {}", x, y); } } } fn ownership() { //! using zero-cost abstractions //! ownership is a primary example of zero-cost abstractions //! all features talked about are done compile time // Vector v will be deallocated deterministically after it goes out of scope // even if it is allocated on the heap let v = vec![1, 2, 3]; // The ownership is transferred to v2 let v2 = v; // println!("v[0] is: {}", v[0]); // This will generate an error. take_ownership(v2); // println!("v2[0] is: {}", v2[0]); // This will also generate an error. // Copy types (trait) let v = 1; let v2 = v; println!("v is {} and v2 is {}", v, v2); } fn take_ownership(v: Vec<i32>) -> i32 { // nothing happens v[0] } fn reference_and_borrowing() { let v = vec![1, 2, 3]; take_reference(&v); println!("v[0] is {}", v[0]); // Mutable reference let mut x = 5; { let y = &mut x; *y += 1; } println!("Mutable x is now {}", x); // The rules // Borrower scope should never lasts longer than the owner // You can only have one or the other type of borrows // Only one mutable reference is allowed } fn take_reference(v: &Vec<i32>) -> i32 { // v[1] = 1; // Reference (borrowed) are immutable. v[0] } fn lifetimes() { explicit_lifetime(&10); function_with_lifetime(); let e = ExplicitLifetime { x: &5 }; println!("{}", e.x()); // Static lifetime for the entire program. let x: &'static str = "Hello World!"; println!("{}", x); // Lifetime Elision // input lifetime: parameter // output lifetime: return value // elide input lifetime and use this to infer output lifetime // 1. each argument has distinct life time // 2. if only one input lifetime, same output lifetime. // 3. if multiple lifetime, but one is "self", lifetime of self for output // otherwise, fail. } fn explicit_lifetime<'a>(x: &'a i32) { println!("x is {}", x); } fn function_with_lifetime<'a, 'b>() { } // The ExplicitLifetime struct cannot outlive the x it contains struct ExplicitLifetime<'a> { x: &'a i32, } impl<'a> ExplicitLifetime<'a> { fn x(&self) -> &'a i32 { self.x } } fn mutability() { // mutable variable binding let mut x = 5; x = 6; println!("{}", x); // mutable reference let mut x = 5; let y = &mut x; // This is immutable reference. *y = 10; println!("y is {}", *y); let mut x = 5; let mut z = 10; let mut y = &mut x; y = &mut z; println!("y is {}", *y); // Interior vs exterior mutability // Field level mutability struct Point { x: i32, y: Cell<i32>, } let point = Point { x: 10, y: Cell::new(10) }; point.y.set(11); println!("point is {}, {:?}", point.x, point.y); } fn struct_() { // Update syntax struct Point3d { x: i32, y: i32, z: i32, } let a = Point3d { x: 1, y: 2, z: 3 }; let b = Point3d { y: 10, .. a }; println!("{}, {}, {}", a.x, a.y, a.z); println!("{}, {}, {}", a.x, b.y, b.z); // Tuple structs // better to use struct than tuple structs struct Color(i32, i32, i32); // "newtype" pattern struct Inches(i32); let length = Inches(10); let Inches(integer_length) = length; println!("length is {} inches", integer_length); // Unit-like struct struct Unit; let x = Unit; } fn enums() { enum Message { Quit, ChangeColor(i32, i32, i32), Move {x: i32, y: i32}, Write(String), } let m1 = Message::Quit; let m2 = Message::Move {x: 10, y: 20}; // Constructor as functions let m3 = Message::Write("Hello World!".to_string()); } fn match_() { let x = 5; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), 4 => println!("four"), 5 => println!("five"), _ => println!("something else"), } let number = match x { 1 => "one", 2 => "two", 5 => "five", _ => "other", }; // Matching on enums enum Message { Quit, Move {x: i32, y: i32}, } let msg = Message::Move {x: 1, y: 2}; match msg { Message::Quit => println!("Quitting"), Message::Move {x: x, y: y} => println!("Moving to {} {}", x, y), } } fn patterns() { let x = "x"; let c = "c"; match c { x => println!("x: {} c: {}", x, c), } println!("x: {}", x); // Multiple patterns match x { "x" | "y" => println!("is x or y"), _ => println!("not x or y"), } // Destrcturing struct Point { x: i32, y: i32, } let origin = Point { x: 0, y: 0 }; match origin { Point { x: x1, .. } => println!("({}, 0)", x1), } // Ignoring bindings // Use _ or .. inside the pattern // ref and ref mut let mut x = 5; match x { ref r => println!("Got a reference to {}", r), } match x { ref mut mr => println!("Got a mutable reference to {}", mr), } // Ranges // Use ..., mostly used with integers and chars // Bindings // Use @ match x { a @ 1 ... 2 | a @ 3 ... 5 => println!("one through five ({}).", a), 6 ... 10 => println!("six through ten"), _ => println!("everything else"), } // Guards enum OptionalInt { Value(i32), Missing, } let x = OptionalInt::Value(5); match x { OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"), OptionalInt::Value(..) => println!("Got an int!"), OptionalInt::Missing => println!("No such luck!"), } } fn method_syntax() { struct Circle { x: f64, y: f64, radius: f64, } impl Circle { // Associated function fn new(x: f64, y: f64, radius: f64) -> Circle { Circle { x: x, y: y, radius: radius, } } fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } fn grow(&self, increment: f64) -> Circle { Circle { x: self.x, y: self.y, radius: self.radius + increment } } } let c = Circle::new(0.0, 0.0, 2.0); println!("area is {}", c.area()); // Chaining method calls println!("c2's area is {}", c.grow(2.0).area()); // Builder pattern struct CircleBuilder { x: f64, y: f64, radius: f64, } impl CircleBuilder { fn new() -> CircleBuilder { CircleBuilder { x: 0.0, y: 0.0, radius: 1.0 } } fn x(&mut self, coordinate: f64) -> &mut CircleBuilder { self.x = coordinate; self } fn y(&mut self, coordinate: f64) -> &mut CircleBuilder { self.y = coordinate; self } fn radius(&mut self, coordinate: f64) -> &mut CircleBuilder { self.radius = coordinate; self } fn finalize(&self) -> Circle { Circle::new(self.x, self.y, self.radius) } } let c3 = CircleBuilder::new() .x(3.0) .radius(10.0) .finalize(); println!("area is {}", c3.area()); } fn vectors() { let v = vec![1, 2, 3, 4, 5]; let v2 = vec![0; 10]; // ten zeros println!("the third element is {}", v[2]); // Index is usize type // Iterating for i in &v2 { println!("A reference to {}", i); } } fn strings() { // resizable, a sequence of utf-8 characters, not null terminated // &str is a string slice, has fixed size. let greeting = "Hello there."; // &'static str let s = "foo bar"; let s2 = "foo\ bar"; println!("{}", s); println!("{}", s2); let mut s = "Hello".to_string(); // String s.push_str(", world."); println!("{}", s); // Indexing // because of utf-8 strings do not support indexing let name = "赵洋磊"; for b in name.as_bytes() { print!("{} ", b); } println!(""); for c in name.chars() { print!("{} ", c); } println!(""); // Slicing // but for some reason you can do slicing let last_name = &name[0..3]; // byte offsets, has to end on character boundary println!("{}", last_name); // Concatenation let hello = "Hello ".to_string(); let world = "world!"; let hello_world = hello + world; println!("{}", hello_world); } fn generics() { enum MyOption<T> { // T is just convention. Some(T), None, } let x: MyOption<i32> = MyOption::Some(5); let y: MyOption<f64> = MyOption::Some(10.24); // Also can have mutliple types. // enum Result<A, Z> {} // Generic functions // fn takes_anything<T>(x: T) { // } // Generic structs // struct Point<T> { // x: T, // y: T, // } // impl<T> Point<T> {} } fn traits() { trait HasArea { fn area(&self) -> f64; } struct Circle { radius: f64, } impl HasArea for Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } } struct Square { side: f64, } impl HasArea for Square { fn area(&self) -> f64 { self.side * self.side } } // Trait bounds on generic functions fn print_area<T: HasArea>(shape: T) { println!("This shape has an area of {}", shape.area()); } let c = Circle { radius: 2.0 }; let s = Square { side: 2.0 }; print_area(c); print_area(s); // Trait bounds on generic structs struct Rectangle<T> { width: T, height: T, } impl<T: PartialEq> Rectangle<T> { fn is_square(&self) -> bool { self.width == self.height } } let r = Rectangle { width: 47, height: 47, }; println!("This is a square? {}", r.is_square()); // Rules for implementing traits impl HasArea for i32 { fn area(&self) -> f64 { *self as f64 } } println!("silly {}", 5.area()); // Two rules: // Traits has to be defined in your scope to apply (use "use") // Either the trait, or the type you're writing impl for, must be defined by you. // Mutliple bounds // use + // fn foo<T: Clone + Debug>(x: T) {} // Where clause // syntax sugar // fn foo<T: Clone, K: Clone + Debug>(x: T, y: K) {} // equals // fn bar<T, K>(x: T, y: K) where T: Clone, K: Clone + Debug {} // Default methods trait foo { fn is_valid(&self) -> bool; fn is_invalid(&self) -> bool { !self.is_valid() } } // Inheritance trait bar : foo { fn is_good(&self); } // Deriving #[derive(Debug)] struct Foo; println!("{:?}", Foo); } fn drop() { // A special trait from Rust standard library. When things goes out of scope. struct Firework { strength: i32, }; impl Drop for Firework { fn drop(&mut self) { println!("Dropping {}!", self.strength); } } // First in, last out let small = Firework { strength: 1 }; let big = Firework { strength: 100 }; } fn if_let() { let option = Option::Some(5); if let Some(x) = option { println!("{}", x); } else { println!("Nothing"); } let mut v = vec![1, 3, 5, 7, 11]; while let Some(x) = v.pop() { println!("{}", x); } } fn trait_objects() { trait Foo { fn method(&self) -> String; } impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } } let x = 5u8; let y = "Hello".to_string(); // Static dispatching fn do_something<T: Foo>(x: T) { println!("{}", x.method()); } do_something(x); do_something(y); // Trait objects can store any type that implement the trait. // obtained by casting or coercing // Dynamic dispatching fn do_something_else(x: &Foo) { println!("{}", x.method()); } do_something_else(&x); } fn closures() { // This is a closure: |args| expression let plus_one = |x: i32| x + 1; assert_eq!(2, plus_one(1)); // {} is expression, so multiline closure, arguments/return value don't // have to be annotated, but could let plus_two = |x| -> i32 { let mut result: i32 = x; result += 2; result }; assert_eq!(4, plus_two(2)); let num = 5; // Here plus_num borrows the variable binding num let plus_num = |x: i32| x + num; // move closures // regular closure, which borrows the variable num_a, and modify the // underlying value in the closure. let mut num_a = 5; { let mut add_num = |x: i32| num_a += x; add_num(5); } assert_eq!(10, num_a); // move closures, which creates an copy and takes ownership of the variable let mut num_b = 5; { let mut add_num = move |x: i32| num_b += x; add_num(5); } assert_eq!(5, num_b); // Closures are traits, Fn, FnMut, FnOnce. // The following is statically dispatched fn call_with_one<F>(some_closure: F) -> i32 where F: Fn(i32) -> i32 { some_closure(1) } let answer = call_with_one(|x| x + 2); assert_eq!(3, answer); // This is dynamically dispatched (trait object) fn call_with_two(some_closure: &Fn(i32) -> i32) -> i32 { some_closure(2) } let answer = call_with_two(&|x| x + 2); assert_eq!(4, answer); // How to return a closure fn factory() -> Box<Fn(i32) -> i32> { let num = 5; Box::new(move |x| x + num) } let f = factory(); let answer = f(1); assert_eq!(6, answer); }
primitive_types
identifier_name
main.rs
use std::cell::Cell; fn main() { variable_bindings(); functions(); primitive_types(); comments(); if_(); loops(); ownership(); reference_and_borrowing(); lifetimes(); mutability(); struct_(); enums(); match_(); patterns(); method_syntax(); vectors(); strings(); generics(); traits(); drop(); if_let(); trait_objects(); closures(); } fn variable_bindings() { // Variable bindings let x = 5; println!("{}", x); // Patterns let (x, y) = (2, 3); println!("{}, {}", x, y); // Type annotation let y: u32 = 10; println!("{}", y); // Mutability let mut x = 10; println!("x is {} before mutation", x); x = 5; println!("x is {} after mutation", x); // Initializing bindings // The following won't compile because x is not initialized. // let x: i32; // println!("{}", x); // Scope and shadowing { println!("x is {} inside the scope, before shadowing", x); let x: u16 = 121; println!("x is {} inside the scope", x); } println!("x is {} outside the scope", x); // Here the variable is no longer mutable let x = x; println!("x is {}", x); } fn functions() { addition(50, 100); println!("{} plus one is {}", 10, add_by_one(10)); // Expression vs statements // expression returns a value, statements don't // This is an declaration statement // let x = 10; // The evaluation of "x = 10" is empty tuple () // Expression statement turns express to statments. println!("{} is even? {}", 3, is_even(3)); // Function pointers let f: fn(i32) -> i32 = add_by_one; println!("Using function pointers {}", f(10)); } fn addition(x: i32, y: i32) { println!("{} + {} = {}", x, y, x + y); } fn add_by_one(x: i32) -> i32 { x + 1 } fn is_even(i: i32) -> bool { if i % 2 == 0 { return true; } false } // Can be used as any type fn diverges() -> ! { loop {}; } fn primitive_types() { // Booleans let x: bool = false; println!("x is {}", x); // char, supports Unicode let x: char = 'A'; println!("x is {}", x); // Numeric values // signed and fixed size let x: i8 = -12; println!("x is {}", x); // unsigned and fixed size let x: u8 = 12; println!("x is {}", x); // variable size (depending on underlying machine size) let x: usize = 1200; println!("x is {}", x); // floating point let x = 1.0; println!("x is {}", x); // Arrays (fixed sized) let a: [u8; 3] = [1, 2, 3]; println!("a[0] is {}", a[0]); // shorthand initialization let a = [100; 20]; println!("a[0] is {}", a[0]); println!("length of a is {}", a.len()); // Slices let complete = &a[..]; println!("length of complete is {}", complete.len()); let some: &[u32] = &a[5..10]; println!("length of some is {}", some.len()); // str // Is an unsized type // Tuples // Ordered list of fixed size let mut x: (i32, &str) = (1, "hello"); let y = (2, "hellos"); x = y; // accessing values in tuple with destructuring let let (number, word) = x; println!("There are {} {}.", number, word); // single element tuple (0,); // Tuple indexing println!("There are {} {}.", x.0, x.1); } /// # Doc comments here /// /// Markdown is supported fn comments() { //! # This documents the containing element //! instead of the following element (0,); // This is a line comment. } fn if_() { let x = 5; if x == 5 { println!("x is five!"); } else if x == 6 { println!("x is six!"); } else { println!("x is not five or six :("); } // if is an expression let y = if x == 6 { 10 } else { 20 }; println!("y is {}", y); } fn loops() { // loop // indefinite loop loop { break; } // while let mut x = 0; while x < 2 { println!("x is now {} in while loop", x); x += 1; } // for // for var in expression { code } for x in 0..5 { println!("x is now {} in for loop", x); } // Enumerate for (i, j) in (5..10).enumerate() { println!("i is {} and j is {}", i, j); } // Ending iteration early // break let mut x = 5; loop { x += x - 3; println!("x is {}", x); if x % 5 == 0 { break; } } // continue for x in 0..10 { if x % 2 == 0 { continue; } println!("x is {}", x); } // Loop labels 'outer: for x in 0..6 { 'inner: for y in 0..6 { if x % 2 == 0 { continue 'outer }; if y % 2 == 0 { continue 'inner }; println!("x is {} and y is {}", x, y); } } } fn ownership() { //! using zero-cost abstractions //! ownership is a primary example of zero-cost abstractions //! all features talked about are done compile time // Vector v will be deallocated deterministically after it goes out of scope // even if it is allocated on the heap let v = vec![1, 2, 3]; // The ownership is transferred to v2 let v2 = v; // println!("v[0] is: {}", v[0]); // This will generate an error. take_ownership(v2); // println!("v2[0] is: {}", v2[0]); // This will also generate an error. // Copy types (trait) let v = 1; let v2 = v; println!("v is {} and v2 is {}", v, v2); } fn take_ownership(v: Vec<i32>) -> i32 { // nothing happens v[0] } fn reference_and_borrowing() { let v = vec![1, 2, 3]; take_reference(&v); println!("v[0] is {}", v[0]); // Mutable reference let mut x = 5; { let y = &mut x; *y += 1; } println!("Mutable x is now {}", x); // The rules // Borrower scope should never lasts longer than the owner // You can only have one or the other type of borrows // Only one mutable reference is allowed } fn take_reference(v: &Vec<i32>) -> i32 { // v[1] = 1; // Reference (borrowed) are immutable. v[0] } fn lifetimes() { explicit_lifetime(&10); function_with_lifetime(); let e = ExplicitLifetime { x: &5 }; println!("{}", e.x()); // Static lifetime for the entire program. let x: &'static str = "Hello World!"; println!("{}", x); // Lifetime Elision // input lifetime: parameter // output lifetime: return value // elide input lifetime and use this to infer output lifetime // 1. each argument has distinct life time // 2. if only one input lifetime, same output lifetime. // 3. if multiple lifetime, but one is "self", lifetime of self for output // otherwise, fail. } fn explicit_lifetime<'a>(x: &'a i32) { println!("x is {}", x); } fn function_with_lifetime<'a, 'b>() { } // The ExplicitLifetime struct cannot outlive the x it contains struct ExplicitLifetime<'a> { x: &'a i32, } impl<'a> ExplicitLifetime<'a> { fn x(&self) -> &'a i32 { self.x } } fn mutability() { // mutable variable binding let mut x = 5; x = 6; println!("{}", x); // mutable reference let mut x = 5; let y = &mut x; // This is immutable reference. *y = 10; println!("y is {}", *y); let mut x = 5; let mut z = 10; let mut y = &mut x; y = &mut z; println!("y is {}", *y); // Interior vs exterior mutability // Field level mutability struct Point { x: i32, y: Cell<i32>, } let point = Point { x: 10, y: Cell::new(10) }; point.y.set(11); println!("point is {}, {:?}", point.x, point.y); } fn struct_() { // Update syntax struct Point3d { x: i32, y: i32, z: i32, } let a = Point3d { x: 1, y: 2, z: 3 }; let b = Point3d { y: 10, .. a }; println!("{}, {}, {}", a.x, a.y, a.z); println!("{}, {}, {}", a.x, b.y, b.z); // Tuple structs // better to use struct than tuple structs struct Color(i32, i32, i32); // "newtype" pattern struct Inches(i32); let length = Inches(10); let Inches(integer_length) = length; println!("length is {} inches", integer_length); // Unit-like struct struct Unit; let x = Unit; } fn enums() { enum Message { Quit, ChangeColor(i32, i32, i32), Move {x: i32, y: i32}, Write(String), } let m1 = Message::Quit; let m2 = Message::Move {x: 10, y: 20}; // Constructor as functions let m3 = Message::Write("Hello World!".to_string()); } fn match_() { let x = 5; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), 4 => println!("four"), 5 => println!("five"), _ => println!("something else"), } let number = match x { 1 => "one", 2 => "two", 5 => "five", _ => "other", }; // Matching on enums enum Message { Quit, Move {x: i32, y: i32}, } let msg = Message::Move {x: 1, y: 2}; match msg { Message::Quit => println!("Quitting"), Message::Move {x: x, y: y} => println!("Moving to {} {}", x, y), } } fn patterns() { let x = "x"; let c = "c"; match c { x => println!("x: {} c: {}", x, c), } println!("x: {}", x); // Multiple patterns match x { "x" | "y" => println!("is x or y"), _ => println!("not x or y"), } // Destrcturing struct Point { x: i32, y: i32, } let origin = Point { x: 0, y: 0 }; match origin { Point { x: x1, .. } => println!("({}, 0)", x1), } // Ignoring bindings // Use _ or .. inside the pattern // ref and ref mut let mut x = 5; match x { ref r => println!("Got a reference to {}", r), } match x { ref mut mr => println!("Got a mutable reference to {}", mr), } // Ranges // Use ..., mostly used with integers and chars // Bindings // Use @ match x { a @ 1 ... 2 | a @ 3 ... 5 => println!("one through five ({}).", a), 6 ... 10 => println!("six through ten"), _ => println!("everything else"), } // Guards enum OptionalInt { Value(i32), Missing, } let x = OptionalInt::Value(5); match x { OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"), OptionalInt::Value(..) => println!("Got an int!"), OptionalInt::Missing => println!("No such luck!"), } } fn method_syntax() { struct Circle { x: f64, y: f64, radius: f64, } impl Circle { // Associated function fn new(x: f64, y: f64, radius: f64) -> Circle { Circle { x: x, y: y, radius: radius, } } fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } fn grow(&self, increment: f64) -> Circle { Circle { x: self.x, y: self.y, radius: self.radius + increment } } } let c = Circle::new(0.0, 0.0, 2.0); println!("area is {}", c.area()); // Chaining method calls println!("c2's area is {}", c.grow(2.0).area()); // Builder pattern struct CircleBuilder { x: f64, y: f64, radius: f64, } impl CircleBuilder { fn new() -> CircleBuilder { CircleBuilder { x: 0.0, y: 0.0, radius: 1.0 } } fn x(&mut self, coordinate: f64) -> &mut CircleBuilder { self.x = coordinate; self } fn y(&mut self, coordinate: f64) -> &mut CircleBuilder { self.y = coordinate; self } fn radius(&mut self, coordinate: f64) -> &mut CircleBuilder { self.radius = coordinate; self } fn finalize(&self) -> Circle { Circle::new(self.x, self.y, self.radius) } } let c3 = CircleBuilder::new() .x(3.0) .radius(10.0) .finalize(); println!("area is {}", c3.area()); } fn vectors() { let v = vec![1, 2, 3, 4, 5]; let v2 = vec![0; 10]; // ten zeros println!("the third element is {}", v[2]); // Index is usize type // Iterating for i in &v2 { println!("A reference to {}", i); } } fn strings() { // resizable, a sequence of utf-8 characters, not null terminated // &str is a string slice, has fixed size. let greeting = "Hello there."; // &'static str let s = "foo bar"; let s2 = "foo\ bar"; println!("{}", s); println!("{}", s2); let mut s = "Hello".to_string(); // String s.push_str(", world."); println!("{}", s); // Indexing // because of utf-8 strings do not support indexing let name = "赵洋磊"; for b in name.as_bytes() { print!("{} ", b); } println!(""); for c in name.chars() { print!("{} ", c); } println!(""); // Slicing // but for some reason you can do slicing let last_name = &name[0..3]; // byte offsets, has to end on character boundary println!("{}", last_name); // Concatenation let hello = "Hello ".to_string(); let world = "world!"; let hello_world = hello + world; println!("{}", hello_world); } fn generics() { enum MyOption<T> { // T is just convention. Some(T), None, } let x: MyOption<i32> = MyOption::Some(5); let y: MyOption<f64> = MyOption::Some(10.24); // Also can have mutliple types. // enum Result<A, Z> {} // Generic functions // fn takes_anything<T>(x: T) { // } // Generic structs // struct Point<T> { // x: T, // y: T, // } // impl<T> Point<T> {} } fn traits() { trait HasArea { fn area(&self) -> f64; } struct Circle { radius: f64, } impl HasArea for Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } } struct Square { side: f64, } impl HasArea for Square { fn area(&self) -> f64 { self.side * self.side } } // Trait bounds on generic functions fn print_area<T: HasArea>(shape: T) { println!("This shape has an area of {}", shape.area()); } let c = Circle { radius: 2.0 }; let s = Square { side: 2.0 }; print_area(c); print_area(s); // Trait bounds on generic structs struct Rectangle<T> { width: T, height: T, } impl<T: PartialEq> Rectangle<T> { fn is_square(&self) -> bool { self.width == self.height } } let r = Rectangle { width: 47, height: 47, }; println!("This is a square? {}", r.is_square()); // Rules for implementing traits impl HasArea for i32 { fn area(&self) -> f64 { *self as f64 } } println!("silly {}", 5.area()); // Two rules: // Traits has to be defined in your scope to apply (use "use") // Either the trait, or the type you're writing impl for, must be defined by you. // Mutliple bounds // use + // fn foo<T: Clone + Debug>(x: T) {} // Where clause // syntax sugar // fn foo<T: Clone, K: Clone + Debug>(x: T, y: K) {} // equals // fn bar<T, K>(x: T, y: K) where T: Clone, K: Clone + Debug {} // Default methods trait foo { fn is_valid(&self) -> bool; fn is_invalid(&self) -> bool { !sel
// Inheritance trait bar : foo { fn is_good(&self); } // Deriving #[derive(Debug)] struct Foo; println!("{:?}", Foo); } fn drop() { // A special trait from Rust standard library. When things goes out of scope. struct Firework { strength: i32, }; impl Drop for Firework { fn drop(&mut self) { println!("Dropping {}!", self.strength); } } // First in, last out let small = Firework { strength: 1 }; let big = Firework { strength: 100 }; } fn if_let() { let option = Option::Some(5); if let Some(x) = option { println!("{}", x); } else { println!("Nothing"); } let mut v = vec![1, 3, 5, 7, 11]; while let Some(x) = v.pop() { println!("{}", x); } } fn trait_objects() { trait Foo { fn method(&self) -> String; } impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } } let x = 5u8; let y = "Hello".to_string(); // Static dispatching fn do_something<T: Foo>(x: T) { println!("{}", x.method()); } do_something(x); do_something(y); // Trait objects can store any type that implement the trait. // obtained by casting or coercing // Dynamic dispatching fn do_something_else(x: &Foo) { println!("{}", x.method()); } do_something_else(&x); } fn closures() { // This is a closure: |args| expression let plus_one = |x: i32| x + 1; assert_eq!(2, plus_one(1)); // {} is expression, so multiline closure, arguments/return value don't // have to be annotated, but could let plus_two = |x| -> i32 { let mut result: i32 = x; result += 2; result }; assert_eq!(4, plus_two(2)); let num = 5; // Here plus_num borrows the variable binding num let plus_num = |x: i32| x + num; // move closures // regular closure, which borrows the variable num_a, and modify the // underlying value in the closure. let mut num_a = 5; { let mut add_num = |x: i32| num_a += x; add_num(5); } assert_eq!(10, num_a); // move closures, which creates an copy and takes ownership of the variable let mut num_b = 5; { let mut add_num = move |x: i32| num_b += x; add_num(5); } assert_eq!(5, num_b); // Closures are traits, Fn, FnMut, FnOnce. // The following is statically dispatched fn call_with_one<F>(some_closure: F) -> i32 where F: Fn(i32) -> i32 { some_closure(1) } let answer = call_with_one(|x| x + 2); assert_eq!(3, answer); // This is dynamically dispatched (trait object) fn call_with_two(some_closure: &Fn(i32) -> i32) -> i32 { some_closure(2) } let answer = call_with_two(&|x| x + 2); assert_eq!(4, answer); // How to return a closure fn factory() -> Box<Fn(i32) -> i32> { let num = 5; Box::new(move |x| x + num) } let f = factory(); let answer = f(1); assert_eq!(6, answer); }
f.is_valid() } }
identifier_body
main.rs
use std::cell::Cell; fn main() { variable_bindings(); functions(); primitive_types(); comments(); if_(); loops(); ownership(); reference_and_borrowing(); lifetimes(); mutability(); struct_(); enums(); match_(); patterns(); method_syntax(); vectors(); strings(); generics(); traits(); drop(); if_let(); trait_objects(); closures(); } fn variable_bindings() { // Variable bindings let x = 5; println!("{}", x); // Patterns let (x, y) = (2, 3); println!("{}, {}", x, y); // Type annotation let y: u32 = 10; println!("{}", y); // Mutability let mut x = 10; println!("x is {} before mutation", x); x = 5; println!("x is {} after mutation", x); // Initializing bindings // The following won't compile because x is not initialized. // let x: i32; // println!("{}", x); // Scope and shadowing { println!("x is {} inside the scope, before shadowing", x); let x: u16 = 121; println!("x is {} inside the scope", x); } println!("x is {} outside the scope", x); // Here the variable is no longer mutable let x = x; println!("x is {}", x); } fn functions() { addition(50, 100); println!("{} plus one is {}", 10, add_by_one(10)); // Expression vs statements // expression returns a value, statements don't // This is an declaration statement // let x = 10; // The evaluation of "x = 10" is empty tuple () // Expression statement turns express to statments. println!("{} is even? {}", 3, is_even(3)); // Function pointers let f: fn(i32) -> i32 = add_by_one; println!("Using function pointers {}", f(10)); } fn addition(x: i32, y: i32) { println!("{} + {} = {}", x, y, x + y); } fn add_by_one(x: i32) -> i32 { x + 1 } fn is_even(i: i32) -> bool { if i % 2 == 0 { return true; } false } // Can be used as any type fn diverges() -> ! { loop {}; } fn primitive_types() { // Booleans let x: bool = false; println!("x is {}", x); // char, supports Unicode let x: char = 'A'; println!("x is {}", x); // Numeric values // signed and fixed size let x: i8 = -12; println!("x is {}", x); // unsigned and fixed size let x: u8 = 12; println!("x is {}", x); // variable size (depending on underlying machine size) let x: usize = 1200; println!("x is {}", x); // floating point let x = 1.0; println!("x is {}", x); // Arrays (fixed sized) let a: [u8; 3] = [1, 2, 3]; println!("a[0] is {}", a[0]); // shorthand initialization let a = [100; 20]; println!("a[0] is {}", a[0]); println!("length of a is {}", a.len()); // Slices let complete = &a[..]; println!("length of complete is {}", complete.len()); let some: &[u32] = &a[5..10]; println!("length of some is {}", some.len()); // str // Is an unsized type // Tuples // Ordered list of fixed size let mut x: (i32, &str) = (1, "hello"); let y = (2, "hellos"); x = y; // accessing values in tuple with destructuring let let (number, word) = x; println!("There are {} {}.", number, word); // single element tuple (0,); // Tuple indexing println!("There are {} {}.", x.0, x.1); } /// # Doc comments here /// /// Markdown is supported fn comments() { //! # This documents the containing element //! instead of the following element (0,); // This is a line comment. } fn if_() { let x = 5; if x == 5 { println!("x is five!"); } else if x == 6 { println!("x is six!"); } else { println!("x is not five or six :("); } // if is an expression let y = if x == 6 { 10 } else { 20 }; println!("y is {}", y); } fn loops() { // loop // indefinite loop loop { break; } // while let mut x = 0; while x < 2 { println!("x is now {} in while loop", x); x += 1; } // for // for var in expression { code } for x in 0..5 { println!("x is now {} in for loop", x); } // Enumerate for (i, j) in (5..10).enumerate() { println!("i is {} and j is {}", i, j); } // Ending iteration early // break let mut x = 5; loop { x += x - 3; println!("x is {}", x); if x % 5 == 0 { break; } } // continue for x in 0..10 { if x % 2 == 0 { continue; } println!("x is {}", x); } // Loop labels 'outer: for x in 0..6 { 'inner: for y in 0..6 { if x % 2 == 0 { continue 'outer }; if y % 2 == 0 { continue 'inner }; println!("x is {} and y is {}", x, y); } } } fn ownership() { //! using zero-cost abstractions //! ownership is a primary example of zero-cost abstractions //! all features talked about are done compile time // Vector v will be deallocated deterministically after it goes out of scope // even if it is allocated on the heap let v = vec![1, 2, 3]; // The ownership is transferred to v2 let v2 = v; // println!("v[0] is: {}", v[0]); // This will generate an error. take_ownership(v2); // println!("v2[0] is: {}", v2[0]); // This will also generate an error. // Copy types (trait) let v = 1; let v2 = v; println!("v is {} and v2 is {}", v, v2); } fn take_ownership(v: Vec<i32>) -> i32 { // nothing happens v[0] } fn reference_and_borrowing() { let v = vec![1, 2, 3]; take_reference(&v); println!("v[0] is {}", v[0]); // Mutable reference let mut x = 5; { let y = &mut x; *y += 1; } println!("Mutable x is now {}", x); // The rules // Borrower scope should never lasts longer than the owner // You can only have one or the other type of borrows // Only one mutable reference is allowed } fn take_reference(v: &Vec<i32>) -> i32 { // v[1] = 1; // Reference (borrowed) are immutable. v[0] } fn lifetimes() { explicit_lifetime(&10); function_with_lifetime(); let e = ExplicitLifetime { x: &5 }; println!("{}", e.x()); // Static lifetime for the entire program. let x: &'static str = "Hello World!"; println!("{}", x); // Lifetime Elision // input lifetime: parameter // output lifetime: return value // elide input lifetime and use this to infer output lifetime // 1. each argument has distinct life time // 2. if only one input lifetime, same output lifetime. // 3. if multiple lifetime, but one is "self", lifetime of self for output // otherwise, fail. } fn explicit_lifetime<'a>(x: &'a i32) { println!("x is {}", x); } fn function_with_lifetime<'a, 'b>() { } // The ExplicitLifetime struct cannot outlive the x it contains struct ExplicitLifetime<'a> { x: &'a i32, } impl<'a> ExplicitLifetime<'a> { fn x(&self) -> &'a i32 { self.x } } fn mutability() { // mutable variable binding let mut x = 5; x = 6; println!("{}", x); // mutable reference let mut x = 5; let y = &mut x; // This is immutable reference. *y = 10; println!("y is {}", *y); let mut x = 5; let mut z = 10; let mut y = &mut x; y = &mut z; println!("y is {}", *y); // Interior vs exterior mutability // Field level mutability struct Point { x: i32, y: Cell<i32>, } let point = Point { x: 10, y: Cell::new(10) }; point.y.set(11); println!("point is {}, {:?}", point.x, point.y); } fn struct_() { // Update syntax struct Point3d { x: i32, y: i32, z: i32, } let a = Point3d { x: 1, y: 2, z: 3 }; let b = Point3d { y: 10, .. a }; println!("{}, {}, {}", a.x, a.y, a.z); println!("{}, {}, {}", a.x, b.y, b.z); // Tuple structs // better to use struct than tuple structs struct Color(i32, i32, i32); // "newtype" pattern struct Inches(i32); let length = Inches(10); let Inches(integer_length) = length; println!("length is {} inches", integer_length); // Unit-like struct struct Unit; let x = Unit; } fn enums() { enum Message { Quit, ChangeColor(i32, i32, i32), Move {x: i32, y: i32}, Write(String), } let m1 = Message::Quit; let m2 = Message::Move {x: 10, y: 20}; // Constructor as functions let m3 = Message::Write("Hello World!".to_string()); } fn match_() { let x = 5; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), 4 => println!("four"), 5 => println!("five"), _ => println!("something else"), } let number = match x { 1 => "one", 2 => "two", 5 => "five", _ => "other", }; // Matching on enums enum Message { Quit, Move {x: i32, y: i32}, } let msg = Message::Move {x: 1, y: 2}; match msg { Message::Quit => println!("Quitting"), Message::Move {x: x, y: y} => println!("Moving to {} {}", x, y), } } fn patterns() { let x = "x"; let c = "c"; match c { x => println!("x: {} c: {}", x, c), } println!("x: {}", x); // Multiple patterns match x { "x" | "y" => println!("is x or y"), _ => println!("not x or y"), } // Destrcturing struct Point { x: i32, y: i32, } let origin = Point { x: 0, y: 0 }; match origin { Point { x: x1, .. } => println!("({}, 0)", x1), } // Ignoring bindings // Use _ or .. inside the pattern // ref and ref mut let mut x = 5; match x { ref r => println!("Got a reference to {}", r), } match x { ref mut mr => println!("Got a mutable reference to {}", mr), } // Ranges // Use ..., mostly used with integers and chars // Bindings // Use @ match x { a @ 1 ... 2 | a @ 3 ... 5 => println!("one through five ({}).", a), 6 ... 10 => println!("six through ten"), _ => println!("everything else"), } // Guards enum OptionalInt { Value(i32), Missing, } let x = OptionalInt::Value(5); match x { OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"), OptionalInt::Value(..) => println!("Got an int!"), OptionalInt::Missing => println!("No such luck!"), } } fn method_syntax() { struct Circle { x: f64, y: f64, radius: f64, } impl Circle { // Associated function fn new(x: f64, y: f64, radius: f64) -> Circle { Circle { x: x, y: y, radius: radius, } } fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } fn grow(&self, increment: f64) -> Circle { Circle { x: self.x, y: self.y, radius: self.radius + increment } } } let c = Circle::new(0.0, 0.0, 2.0); println!("area is {}", c.area()); // Chaining method calls println!("c2's area is {}", c.grow(2.0).area()); // Builder pattern struct CircleBuilder { x: f64, y: f64, radius: f64, } impl CircleBuilder { fn new() -> CircleBuilder { CircleBuilder { x: 0.0, y: 0.0, radius: 1.0 } } fn x(&mut self, coordinate: f64) -> &mut CircleBuilder { self.x = coordinate; self } fn y(&mut self, coordinate: f64) -> &mut CircleBuilder { self.y = coordinate; self } fn radius(&mut self, coordinate: f64) -> &mut CircleBuilder { self.radius = coordinate; self } fn finalize(&self) -> Circle { Circle::new(self.x, self.y, self.radius) } } let c3 = CircleBuilder::new() .x(3.0) .radius(10.0) .finalize(); println!("area is {}", c3.area()); } fn vectors() { let v = vec![1, 2, 3, 4, 5]; let v2 = vec![0; 10]; // ten zeros println!("the third element is {}", v[2]); // Index is usize type // Iterating
} } fn strings() { // resizable, a sequence of utf-8 characters, not null terminated // &str is a string slice, has fixed size. let greeting = "Hello there."; // &'static str let s = "foo bar"; let s2 = "foo\ bar"; println!("{}", s); println!("{}", s2); let mut s = "Hello".to_string(); // String s.push_str(", world."); println!("{}", s); // Indexing // because of utf-8 strings do not support indexing let name = "赵洋磊"; for b in name.as_bytes() { print!("{} ", b); } println!(""); for c in name.chars() { print!("{} ", c); } println!(""); // Slicing // but for some reason you can do slicing let last_name = &name[0..3]; // byte offsets, has to end on character boundary println!("{}", last_name); // Concatenation let hello = "Hello ".to_string(); let world = "world!"; let hello_world = hello + world; println!("{}", hello_world); } fn generics() { enum MyOption<T> { // T is just convention. Some(T), None, } let x: MyOption<i32> = MyOption::Some(5); let y: MyOption<f64> = MyOption::Some(10.24); // Also can have mutliple types. // enum Result<A, Z> {} // Generic functions // fn takes_anything<T>(x: T) { // } // Generic structs // struct Point<T> { // x: T, // y: T, // } // impl<T> Point<T> {} } fn traits() { trait HasArea { fn area(&self) -> f64; } struct Circle { radius: f64, } impl HasArea for Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } } struct Square { side: f64, } impl HasArea for Square { fn area(&self) -> f64 { self.side * self.side } } // Trait bounds on generic functions fn print_area<T: HasArea>(shape: T) { println!("This shape has an area of {}", shape.area()); } let c = Circle { radius: 2.0 }; let s = Square { side: 2.0 }; print_area(c); print_area(s); // Trait bounds on generic structs struct Rectangle<T> { width: T, height: T, } impl<T: PartialEq> Rectangle<T> { fn is_square(&self) -> bool { self.width == self.height } } let r = Rectangle { width: 47, height: 47, }; println!("This is a square? {}", r.is_square()); // Rules for implementing traits impl HasArea for i32 { fn area(&self) -> f64 { *self as f64 } } println!("silly {}", 5.area()); // Two rules: // Traits has to be defined in your scope to apply (use "use") // Either the trait, or the type you're writing impl for, must be defined by you. // Mutliple bounds // use + // fn foo<T: Clone + Debug>(x: T) {} // Where clause // syntax sugar // fn foo<T: Clone, K: Clone + Debug>(x: T, y: K) {} // equals // fn bar<T, K>(x: T, y: K) where T: Clone, K: Clone + Debug {} // Default methods trait foo { fn is_valid(&self) -> bool; fn is_invalid(&self) -> bool { !self.is_valid() } } // Inheritance trait bar : foo { fn is_good(&self); } // Deriving #[derive(Debug)] struct Foo; println!("{:?}", Foo); } fn drop() { // A special trait from Rust standard library. When things goes out of scope. struct Firework { strength: i32, }; impl Drop for Firework { fn drop(&mut self) { println!("Dropping {}!", self.strength); } } // First in, last out let small = Firework { strength: 1 }; let big = Firework { strength: 100 }; } fn if_let() { let option = Option::Some(5); if let Some(x) = option { println!("{}", x); } else { println!("Nothing"); } let mut v = vec![1, 3, 5, 7, 11]; while let Some(x) = v.pop() { println!("{}", x); } } fn trait_objects() { trait Foo { fn method(&self) -> String; } impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } } impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } } let x = 5u8; let y = "Hello".to_string(); // Static dispatching fn do_something<T: Foo>(x: T) { println!("{}", x.method()); } do_something(x); do_something(y); // Trait objects can store any type that implement the trait. // obtained by casting or coercing // Dynamic dispatching fn do_something_else(x: &Foo) { println!("{}", x.method()); } do_something_else(&x); } fn closures() { // This is a closure: |args| expression let plus_one = |x: i32| x + 1; assert_eq!(2, plus_one(1)); // {} is expression, so multiline closure, arguments/return value don't // have to be annotated, but could let plus_two = |x| -> i32 { let mut result: i32 = x; result += 2; result }; assert_eq!(4, plus_two(2)); let num = 5; // Here plus_num borrows the variable binding num let plus_num = |x: i32| x + num; // move closures // regular closure, which borrows the variable num_a, and modify the // underlying value in the closure. let mut num_a = 5; { let mut add_num = |x: i32| num_a += x; add_num(5); } assert_eq!(10, num_a); // move closures, which creates an copy and takes ownership of the variable let mut num_b = 5; { let mut add_num = move |x: i32| num_b += x; add_num(5); } assert_eq!(5, num_b); // Closures are traits, Fn, FnMut, FnOnce. // The following is statically dispatched fn call_with_one<F>(some_closure: F) -> i32 where F: Fn(i32) -> i32 { some_closure(1) } let answer = call_with_one(|x| x + 2); assert_eq!(3, answer); // This is dynamically dispatched (trait object) fn call_with_two(some_closure: &Fn(i32) -> i32) -> i32 { some_closure(2) } let answer = call_with_two(&|x| x + 2); assert_eq!(4, answer); // How to return a closure fn factory() -> Box<Fn(i32) -> i32> { let num = 5; Box::new(move |x| x + num) } let f = factory(); let answer = f(1); assert_eq!(6, answer); }
for i in &v2 { println!("A reference to {}", i);
random_line_split
pipes.ts
/*---------------------------------------------------------------app.component.html---------------------------------------*/ <div class="container"> <div class="row"> <label class="col-sm-2">DOB:</label> <input type="date" style="margin-left: 8px;" [(ngModel)]="birthdate"> <div style="margin-left: 8px;"> <strong>{{birthdate | ageCaluclator: birthdate }} </strong> </div> </div> <br> <div class="row"> <label class="col-sm-2"> CC_number:</label> <input type="text" [(ngModel)]="num" placeholder="CreditCard number"> <div style="margin: 8px;"> <strong> {{num | formattingCreditCardNumber:num}}</strong> </div> </div> <br> <div class="row"> <label class="col-sm-2">Account number:</label> <input type="text" [(ngModel)]="Account_balance" placeholder="Account number"> <div> <strong> {{Account_balance | showbalance:Account_balance}}</strong> </div> </div> <br> <div class="row"> <label class="col-sm-2">creditcard number:</label> <input type="text" id="idnum" onkeyup="addHyphen(this)" [(ngModel)]="Limit" placeholder="CreditCard number"> <div> <strong> {{Limit | showbalanceofcreditcardnumber:Limit}}</strong> </div> </div> <br> <div> <h5>Currency conversion</h5> <div> <p> <strong>From : </strong> <select [(ngModel)]="From"> <option *ngFor="let cnt of currency" value={{cnt.id}}>{{cnt.code}}</option> </select> <strong> To : </strong> <select [(ngModel)]="To"> <option *ngFor="let cnt of currency">{{cnt.code}}</option> </select> </p> </div> <div> <p> Enter the amount: <input type="number" placeholder="Enter amount" [(ngModel)]="value"/> </p> </div> <p><strong>The value in {{To}} is {{value | currencyconverter:From:To:value | currency:To}}</strong> </p> </div> </div> /*-----------------------------------------------------------app.component.ts------------------------------------------------------------*/ import { asNativeElements, Component, OnInit} from '@angular/core'; import {Validator,FormBuilder, FormGroup, Validators ,ReactiveFormsModule} from '@angular/forms'; import {ForexserviceService} from './forexservice.service'; import {PaymentPayLoadService} from './payment-pay-load.service'; import { FraudulentPaymentService } from './fraudulent-payment.service'; import {FormControl} from '@angular/forms'; import {NgForm} from '@angular/forms'; import {OneconversionService} from './oneconversion.service'; import {Pipe,PipeTransform} from '@angular/core' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { ngOnInit(): void { } age:number; birthdate:string; num:string; Account_balance:string Limit:string; From:number; To:string; value:number; Result:any; code:string; currency=[ {id:0,code:'AUD'}, {id:1,code:'CAD'}, {id:2,code:'EUR'}, {id:3,code:'GBP'}, {id:4,code:'INR'}, {id:5,code:'NZD'}, {id:6,code:'USD'}, ] } /*---------------------------------------------------------------------c.js-------------------------------------------------------------*/ function addHyphen (element) { let ele = document.getElementById(element.id); ele = ele.value.split('-').join(''); let finalVal = ele.match(/.{1,4}/g).join('-'); document.getElementById(element.id).value = finalVal; } /*-------------------------------------------------------------------app.component.css-------------------------------------------------*/ .container { padding-top: 10%; padding-left: 20%; } /*-------------------------------------------------------------------age-caluclator.pipe.ts--------------------------------------------*/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'ageCaluclator' }) export class AgeCaluclatorPipe implements PipeTransform { transform(value: string, bir:string): string { if(bir!=undefined) { var today= new Date(); const b =new Date(bir) var diff_year=today.getFullYear()-b.getFullYear(); var diff_month=today.getMonth()-b.getMonth(); if(diff_month<0 || (diff_month===0 && today.getDate()<b.getDate())) { diff_year--; } return `Your age is ${diff_year}` } } } /--------------------------------------------------------------------formatting-creditcard-number.pipe.ts-------------------------------------/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'formattingCreditCardNumber' }) export class FormattingCreditCardNumberPipe implements PipeTransform { transform(value: string,n:string): string { if(n!=undefined) { var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '') var matches = value.match(/\d{4,16}/g); var match = matches && matches[0] || '' var parts = [] for (var i=0, len=match.length; i<len; i+=4) { parts.push(match.substring(i, i+4)) } if (parts.length) { return `Formatted credit card number ${parts.join(' ')}` } else
} } } /-----------------------------------------------------------------showbalance.pipe.ts----------------------------------------------------/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'showbalance' }) export class ShowbalancePipe implements PipeTransform { transform(value: string): string { if(value!=undefined) { if(value==='11111111111') { return 'Your balance is $20,000' } } } } /----------------------------------------------------------------showbalanceofcreditcardnumber.pipe.ts--------------------------/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'showbalanceofcreditcardnumber' }) export class ShowbalanceofcreditcardnumberPipe implements PipeTransform { transform(value:string): string { console.log(value) if(value!=undefined) { if(value.length<19) { return ' ' } else if(value==="8888-8888-8888-8888") { return 'you can withdraw 10,000 per day'; } else{ return 'You enterd a invalid credt card number' } } } } /*----------------------------------------------------------------------------currencyconversion.pipe.ts---------------------------------*/ import { Pipe, PipeTransform } from '@angular/core'; import { from } from 'rxjs'; @Pipe({ name: 'currencyconverter' }) export class CurrencyconverterPipe implements PipeTransform { transform(value:number,From:string,To:number): number { if(From!=undefined && To!=undefined && value!=undefined) { var currency_codes=[ {AUD:1,CAD:0.96,EUR:0.61,GBP:0.56,INR:52.62,NZD:1.08,USD:0.72}, //AUD-0(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.05,CAD:1,EUR:0.64,GBP:0.59,INR:55.06,NZD:1.13,USD:0.75}, //CAD-1(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.63,CAD:1.56,EUR:1,GBP:0.91,INR:85.96,NZD:1.77,USD:1.17}, //EUR-2(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.79,CAD:1.71,EUR:1.09,GBP:1,INR:94.02,NZD:1.94,USD:1.29}, //GBP-3(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:0.019,CAD:0.018,EUR:0.012,GBP:0.011,INR:1,NZD:0.021,USD:0.014}, //INR-4(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:0.92,CAD:0.88,EUR:0.57,GBP:0.52,INR:48.56,NZD:1,USD:0.66}, //NZD-5(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.39,CAD:1.333,EUR:0.85,GBP:0.78,INR:73.32,NZD:1.51,USD:1}]; //USD-6(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} var res=currency_codes[From][To]*value; return res } } } /*--------------------------------------------------------------------app.module.ts------------------------------------*/ import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule,ReactiveFormsModule } from '@angular/forms'; import {ForexserviceService} from './forexservice.service'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ChildComponent } from './child/child.component'; import { HttpClientModule} from '@angular/common/http'; import {OneconversionService} from './oneconversion.service'; import { AgeCaluclatorPipe } from './age-caluclator.pipe'; import { FormattingCreditCardNumberPipe } from './formatting-credit-card-number.pipe'; import { CurrencyconverterPipe } from './currencyconverter.pipe'; import { ShowbalancePipe } from './showbalance.pipe'; import { ShowbalanceofcreditcardnumberPipe } from './showbalanceofcreditcardnumber.pipe'; @NgModule({ declarations: [ AppComponent, ChildComponent, AgeCaluclatorPipe, FormattingCreditCardNumberPipe, CurrencyconverterPipe, ShowbalancePipe, ShowbalanceofcreditcardnumberPipe ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule, HttpClientModule ], providers: [ForexserviceService, OneconversionService], bootstrap: [AppComponent] }) export class AppModule { }
{ return `Formateed credit card number ${value}`; }
conditional_block
pipes.ts
/*---------------------------------------------------------------app.component.html---------------------------------------*/ <div class="container"> <div class="row"> <label class="col-sm-2">DOB:</label> <input type="date" style="margin-left: 8px;" [(ngModel)]="birthdate"> <div style="margin-left: 8px;"> <strong>{{birthdate | ageCaluclator: birthdate }} </strong> </div> </div> <br> <div class="row"> <label class="col-sm-2"> CC_number:</label> <input type="text" [(ngModel)]="num" placeholder="CreditCard number"> <div style="margin: 8px;"> <strong> {{num | formattingCreditCardNumber:num}}</strong> </div> </div> <br> <div class="row"> <label class="col-sm-2">Account number:</label> <input type="text" [(ngModel)]="Account_balance" placeholder="Account number"> <div> <strong> {{Account_balance | showbalance:Account_balance}}</strong> </div> </div> <br> <div class="row"> <label class="col-sm-2">creditcard number:</label> <input type="text" id="idnum" onkeyup="addHyphen(this)" [(ngModel)]="Limit" placeholder="CreditCard number"> <div> <strong> {{Limit | showbalanceofcreditcardnumber:Limit}}</strong> </div> </div> <br> <div> <h5>Currency conversion</h5> <div> <p> <strong>From : </strong> <select [(ngModel)]="From"> <option *ngFor="let cnt of currency" value={{cnt.id}}>{{cnt.code}}</option> </select> <strong> To : </strong> <select [(ngModel)]="To"> <option *ngFor="let cnt of currency">{{cnt.code}}</option> </select> </p> </div> <div> <p> Enter the amount: <input type="number" placeholder="Enter amount" [(ngModel)]="value"/> </p> </div> <p><strong>The value in {{To}} is {{value | currencyconverter:From:To:value | currency:To}}</strong> </p> </div> </div> /*-----------------------------------------------------------app.component.ts------------------------------------------------------------*/ import { asNativeElements, Component, OnInit} from '@angular/core'; import {Validator,FormBuilder, FormGroup, Validators ,ReactiveFormsModule} from '@angular/forms'; import {ForexserviceService} from './forexservice.service'; import {PaymentPayLoadService} from './payment-pay-load.service'; import { FraudulentPaymentService } from './fraudulent-payment.service'; import {FormControl} from '@angular/forms'; import {NgForm} from '@angular/forms'; import {OneconversionService} from './oneconversion.service'; import {Pipe,PipeTransform} from '@angular/core' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { ngOnInit(): void { } age:number; birthdate:string; num:string; Account_balance:string Limit:string; From:number; To:string; value:number; Result:any; code:string; currency=[ {id:0,code:'AUD'}, {id:1,code:'CAD'}, {id:2,code:'EUR'}, {id:3,code:'GBP'}, {id:4,code:'INR'}, {id:5,code:'NZD'}, {id:6,code:'USD'}, ] } /*---------------------------------------------------------------------c.js-------------------------------------------------------------*/ function addHyphen (element) { let ele = document.getElementById(element.id); ele = ele.value.split('-').join(''); let finalVal = ele.match(/.{1,4}/g).join('-'); document.getElementById(element.id).value = finalVal; } /*-------------------------------------------------------------------app.component.css-------------------------------------------------*/ .container { padding-top: 10%; padding-left: 20%; } /*-------------------------------------------------------------------age-caluclator.pipe.ts--------------------------------------------*/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'ageCaluclator' }) export class AgeCaluclatorPipe implements PipeTransform {
(value: string, bir:string): string { if(bir!=undefined) { var today= new Date(); const b =new Date(bir) var diff_year=today.getFullYear()-b.getFullYear(); var diff_month=today.getMonth()-b.getMonth(); if(diff_month<0 || (diff_month===0 && today.getDate()<b.getDate())) { diff_year--; } return `Your age is ${diff_year}` } } } /--------------------------------------------------------------------formatting-creditcard-number.pipe.ts-------------------------------------/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'formattingCreditCardNumber' }) export class FormattingCreditCardNumberPipe implements PipeTransform { transform(value: string,n:string): string { if(n!=undefined) { var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '') var matches = value.match(/\d{4,16}/g); var match = matches && matches[0] || '' var parts = [] for (var i=0, len=match.length; i<len; i+=4) { parts.push(match.substring(i, i+4)) } if (parts.length) { return `Formatted credit card number ${parts.join(' ')}` } else { return `Formateed credit card number ${value}`; } } } } /-----------------------------------------------------------------showbalance.pipe.ts----------------------------------------------------/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'showbalance' }) export class ShowbalancePipe implements PipeTransform { transform(value: string): string { if(value!=undefined) { if(value==='11111111111') { return 'Your balance is $20,000' } } } } /----------------------------------------------------------------showbalanceofcreditcardnumber.pipe.ts--------------------------/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'showbalanceofcreditcardnumber' }) export class ShowbalanceofcreditcardnumberPipe implements PipeTransform { transform(value:string): string { console.log(value) if(value!=undefined) { if(value.length<19) { return ' ' } else if(value==="8888-8888-8888-8888") { return 'you can withdraw 10,000 per day'; } else{ return 'You enterd a invalid credt card number' } } } } /*----------------------------------------------------------------------------currencyconversion.pipe.ts---------------------------------*/ import { Pipe, PipeTransform } from '@angular/core'; import { from } from 'rxjs'; @Pipe({ name: 'currencyconverter' }) export class CurrencyconverterPipe implements PipeTransform { transform(value:number,From:string,To:number): number { if(From!=undefined && To!=undefined && value!=undefined) { var currency_codes=[ {AUD:1,CAD:0.96,EUR:0.61,GBP:0.56,INR:52.62,NZD:1.08,USD:0.72}, //AUD-0(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.05,CAD:1,EUR:0.64,GBP:0.59,INR:55.06,NZD:1.13,USD:0.75}, //CAD-1(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.63,CAD:1.56,EUR:1,GBP:0.91,INR:85.96,NZD:1.77,USD:1.17}, //EUR-2(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.79,CAD:1.71,EUR:1.09,GBP:1,INR:94.02,NZD:1.94,USD:1.29}, //GBP-3(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:0.019,CAD:0.018,EUR:0.012,GBP:0.011,INR:1,NZD:0.021,USD:0.014}, //INR-4(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:0.92,CAD:0.88,EUR:0.57,GBP:0.52,INR:48.56,NZD:1,USD:0.66}, //NZD-5(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.39,CAD:1.333,EUR:0.85,GBP:0.78,INR:73.32,NZD:1.51,USD:1}]; //USD-6(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} var res=currency_codes[From][To]*value; return res } } } /*--------------------------------------------------------------------app.module.ts------------------------------------*/ import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule,ReactiveFormsModule } from '@angular/forms'; import {ForexserviceService} from './forexservice.service'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ChildComponent } from './child/child.component'; import { HttpClientModule} from '@angular/common/http'; import {OneconversionService} from './oneconversion.service'; import { AgeCaluclatorPipe } from './age-caluclator.pipe'; import { FormattingCreditCardNumberPipe } from './formatting-credit-card-number.pipe'; import { CurrencyconverterPipe } from './currencyconverter.pipe'; import { ShowbalancePipe } from './showbalance.pipe'; import { ShowbalanceofcreditcardnumberPipe } from './showbalanceofcreditcardnumber.pipe'; @NgModule({ declarations: [ AppComponent, ChildComponent, AgeCaluclatorPipe, FormattingCreditCardNumberPipe, CurrencyconverterPipe, ShowbalancePipe, ShowbalanceofcreditcardnumberPipe ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule, HttpClientModule ], providers: [ForexserviceService, OneconversionService], bootstrap: [AppComponent] }) export class AppModule { }
transform
identifier_name
pipes.ts
/*---------------------------------------------------------------app.component.html---------------------------------------*/ <div class="container"> <div class="row"> <label class="col-sm-2">DOB:</label> <input type="date" style="margin-left: 8px;" [(ngModel)]="birthdate"> <div style="margin-left: 8px;"> <strong>{{birthdate | ageCaluclator: birthdate }} </strong> </div> </div> <br> <div class="row"> <label class="col-sm-2"> CC_number:</label> <input type="text" [(ngModel)]="num" placeholder="CreditCard number"> <div style="margin: 8px;"> <strong> {{num | formattingCreditCardNumber:num}}</strong> </div> </div> <br> <div class="row"> <label class="col-sm-2">Account number:</label> <input type="text" [(ngModel)]="Account_balance" placeholder="Account number"> <div> <strong> {{Account_balance | showbalance:Account_balance}}</strong> </div> </div> <br> <div class="row"> <label class="col-sm-2">creditcard number:</label> <input type="text" id="idnum" onkeyup="addHyphen(this)" [(ngModel)]="Limit" placeholder="CreditCard number"> <div> <strong> {{Limit | showbalanceofcreditcardnumber:Limit}}</strong> </div> </div> <br> <div> <h5>Currency conversion</h5> <div> <p> <strong>From : </strong> <select [(ngModel)]="From"> <option *ngFor="let cnt of currency" value={{cnt.id}}>{{cnt.code}}</option> </select> <strong> To : </strong> <select [(ngModel)]="To"> <option *ngFor="let cnt of currency">{{cnt.code}}</option> </select> </p> </div> <div> <p> Enter the amount: <input type="number" placeholder="Enter amount" [(ngModel)]="value"/> </p> </div> <p><strong>The value in {{To}} is {{value | currencyconverter:From:To:value | currency:To}}</strong> </p> </div> </div> /*-----------------------------------------------------------app.component.ts------------------------------------------------------------*/ import { asNativeElements, Component, OnInit} from '@angular/core'; import {Validator,FormBuilder, FormGroup, Validators ,ReactiveFormsModule} from '@angular/forms'; import {ForexserviceService} from './forexservice.service'; import {PaymentPayLoadService} from './payment-pay-load.service'; import { FraudulentPaymentService } from './fraudulent-payment.service'; import {FormControl} from '@angular/forms'; import {NgForm} from '@angular/forms'; import {OneconversionService} from './oneconversion.service'; import {Pipe,PipeTransform} from '@angular/core' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { ngOnInit(): void { } age:number; birthdate:string; num:string; Account_balance:string Limit:string; From:number; To:string; value:number; Result:any; code:string; currency=[ {id:0,code:'AUD'}, {id:1,code:'CAD'}, {id:2,code:'EUR'}, {id:3,code:'GBP'}, {id:4,code:'INR'}, {id:5,code:'NZD'}, {id:6,code:'USD'}, ] } /*---------------------------------------------------------------------c.js-------------------------------------------------------------*/ function addHyphen (element) { let ele = document.getElementById(element.id); ele = ele.value.split('-').join(''); let finalVal = ele.match(/.{1,4}/g).join('-'); document.getElementById(element.id).value = finalVal; } /*-------------------------------------------------------------------app.component.css-------------------------------------------------*/ .container { padding-top: 10%; padding-left: 20%; } /*-------------------------------------------------------------------age-caluclator.pipe.ts--------------------------------------------*/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'ageCaluclator' }) export class AgeCaluclatorPipe implements PipeTransform { transform(value: string, bir:string): string { if(bir!=undefined) { var today= new Date(); const b =new Date(bir) var diff_year=today.getFullYear()-b.getFullYear(); var diff_month=today.getMonth()-b.getMonth(); if(diff_month<0 || (diff_month===0 && today.getDate()<b.getDate())) { diff_year--; } return `Your age is ${diff_year}` } } } /--------------------------------------------------------------------formatting-creditcard-number.pipe.ts-------------------------------------/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'formattingCreditCardNumber' }) export class FormattingCreditCardNumberPipe implements PipeTransform { transform(value: string,n:string): string { if(n!=undefined) { var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '') var matches = value.match(/\d{4,16}/g); var match = matches && matches[0] || ''
} if (parts.length) { return `Formatted credit card number ${parts.join(' ')}` } else { return `Formateed credit card number ${value}`; } } } } /-----------------------------------------------------------------showbalance.pipe.ts----------------------------------------------------/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'showbalance' }) export class ShowbalancePipe implements PipeTransform { transform(value: string): string { if(value!=undefined) { if(value==='11111111111') { return 'Your balance is $20,000' } } } } /----------------------------------------------------------------showbalanceofcreditcardnumber.pipe.ts--------------------------/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'showbalanceofcreditcardnumber' }) export class ShowbalanceofcreditcardnumberPipe implements PipeTransform { transform(value:string): string { console.log(value) if(value!=undefined) { if(value.length<19) { return ' ' } else if(value==="8888-8888-8888-8888") { return 'you can withdraw 10,000 per day'; } else{ return 'You enterd a invalid credt card number' } } } } /*----------------------------------------------------------------------------currencyconversion.pipe.ts---------------------------------*/ import { Pipe, PipeTransform } from '@angular/core'; import { from } from 'rxjs'; @Pipe({ name: 'currencyconverter' }) export class CurrencyconverterPipe implements PipeTransform { transform(value:number,From:string,To:number): number { if(From!=undefined && To!=undefined && value!=undefined) { var currency_codes=[ {AUD:1,CAD:0.96,EUR:0.61,GBP:0.56,INR:52.62,NZD:1.08,USD:0.72}, //AUD-0(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.05,CAD:1,EUR:0.64,GBP:0.59,INR:55.06,NZD:1.13,USD:0.75}, //CAD-1(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.63,CAD:1.56,EUR:1,GBP:0.91,INR:85.96,NZD:1.77,USD:1.17}, //EUR-2(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.79,CAD:1.71,EUR:1.09,GBP:1,INR:94.02,NZD:1.94,USD:1.29}, //GBP-3(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:0.019,CAD:0.018,EUR:0.012,GBP:0.011,INR:1,NZD:0.021,USD:0.014}, //INR-4(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:0.92,CAD:0.88,EUR:0.57,GBP:0.52,INR:48.56,NZD:1,USD:0.66}, //NZD-5(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.39,CAD:1.333,EUR:0.85,GBP:0.78,INR:73.32,NZD:1.51,USD:1}]; //USD-6(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} var res=currency_codes[From][To]*value; return res } } } /*--------------------------------------------------------------------app.module.ts------------------------------------*/ import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule,ReactiveFormsModule } from '@angular/forms'; import {ForexserviceService} from './forexservice.service'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ChildComponent } from './child/child.component'; import { HttpClientModule} from '@angular/common/http'; import {OneconversionService} from './oneconversion.service'; import { AgeCaluclatorPipe } from './age-caluclator.pipe'; import { FormattingCreditCardNumberPipe } from './formatting-credit-card-number.pipe'; import { CurrencyconverterPipe } from './currencyconverter.pipe'; import { ShowbalancePipe } from './showbalance.pipe'; import { ShowbalanceofcreditcardnumberPipe } from './showbalanceofcreditcardnumber.pipe'; @NgModule({ declarations: [ AppComponent, ChildComponent, AgeCaluclatorPipe, FormattingCreditCardNumberPipe, CurrencyconverterPipe, ShowbalancePipe, ShowbalanceofcreditcardnumberPipe ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule, HttpClientModule ], providers: [ForexserviceService, OneconversionService], bootstrap: [AppComponent] }) export class AppModule { }
var parts = [] for (var i=0, len=match.length; i<len; i+=4) { parts.push(match.substring(i, i+4))
random_line_split
pipes.ts
/*---------------------------------------------------------------app.component.html---------------------------------------*/ <div class="container"> <div class="row"> <label class="col-sm-2">DOB:</label> <input type="date" style="margin-left: 8px;" [(ngModel)]="birthdate"> <div style="margin-left: 8px;"> <strong>{{birthdate | ageCaluclator: birthdate }} </strong> </div> </div> <br> <div class="row"> <label class="col-sm-2"> CC_number:</label> <input type="text" [(ngModel)]="num" placeholder="CreditCard number"> <div style="margin: 8px;"> <strong> {{num | formattingCreditCardNumber:num}}</strong> </div> </div> <br> <div class="row"> <label class="col-sm-2">Account number:</label> <input type="text" [(ngModel)]="Account_balance" placeholder="Account number"> <div> <strong> {{Account_balance | showbalance:Account_balance}}</strong> </div> </div> <br> <div class="row"> <label class="col-sm-2">creditcard number:</label> <input type="text" id="idnum" onkeyup="addHyphen(this)" [(ngModel)]="Limit" placeholder="CreditCard number"> <div> <strong> {{Limit | showbalanceofcreditcardnumber:Limit}}</strong> </div> </div> <br> <div> <h5>Currency conversion</h5> <div> <p> <strong>From : </strong> <select [(ngModel)]="From"> <option *ngFor="let cnt of currency" value={{cnt.id}}>{{cnt.code}}</option> </select> <strong> To : </strong> <select [(ngModel)]="To"> <option *ngFor="let cnt of currency">{{cnt.code}}</option> </select> </p> </div> <div> <p> Enter the amount: <input type="number" placeholder="Enter amount" [(ngModel)]="value"/> </p> </div> <p><strong>The value in {{To}} is {{value | currencyconverter:From:To:value | currency:To}}</strong> </p> </div> </div> /*-----------------------------------------------------------app.component.ts------------------------------------------------------------*/ import { asNativeElements, Component, OnInit} from '@angular/core'; import {Validator,FormBuilder, FormGroup, Validators ,ReactiveFormsModule} from '@angular/forms'; import {ForexserviceService} from './forexservice.service'; import {PaymentPayLoadService} from './payment-pay-load.service'; import { FraudulentPaymentService } from './fraudulent-payment.service'; import {FormControl} from '@angular/forms'; import {NgForm} from '@angular/forms'; import {OneconversionService} from './oneconversion.service'; import {Pipe,PipeTransform} from '@angular/core' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { ngOnInit(): void { } age:number; birthdate:string; num:string; Account_balance:string Limit:string; From:number; To:string; value:number; Result:any; code:string; currency=[ {id:0,code:'AUD'}, {id:1,code:'CAD'}, {id:2,code:'EUR'}, {id:3,code:'GBP'}, {id:4,code:'INR'}, {id:5,code:'NZD'}, {id:6,code:'USD'}, ] } /*---------------------------------------------------------------------c.js-------------------------------------------------------------*/ function addHyphen (element) { let ele = document.getElementById(element.id); ele = ele.value.split('-').join(''); let finalVal = ele.match(/.{1,4}/g).join('-'); document.getElementById(element.id).value = finalVal; } /*-------------------------------------------------------------------app.component.css-------------------------------------------------*/ .container { padding-top: 10%; padding-left: 20%; } /*-------------------------------------------------------------------age-caluclator.pipe.ts--------------------------------------------*/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'ageCaluclator' }) export class AgeCaluclatorPipe implements PipeTransform { transform(value: string, bir:string): string { if(bir!=undefined) { var today= new Date(); const b =new Date(bir) var diff_year=today.getFullYear()-b.getFullYear(); var diff_month=today.getMonth()-b.getMonth(); if(diff_month<0 || (diff_month===0 && today.getDate()<b.getDate())) { diff_year--; } return `Your age is ${diff_year}` } } } /--------------------------------------------------------------------formatting-creditcard-number.pipe.ts-------------------------------------/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'formattingCreditCardNumber' }) export class FormattingCreditCardNumberPipe implements PipeTransform { transform(value: string,n:string): string { if(n!=undefined) { var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '') var matches = value.match(/\d{4,16}/g); var match = matches && matches[0] || '' var parts = [] for (var i=0, len=match.length; i<len; i+=4) { parts.push(match.substring(i, i+4)) } if (parts.length) { return `Formatted credit card number ${parts.join(' ')}` } else { return `Formateed credit card number ${value}`; } } } } /-----------------------------------------------------------------showbalance.pipe.ts----------------------------------------------------/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'showbalance' }) export class ShowbalancePipe implements PipeTransform { transform(value: string): string { if(value!=undefined) { if(value==='11111111111') { return 'Your balance is $20,000' } } } } /----------------------------------------------------------------showbalanceofcreditcardnumber.pipe.ts--------------------------/ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'showbalanceofcreditcardnumber' }) export class ShowbalanceofcreditcardnumberPipe implements PipeTransform { transform(value:string): string
} /*----------------------------------------------------------------------------currencyconversion.pipe.ts---------------------------------*/ import { Pipe, PipeTransform } from '@angular/core'; import { from } from 'rxjs'; @Pipe({ name: 'currencyconverter' }) export class CurrencyconverterPipe implements PipeTransform { transform(value:number,From:string,To:number): number { if(From!=undefined && To!=undefined && value!=undefined) { var currency_codes=[ {AUD:1,CAD:0.96,EUR:0.61,GBP:0.56,INR:52.62,NZD:1.08,USD:0.72}, //AUD-0(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.05,CAD:1,EUR:0.64,GBP:0.59,INR:55.06,NZD:1.13,USD:0.75}, //CAD-1(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.63,CAD:1.56,EUR:1,GBP:0.91,INR:85.96,NZD:1.77,USD:1.17}, //EUR-2(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.79,CAD:1.71,EUR:1.09,GBP:1,INR:94.02,NZD:1.94,USD:1.29}, //GBP-3(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:0.019,CAD:0.018,EUR:0.012,GBP:0.011,INR:1,NZD:0.021,USD:0.014}, //INR-4(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:0.92,CAD:0.88,EUR:0.57,GBP:0.52,INR:48.56,NZD:1,USD:0.66}, //NZD-5(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} {AUD:1.39,CAD:1.333,EUR:0.85,GBP:0.78,INR:73.32,NZD:1.51,USD:1}]; //USD-6(Id) to {AUD,CAD,EUR,GBP,INR,NZD,USD} var res=currency_codes[From][To]*value; return res } } } /*--------------------------------------------------------------------app.module.ts------------------------------------*/ import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule,ReactiveFormsModule } from '@angular/forms'; import {ForexserviceService} from './forexservice.service'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ChildComponent } from './child/child.component'; import { HttpClientModule} from '@angular/common/http'; import {OneconversionService} from './oneconversion.service'; import { AgeCaluclatorPipe } from './age-caluclator.pipe'; import { FormattingCreditCardNumberPipe } from './formatting-credit-card-number.pipe'; import { CurrencyconverterPipe } from './currencyconverter.pipe'; import { ShowbalancePipe } from './showbalance.pipe'; import { ShowbalanceofcreditcardnumberPipe } from './showbalanceofcreditcardnumber.pipe'; @NgModule({ declarations: [ AppComponent, ChildComponent, AgeCaluclatorPipe, FormattingCreditCardNumberPipe, CurrencyconverterPipe, ShowbalancePipe, ShowbalanceofcreditcardnumberPipe ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule, HttpClientModule ], providers: [ForexserviceService, OneconversionService], bootstrap: [AppComponent] }) export class AppModule { }
{ console.log(value) if(value!=undefined) { if(value.length<19) { return ' ' } else if(value==="8888-8888-8888-8888") { return 'you can withdraw 10,000 per day'; } else{ return 'You enterd a invalid credt card number' } } }
identifier_body
task.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/cloud/tasks/v2beta3/task.proto package tasks // import "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import duration "github.com/golang/protobuf/ptypes/duration" import timestamp "github.com/golang/protobuf/ptypes/timestamp" import _ "google.golang.org/genproto/googleapis/api/annotations" import status "google.golang.org/genproto/googleapis/rpc/status" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // The view specifies a subset of [Task][google.cloud.tasks.v2beta3.Task] data. // // When a task is returned in a response, not all // information is retrieved by default because some data, such as // payloads, might be desirable to return only when needed because // of its large size or because of the sensitivity of data that it // contains. type Task_View int32 const ( // Unspecified. Defaults to BASIC. Task_VIEW_UNSPECIFIED Task_View = 0 // The basic view omits fields which can be large or can contain // sensitive data. // // This view does not include the // [body in AppEngineHttpRequest][google.cloud.tasks.v2beta3.AppEngineHttpRequest.body]. // Bodies are desirable to return only when needed, because they // can be large and because of the sensitivity of the data that you // choose to store in it. Task_BASIC Task_View = 1 // All information is returned. // // Authorization for [FULL][google.cloud.tasks.v2beta3.Task.View.FULL] requires // `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) // permission on the [Queue][google.cloud.tasks.v2beta3.Queue] resource. Task_FULL Task_View = 2 ) var Task_View_name = map[int32]string{ 0: "VIEW_UNSPECIFIED", 1: "BASIC", 2: "FULL", } var Task_View_value = map[string]int32{ "VIEW_UNSPECIFIED": 0, "BASIC": 1, "FULL": 2, } func (x Task_View) String() string { return proto.EnumName(Task_View_name, int32(x)) } func (Task_View) EnumDescriptor() ([]byte, []int)
// A unit of scheduled work. type Task struct { // Optionally caller-specified in [CreateTask][google.cloud.tasks.v2beta3.CloudTasks.CreateTask]. // // The task name. // // The task name must have the following format: // `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` // // * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), // hyphens (-), colons (:), or periods (.). // For more information, see // [Identifying // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) // * `LOCATION_ID` is the canonical ID for the task's location. // The list of available locations can be obtained by calling // [ListLocations][google.cloud.location.Locations.ListLocations]. // For more information, see https://cloud.google.com/about/locations/. // * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or // hyphens (-). The maximum length is 100 characters. // * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), // hyphens (-), or underscores (_). The maximum length is 500 characters. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. The message to send to the worker. // // Types that are valid to be assigned to PayloadType: // *Task_AppEngineHttpRequest // *Task_HttpRequest PayloadType isTask_PayloadType `protobuf_oneof:"payload_type"` // The time when the task is scheduled to be attempted. // // For App Engine queues, this is when the task will be attempted or retried. // // `schedule_time` will be truncated to the nearest microsecond. ScheduleTime *timestamp.Timestamp `protobuf:"bytes,4,opt,name=schedule_time,json=scheduleTime,proto3" json:"schedule_time,omitempty"` // Output only. The time that the task was created. // // `create_time` will be truncated to the nearest second. CreateTime *timestamp.Timestamp `protobuf:"bytes,5,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` // The deadline for requests sent to the worker. If the worker does not // respond by this deadline then the request is cancelled and the attempt // is marked as a `DEADLINE_EXCEEDED` failure. Cloud Tasks will retry the // task according to the [RetryConfig][google.cloud.tasks.v2beta3.RetryConfig]. // // Note that when the request is cancelled, Cloud Tasks will stop listing for // the response, but whether the worker stops processing depends on the // worker. For example, if the worker is stuck, it may not react to cancelled // requests. // // The default and maximum values depend on the type of request: // // * For [HTTP tasks][google.cloud.tasks.v2beta3.HttpRequest], the default is // 10 minutes. // The deadline must be in the interval [15 seconds, 30 minutes]. // // * For [App Engine tasks][google.cloud.tasks.v2beta3.AppEngineHttpRequest], 0 indicates that the // request has the default deadline. The default deadline depends on the // [scaling type](https://cloud.google.com/appengine/docs/standard/go/how-instances-are-managed#instance_scaling) // of the service: 10 minutes for standard apps with automatic scaling, 24 // hours for standard apps with manual and basic scaling, and 60 minutes for // flex apps. If the request deadline is set, it must be in the interval [15 // seconds, 24 hours 15 seconds]. Regardless of the task's // `dispatch_deadline`, the app handler will not run for longer than than // the service's timeout. We recommend setting the `dispatch_deadline` to // at most a few seconds more than the app handler's timeout. For more // information see // [Timeouts](https://cloud.google.com/tasks/docs/creating-appengine-handlers#timeouts). // // `dispatch_deadline` will be truncated to the nearest millisecond. The // deadline is an approximate deadline. DispatchDeadline *duration.Duration `protobuf:"bytes,12,opt,name=dispatch_deadline,json=dispatchDeadline,proto3" json:"dispatch_deadline,omitempty"` // Output only. The number of attempts dispatched. // // This count includes attempts which have been dispatched but haven't // received a response. DispatchCount int32 `protobuf:"varint,6,opt,name=dispatch_count,json=dispatchCount,proto3" json:"dispatch_count,omitempty"` // Output only. The number of attempts which have received a response. ResponseCount int32 `protobuf:"varint,7,opt,name=response_count,json=responseCount,proto3" json:"response_count,omitempty"` // Output only. The status of the task's first attempt. // // Only [dispatch_time][google.cloud.tasks.v2beta3.Attempt.dispatch_time] will be set. // The other [Attempt][google.cloud.tasks.v2beta3.Attempt] information is not retained by Cloud Tasks. FirstAttempt *Attempt `protobuf:"bytes,8,opt,name=first_attempt,json=firstAttempt,proto3" json:"first_attempt,omitempty"` // Output only. The status of the task's last attempt. LastAttempt *Attempt `protobuf:"bytes,9,opt,name=last_attempt,json=lastAttempt,proto3" json:"last_attempt,omitempty"` // Output only. The view specifies which subset of the [Task][google.cloud.tasks.v2beta3.Task] has // been returned. View Task_View `protobuf:"varint,10,opt,name=view,proto3,enum=google.cloud.tasks.v2beta3.Task_View" json:"view,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Task) Reset() { *m = Task{} } func (m *Task) String() string { return proto.CompactTextString(m) } func (*Task) ProtoMessage() {} func (*Task) Descriptor() ([]byte, []int) { return fileDescriptor_task_e4ac2456a2f2128b, []int{0} } func (m *Task) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Task.Unmarshal(m, b) } func (m *Task) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Task.Marshal(b, m, deterministic) } func (dst *Task) XXX_Merge(src proto.Message) { xxx_messageInfo_Task.Merge(dst, src) } func (m *Task) XXX_Size() int { return xxx_messageInfo_Task.Size(m) } func (m *Task) XXX_DiscardUnknown() { xxx_messageInfo_Task.DiscardUnknown(m) } var xxx_messageInfo_Task proto.InternalMessageInfo func (m *Task) GetName() string { if m != nil { return m.Name } return "" } type isTask_PayloadType interface { isTask_PayloadType() } type Task_AppEngineHttpRequest struct { AppEngineHttpRequest *AppEngineHttpRequest `protobuf:"bytes,3,opt,name=app_engine_http_request,json=appEngineHttpRequest,proto3,oneof"` } type Task_HttpRequest struct { HttpRequest *HttpRequest `protobuf:"bytes,11,opt,name=http_request,json=httpRequest,proto3,oneof"` } func (*Task_AppEngineHttpRequest) isTask_PayloadType() {} func (*Task_HttpRequest) isTask_PayloadType() {} func (m *Task) GetPayloadType() isTask_PayloadType { if m != nil { return m.PayloadType } return nil } func (m *Task) GetAppEngineHttpRequest() *AppEngineHttpRequest { if x, ok := m.GetPayloadType().(*Task_AppEngineHttpRequest); ok { return x.AppEngineHttpRequest } return nil } func (m *Task) GetHttpRequest() *HttpRequest { if x, ok := m.GetPayloadType().(*Task_HttpRequest); ok { return x.HttpRequest } return nil } func (m *Task) GetScheduleTime() *timestamp.Timestamp { if m != nil { return m.ScheduleTime } return nil } func (m *Task) GetCreateTime() *timestamp.Timestamp { if m != nil { return m.CreateTime } return nil } func (m *Task) GetDispatchDeadline() *duration.Duration { if m != nil { return m.DispatchDeadline } return nil } func (m *Task) GetDispatchCount() int32 { if m != nil { return m.DispatchCount } return 0 } func (m *Task) GetResponseCount() int32 { if m != nil { return m.ResponseCount } return 0 } func (m *Task) GetFirstAttempt() *Attempt { if m != nil { return m.FirstAttempt } return nil } func (m *Task) GetLastAttempt() *Attempt { if m != nil { return m.LastAttempt } return nil } func (m *Task) GetView() Task_View { if m != nil { return m.View } return Task_VIEW_UNSPECIFIED } // XXX_OneofFuncs is for the internal use of the proto package. func (*Task) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Task_OneofMarshaler, _Task_OneofUnmarshaler, _Task_OneofSizer, []interface{}{ (*Task_AppEngineHttpRequest)(nil), (*Task_HttpRequest)(nil), } } func _Task_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Task) // payload_type switch x := m.PayloadType.(type) { case *Task_AppEngineHttpRequest: b.EncodeVarint(3<<3 | proto.WireBytes) if err := b.EncodeMessage(x.AppEngineHttpRequest); err != nil { return err } case *Task_HttpRequest: b.EncodeVarint(11<<3 | proto.WireBytes) if err := b.EncodeMessage(x.HttpRequest); err != nil { return err } case nil: default: return fmt.Errorf("Task.PayloadType has unexpected type %T", x) } return nil } func _Task_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Task) switch tag { case 3: // payload_type.app_engine_http_request if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(AppEngineHttpRequest) err := b.DecodeMessage(msg) m.PayloadType = &Task_AppEngineHttpRequest{msg} return true, err case 11: // payload_type.http_request if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(HttpRequest) err := b.DecodeMessage(msg) m.PayloadType = &Task_HttpRequest{msg} return true, err default: return false, nil } } func _Task_OneofSizer(msg proto.Message) (n int) { m := msg.(*Task) // payload_type switch x := m.PayloadType.(type) { case *Task_AppEngineHttpRequest: s := proto.Size(x.AppEngineHttpRequest) n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case *Task_HttpRequest: s := proto.Size(x.HttpRequest) n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } // The status of a task attempt. type Attempt struct { // Output only. The time that this attempt was scheduled. // // `schedule_time` will be truncated to the nearest microsecond. ScheduleTime *timestamp.Timestamp `protobuf:"bytes,1,opt,name=schedule_time,json=scheduleTime,proto3" json:"schedule_time,omitempty"` // Output only. The time that this attempt was dispatched. // // `dispatch_time` will be truncated to the nearest microsecond. DispatchTime *timestamp.Timestamp `protobuf:"bytes,2,opt,name=dispatch_time,json=dispatchTime,proto3" json:"dispatch_time,omitempty"` // Output only. The time that this attempt response was received. // // `response_time` will be truncated to the nearest microsecond. ResponseTime *timestamp.Timestamp `protobuf:"bytes,3,opt,name=response_time,json=responseTime,proto3" json:"response_time,omitempty"` // Output only. The response from the worker for this attempt. // // If `response_time` is unset, then the task has not been attempted or is // currently running and the `response_status` field is meaningless. ResponseStatus *status.Status `protobuf:"bytes,4,opt,name=response_status,json=responseStatus,proto3" json:"response_status,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Attempt) Reset() { *m = Attempt{} } func (m *Attempt) String() string { return proto.CompactTextString(m) } func (*Attempt) ProtoMessage() {} func (*Attempt) Descriptor() ([]byte, []int) { return fileDescriptor_task_e4ac2456a2f2128b, []int{1} } func (m *Attempt) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Attempt.Unmarshal(m, b) } func (m *Attempt) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Attempt.Marshal(b, m, deterministic) } func (dst *Attempt) XXX_Merge(src proto.Message) { xxx_messageInfo_Attempt.Merge(dst, src) } func (m *Attempt) XXX_Size() int { return xxx_messageInfo_Attempt.Size(m) } func (m *Attempt) XXX_DiscardUnknown() { xxx_messageInfo_Attempt.DiscardUnknown(m) } var xxx_messageInfo_Attempt proto.InternalMessageInfo func (m *Attempt) GetScheduleTime() *timestamp.Timestamp { if m != nil { return m.ScheduleTime } return nil } func (m *Attempt) GetDispatchTime() *timestamp.Timestamp { if m != nil { return m.DispatchTime } return nil } func (m *Attempt) GetResponseTime() *timestamp.Timestamp { if m != nil { return m.ResponseTime } return nil } func (m *Attempt) GetResponseStatus() *status.Status { if m != nil { return m.ResponseStatus } return nil } func init() { proto.RegisterType((*Task)(nil), "google.cloud.tasks.v2beta3.Task") proto.RegisterType((*Attempt)(nil), "google.cloud.tasks.v2beta3.Attempt") proto.RegisterEnum("google.cloud.tasks.v2beta3.Task_View", Task_View_name, Task_View_value) } func init() { proto.RegisterFile("google/cloud/tasks/v2beta3/task.proto", fileDescriptor_task_e4ac2456a2f2128b) } var fileDescriptor_task_e4ac2456a2f2128b = []byte{ // 589 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xdf, 0x4f, 0xdb, 0x30, 0x10, 0xc7, 0x09, 0xa4, 0x40, 0xdd, 0xd0, 0x75, 0x16, 0x12, 0x59, 0x35, 0xb1, 0xaa, 0x53, 0x45, 0x9f, 0x92, 0xad, 0x3c, 0x4d, 0x3c, 0x54, 0xf4, 0x97, 0x5a, 0xa9, 0x9a, 0xaa, 0x14, 0x98, 0xb4, 0x97, 0xc8, 0x4d, 0x4c, 0x1a, 0x91, 0xda, 0x5e, 0xec, 0x80, 0xf8, 0x13, 0xf6, 0x17, 0xef, 0x75, 0x8a, 0x63, 0x57, 0x30, 0x58, 0xbb, 0xbd, 0xf5, 0xee, 0xbe, 0xdf, 0x4f, 0x2f, 0x77, 0x97, 0x80, 0x56, 0x44, 0x69, 0x94, 0x60, 0x37, 0x48, 0x68, 0x16, 0xba, 0x02, 0xf1, 0x3b, 0xee, 0xde, 0x77, 0x16, 0x58, 0xa0, 0x73, 0x19, 0x39, 0x2c, 0xa5, 0x82, 0xc2, 0x7a, 0x21, 0x73, 0xa4, 0xcc, 0x91, 0x32, 0x47, 0xc9, 0xea, 0xef, 0x15, 0x02, 0xb1, 0xd8, 0x45, 0x84, 0x50, 0x81, 0x44, 0x4c, 0x09, 0x2f, 0x9c, 0xf5, 0xb3, 0x8d, 0x7f, 0x90, 0x46, 0x58, 0x28, 0xe1, 0xa9, 0x12, 0xca, 0x68, 0x91, 0xdd, 0xba, 0x61, 0x96, 0x4a, 0x92, 0xaa, 0x7f, 0xf8, 0xb3, 0x2e, 0xe2, 0x15, 0xe6, 0x02, 0xad, 0x98, 0x12, 0x9c, 0x28, 0x41, 0xca, 0x02, 0x97, 0x0b, 0x24, 0x32, 0xd5, 0x42, 0xf3, 0x57, 0x09, 0x98, 0x57, 0x88, 0xdf, 0x41, 0x08, 0x4c, 0x82, 0x56, 0xd8, 0x36, 0x1a, 0x46, 0xbb, 0xec, 0xc9, 0xdf, 0x30, 0x06, 0x27, 0x88, 0x31, 0x1f, 0x93, 0x28, 0x26, 0xd8, 0x5f, 0x0a, 0xc1, 0xfc, 0x14, 0xff, 0xc8, 0x30, 0x17, 0xf6, 0x5e, 0xc3, 0x68, 0x57, 0x3a, 0x9f, 0x9c, 0xbf, 0x3f, 0xbb, 0x73, 0xc9, 0xd8, 0x50, 0x3a, 0xc7, 0x42, 0x30, 0xaf, 0xf0, 0x8d, 0x77, 0xbc, 0x63, 0xf4, 0x4a, 0x1e, 0x4e, 0x81, 0xf5, 0x8c, 0x5f, 0x91, 0xfc, 0xb3, 0x4d, 0xfc, 0xe7, 0xd8, 0xca, 0xf2, 0x09, 0xad, 0x0b, 0x8e, 0x78, 0xb0, 0xc4, 0x61, 0x96, 0x60, 0x3f, 0x1f, 0x85, 0x6d, 0x4a, 0x5c, 0x5d, 0xe3, 0xf4, 0x9c, 0x9c, 0x2b, 0x3d, 0x27, 0xcf, 0xd2, 0x86, 0x3c, 0x05, 0x2f, 0x40, 0x25, 0x48, 0x31, 0x12, 0xca, 0x5e, 0xda, 0x6a, 0x07, 0x85, 0x5c, 0x9a, 0x47, 0xe0, 0x6d, 0x18, 0x73, 0x86, 0x44, 0xb0, 0xf4, 0x43, 0x8c, 0xc2, 0x24, 0x26, 0xd8, 0xb6, 0x24, 0xe2, 0xdd, 0x0b, 0xc4, 0x40, 0x6d, 0xd2, 0xab, 0x69, 0xcf, 0x40, 0x59, 0x60, 0x0b, 0x54, 0xd7, 0x9c, 0x80, 0x66, 0x44, 0xd8, 0xfb, 0x0d, 0xa3, 0x5d, 0xf2, 0x8e, 0x74, 0xb6, 0x9f, 0x27, 0x73, 0x59, 0x8a, 0x39, 0xa3, 0x84, 0x63, 0x25, 0x3b, 0x28, 0x64, 0x3a, 0x5b, 0xc8, 0xc6, 0xe0, 0xe8, 0x36, 0x4e, 0xb9, 0xf0, 0x91, 0x10, 0x78, 0xc5, 0x84, 0x7d, 0x28, 0x3b, 0xfa, 0xb8, 0x71, 0x85, 0x85, 0xd4, 0xb3, 0xa4, 0x53, 0x45, 0x70, 0x04, 0xac, 0x04, 0x3d, 0x01, 0x95, 0xff, 0x1d, 0x54, 0xc9, 0x8d, 0x9a, 0xf3, 0x05, 0x98, 0xf7, 0x31, 0x7e, 0xb0, 0x41, 0xc3, 0x68, 0x57, 0x3b, 0xad, 0x4d, 0xfe, 0xfc, 0x44, 0x9d, 0x9b, 0x18, 0x3f, 0x78, 0xd2, 0xd2, 0xfc, 0x0c, 0xcc, 0x3c, 0x82, 0xc7, 0xa0, 0x76, 0x33, 0x19, 0x7e, 0xf3, 0xaf, 0xbf, 0xce, 0x67, 0xc3, 0xfe, 0x64, 0x34, 0x19, 0x0e, 0x6a, 0x3b, 0xb0, 0x0c, 0x4a, 0xbd, 0xcb, 0xf9, 0xa4, 0x5f, 0x33, 0xe0, 0x21, 0x30, 0x47, 0xd7, 0xd3, 0x69, 0x6d, 0xb7, 0x57, 0x05, 0x16, 0x43, 0x8f, 0x09, 0x45, 0xa1, 0x2f, 0x1e, 0x19, 0x6e, 0xfe, 0xdc, 0x05, 0x07, 0xba, 0x93, 0x17, 0xf7, 0x62, 0xfc, 0xe7, 0xbd, 0x74, 0xc1, 0x7a, 0x29, 0x05, 0x60, 0x77, 0x3b, 0x40, 0x1b, 0x34, 0x60, 0xbd, 0x44, 0x09, 0xd8, 0xdb, 0x0e, 0xd0, 0x06, 0x75, 0xb1, 0x6f, 0xd6, 0x80, 0xe2, 0x0d, 0x57, 0x47, 0x0f, 0x35, 0x22, 0x65, 0x81, 0x33, 0x97, 0x15, 0x6f, 0x7d, 0x30, 0x45, 0xdc, 0x23, 0xe0, 0x34, 0xa0, 0xab, 0x0d, 0x0b, 0xe8, 0x95, 0xf3, 0x0d, 0xcc, 0xf2, 0x26, 0x66, 0xc6, 0xf7, 0xae, 0x12, 0x46, 0x34, 0x41, 0x24, 0x72, 0x68, 0x1a, 0xb9, 0x11, 0x26, 0xb2, 0x45, 0xb7, 0x28, 0x21, 0x16, 0xf3, 0xd7, 0x3e, 0x6b, 0x17, 0x32, 0x5a, 0xec, 0x4b, 0xed, 0xf9, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0xa8, 0x61, 0xbf, 0x79, 0x62, 0x05, 0x00, 0x00, }
{ return fileDescriptor_task_e4ac2456a2f2128b, []int{0, 0} }
identifier_body
task.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/cloud/tasks/v2beta3/task.proto package tasks // import "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import duration "github.com/golang/protobuf/ptypes/duration" import timestamp "github.com/golang/protobuf/ptypes/timestamp" import _ "google.golang.org/genproto/googleapis/api/annotations" import status "google.golang.org/genproto/googleapis/rpc/status" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // The view specifies a subset of [Task][google.cloud.tasks.v2beta3.Task] data. // // When a task is returned in a response, not all // information is retrieved by default because some data, such as // payloads, might be desirable to return only when needed because // of its large size or because of the sensitivity of data that it // contains. type Task_View int32 const ( // Unspecified. Defaults to BASIC. Task_VIEW_UNSPECIFIED Task_View = 0 // The basic view omits fields which can be large or can contain // sensitive data. // // This view does not include the // [body in AppEngineHttpRequest][google.cloud.tasks.v2beta3.AppEngineHttpRequest.body]. // Bodies are desirable to return only when needed, because they // can be large and because of the sensitivity of the data that you // choose to store in it. Task_BASIC Task_View = 1 // All information is returned. // // Authorization for [FULL][google.cloud.tasks.v2beta3.Task.View.FULL] requires // `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) // permission on the [Queue][google.cloud.tasks.v2beta3.Queue] resource. Task_FULL Task_View = 2 ) var Task_View_name = map[int32]string{ 0: "VIEW_UNSPECIFIED", 1: "BASIC", 2: "FULL", } var Task_View_value = map[string]int32{ "VIEW_UNSPECIFIED": 0, "BASIC": 1, "FULL": 2, } func (x Task_View) String() string { return proto.EnumName(Task_View_name, int32(x)) } func (Task_View) EnumDescriptor() ([]byte, []int) { return fileDescriptor_task_e4ac2456a2f2128b, []int{0, 0} } // A unit of scheduled work. type Task struct { // Optionally caller-specified in [CreateTask][google.cloud.tasks.v2beta3.CloudTasks.CreateTask]. // // The task name. // // The task name must have the following format: // `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` // // * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), // hyphens (-), colons (:), or periods (.). // For more information, see // [Identifying // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) // * `LOCATION_ID` is the canonical ID for the task's location. // The list of available locations can be obtained by calling // [ListLocations][google.cloud.location.Locations.ListLocations]. // For more information, see https://cloud.google.com/about/locations/. // * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or // hyphens (-). The maximum length is 100 characters. // * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), // hyphens (-), or underscores (_). The maximum length is 500 characters. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. The message to send to the worker. // // Types that are valid to be assigned to PayloadType: // *Task_AppEngineHttpRequest // *Task_HttpRequest PayloadType isTask_PayloadType `protobuf_oneof:"payload_type"` // The time when the task is scheduled to be attempted. // // For App Engine queues, this is when the task will be attempted or retried. // // `schedule_time` will be truncated to the nearest microsecond. ScheduleTime *timestamp.Timestamp `protobuf:"bytes,4,opt,name=schedule_time,json=scheduleTime,proto3" json:"schedule_time,omitempty"` // Output only. The time that the task was created. // // `create_time` will be truncated to the nearest second. CreateTime *timestamp.Timestamp `protobuf:"bytes,5,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` // The deadline for requests sent to the worker. If the worker does not // respond by this deadline then the request is cancelled and the attempt // is marked as a `DEADLINE_EXCEEDED` failure. Cloud Tasks will retry the // task according to the [RetryConfig][google.cloud.tasks.v2beta3.RetryConfig]. // // Note that when the request is cancelled, Cloud Tasks will stop listing for // the response, but whether the worker stops processing depends on the // worker. For example, if the worker is stuck, it may not react to cancelled
// requests. // // The default and maximum values depend on the type of request: // // * For [HTTP tasks][google.cloud.tasks.v2beta3.HttpRequest], the default is // 10 minutes. // The deadline must be in the interval [15 seconds, 30 minutes]. // // * For [App Engine tasks][google.cloud.tasks.v2beta3.AppEngineHttpRequest], 0 indicates that the // request has the default deadline. The default deadline depends on the // [scaling type](https://cloud.google.com/appengine/docs/standard/go/how-instances-are-managed#instance_scaling) // of the service: 10 minutes for standard apps with automatic scaling, 24 // hours for standard apps with manual and basic scaling, and 60 minutes for // flex apps. If the request deadline is set, it must be in the interval [15 // seconds, 24 hours 15 seconds]. Regardless of the task's // `dispatch_deadline`, the app handler will not run for longer than than // the service's timeout. We recommend setting the `dispatch_deadline` to // at most a few seconds more than the app handler's timeout. For more // information see // [Timeouts](https://cloud.google.com/tasks/docs/creating-appengine-handlers#timeouts). // // `dispatch_deadline` will be truncated to the nearest millisecond. The // deadline is an approximate deadline. DispatchDeadline *duration.Duration `protobuf:"bytes,12,opt,name=dispatch_deadline,json=dispatchDeadline,proto3" json:"dispatch_deadline,omitempty"` // Output only. The number of attempts dispatched. // // This count includes attempts which have been dispatched but haven't // received a response. DispatchCount int32 `protobuf:"varint,6,opt,name=dispatch_count,json=dispatchCount,proto3" json:"dispatch_count,omitempty"` // Output only. The number of attempts which have received a response. ResponseCount int32 `protobuf:"varint,7,opt,name=response_count,json=responseCount,proto3" json:"response_count,omitempty"` // Output only. The status of the task's first attempt. // // Only [dispatch_time][google.cloud.tasks.v2beta3.Attempt.dispatch_time] will be set. // The other [Attempt][google.cloud.tasks.v2beta3.Attempt] information is not retained by Cloud Tasks. FirstAttempt *Attempt `protobuf:"bytes,8,opt,name=first_attempt,json=firstAttempt,proto3" json:"first_attempt,omitempty"` // Output only. The status of the task's last attempt. LastAttempt *Attempt `protobuf:"bytes,9,opt,name=last_attempt,json=lastAttempt,proto3" json:"last_attempt,omitempty"` // Output only. The view specifies which subset of the [Task][google.cloud.tasks.v2beta3.Task] has // been returned. View Task_View `protobuf:"varint,10,opt,name=view,proto3,enum=google.cloud.tasks.v2beta3.Task_View" json:"view,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Task) Reset() { *m = Task{} } func (m *Task) String() string { return proto.CompactTextString(m) } func (*Task) ProtoMessage() {} func (*Task) Descriptor() ([]byte, []int) { return fileDescriptor_task_e4ac2456a2f2128b, []int{0} } func (m *Task) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Task.Unmarshal(m, b) } func (m *Task) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Task.Marshal(b, m, deterministic) } func (dst *Task) XXX_Merge(src proto.Message) { xxx_messageInfo_Task.Merge(dst, src) } func (m *Task) XXX_Size() int { return xxx_messageInfo_Task.Size(m) } func (m *Task) XXX_DiscardUnknown() { xxx_messageInfo_Task.DiscardUnknown(m) } var xxx_messageInfo_Task proto.InternalMessageInfo func (m *Task) GetName() string { if m != nil { return m.Name } return "" } type isTask_PayloadType interface { isTask_PayloadType() } type Task_AppEngineHttpRequest struct { AppEngineHttpRequest *AppEngineHttpRequest `protobuf:"bytes,3,opt,name=app_engine_http_request,json=appEngineHttpRequest,proto3,oneof"` } type Task_HttpRequest struct { HttpRequest *HttpRequest `protobuf:"bytes,11,opt,name=http_request,json=httpRequest,proto3,oneof"` } func (*Task_AppEngineHttpRequest) isTask_PayloadType() {} func (*Task_HttpRequest) isTask_PayloadType() {} func (m *Task) GetPayloadType() isTask_PayloadType { if m != nil { return m.PayloadType } return nil } func (m *Task) GetAppEngineHttpRequest() *AppEngineHttpRequest { if x, ok := m.GetPayloadType().(*Task_AppEngineHttpRequest); ok { return x.AppEngineHttpRequest } return nil } func (m *Task) GetHttpRequest() *HttpRequest { if x, ok := m.GetPayloadType().(*Task_HttpRequest); ok { return x.HttpRequest } return nil } func (m *Task) GetScheduleTime() *timestamp.Timestamp { if m != nil { return m.ScheduleTime } return nil } func (m *Task) GetCreateTime() *timestamp.Timestamp { if m != nil { return m.CreateTime } return nil } func (m *Task) GetDispatchDeadline() *duration.Duration { if m != nil { return m.DispatchDeadline } return nil } func (m *Task) GetDispatchCount() int32 { if m != nil { return m.DispatchCount } return 0 } func (m *Task) GetResponseCount() int32 { if m != nil { return m.ResponseCount } return 0 } func (m *Task) GetFirstAttempt() *Attempt { if m != nil { return m.FirstAttempt } return nil } func (m *Task) GetLastAttempt() *Attempt { if m != nil { return m.LastAttempt } return nil } func (m *Task) GetView() Task_View { if m != nil { return m.View } return Task_VIEW_UNSPECIFIED } // XXX_OneofFuncs is for the internal use of the proto package. func (*Task) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Task_OneofMarshaler, _Task_OneofUnmarshaler, _Task_OneofSizer, []interface{}{ (*Task_AppEngineHttpRequest)(nil), (*Task_HttpRequest)(nil), } } func _Task_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Task) // payload_type switch x := m.PayloadType.(type) { case *Task_AppEngineHttpRequest: b.EncodeVarint(3<<3 | proto.WireBytes) if err := b.EncodeMessage(x.AppEngineHttpRequest); err != nil { return err } case *Task_HttpRequest: b.EncodeVarint(11<<3 | proto.WireBytes) if err := b.EncodeMessage(x.HttpRequest); err != nil { return err } case nil: default: return fmt.Errorf("Task.PayloadType has unexpected type %T", x) } return nil } func _Task_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Task) switch tag { case 3: // payload_type.app_engine_http_request if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(AppEngineHttpRequest) err := b.DecodeMessage(msg) m.PayloadType = &Task_AppEngineHttpRequest{msg} return true, err case 11: // payload_type.http_request if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(HttpRequest) err := b.DecodeMessage(msg) m.PayloadType = &Task_HttpRequest{msg} return true, err default: return false, nil } } func _Task_OneofSizer(msg proto.Message) (n int) { m := msg.(*Task) // payload_type switch x := m.PayloadType.(type) { case *Task_AppEngineHttpRequest: s := proto.Size(x.AppEngineHttpRequest) n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case *Task_HttpRequest: s := proto.Size(x.HttpRequest) n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } // The status of a task attempt. type Attempt struct { // Output only. The time that this attempt was scheduled. // // `schedule_time` will be truncated to the nearest microsecond. ScheduleTime *timestamp.Timestamp `protobuf:"bytes,1,opt,name=schedule_time,json=scheduleTime,proto3" json:"schedule_time,omitempty"` // Output only. The time that this attempt was dispatched. // // `dispatch_time` will be truncated to the nearest microsecond. DispatchTime *timestamp.Timestamp `protobuf:"bytes,2,opt,name=dispatch_time,json=dispatchTime,proto3" json:"dispatch_time,omitempty"` // Output only. The time that this attempt response was received. // // `response_time` will be truncated to the nearest microsecond. ResponseTime *timestamp.Timestamp `protobuf:"bytes,3,opt,name=response_time,json=responseTime,proto3" json:"response_time,omitempty"` // Output only. The response from the worker for this attempt. // // If `response_time` is unset, then the task has not been attempted or is // currently running and the `response_status` field is meaningless. ResponseStatus *status.Status `protobuf:"bytes,4,opt,name=response_status,json=responseStatus,proto3" json:"response_status,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Attempt) Reset() { *m = Attempt{} } func (m *Attempt) String() string { return proto.CompactTextString(m) } func (*Attempt) ProtoMessage() {} func (*Attempt) Descriptor() ([]byte, []int) { return fileDescriptor_task_e4ac2456a2f2128b, []int{1} } func (m *Attempt) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Attempt.Unmarshal(m, b) } func (m *Attempt) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Attempt.Marshal(b, m, deterministic) } func (dst *Attempt) XXX_Merge(src proto.Message) { xxx_messageInfo_Attempt.Merge(dst, src) } func (m *Attempt) XXX_Size() int { return xxx_messageInfo_Attempt.Size(m) } func (m *Attempt) XXX_DiscardUnknown() { xxx_messageInfo_Attempt.DiscardUnknown(m) } var xxx_messageInfo_Attempt proto.InternalMessageInfo func (m *Attempt) GetScheduleTime() *timestamp.Timestamp { if m != nil { return m.ScheduleTime } return nil } func (m *Attempt) GetDispatchTime() *timestamp.Timestamp { if m != nil { return m.DispatchTime } return nil } func (m *Attempt) GetResponseTime() *timestamp.Timestamp { if m != nil { return m.ResponseTime } return nil } func (m *Attempt) GetResponseStatus() *status.Status { if m != nil { return m.ResponseStatus } return nil } func init() { proto.RegisterType((*Task)(nil), "google.cloud.tasks.v2beta3.Task") proto.RegisterType((*Attempt)(nil), "google.cloud.tasks.v2beta3.Attempt") proto.RegisterEnum("google.cloud.tasks.v2beta3.Task_View", Task_View_name, Task_View_value) } func init() { proto.RegisterFile("google/cloud/tasks/v2beta3/task.proto", fileDescriptor_task_e4ac2456a2f2128b) } var fileDescriptor_task_e4ac2456a2f2128b = []byte{ // 589 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xdf, 0x4f, 0xdb, 0x30, 0x10, 0xc7, 0x09, 0xa4, 0x40, 0xdd, 0xd0, 0x75, 0x16, 0x12, 0x59, 0x35, 0xb1, 0xaa, 0x53, 0x45, 0x9f, 0x92, 0xad, 0x3c, 0x4d, 0x3c, 0x54, 0xf4, 0x97, 0x5a, 0xa9, 0x9a, 0xaa, 0x14, 0x98, 0xb4, 0x97, 0xc8, 0x4d, 0x4c, 0x1a, 0x91, 0xda, 0x5e, 0xec, 0x80, 0xf8, 0x13, 0xf6, 0x17, 0xef, 0x75, 0x8a, 0x63, 0x57, 0x30, 0x58, 0xbb, 0xbd, 0xf5, 0xee, 0xbe, 0xdf, 0x4f, 0x2f, 0x77, 0x97, 0x80, 0x56, 0x44, 0x69, 0x94, 0x60, 0x37, 0x48, 0x68, 0x16, 0xba, 0x02, 0xf1, 0x3b, 0xee, 0xde, 0x77, 0x16, 0x58, 0xa0, 0x73, 0x19, 0x39, 0x2c, 0xa5, 0x82, 0xc2, 0x7a, 0x21, 0x73, 0xa4, 0xcc, 0x91, 0x32, 0x47, 0xc9, 0xea, 0xef, 0x15, 0x02, 0xb1, 0xd8, 0x45, 0x84, 0x50, 0x81, 0x44, 0x4c, 0x09, 0x2f, 0x9c, 0xf5, 0xb3, 0x8d, 0x7f, 0x90, 0x46, 0x58, 0x28, 0xe1, 0xa9, 0x12, 0xca, 0x68, 0x91, 0xdd, 0xba, 0x61, 0x96, 0x4a, 0x92, 0xaa, 0x7f, 0xf8, 0xb3, 0x2e, 0xe2, 0x15, 0xe6, 0x02, 0xad, 0x98, 0x12, 0x9c, 0x28, 0x41, 0xca, 0x02, 0x97, 0x0b, 0x24, 0x32, 0xd5, 0x42, 0xf3, 0x57, 0x09, 0x98, 0x57, 0x88, 0xdf, 0x41, 0x08, 0x4c, 0x82, 0x56, 0xd8, 0x36, 0x1a, 0x46, 0xbb, 0xec, 0xc9, 0xdf, 0x30, 0x06, 0x27, 0x88, 0x31, 0x1f, 0x93, 0x28, 0x26, 0xd8, 0x5f, 0x0a, 0xc1, 0xfc, 0x14, 0xff, 0xc8, 0x30, 0x17, 0xf6, 0x5e, 0xc3, 0x68, 0x57, 0x3a, 0x9f, 0x9c, 0xbf, 0x3f, 0xbb, 0x73, 0xc9, 0xd8, 0x50, 0x3a, 0xc7, 0x42, 0x30, 0xaf, 0xf0, 0x8d, 0x77, 0xbc, 0x63, 0xf4, 0x4a, 0x1e, 0x4e, 0x81, 0xf5, 0x8c, 0x5f, 0x91, 0xfc, 0xb3, 0x4d, 0xfc, 0xe7, 0xd8, 0xca, 0xf2, 0x09, 0xad, 0x0b, 0x8e, 0x78, 0xb0, 0xc4, 0x61, 0x96, 0x60, 0x3f, 0x1f, 0x85, 0x6d, 0x4a, 0x5c, 0x5d, 0xe3, 0xf4, 0x9c, 0x9c, 0x2b, 0x3d, 0x27, 0xcf, 0xd2, 0x86, 0x3c, 0x05, 0x2f, 0x40, 0x25, 0x48, 0x31, 0x12, 0xca, 0x5e, 0xda, 0x6a, 0x07, 0x85, 0x5c, 0x9a, 0x47, 0xe0, 0x6d, 0x18, 0x73, 0x86, 0x44, 0xb0, 0xf4, 0x43, 0x8c, 0xc2, 0x24, 0x26, 0xd8, 0xb6, 0x24, 0xe2, 0xdd, 0x0b, 0xc4, 0x40, 0x6d, 0xd2, 0xab, 0x69, 0xcf, 0x40, 0x59, 0x60, 0x0b, 0x54, 0xd7, 0x9c, 0x80, 0x66, 0x44, 0xd8, 0xfb, 0x0d, 0xa3, 0x5d, 0xf2, 0x8e, 0x74, 0xb6, 0x9f, 0x27, 0x73, 0x59, 0x8a, 0x39, 0xa3, 0x84, 0x63, 0x25, 0x3b, 0x28, 0x64, 0x3a, 0x5b, 0xc8, 0xc6, 0xe0, 0xe8, 0x36, 0x4e, 0xb9, 0xf0, 0x91, 0x10, 0x78, 0xc5, 0x84, 0x7d, 0x28, 0x3b, 0xfa, 0xb8, 0x71, 0x85, 0x85, 0xd4, 0xb3, 0xa4, 0x53, 0x45, 0x70, 0x04, 0xac, 0x04, 0x3d, 0x01, 0x95, 0xff, 0x1d, 0x54, 0xc9, 0x8d, 0x9a, 0xf3, 0x05, 0x98, 0xf7, 0x31, 0x7e, 0xb0, 0x41, 0xc3, 0x68, 0x57, 0x3b, 0xad, 0x4d, 0xfe, 0xfc, 0x44, 0x9d, 0x9b, 0x18, 0x3f, 0x78, 0xd2, 0xd2, 0xfc, 0x0c, 0xcc, 0x3c, 0x82, 0xc7, 0xa0, 0x76, 0x33, 0x19, 0x7e, 0xf3, 0xaf, 0xbf, 0xce, 0x67, 0xc3, 0xfe, 0x64, 0x34, 0x19, 0x0e, 0x6a, 0x3b, 0xb0, 0x0c, 0x4a, 0xbd, 0xcb, 0xf9, 0xa4, 0x5f, 0x33, 0xe0, 0x21, 0x30, 0x47, 0xd7, 0xd3, 0x69, 0x6d, 0xb7, 0x57, 0x05, 0x16, 0x43, 0x8f, 0x09, 0x45, 0xa1, 0x2f, 0x1e, 0x19, 0x6e, 0xfe, 0xdc, 0x05, 0x07, 0xba, 0x93, 0x17, 0xf7, 0x62, 0xfc, 0xe7, 0xbd, 0x74, 0xc1, 0x7a, 0x29, 0x05, 0x60, 0x77, 0x3b, 0x40, 0x1b, 0x34, 0x60, 0xbd, 0x44, 0x09, 0xd8, 0xdb, 0x0e, 0xd0, 0x06, 0x75, 0xb1, 0x6f, 0xd6, 0x80, 0xe2, 0x0d, 0x57, 0x47, 0x0f, 0x35, 0x22, 0x65, 0x81, 0x33, 0x97, 0x15, 0x6f, 0x7d, 0x30, 0x45, 0xdc, 0x23, 0xe0, 0x34, 0xa0, 0xab, 0x0d, 0x0b, 0xe8, 0x95, 0xf3, 0x0d, 0xcc, 0xf2, 0x26, 0x66, 0xc6, 0xf7, 0xae, 0x12, 0x46, 0x34, 0x41, 0x24, 0x72, 0x68, 0x1a, 0xb9, 0x11, 0x26, 0xb2, 0x45, 0xb7, 0x28, 0x21, 0x16, 0xf3, 0xd7, 0x3e, 0x6b, 0x17, 0x32, 0x5a, 0xec, 0x4b, 0xed, 0xf9, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0xa8, 0x61, 0xbf, 0x79, 0x62, 0x05, 0x00, 0x00, }
random_line_split
task.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/cloud/tasks/v2beta3/task.proto package tasks // import "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import duration "github.com/golang/protobuf/ptypes/duration" import timestamp "github.com/golang/protobuf/ptypes/timestamp" import _ "google.golang.org/genproto/googleapis/api/annotations" import status "google.golang.org/genproto/googleapis/rpc/status" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // The view specifies a subset of [Task][google.cloud.tasks.v2beta3.Task] data. // // When a task is returned in a response, not all // information is retrieved by default because some data, such as // payloads, might be desirable to return only when needed because // of its large size or because of the sensitivity of data that it // contains. type Task_View int32 const ( // Unspecified. Defaults to BASIC. Task_VIEW_UNSPECIFIED Task_View = 0 // The basic view omits fields which can be large or can contain // sensitive data. // // This view does not include the // [body in AppEngineHttpRequest][google.cloud.tasks.v2beta3.AppEngineHttpRequest.body]. // Bodies are desirable to return only when needed, because they // can be large and because of the sensitivity of the data that you // choose to store in it. Task_BASIC Task_View = 1 // All information is returned. // // Authorization for [FULL][google.cloud.tasks.v2beta3.Task.View.FULL] requires // `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) // permission on the [Queue][google.cloud.tasks.v2beta3.Queue] resource. Task_FULL Task_View = 2 ) var Task_View_name = map[int32]string{ 0: "VIEW_UNSPECIFIED", 1: "BASIC", 2: "FULL", } var Task_View_value = map[string]int32{ "VIEW_UNSPECIFIED": 0, "BASIC": 1, "FULL": 2, } func (x Task_View) String() string { return proto.EnumName(Task_View_name, int32(x)) } func (Task_View) EnumDescriptor() ([]byte, []int) { return fileDescriptor_task_e4ac2456a2f2128b, []int{0, 0} } // A unit of scheduled work. type Task struct { // Optionally caller-specified in [CreateTask][google.cloud.tasks.v2beta3.CloudTasks.CreateTask]. // // The task name. // // The task name must have the following format: // `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` // // * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), // hyphens (-), colons (:), or periods (.). // For more information, see // [Identifying // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) // * `LOCATION_ID` is the canonical ID for the task's location. // The list of available locations can be obtained by calling // [ListLocations][google.cloud.location.Locations.ListLocations]. // For more information, see https://cloud.google.com/about/locations/. // * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or // hyphens (-). The maximum length is 100 characters. // * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), // hyphens (-), or underscores (_). The maximum length is 500 characters. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. The message to send to the worker. // // Types that are valid to be assigned to PayloadType: // *Task_AppEngineHttpRequest // *Task_HttpRequest PayloadType isTask_PayloadType `protobuf_oneof:"payload_type"` // The time when the task is scheduled to be attempted. // // For App Engine queues, this is when the task will be attempted or retried. // // `schedule_time` will be truncated to the nearest microsecond. ScheduleTime *timestamp.Timestamp `protobuf:"bytes,4,opt,name=schedule_time,json=scheduleTime,proto3" json:"schedule_time,omitempty"` // Output only. The time that the task was created. // // `create_time` will be truncated to the nearest second. CreateTime *timestamp.Timestamp `protobuf:"bytes,5,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` // The deadline for requests sent to the worker. If the worker does not // respond by this deadline then the request is cancelled and the attempt // is marked as a `DEADLINE_EXCEEDED` failure. Cloud Tasks will retry the // task according to the [RetryConfig][google.cloud.tasks.v2beta3.RetryConfig]. // // Note that when the request is cancelled, Cloud Tasks will stop listing for // the response, but whether the worker stops processing depends on the // worker. For example, if the worker is stuck, it may not react to cancelled // requests. // // The default and maximum values depend on the type of request: // // * For [HTTP tasks][google.cloud.tasks.v2beta3.HttpRequest], the default is // 10 minutes. // The deadline must be in the interval [15 seconds, 30 minutes]. // // * For [App Engine tasks][google.cloud.tasks.v2beta3.AppEngineHttpRequest], 0 indicates that the // request has the default deadline. The default deadline depends on the // [scaling type](https://cloud.google.com/appengine/docs/standard/go/how-instances-are-managed#instance_scaling) // of the service: 10 minutes for standard apps with automatic scaling, 24 // hours for standard apps with manual and basic scaling, and 60 minutes for // flex apps. If the request deadline is set, it must be in the interval [15 // seconds, 24 hours 15 seconds]. Regardless of the task's // `dispatch_deadline`, the app handler will not run for longer than than // the service's timeout. We recommend setting the `dispatch_deadline` to // at most a few seconds more than the app handler's timeout. For more // information see // [Timeouts](https://cloud.google.com/tasks/docs/creating-appengine-handlers#timeouts). // // `dispatch_deadline` will be truncated to the nearest millisecond. The // deadline is an approximate deadline. DispatchDeadline *duration.Duration `protobuf:"bytes,12,opt,name=dispatch_deadline,json=dispatchDeadline,proto3" json:"dispatch_deadline,omitempty"` // Output only. The number of attempts dispatched. // // This count includes attempts which have been dispatched but haven't // received a response. DispatchCount int32 `protobuf:"varint,6,opt,name=dispatch_count,json=dispatchCount,proto3" json:"dispatch_count,omitempty"` // Output only. The number of attempts which have received a response. ResponseCount int32 `protobuf:"varint,7,opt,name=response_count,json=responseCount,proto3" json:"response_count,omitempty"` // Output only. The status of the task's first attempt. // // Only [dispatch_time][google.cloud.tasks.v2beta3.Attempt.dispatch_time] will be set. // The other [Attempt][google.cloud.tasks.v2beta3.Attempt] information is not retained by Cloud Tasks. FirstAttempt *Attempt `protobuf:"bytes,8,opt,name=first_attempt,json=firstAttempt,proto3" json:"first_attempt,omitempty"` // Output only. The status of the task's last attempt. LastAttempt *Attempt `protobuf:"bytes,9,opt,name=last_attempt,json=lastAttempt,proto3" json:"last_attempt,omitempty"` // Output only. The view specifies which subset of the [Task][google.cloud.tasks.v2beta3.Task] has // been returned. View Task_View `protobuf:"varint,10,opt,name=view,proto3,enum=google.cloud.tasks.v2beta3.Task_View" json:"view,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Task) Reset() { *m = Task{} } func (m *Task) String() string { return proto.CompactTextString(m) } func (*Task) ProtoMessage() {} func (*Task) Descriptor() ([]byte, []int) { return fileDescriptor_task_e4ac2456a2f2128b, []int{0} } func (m *Task) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Task.Unmarshal(m, b) } func (m *Task) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Task.Marshal(b, m, deterministic) } func (dst *Task) XXX_Merge(src proto.Message) { xxx_messageInfo_Task.Merge(dst, src) } func (m *Task) XXX_Size() int { return xxx_messageInfo_Task.Size(m) } func (m *Task) XXX_DiscardUnknown() { xxx_messageInfo_Task.DiscardUnknown(m) } var xxx_messageInfo_Task proto.InternalMessageInfo func (m *Task) GetName() string { if m != nil { return m.Name } return "" } type isTask_PayloadType interface { isTask_PayloadType() } type Task_AppEngineHttpRequest struct { AppEngineHttpRequest *AppEngineHttpRequest `protobuf:"bytes,3,opt,name=app_engine_http_request,json=appEngineHttpRequest,proto3,oneof"` } type Task_HttpRequest struct { HttpRequest *HttpRequest `protobuf:"bytes,11,opt,name=http_request,json=httpRequest,proto3,oneof"` } func (*Task_AppEngineHttpRequest) isTask_PayloadType() {} func (*Task_HttpRequest) isTask_PayloadType() {} func (m *Task) GetPayloadType() isTask_PayloadType { if m != nil { return m.PayloadType } return nil } func (m *Task) GetAppEngineHttpRequest() *AppEngineHttpRequest { if x, ok := m.GetPayloadType().(*Task_AppEngineHttpRequest); ok { return x.AppEngineHttpRequest } return nil } func (m *Task) GetHttpRequest() *HttpRequest { if x, ok := m.GetPayloadType().(*Task_HttpRequest); ok { return x.HttpRequest } return nil } func (m *Task) GetScheduleTime() *timestamp.Timestamp { if m != nil { return m.ScheduleTime } return nil } func (m *Task) GetCreateTime() *timestamp.Timestamp { if m != nil { return m.CreateTime } return nil } func (m *Task) GetDispatchDeadline() *duration.Duration { if m != nil { return m.DispatchDeadline } return nil } func (m *Task)
() int32 { if m != nil { return m.DispatchCount } return 0 } func (m *Task) GetResponseCount() int32 { if m != nil { return m.ResponseCount } return 0 } func (m *Task) GetFirstAttempt() *Attempt { if m != nil { return m.FirstAttempt } return nil } func (m *Task) GetLastAttempt() *Attempt { if m != nil { return m.LastAttempt } return nil } func (m *Task) GetView() Task_View { if m != nil { return m.View } return Task_VIEW_UNSPECIFIED } // XXX_OneofFuncs is for the internal use of the proto package. func (*Task) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Task_OneofMarshaler, _Task_OneofUnmarshaler, _Task_OneofSizer, []interface{}{ (*Task_AppEngineHttpRequest)(nil), (*Task_HttpRequest)(nil), } } func _Task_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Task) // payload_type switch x := m.PayloadType.(type) { case *Task_AppEngineHttpRequest: b.EncodeVarint(3<<3 | proto.WireBytes) if err := b.EncodeMessage(x.AppEngineHttpRequest); err != nil { return err } case *Task_HttpRequest: b.EncodeVarint(11<<3 | proto.WireBytes) if err := b.EncodeMessage(x.HttpRequest); err != nil { return err } case nil: default: return fmt.Errorf("Task.PayloadType has unexpected type %T", x) } return nil } func _Task_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Task) switch tag { case 3: // payload_type.app_engine_http_request if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(AppEngineHttpRequest) err := b.DecodeMessage(msg) m.PayloadType = &Task_AppEngineHttpRequest{msg} return true, err case 11: // payload_type.http_request if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(HttpRequest) err := b.DecodeMessage(msg) m.PayloadType = &Task_HttpRequest{msg} return true, err default: return false, nil } } func _Task_OneofSizer(msg proto.Message) (n int) { m := msg.(*Task) // payload_type switch x := m.PayloadType.(type) { case *Task_AppEngineHttpRequest: s := proto.Size(x.AppEngineHttpRequest) n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case *Task_HttpRequest: s := proto.Size(x.HttpRequest) n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } // The status of a task attempt. type Attempt struct { // Output only. The time that this attempt was scheduled. // // `schedule_time` will be truncated to the nearest microsecond. ScheduleTime *timestamp.Timestamp `protobuf:"bytes,1,opt,name=schedule_time,json=scheduleTime,proto3" json:"schedule_time,omitempty"` // Output only. The time that this attempt was dispatched. // // `dispatch_time` will be truncated to the nearest microsecond. DispatchTime *timestamp.Timestamp `protobuf:"bytes,2,opt,name=dispatch_time,json=dispatchTime,proto3" json:"dispatch_time,omitempty"` // Output only. The time that this attempt response was received. // // `response_time` will be truncated to the nearest microsecond. ResponseTime *timestamp.Timestamp `protobuf:"bytes,3,opt,name=response_time,json=responseTime,proto3" json:"response_time,omitempty"` // Output only. The response from the worker for this attempt. // // If `response_time` is unset, then the task has not been attempted or is // currently running and the `response_status` field is meaningless. ResponseStatus *status.Status `protobuf:"bytes,4,opt,name=response_status,json=responseStatus,proto3" json:"response_status,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Attempt) Reset() { *m = Attempt{} } func (m *Attempt) String() string { return proto.CompactTextString(m) } func (*Attempt) ProtoMessage() {} func (*Attempt) Descriptor() ([]byte, []int) { return fileDescriptor_task_e4ac2456a2f2128b, []int{1} } func (m *Attempt) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Attempt.Unmarshal(m, b) } func (m *Attempt) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Attempt.Marshal(b, m, deterministic) } func (dst *Attempt) XXX_Merge(src proto.Message) { xxx_messageInfo_Attempt.Merge(dst, src) } func (m *Attempt) XXX_Size() int { return xxx_messageInfo_Attempt.Size(m) } func (m *Attempt) XXX_DiscardUnknown() { xxx_messageInfo_Attempt.DiscardUnknown(m) } var xxx_messageInfo_Attempt proto.InternalMessageInfo func (m *Attempt) GetScheduleTime() *timestamp.Timestamp { if m != nil { return m.ScheduleTime } return nil } func (m *Attempt) GetDispatchTime() *timestamp.Timestamp { if m != nil { return m.DispatchTime } return nil } func (m *Attempt) GetResponseTime() *timestamp.Timestamp { if m != nil { return m.ResponseTime } return nil } func (m *Attempt) GetResponseStatus() *status.Status { if m != nil { return m.ResponseStatus } return nil } func init() { proto.RegisterType((*Task)(nil), "google.cloud.tasks.v2beta3.Task") proto.RegisterType((*Attempt)(nil), "google.cloud.tasks.v2beta3.Attempt") proto.RegisterEnum("google.cloud.tasks.v2beta3.Task_View", Task_View_name, Task_View_value) } func init() { proto.RegisterFile("google/cloud/tasks/v2beta3/task.proto", fileDescriptor_task_e4ac2456a2f2128b) } var fileDescriptor_task_e4ac2456a2f2128b = []byte{ // 589 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xdf, 0x4f, 0xdb, 0x30, 0x10, 0xc7, 0x09, 0xa4, 0x40, 0xdd, 0xd0, 0x75, 0x16, 0x12, 0x59, 0x35, 0xb1, 0xaa, 0x53, 0x45, 0x9f, 0x92, 0xad, 0x3c, 0x4d, 0x3c, 0x54, 0xf4, 0x97, 0x5a, 0xa9, 0x9a, 0xaa, 0x14, 0x98, 0xb4, 0x97, 0xc8, 0x4d, 0x4c, 0x1a, 0x91, 0xda, 0x5e, 0xec, 0x80, 0xf8, 0x13, 0xf6, 0x17, 0xef, 0x75, 0x8a, 0x63, 0x57, 0x30, 0x58, 0xbb, 0xbd, 0xf5, 0xee, 0xbe, 0xdf, 0x4f, 0x2f, 0x77, 0x97, 0x80, 0x56, 0x44, 0x69, 0x94, 0x60, 0x37, 0x48, 0x68, 0x16, 0xba, 0x02, 0xf1, 0x3b, 0xee, 0xde, 0x77, 0x16, 0x58, 0xa0, 0x73, 0x19, 0x39, 0x2c, 0xa5, 0x82, 0xc2, 0x7a, 0x21, 0x73, 0xa4, 0xcc, 0x91, 0x32, 0x47, 0xc9, 0xea, 0xef, 0x15, 0x02, 0xb1, 0xd8, 0x45, 0x84, 0x50, 0x81, 0x44, 0x4c, 0x09, 0x2f, 0x9c, 0xf5, 0xb3, 0x8d, 0x7f, 0x90, 0x46, 0x58, 0x28, 0xe1, 0xa9, 0x12, 0xca, 0x68, 0x91, 0xdd, 0xba, 0x61, 0x96, 0x4a, 0x92, 0xaa, 0x7f, 0xf8, 0xb3, 0x2e, 0xe2, 0x15, 0xe6, 0x02, 0xad, 0x98, 0x12, 0x9c, 0x28, 0x41, 0xca, 0x02, 0x97, 0x0b, 0x24, 0x32, 0xd5, 0x42, 0xf3, 0x57, 0x09, 0x98, 0x57, 0x88, 0xdf, 0x41, 0x08, 0x4c, 0x82, 0x56, 0xd8, 0x36, 0x1a, 0x46, 0xbb, 0xec, 0xc9, 0xdf, 0x30, 0x06, 0x27, 0x88, 0x31, 0x1f, 0x93, 0x28, 0x26, 0xd8, 0x5f, 0x0a, 0xc1, 0xfc, 0x14, 0xff, 0xc8, 0x30, 0x17, 0xf6, 0x5e, 0xc3, 0x68, 0x57, 0x3a, 0x9f, 0x9c, 0xbf, 0x3f, 0xbb, 0x73, 0xc9, 0xd8, 0x50, 0x3a, 0xc7, 0x42, 0x30, 0xaf, 0xf0, 0x8d, 0x77, 0xbc, 0x63, 0xf4, 0x4a, 0x1e, 0x4e, 0x81, 0xf5, 0x8c, 0x5f, 0x91, 0xfc, 0xb3, 0x4d, 0xfc, 0xe7, 0xd8, 0xca, 0xf2, 0x09, 0xad, 0x0b, 0x8e, 0x78, 0xb0, 0xc4, 0x61, 0x96, 0x60, 0x3f, 0x1f, 0x85, 0x6d, 0x4a, 0x5c, 0x5d, 0xe3, 0xf4, 0x9c, 0x9c, 0x2b, 0x3d, 0x27, 0xcf, 0xd2, 0x86, 0x3c, 0x05, 0x2f, 0x40, 0x25, 0x48, 0x31, 0x12, 0xca, 0x5e, 0xda, 0x6a, 0x07, 0x85, 0x5c, 0x9a, 0x47, 0xe0, 0x6d, 0x18, 0x73, 0x86, 0x44, 0xb0, 0xf4, 0x43, 0x8c, 0xc2, 0x24, 0x26, 0xd8, 0xb6, 0x24, 0xe2, 0xdd, 0x0b, 0xc4, 0x40, 0x6d, 0xd2, 0xab, 0x69, 0xcf, 0x40, 0x59, 0x60, 0x0b, 0x54, 0xd7, 0x9c, 0x80, 0x66, 0x44, 0xd8, 0xfb, 0x0d, 0xa3, 0x5d, 0xf2, 0x8e, 0x74, 0xb6, 0x9f, 0x27, 0x73, 0x59, 0x8a, 0x39, 0xa3, 0x84, 0x63, 0x25, 0x3b, 0x28, 0x64, 0x3a, 0x5b, 0xc8, 0xc6, 0xe0, 0xe8, 0x36, 0x4e, 0xb9, 0xf0, 0x91, 0x10, 0x78, 0xc5, 0x84, 0x7d, 0x28, 0x3b, 0xfa, 0xb8, 0x71, 0x85, 0x85, 0xd4, 0xb3, 0xa4, 0x53, 0x45, 0x70, 0x04, 0xac, 0x04, 0x3d, 0x01, 0x95, 0xff, 0x1d, 0x54, 0xc9, 0x8d, 0x9a, 0xf3, 0x05, 0x98, 0xf7, 0x31, 0x7e, 0xb0, 0x41, 0xc3, 0x68, 0x57, 0x3b, 0xad, 0x4d, 0xfe, 0xfc, 0x44, 0x9d, 0x9b, 0x18, 0x3f, 0x78, 0xd2, 0xd2, 0xfc, 0x0c, 0xcc, 0x3c, 0x82, 0xc7, 0xa0, 0x76, 0x33, 0x19, 0x7e, 0xf3, 0xaf, 0xbf, 0xce, 0x67, 0xc3, 0xfe, 0x64, 0x34, 0x19, 0x0e, 0x6a, 0x3b, 0xb0, 0x0c, 0x4a, 0xbd, 0xcb, 0xf9, 0xa4, 0x5f, 0x33, 0xe0, 0x21, 0x30, 0x47, 0xd7, 0xd3, 0x69, 0x6d, 0xb7, 0x57, 0x05, 0x16, 0x43, 0x8f, 0x09, 0x45, 0xa1, 0x2f, 0x1e, 0x19, 0x6e, 0xfe, 0xdc, 0x05, 0x07, 0xba, 0x93, 0x17, 0xf7, 0x62, 0xfc, 0xe7, 0xbd, 0x74, 0xc1, 0x7a, 0x29, 0x05, 0x60, 0x77, 0x3b, 0x40, 0x1b, 0x34, 0x60, 0xbd, 0x44, 0x09, 0xd8, 0xdb, 0x0e, 0xd0, 0x06, 0x75, 0xb1, 0x6f, 0xd6, 0x80, 0xe2, 0x0d, 0x57, 0x47, 0x0f, 0x35, 0x22, 0x65, 0x81, 0x33, 0x97, 0x15, 0x6f, 0x7d, 0x30, 0x45, 0xdc, 0x23, 0xe0, 0x34, 0xa0, 0xab, 0x0d, 0x0b, 0xe8, 0x95, 0xf3, 0x0d, 0xcc, 0xf2, 0x26, 0x66, 0xc6, 0xf7, 0xae, 0x12, 0x46, 0x34, 0x41, 0x24, 0x72, 0x68, 0x1a, 0xb9, 0x11, 0x26, 0xb2, 0x45, 0xb7, 0x28, 0x21, 0x16, 0xf3, 0xd7, 0x3e, 0x6b, 0x17, 0x32, 0x5a, 0xec, 0x4b, 0xed, 0xf9, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0xa8, 0x61, 0xbf, 0x79, 0x62, 0x05, 0x00, 0x00, }
GetDispatchCount
identifier_name
task.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/cloud/tasks/v2beta3/task.proto package tasks // import "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import duration "github.com/golang/protobuf/ptypes/duration" import timestamp "github.com/golang/protobuf/ptypes/timestamp" import _ "google.golang.org/genproto/googleapis/api/annotations" import status "google.golang.org/genproto/googleapis/rpc/status" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // The view specifies a subset of [Task][google.cloud.tasks.v2beta3.Task] data. // // When a task is returned in a response, not all // information is retrieved by default because some data, such as // payloads, might be desirable to return only when needed because // of its large size or because of the sensitivity of data that it // contains. type Task_View int32 const ( // Unspecified. Defaults to BASIC. Task_VIEW_UNSPECIFIED Task_View = 0 // The basic view omits fields which can be large or can contain // sensitive data. // // This view does not include the // [body in AppEngineHttpRequest][google.cloud.tasks.v2beta3.AppEngineHttpRequest.body]. // Bodies are desirable to return only when needed, because they // can be large and because of the sensitivity of the data that you // choose to store in it. Task_BASIC Task_View = 1 // All information is returned. // // Authorization for [FULL][google.cloud.tasks.v2beta3.Task.View.FULL] requires // `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) // permission on the [Queue][google.cloud.tasks.v2beta3.Queue] resource. Task_FULL Task_View = 2 ) var Task_View_name = map[int32]string{ 0: "VIEW_UNSPECIFIED", 1: "BASIC", 2: "FULL", } var Task_View_value = map[string]int32{ "VIEW_UNSPECIFIED": 0, "BASIC": 1, "FULL": 2, } func (x Task_View) String() string { return proto.EnumName(Task_View_name, int32(x)) } func (Task_View) EnumDescriptor() ([]byte, []int) { return fileDescriptor_task_e4ac2456a2f2128b, []int{0, 0} } // A unit of scheduled work. type Task struct { // Optionally caller-specified in [CreateTask][google.cloud.tasks.v2beta3.CloudTasks.CreateTask]. // // The task name. // // The task name must have the following format: // `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` // // * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), // hyphens (-), colons (:), or periods (.). // For more information, see // [Identifying // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) // * `LOCATION_ID` is the canonical ID for the task's location. // The list of available locations can be obtained by calling // [ListLocations][google.cloud.location.Locations.ListLocations]. // For more information, see https://cloud.google.com/about/locations/. // * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or // hyphens (-). The maximum length is 100 characters. // * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), // hyphens (-), or underscores (_). The maximum length is 500 characters. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. The message to send to the worker. // // Types that are valid to be assigned to PayloadType: // *Task_AppEngineHttpRequest // *Task_HttpRequest PayloadType isTask_PayloadType `protobuf_oneof:"payload_type"` // The time when the task is scheduled to be attempted. // // For App Engine queues, this is when the task will be attempted or retried. // // `schedule_time` will be truncated to the nearest microsecond. ScheduleTime *timestamp.Timestamp `protobuf:"bytes,4,opt,name=schedule_time,json=scheduleTime,proto3" json:"schedule_time,omitempty"` // Output only. The time that the task was created. // // `create_time` will be truncated to the nearest second. CreateTime *timestamp.Timestamp `protobuf:"bytes,5,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` // The deadline for requests sent to the worker. If the worker does not // respond by this deadline then the request is cancelled and the attempt // is marked as a `DEADLINE_EXCEEDED` failure. Cloud Tasks will retry the // task according to the [RetryConfig][google.cloud.tasks.v2beta3.RetryConfig]. // // Note that when the request is cancelled, Cloud Tasks will stop listing for // the response, but whether the worker stops processing depends on the // worker. For example, if the worker is stuck, it may not react to cancelled // requests. // // The default and maximum values depend on the type of request: // // * For [HTTP tasks][google.cloud.tasks.v2beta3.HttpRequest], the default is // 10 minutes. // The deadline must be in the interval [15 seconds, 30 minutes]. // // * For [App Engine tasks][google.cloud.tasks.v2beta3.AppEngineHttpRequest], 0 indicates that the // request has the default deadline. The default deadline depends on the // [scaling type](https://cloud.google.com/appengine/docs/standard/go/how-instances-are-managed#instance_scaling) // of the service: 10 minutes for standard apps with automatic scaling, 24 // hours for standard apps with manual and basic scaling, and 60 minutes for // flex apps. If the request deadline is set, it must be in the interval [15 // seconds, 24 hours 15 seconds]. Regardless of the task's // `dispatch_deadline`, the app handler will not run for longer than than // the service's timeout. We recommend setting the `dispatch_deadline` to // at most a few seconds more than the app handler's timeout. For more // information see // [Timeouts](https://cloud.google.com/tasks/docs/creating-appengine-handlers#timeouts). // // `dispatch_deadline` will be truncated to the nearest millisecond. The // deadline is an approximate deadline. DispatchDeadline *duration.Duration `protobuf:"bytes,12,opt,name=dispatch_deadline,json=dispatchDeadline,proto3" json:"dispatch_deadline,omitempty"` // Output only. The number of attempts dispatched. // // This count includes attempts which have been dispatched but haven't // received a response. DispatchCount int32 `protobuf:"varint,6,opt,name=dispatch_count,json=dispatchCount,proto3" json:"dispatch_count,omitempty"` // Output only. The number of attempts which have received a response. ResponseCount int32 `protobuf:"varint,7,opt,name=response_count,json=responseCount,proto3" json:"response_count,omitempty"` // Output only. The status of the task's first attempt. // // Only [dispatch_time][google.cloud.tasks.v2beta3.Attempt.dispatch_time] will be set. // The other [Attempt][google.cloud.tasks.v2beta3.Attempt] information is not retained by Cloud Tasks. FirstAttempt *Attempt `protobuf:"bytes,8,opt,name=first_attempt,json=firstAttempt,proto3" json:"first_attempt,omitempty"` // Output only. The status of the task's last attempt. LastAttempt *Attempt `protobuf:"bytes,9,opt,name=last_attempt,json=lastAttempt,proto3" json:"last_attempt,omitempty"` // Output only. The view specifies which subset of the [Task][google.cloud.tasks.v2beta3.Task] has // been returned. View Task_View `protobuf:"varint,10,opt,name=view,proto3,enum=google.cloud.tasks.v2beta3.Task_View" json:"view,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Task) Reset() { *m = Task{} } func (m *Task) String() string { return proto.CompactTextString(m) } func (*Task) ProtoMessage() {} func (*Task) Descriptor() ([]byte, []int) { return fileDescriptor_task_e4ac2456a2f2128b, []int{0} } func (m *Task) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Task.Unmarshal(m, b) } func (m *Task) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Task.Marshal(b, m, deterministic) } func (dst *Task) XXX_Merge(src proto.Message) { xxx_messageInfo_Task.Merge(dst, src) } func (m *Task) XXX_Size() int { return xxx_messageInfo_Task.Size(m) } func (m *Task) XXX_DiscardUnknown() { xxx_messageInfo_Task.DiscardUnknown(m) } var xxx_messageInfo_Task proto.InternalMessageInfo func (m *Task) GetName() string { if m != nil { return m.Name } return "" } type isTask_PayloadType interface { isTask_PayloadType() } type Task_AppEngineHttpRequest struct { AppEngineHttpRequest *AppEngineHttpRequest `protobuf:"bytes,3,opt,name=app_engine_http_request,json=appEngineHttpRequest,proto3,oneof"` } type Task_HttpRequest struct { HttpRequest *HttpRequest `protobuf:"bytes,11,opt,name=http_request,json=httpRequest,proto3,oneof"` } func (*Task_AppEngineHttpRequest) isTask_PayloadType() {} func (*Task_HttpRequest) isTask_PayloadType() {} func (m *Task) GetPayloadType() isTask_PayloadType { if m != nil { return m.PayloadType } return nil } func (m *Task) GetAppEngineHttpRequest() *AppEngineHttpRequest { if x, ok := m.GetPayloadType().(*Task_AppEngineHttpRequest); ok { return x.AppEngineHttpRequest } return nil } func (m *Task) GetHttpRequest() *HttpRequest { if x, ok := m.GetPayloadType().(*Task_HttpRequest); ok { return x.HttpRequest } return nil } func (m *Task) GetScheduleTime() *timestamp.Timestamp { if m != nil { return m.ScheduleTime } return nil } func (m *Task) GetCreateTime() *timestamp.Timestamp { if m != nil { return m.CreateTime } return nil } func (m *Task) GetDispatchDeadline() *duration.Duration { if m != nil { return m.DispatchDeadline } return nil } func (m *Task) GetDispatchCount() int32 { if m != nil { return m.DispatchCount } return 0 } func (m *Task) GetResponseCount() int32 { if m != nil { return m.ResponseCount } return 0 } func (m *Task) GetFirstAttempt() *Attempt { if m != nil { return m.FirstAttempt } return nil } func (m *Task) GetLastAttempt() *Attempt { if m != nil { return m.LastAttempt } return nil } func (m *Task) GetView() Task_View { if m != nil
return Task_VIEW_UNSPECIFIED } // XXX_OneofFuncs is for the internal use of the proto package. func (*Task) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Task_OneofMarshaler, _Task_OneofUnmarshaler, _Task_OneofSizer, []interface{}{ (*Task_AppEngineHttpRequest)(nil), (*Task_HttpRequest)(nil), } } func _Task_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Task) // payload_type switch x := m.PayloadType.(type) { case *Task_AppEngineHttpRequest: b.EncodeVarint(3<<3 | proto.WireBytes) if err := b.EncodeMessage(x.AppEngineHttpRequest); err != nil { return err } case *Task_HttpRequest: b.EncodeVarint(11<<3 | proto.WireBytes) if err := b.EncodeMessage(x.HttpRequest); err != nil { return err } case nil: default: return fmt.Errorf("Task.PayloadType has unexpected type %T", x) } return nil } func _Task_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Task) switch tag { case 3: // payload_type.app_engine_http_request if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(AppEngineHttpRequest) err := b.DecodeMessage(msg) m.PayloadType = &Task_AppEngineHttpRequest{msg} return true, err case 11: // payload_type.http_request if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(HttpRequest) err := b.DecodeMessage(msg) m.PayloadType = &Task_HttpRequest{msg} return true, err default: return false, nil } } func _Task_OneofSizer(msg proto.Message) (n int) { m := msg.(*Task) // payload_type switch x := m.PayloadType.(type) { case *Task_AppEngineHttpRequest: s := proto.Size(x.AppEngineHttpRequest) n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case *Task_HttpRequest: s := proto.Size(x.HttpRequest) n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } // The status of a task attempt. type Attempt struct { // Output only. The time that this attempt was scheduled. // // `schedule_time` will be truncated to the nearest microsecond. ScheduleTime *timestamp.Timestamp `protobuf:"bytes,1,opt,name=schedule_time,json=scheduleTime,proto3" json:"schedule_time,omitempty"` // Output only. The time that this attempt was dispatched. // // `dispatch_time` will be truncated to the nearest microsecond. DispatchTime *timestamp.Timestamp `protobuf:"bytes,2,opt,name=dispatch_time,json=dispatchTime,proto3" json:"dispatch_time,omitempty"` // Output only. The time that this attempt response was received. // // `response_time` will be truncated to the nearest microsecond. ResponseTime *timestamp.Timestamp `protobuf:"bytes,3,opt,name=response_time,json=responseTime,proto3" json:"response_time,omitempty"` // Output only. The response from the worker for this attempt. // // If `response_time` is unset, then the task has not been attempted or is // currently running and the `response_status` field is meaningless. ResponseStatus *status.Status `protobuf:"bytes,4,opt,name=response_status,json=responseStatus,proto3" json:"response_status,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Attempt) Reset() { *m = Attempt{} } func (m *Attempt) String() string { return proto.CompactTextString(m) } func (*Attempt) ProtoMessage() {} func (*Attempt) Descriptor() ([]byte, []int) { return fileDescriptor_task_e4ac2456a2f2128b, []int{1} } func (m *Attempt) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Attempt.Unmarshal(m, b) } func (m *Attempt) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Attempt.Marshal(b, m, deterministic) } func (dst *Attempt) XXX_Merge(src proto.Message) { xxx_messageInfo_Attempt.Merge(dst, src) } func (m *Attempt) XXX_Size() int { return xxx_messageInfo_Attempt.Size(m) } func (m *Attempt) XXX_DiscardUnknown() { xxx_messageInfo_Attempt.DiscardUnknown(m) } var xxx_messageInfo_Attempt proto.InternalMessageInfo func (m *Attempt) GetScheduleTime() *timestamp.Timestamp { if m != nil { return m.ScheduleTime } return nil } func (m *Attempt) GetDispatchTime() *timestamp.Timestamp { if m != nil { return m.DispatchTime } return nil } func (m *Attempt) GetResponseTime() *timestamp.Timestamp { if m != nil { return m.ResponseTime } return nil } func (m *Attempt) GetResponseStatus() *status.Status { if m != nil { return m.ResponseStatus } return nil } func init() { proto.RegisterType((*Task)(nil), "google.cloud.tasks.v2beta3.Task") proto.RegisterType((*Attempt)(nil), "google.cloud.tasks.v2beta3.Attempt") proto.RegisterEnum("google.cloud.tasks.v2beta3.Task_View", Task_View_name, Task_View_value) } func init() { proto.RegisterFile("google/cloud/tasks/v2beta3/task.proto", fileDescriptor_task_e4ac2456a2f2128b) } var fileDescriptor_task_e4ac2456a2f2128b = []byte{ // 589 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xdf, 0x4f, 0xdb, 0x30, 0x10, 0xc7, 0x09, 0xa4, 0x40, 0xdd, 0xd0, 0x75, 0x16, 0x12, 0x59, 0x35, 0xb1, 0xaa, 0x53, 0x45, 0x9f, 0x92, 0xad, 0x3c, 0x4d, 0x3c, 0x54, 0xf4, 0x97, 0x5a, 0xa9, 0x9a, 0xaa, 0x14, 0x98, 0xb4, 0x97, 0xc8, 0x4d, 0x4c, 0x1a, 0x91, 0xda, 0x5e, 0xec, 0x80, 0xf8, 0x13, 0xf6, 0x17, 0xef, 0x75, 0x8a, 0x63, 0x57, 0x30, 0x58, 0xbb, 0xbd, 0xf5, 0xee, 0xbe, 0xdf, 0x4f, 0x2f, 0x77, 0x97, 0x80, 0x56, 0x44, 0x69, 0x94, 0x60, 0x37, 0x48, 0x68, 0x16, 0xba, 0x02, 0xf1, 0x3b, 0xee, 0xde, 0x77, 0x16, 0x58, 0xa0, 0x73, 0x19, 0x39, 0x2c, 0xa5, 0x82, 0xc2, 0x7a, 0x21, 0x73, 0xa4, 0xcc, 0x91, 0x32, 0x47, 0xc9, 0xea, 0xef, 0x15, 0x02, 0xb1, 0xd8, 0x45, 0x84, 0x50, 0x81, 0x44, 0x4c, 0x09, 0x2f, 0x9c, 0xf5, 0xb3, 0x8d, 0x7f, 0x90, 0x46, 0x58, 0x28, 0xe1, 0xa9, 0x12, 0xca, 0x68, 0x91, 0xdd, 0xba, 0x61, 0x96, 0x4a, 0x92, 0xaa, 0x7f, 0xf8, 0xb3, 0x2e, 0xe2, 0x15, 0xe6, 0x02, 0xad, 0x98, 0x12, 0x9c, 0x28, 0x41, 0xca, 0x02, 0x97, 0x0b, 0x24, 0x32, 0xd5, 0x42, 0xf3, 0x57, 0x09, 0x98, 0x57, 0x88, 0xdf, 0x41, 0x08, 0x4c, 0x82, 0x56, 0xd8, 0x36, 0x1a, 0x46, 0xbb, 0xec, 0xc9, 0xdf, 0x30, 0x06, 0x27, 0x88, 0x31, 0x1f, 0x93, 0x28, 0x26, 0xd8, 0x5f, 0x0a, 0xc1, 0xfc, 0x14, 0xff, 0xc8, 0x30, 0x17, 0xf6, 0x5e, 0xc3, 0x68, 0x57, 0x3a, 0x9f, 0x9c, 0xbf, 0x3f, 0xbb, 0x73, 0xc9, 0xd8, 0x50, 0x3a, 0xc7, 0x42, 0x30, 0xaf, 0xf0, 0x8d, 0x77, 0xbc, 0x63, 0xf4, 0x4a, 0x1e, 0x4e, 0x81, 0xf5, 0x8c, 0x5f, 0x91, 0xfc, 0xb3, 0x4d, 0xfc, 0xe7, 0xd8, 0xca, 0xf2, 0x09, 0xad, 0x0b, 0x8e, 0x78, 0xb0, 0xc4, 0x61, 0x96, 0x60, 0x3f, 0x1f, 0x85, 0x6d, 0x4a, 0x5c, 0x5d, 0xe3, 0xf4, 0x9c, 0x9c, 0x2b, 0x3d, 0x27, 0xcf, 0xd2, 0x86, 0x3c, 0x05, 0x2f, 0x40, 0x25, 0x48, 0x31, 0x12, 0xca, 0x5e, 0xda, 0x6a, 0x07, 0x85, 0x5c, 0x9a, 0x47, 0xe0, 0x6d, 0x18, 0x73, 0x86, 0x44, 0xb0, 0xf4, 0x43, 0x8c, 0xc2, 0x24, 0x26, 0xd8, 0xb6, 0x24, 0xe2, 0xdd, 0x0b, 0xc4, 0x40, 0x6d, 0xd2, 0xab, 0x69, 0xcf, 0x40, 0x59, 0x60, 0x0b, 0x54, 0xd7, 0x9c, 0x80, 0x66, 0x44, 0xd8, 0xfb, 0x0d, 0xa3, 0x5d, 0xf2, 0x8e, 0x74, 0xb6, 0x9f, 0x27, 0x73, 0x59, 0x8a, 0x39, 0xa3, 0x84, 0x63, 0x25, 0x3b, 0x28, 0x64, 0x3a, 0x5b, 0xc8, 0xc6, 0xe0, 0xe8, 0x36, 0x4e, 0xb9, 0xf0, 0x91, 0x10, 0x78, 0xc5, 0x84, 0x7d, 0x28, 0x3b, 0xfa, 0xb8, 0x71, 0x85, 0x85, 0xd4, 0xb3, 0xa4, 0x53, 0x45, 0x70, 0x04, 0xac, 0x04, 0x3d, 0x01, 0x95, 0xff, 0x1d, 0x54, 0xc9, 0x8d, 0x9a, 0xf3, 0x05, 0x98, 0xf7, 0x31, 0x7e, 0xb0, 0x41, 0xc3, 0x68, 0x57, 0x3b, 0xad, 0x4d, 0xfe, 0xfc, 0x44, 0x9d, 0x9b, 0x18, 0x3f, 0x78, 0xd2, 0xd2, 0xfc, 0x0c, 0xcc, 0x3c, 0x82, 0xc7, 0xa0, 0x76, 0x33, 0x19, 0x7e, 0xf3, 0xaf, 0xbf, 0xce, 0x67, 0xc3, 0xfe, 0x64, 0x34, 0x19, 0x0e, 0x6a, 0x3b, 0xb0, 0x0c, 0x4a, 0xbd, 0xcb, 0xf9, 0xa4, 0x5f, 0x33, 0xe0, 0x21, 0x30, 0x47, 0xd7, 0xd3, 0x69, 0x6d, 0xb7, 0x57, 0x05, 0x16, 0x43, 0x8f, 0x09, 0x45, 0xa1, 0x2f, 0x1e, 0x19, 0x6e, 0xfe, 0xdc, 0x05, 0x07, 0xba, 0x93, 0x17, 0xf7, 0x62, 0xfc, 0xe7, 0xbd, 0x74, 0xc1, 0x7a, 0x29, 0x05, 0x60, 0x77, 0x3b, 0x40, 0x1b, 0x34, 0x60, 0xbd, 0x44, 0x09, 0xd8, 0xdb, 0x0e, 0xd0, 0x06, 0x75, 0xb1, 0x6f, 0xd6, 0x80, 0xe2, 0x0d, 0x57, 0x47, 0x0f, 0x35, 0x22, 0x65, 0x81, 0x33, 0x97, 0x15, 0x6f, 0x7d, 0x30, 0x45, 0xdc, 0x23, 0xe0, 0x34, 0xa0, 0xab, 0x0d, 0x0b, 0xe8, 0x95, 0xf3, 0x0d, 0xcc, 0xf2, 0x26, 0x66, 0xc6, 0xf7, 0xae, 0x12, 0x46, 0x34, 0x41, 0x24, 0x72, 0x68, 0x1a, 0xb9, 0x11, 0x26, 0xb2, 0x45, 0xb7, 0x28, 0x21, 0x16, 0xf3, 0xd7, 0x3e, 0x6b, 0x17, 0x32, 0x5a, 0xec, 0x4b, 0xed, 0xf9, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0xa8, 0x61, 0xbf, 0x79, 0x62, 0x05, 0x00, 0x00, }
{ return m.View }
conditional_block
mod.rs
//! Provides structs used to interact with the cypher transaction endpoint //! //! The types declared in this module, save for `Statement`, don't need to be instantiated //! directly, since they can be obtained from the `GraphClient`. //! //! # Examples //! //! ## Execute a single query //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! let graph = GraphClient::connect(URL).unwrap(); //! //! graph.cypher().exec("CREATE (n:CYPHER_QUERY {value: 1})").unwrap(); //! let result = graph.cypher().exec("MATCH (n:CYPHER_QUERY) RETURN n.value AS value").unwrap(); //! # assert_eq!(result.data.len(), 1); //! //! // Iterate over the results //! for row in result.rows() { //! let value = row.get::<i32>("value").unwrap(); // or: let value: i32 = row.get("value"); //! assert_eq!(value, 1); //! } //! # graph.cypher().exec("MATCH (n:CYPHER_QUERY) delete n"); //! ``` //! //! ## Execute multiple queries //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! # let graph = GraphClient::connect(URL).unwrap(); //! let mut query = graph.cypher().query() //! .with_statement("MATCH (n:SOME_CYPHER_QUERY) RETURN n.value as value") //! .with_statement("MATCH (n:OTHER_CYPHER_QUERY) RETURN n"); //! //! let results = query.send().unwrap(); //! //! for row in results[0].rows() { //! let value: i32 = row.get("value").unwrap(); //! assert_eq!(value, 1); //! } //! ``` //! //! ## Start a transaction //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! # let graph = GraphClient::connect(URL).unwrap(); //! let (transaction, results) = graph.cypher().transaction() //! .with_statement("MATCH (n:TRANSACTION_CYPHER_QUERY) RETURN n") //! .begin().unwrap(); //! //! # assert_eq!(results.len(), 1); //! ``` pub mod transaction; pub mod statement; pub mod result; pub use self::statement::Statement; pub use self::transaction::Transaction; pub use self::result::CypherResult; use std::convert::Into; use std::collections::BTreeMap; use hyper::client::{Client, Response}; use hyper::header::Headers; use url::Url; use serde::Deserialize; use serde_json::{self, Value}; use serde_json::de as json_de; use serde_json::ser as json_ser; use serde_json::value as json_value; use self::result::{QueryResult, ResultTrait}; use ::error::GraphError; #[cfg(feature = "rustc-serialize")] fn check_param_errors_for_rustc_serialize(statements: &Vec<Statement>) -> Result<(), GraphError> { for stmt in statements.iter() { if stmt.has_param_errors() { let entry = stmt.param_errors().iter().nth(1).unwrap(); return Err(GraphError::new( &format!("Error at parameter '{}' of query '{}': {}", entry.0, stmt.statement(), entry.1) )); } }
#[cfg(not(feature = "rustc-serialize"))] fn check_param_errors_for_rustc_serialize(_: &Vec<Statement>) -> Result<(), GraphError> { Ok(()) } fn send_query(client: &Client, endpoint: &str, headers: &Headers, statements: Vec<Statement>) -> Result<Response, GraphError> { if cfg!(feature = "rustc-serialize") { try!(check_param_errors_for_rustc_serialize(&statements)); } let mut json = BTreeMap::new(); json.insert("statements", statements); let json = match serde_json::to_string(&json) { Ok(json) => json, Err(e) => { error!("Unable to serialize request: {}", e); return Err(GraphError::new_error(Box::new(e))); } }; let req = client.post(endpoint) .headers(headers.clone()) .body(&json); debug!("Seding query:\n{}", json_ser::to_string_pretty(&json).unwrap_or(String::new())); let res = try!(req.send()); Ok(res) } fn parse_response<T: Deserialize + ResultTrait>(res: &mut Response) -> Result<T, GraphError> { let value = json_de::from_reader(res); let result = match value.and_then(|v: Value| json_value::from_value::<T>(v.clone())) { Ok(result) => result, Err(e) => { error!("Unable to parse response: {}", e); return Err(GraphError::new_error(Box::new(e))); } }; if result.errors().len() > 0 { return Err(GraphError::new_neo4j_error(result.errors().clone())); } Ok(result) } /// Represents the cypher endpoint of a neo4j server /// /// The `Cypher` struct holds information about the cypher enpoint. It is used to create the queries /// that are sent to the server. pub struct Cypher { endpoint: Url, client: Client, headers: Headers, } impl Cypher { /// Creates a new Cypher /// /// Its arguments are the cypher transaction endpoint and the HTTP headers containing HTTP /// Basic Authentication, if needed. pub fn new(endpoint: Url, headers: Headers) -> Self { Cypher { endpoint: endpoint, client: Client::new(), headers: headers, } } fn endpoint(&self) -> &Url { &self.endpoint } fn client(&self) -> &Client { &self.client } fn headers(&self) -> &Headers { &self.headers } /// Creates a new `CypherQuery` pub fn query(&self) -> CypherQuery { CypherQuery { statements: Vec::new(), cypher: &self, } } /// Executes the given `Statement` /// /// Parameter can be anything that implements `Into<Statement>`, `&str` or `Statement` itself pub fn exec<S: Into<Statement>>(&self, statement: S) -> Result<CypherResult, GraphError> { let mut query = self.query(); query.add_statement(statement); let mut results = try!(query.send()); match results.pop() { Some(result) => Ok(result), None => Err(GraphError::new("No results returned from server")), } } /// Creates a new `Transaction` pub fn transaction(&self) -> Transaction<self::transaction::Created> { Transaction::new(&self.endpoint.to_string(), &self.headers) } } /// Represents a cypher query /// /// A cypher query is composed by statements, each one containing the query itself and its parameters. /// /// The query parameters must implement `Serialize` so they can be serialized into JSON in order to /// be sent to the server pub struct CypherQuery<'a> { statements: Vec<Statement>, cypher: &'a Cypher, } impl<'a> CypherQuery<'a> { /// Adds statements in builder style pub fn with_statement<T: Into<Statement>>(mut self, statement: T) -> Self { self.add_statement(statement); self } pub fn add_statement<T: Into<Statement>>(&mut self, statement: T) { self.statements.push(statement.into()); } pub fn statements(&self) -> &Vec<Statement> { &self.statements } pub fn set_statements(&mut self, statements: Vec<Statement>) { self.statements = statements; } /// Sends the query to the server /// /// The statements contained in the query are sent to the server and the results are parsed /// into a `Vec<CypherResult>` in order to match the response of the neo4j api. pub fn send(self) -> Result<Vec<CypherResult>, GraphError> { let client = self.cypher.client(); let endpoint = format!("{}/{}", self.cypher.endpoint(), "commit"); let headers = self.cypher.headers(); let mut res = try!(send_query(client, &endpoint, headers, self.statements)); let result: QueryResult = try!(parse_response(&mut res)); if result.errors().len() > 0 { return Err(GraphError::new_neo4j_error(result.errors().clone())) } Ok(result.results) } } #[cfg(test)] mod tests { use super::*; use ::cypher::result::Row; fn get_cypher() -> Cypher { use hyper::Url; use hyper::header::{Authorization, Basic, ContentType, Headers}; let cypher_endpoint = Url::parse("http://localhost:7474/db/data/transaction").unwrap(); let mut headers = Headers::new(); headers.set(Authorization( Basic { username: "neo4j".to_owned(), password: Some("neo4j".to_owned()), } )); headers.set(ContentType::json()); Cypher::new(cypher_endpoint, headers) } #[test] fn query_without_params() { let result = get_cypher().exec("MATCH (n:TEST_CYPHER) RETURN n").unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_string_param() { let statement = Statement::new("MATCH (n:TEST_CYPHER {name: {name}}) RETURN n") .with_param("name", "Neo"); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_int_param() { let statement = Statement::new("MATCH (n:TEST_CYPHER {value: {value}}) RETURN n") .with_param("value", 42); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_complex_param() { #[cfg(not(feature = "rustc-serialize"))] mod inner { #[derive(Serialize, Deserialize)] pub struct ComplexType { pub name: String, pub value: i32, } } #[cfg(feature = "rustc-serialize")] mod inner { #[derive(RustcEncodable, RustcDecodable)] pub struct ComplexType { pub name: String, pub value: i32, } } let cypher = get_cypher(); let complex_param = inner::ComplexType { name: "Complex".to_owned(), value: 42, }; let statement = Statement::new("CREATE (n:TEST_CYPHER_COMPLEX_PARAM {p})") .with_param("p", &complex_param); let result = cypher.exec(statement); assert!(result.is_ok()); let results = cypher.exec("MATCH (n:TEST_CYPHER_COMPLEX_PARAM) RETURN n").unwrap(); let rows: Vec<Row> = results.rows().take(1).collect(); let row = rows.first().unwrap(); let complex_result: inner::ComplexType = row.get("n").unwrap(); assert_eq!(complex_result.name, "Complex"); assert_eq!(complex_result.value, 42); cypher.exec("MATCH (n:TEST_CYPHER_COMPLEX_PARAM) DELETE n").unwrap(); } #[test] fn query_with_multiple_params() { let statement = Statement::new( "MATCH (n:TEST_CYPHER {name: {name}}) WHERE n.value = {value} RETURN n") .with_param("name", "Neo") .with_param("value", 42); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn multiple_queries() { let cypher = get_cypher(); let statement1 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n"); let statement2 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n"); let query = cypher.query() .with_statement(statement1) .with_statement(statement2); let results = query.send().unwrap(); assert_eq!(results.len(), 2); } }
Ok(()) }
random_line_split
mod.rs
//! Provides structs used to interact with the cypher transaction endpoint //! //! The types declared in this module, save for `Statement`, don't need to be instantiated //! directly, since they can be obtained from the `GraphClient`. //! //! # Examples //! //! ## Execute a single query //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! let graph = GraphClient::connect(URL).unwrap(); //! //! graph.cypher().exec("CREATE (n:CYPHER_QUERY {value: 1})").unwrap(); //! let result = graph.cypher().exec("MATCH (n:CYPHER_QUERY) RETURN n.value AS value").unwrap(); //! # assert_eq!(result.data.len(), 1); //! //! // Iterate over the results //! for row in result.rows() { //! let value = row.get::<i32>("value").unwrap(); // or: let value: i32 = row.get("value"); //! assert_eq!(value, 1); //! } //! # graph.cypher().exec("MATCH (n:CYPHER_QUERY) delete n"); //! ``` //! //! ## Execute multiple queries //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! # let graph = GraphClient::connect(URL).unwrap(); //! let mut query = graph.cypher().query() //! .with_statement("MATCH (n:SOME_CYPHER_QUERY) RETURN n.value as value") //! .with_statement("MATCH (n:OTHER_CYPHER_QUERY) RETURN n"); //! //! let results = query.send().unwrap(); //! //! for row in results[0].rows() { //! let value: i32 = row.get("value").unwrap(); //! assert_eq!(value, 1); //! } //! ``` //! //! ## Start a transaction //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! # let graph = GraphClient::connect(URL).unwrap(); //! let (transaction, results) = graph.cypher().transaction() //! .with_statement("MATCH (n:TRANSACTION_CYPHER_QUERY) RETURN n") //! .begin().unwrap(); //! //! # assert_eq!(results.len(), 1); //! ``` pub mod transaction; pub mod statement; pub mod result; pub use self::statement::Statement; pub use self::transaction::Transaction; pub use self::result::CypherResult; use std::convert::Into; use std::collections::BTreeMap; use hyper::client::{Client, Response}; use hyper::header::Headers; use url::Url; use serde::Deserialize; use serde_json::{self, Value}; use serde_json::de as json_de; use serde_json::ser as json_ser; use serde_json::value as json_value; use self::result::{QueryResult, ResultTrait}; use ::error::GraphError; #[cfg(feature = "rustc-serialize")] fn check_param_errors_for_rustc_serialize(statements: &Vec<Statement>) -> Result<(), GraphError> { for stmt in statements.iter() { if stmt.has_param_errors() { let entry = stmt.param_errors().iter().nth(1).unwrap(); return Err(GraphError::new( &format!("Error at parameter '{}' of query '{}': {}", entry.0, stmt.statement(), entry.1) )); } } Ok(()) } #[cfg(not(feature = "rustc-serialize"))] fn check_param_errors_for_rustc_serialize(_: &Vec<Statement>) -> Result<(), GraphError> { Ok(()) } fn send_query(client: &Client, endpoint: &str, headers: &Headers, statements: Vec<Statement>) -> Result<Response, GraphError> { if cfg!(feature = "rustc-serialize") { try!(check_param_errors_for_rustc_serialize(&statements)); } let mut json = BTreeMap::new(); json.insert("statements", statements); let json = match serde_json::to_string(&json) { Ok(json) => json, Err(e) => { error!("Unable to serialize request: {}", e); return Err(GraphError::new_error(Box::new(e))); } }; let req = client.post(endpoint) .headers(headers.clone()) .body(&json); debug!("Seding query:\n{}", json_ser::to_string_pretty(&json).unwrap_or(String::new())); let res = try!(req.send()); Ok(res) } fn parse_response<T: Deserialize + ResultTrait>(res: &mut Response) -> Result<T, GraphError> { let value = json_de::from_reader(res); let result = match value.and_then(|v: Value| json_value::from_value::<T>(v.clone())) { Ok(result) => result, Err(e) => { error!("Unable to parse response: {}", e); return Err(GraphError::new_error(Box::new(e))); } }; if result.errors().len() > 0 { return Err(GraphError::new_neo4j_error(result.errors().clone())); } Ok(result) } /// Represents the cypher endpoint of a neo4j server /// /// The `Cypher` struct holds information about the cypher enpoint. It is used to create the queries /// that are sent to the server. pub struct Cypher { endpoint: Url, client: Client, headers: Headers, } impl Cypher { /// Creates a new Cypher /// /// Its arguments are the cypher transaction endpoint and the HTTP headers containing HTTP /// Basic Authentication, if needed. pub fn new(endpoint: Url, headers: Headers) -> Self { Cypher { endpoint: endpoint, client: Client::new(), headers: headers, } } fn endpoint(&self) -> &Url { &self.endpoint } fn client(&self) -> &Client { &self.client } fn headers(&self) -> &Headers { &self.headers } /// Creates a new `CypherQuery` pub fn query(&self) -> CypherQuery { CypherQuery { statements: Vec::new(), cypher: &self, } } /// Executes the given `Statement` /// /// Parameter can be anything that implements `Into<Statement>`, `&str` or `Statement` itself pub fn exec<S: Into<Statement>>(&self, statement: S) -> Result<CypherResult, GraphError> { let mut query = self.query(); query.add_statement(statement); let mut results = try!(query.send()); match results.pop() { Some(result) => Ok(result), None => Err(GraphError::new("No results returned from server")), } } /// Creates a new `Transaction` pub fn transaction(&self) -> Transaction<self::transaction::Created> { Transaction::new(&self.endpoint.to_string(), &self.headers) } } /// Represents a cypher query /// /// A cypher query is composed by statements, each one containing the query itself and its parameters. /// /// The query parameters must implement `Serialize` so they can be serialized into JSON in order to /// be sent to the server pub struct CypherQuery<'a> { statements: Vec<Statement>, cypher: &'a Cypher, } impl<'a> CypherQuery<'a> { /// Adds statements in builder style pub fn with_statement<T: Into<Statement>>(mut self, statement: T) -> Self { self.add_statement(statement); self } pub fn add_statement<T: Into<Statement>>(&mut self, statement: T) { self.statements.push(statement.into()); } pub fn statements(&self) -> &Vec<Statement> { &self.statements } pub fn set_statements(&mut self, statements: Vec<Statement>) { self.statements = statements; } /// Sends the query to the server /// /// The statements contained in the query are sent to the server and the results are parsed /// into a `Vec<CypherResult>` in order to match the response of the neo4j api. pub fn send(self) -> Result<Vec<CypherResult>, GraphError> { let client = self.cypher.client(); let endpoint = format!("{}/{}", self.cypher.endpoint(), "commit"); let headers = self.cypher.headers(); let mut res = try!(send_query(client, &endpoint, headers, self.statements)); let result: QueryResult = try!(parse_response(&mut res)); if result.errors().len() > 0 { return Err(GraphError::new_neo4j_error(result.errors().clone())) } Ok(result.results) } } #[cfg(test)] mod tests { use super::*; use ::cypher::result::Row; fn get_cypher() -> Cypher { use hyper::Url; use hyper::header::{Authorization, Basic, ContentType, Headers}; let cypher_endpoint = Url::parse("http://localhost:7474/db/data/transaction").unwrap(); let mut headers = Headers::new(); headers.set(Authorization( Basic { username: "neo4j".to_owned(), password: Some("neo4j".to_owned()), } )); headers.set(ContentType::json()); Cypher::new(cypher_endpoint, headers) } #[test] fn query_without_params() { let result = get_cypher().exec("MATCH (n:TEST_CYPHER) RETURN n").unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_string_param() { let statement = Statement::new("MATCH (n:TEST_CYPHER {name: {name}}) RETURN n") .with_param("name", "Neo"); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_int_param() { let statement = Statement::new("MATCH (n:TEST_CYPHER {value: {value}}) RETURN n") .with_param("value", 42); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_complex_param() { #[cfg(not(feature = "rustc-serialize"))] mod inner { #[derive(Serialize, Deserialize)] pub struct ComplexType { pub name: String, pub value: i32, } } #[cfg(feature = "rustc-serialize")] mod inner { #[derive(RustcEncodable, RustcDecodable)] pub struct ComplexType { pub name: String, pub value: i32, } } let cypher = get_cypher(); let complex_param = inner::ComplexType { name: "Complex".to_owned(), value: 42, }; let statement = Statement::new("CREATE (n:TEST_CYPHER_COMPLEX_PARAM {p})") .with_param("p", &complex_param); let result = cypher.exec(statement); assert!(result.is_ok()); let results = cypher.exec("MATCH (n:TEST_CYPHER_COMPLEX_PARAM) RETURN n").unwrap(); let rows: Vec<Row> = results.rows().take(1).collect(); let row = rows.first().unwrap(); let complex_result: inner::ComplexType = row.get("n").unwrap(); assert_eq!(complex_result.name, "Complex"); assert_eq!(complex_result.value, 42); cypher.exec("MATCH (n:TEST_CYPHER_COMPLEX_PARAM) DELETE n").unwrap(); } #[test] fn query_with_multiple_params() { let statement = Statement::new( "MATCH (n:TEST_CYPHER {name: {name}}) WHERE n.value = {value} RETURN n") .with_param("name", "Neo") .with_param("value", 42); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn multiple_queries()
}
{ let cypher = get_cypher(); let statement1 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n"); let statement2 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n"); let query = cypher.query() .with_statement(statement1) .with_statement(statement2); let results = query.send().unwrap(); assert_eq!(results.len(), 2); }
identifier_body
mod.rs
//! Provides structs used to interact with the cypher transaction endpoint //! //! The types declared in this module, save for `Statement`, don't need to be instantiated //! directly, since they can be obtained from the `GraphClient`. //! //! # Examples //! //! ## Execute a single query //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! let graph = GraphClient::connect(URL).unwrap(); //! //! graph.cypher().exec("CREATE (n:CYPHER_QUERY {value: 1})").unwrap(); //! let result = graph.cypher().exec("MATCH (n:CYPHER_QUERY) RETURN n.value AS value").unwrap(); //! # assert_eq!(result.data.len(), 1); //! //! // Iterate over the results //! for row in result.rows() { //! let value = row.get::<i32>("value").unwrap(); // or: let value: i32 = row.get("value"); //! assert_eq!(value, 1); //! } //! # graph.cypher().exec("MATCH (n:CYPHER_QUERY) delete n"); //! ``` //! //! ## Execute multiple queries //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! # let graph = GraphClient::connect(URL).unwrap(); //! let mut query = graph.cypher().query() //! .with_statement("MATCH (n:SOME_CYPHER_QUERY) RETURN n.value as value") //! .with_statement("MATCH (n:OTHER_CYPHER_QUERY) RETURN n"); //! //! let results = query.send().unwrap(); //! //! for row in results[0].rows() { //! let value: i32 = row.get("value").unwrap(); //! assert_eq!(value, 1); //! } //! ``` //! //! ## Start a transaction //! ``` //! # use rusted_cypher::GraphClient; //! # const URL: &'static str = "http://neo4j:neo4j@localhost:7474/db/data"; //! # let graph = GraphClient::connect(URL).unwrap(); //! let (transaction, results) = graph.cypher().transaction() //! .with_statement("MATCH (n:TRANSACTION_CYPHER_QUERY) RETURN n") //! .begin().unwrap(); //! //! # assert_eq!(results.len(), 1); //! ``` pub mod transaction; pub mod statement; pub mod result; pub use self::statement::Statement; pub use self::transaction::Transaction; pub use self::result::CypherResult; use std::convert::Into; use std::collections::BTreeMap; use hyper::client::{Client, Response}; use hyper::header::Headers; use url::Url; use serde::Deserialize; use serde_json::{self, Value}; use serde_json::de as json_de; use serde_json::ser as json_ser; use serde_json::value as json_value; use self::result::{QueryResult, ResultTrait}; use ::error::GraphError; #[cfg(feature = "rustc-serialize")] fn check_param_errors_for_rustc_serialize(statements: &Vec<Statement>) -> Result<(), GraphError> { for stmt in statements.iter() { if stmt.has_param_errors() { let entry = stmt.param_errors().iter().nth(1).unwrap(); return Err(GraphError::new( &format!("Error at parameter '{}' of query '{}': {}", entry.0, stmt.statement(), entry.1) )); } } Ok(()) } #[cfg(not(feature = "rustc-serialize"))] fn check_param_errors_for_rustc_serialize(_: &Vec<Statement>) -> Result<(), GraphError> { Ok(()) } fn
(client: &Client, endpoint: &str, headers: &Headers, statements: Vec<Statement>) -> Result<Response, GraphError> { if cfg!(feature = "rustc-serialize") { try!(check_param_errors_for_rustc_serialize(&statements)); } let mut json = BTreeMap::new(); json.insert("statements", statements); let json = match serde_json::to_string(&json) { Ok(json) => json, Err(e) => { error!("Unable to serialize request: {}", e); return Err(GraphError::new_error(Box::new(e))); } }; let req = client.post(endpoint) .headers(headers.clone()) .body(&json); debug!("Seding query:\n{}", json_ser::to_string_pretty(&json).unwrap_or(String::new())); let res = try!(req.send()); Ok(res) } fn parse_response<T: Deserialize + ResultTrait>(res: &mut Response) -> Result<T, GraphError> { let value = json_de::from_reader(res); let result = match value.and_then(|v: Value| json_value::from_value::<T>(v.clone())) { Ok(result) => result, Err(e) => { error!("Unable to parse response: {}", e); return Err(GraphError::new_error(Box::new(e))); } }; if result.errors().len() > 0 { return Err(GraphError::new_neo4j_error(result.errors().clone())); } Ok(result) } /// Represents the cypher endpoint of a neo4j server /// /// The `Cypher` struct holds information about the cypher enpoint. It is used to create the queries /// that are sent to the server. pub struct Cypher { endpoint: Url, client: Client, headers: Headers, } impl Cypher { /// Creates a new Cypher /// /// Its arguments are the cypher transaction endpoint and the HTTP headers containing HTTP /// Basic Authentication, if needed. pub fn new(endpoint: Url, headers: Headers) -> Self { Cypher { endpoint: endpoint, client: Client::new(), headers: headers, } } fn endpoint(&self) -> &Url { &self.endpoint } fn client(&self) -> &Client { &self.client } fn headers(&self) -> &Headers { &self.headers } /// Creates a new `CypherQuery` pub fn query(&self) -> CypherQuery { CypherQuery { statements: Vec::new(), cypher: &self, } } /// Executes the given `Statement` /// /// Parameter can be anything that implements `Into<Statement>`, `&str` or `Statement` itself pub fn exec<S: Into<Statement>>(&self, statement: S) -> Result<CypherResult, GraphError> { let mut query = self.query(); query.add_statement(statement); let mut results = try!(query.send()); match results.pop() { Some(result) => Ok(result), None => Err(GraphError::new("No results returned from server")), } } /// Creates a new `Transaction` pub fn transaction(&self) -> Transaction<self::transaction::Created> { Transaction::new(&self.endpoint.to_string(), &self.headers) } } /// Represents a cypher query /// /// A cypher query is composed by statements, each one containing the query itself and its parameters. /// /// The query parameters must implement `Serialize` so they can be serialized into JSON in order to /// be sent to the server pub struct CypherQuery<'a> { statements: Vec<Statement>, cypher: &'a Cypher, } impl<'a> CypherQuery<'a> { /// Adds statements in builder style pub fn with_statement<T: Into<Statement>>(mut self, statement: T) -> Self { self.add_statement(statement); self } pub fn add_statement<T: Into<Statement>>(&mut self, statement: T) { self.statements.push(statement.into()); } pub fn statements(&self) -> &Vec<Statement> { &self.statements } pub fn set_statements(&mut self, statements: Vec<Statement>) { self.statements = statements; } /// Sends the query to the server /// /// The statements contained in the query are sent to the server and the results are parsed /// into a `Vec<CypherResult>` in order to match the response of the neo4j api. pub fn send(self) -> Result<Vec<CypherResult>, GraphError> { let client = self.cypher.client(); let endpoint = format!("{}/{}", self.cypher.endpoint(), "commit"); let headers = self.cypher.headers(); let mut res = try!(send_query(client, &endpoint, headers, self.statements)); let result: QueryResult = try!(parse_response(&mut res)); if result.errors().len() > 0 { return Err(GraphError::new_neo4j_error(result.errors().clone())) } Ok(result.results) } } #[cfg(test)] mod tests { use super::*; use ::cypher::result::Row; fn get_cypher() -> Cypher { use hyper::Url; use hyper::header::{Authorization, Basic, ContentType, Headers}; let cypher_endpoint = Url::parse("http://localhost:7474/db/data/transaction").unwrap(); let mut headers = Headers::new(); headers.set(Authorization( Basic { username: "neo4j".to_owned(), password: Some("neo4j".to_owned()), } )); headers.set(ContentType::json()); Cypher::new(cypher_endpoint, headers) } #[test] fn query_without_params() { let result = get_cypher().exec("MATCH (n:TEST_CYPHER) RETURN n").unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_string_param() { let statement = Statement::new("MATCH (n:TEST_CYPHER {name: {name}}) RETURN n") .with_param("name", "Neo"); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_int_param() { let statement = Statement::new("MATCH (n:TEST_CYPHER {value: {value}}) RETURN n") .with_param("value", 42); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn query_with_complex_param() { #[cfg(not(feature = "rustc-serialize"))] mod inner { #[derive(Serialize, Deserialize)] pub struct ComplexType { pub name: String, pub value: i32, } } #[cfg(feature = "rustc-serialize")] mod inner { #[derive(RustcEncodable, RustcDecodable)] pub struct ComplexType { pub name: String, pub value: i32, } } let cypher = get_cypher(); let complex_param = inner::ComplexType { name: "Complex".to_owned(), value: 42, }; let statement = Statement::new("CREATE (n:TEST_CYPHER_COMPLEX_PARAM {p})") .with_param("p", &complex_param); let result = cypher.exec(statement); assert!(result.is_ok()); let results = cypher.exec("MATCH (n:TEST_CYPHER_COMPLEX_PARAM) RETURN n").unwrap(); let rows: Vec<Row> = results.rows().take(1).collect(); let row = rows.first().unwrap(); let complex_result: inner::ComplexType = row.get("n").unwrap(); assert_eq!(complex_result.name, "Complex"); assert_eq!(complex_result.value, 42); cypher.exec("MATCH (n:TEST_CYPHER_COMPLEX_PARAM) DELETE n").unwrap(); } #[test] fn query_with_multiple_params() { let statement = Statement::new( "MATCH (n:TEST_CYPHER {name: {name}}) WHERE n.value = {value} RETURN n") .with_param("name", "Neo") .with_param("value", 42); let result = get_cypher().exec(statement).unwrap(); assert_eq!(result.columns.len(), 1); assert_eq!(result.columns[0], "n"); } #[test] fn multiple_queries() { let cypher = get_cypher(); let statement1 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n"); let statement2 = Statement::new("MATCH (n:TEST_CYPHER) RETURN n"); let query = cypher.query() .with_statement(statement1) .with_statement(statement2); let results = query.send().unwrap(); assert_eq!(results.len(), 2); } }
send_query
identifier_name
text.rs
//! This protocol is used to handle input and output of //! text-based information intended for the system user during the operation of code in the boot //! services environment. Also included here are the definitions of three console devices: one for input //! and one each for normal output and errors. use core::fmt; use crate::{ status::{Error, Status, Warning}, system::SystemTable, Event, }; /// Keystroke information for the key that was pressed. #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct TextInputKey { /// If there is a pending keystroke, then ScanCode is the EFI scan code defined in /// Table 104. pub ScanCode: u16, /// The UnicodeChar is the actual printable /// character or is zero if the key does not represent a printable /// character (control key, function key, etc.). pub UnicodeChar: u16, } /// This protocol is used to obtain input from the ConsoleIn device. The EFI specification requires that /// the EFI_SIMPLE_TEXT_INPUT_PROTOCOL supports the same languages as the corresponding /// EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL. #[repr(C)] pub struct TextInput { /// Reset the ConsoleIn device. pub Reset: extern "win64" fn(&TextInput, bool) -> Status, /// Returns the next input character. pub ReadKeyStroke: extern "win64" fn(&TextInput, &mut TextInputKey) -> Status, /// Event to use with EFI_BOOT_SERVICES.WaitForEvent() to wait for a key to be available. pub WaitForKey: Event, } impl TextInput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Returns the next input character, if it exists. pub fn try_read_key_stroke(&self) -> Result<TextInputKey, Error> { let mut key = TextInputKey::default(); (self.ReadKeyStroke)(self, &mut key)?; Ok(key) } /// Returns the next input character after waiting for it. pub fn read_key_stroke( &self, system_table: &'static SystemTable, ) -> Result<TextInputKey, Error> { system_table.BootServices.wait_for_event(&self.WaitForKey)?; self.try_read_key_stroke() } } /// The following data values in the SIMPLE_TEXT_OUTPUT_MODE interface are read-only and are /// changed by using the appropriate interface functions. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct TextOutputMode { /// The number of modes supported by QueryMode() and SetMode(). pub MaxMode: i32, /// The text mode of the output device(s). pub Mode: i32, /// The current character output attribute. pub Attribute: i32, /// The cursor’s column. pub CursorColumn: i32, /// The cursor’s row. pub CursorRow: i32, /// The cursor is currently visible or not. pub CursorVisible: bool, } /// This protocol is used to control text-based output devices. #[repr(C)] pub struct TextOutput { /// Reset the ConsoleOut device. pub Reset: extern "win64" fn(&TextOutput, bool) -> Status, /// Displays the string on the device at the current cursor location. pub OutputString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Tests to see if the ConsoleOut device supports this string. pub TestString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Queries information concerning the output device’s supported text mode. pub QueryMode: extern "win64" fn(&TextOutput, usize, &mut usize, &mut usize) -> Status, /// Sets the current mode of the output device. pub SetMode: extern "win64" fn(&TextOutput, usize) -> Status, /// Sets the foreground and background color of the text that is output. pub SetAttribute: extern "win64" fn(&TextOutput, usize) -> Status, /// Clears the screen with the currently set background color. pub ClearScreen: extern "win64" fn(&TextOutput) -> Status, /// Sets the current cursor position. pub SetCursorPosition: extern "win64" fn(&TextOutput, usize, usize) -> Status, /// Turns the visibility of the cursor on/off. pub EnableCursor: extern "win64" fn(&TextOutput, bool) -> Status, /// Reference to SIMPLE_TEXT_OUTPUT_MODE data. pub Mode: &'static TextOutputMode, } impl TextOutput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Displays the string on the device at the current cursor location. pub fn output_string(&self, string: &str) -> Result<Warning, Error> { with_utf16_str(string, |utf16| (self.OutputString)(self, utf16)) } /// Tests to see if the ConsoleOut device supports this string. pub fn test_string(&self, string: &str) -> Result<(), Error> { with_utf16_str(string, |utf16| (self.TestString)(self, utf16))?; Ok(()) } /// Queries information concerning the output device’s supported text mode. /// /// Returns the number of columns and rows, if successful. pub fn query_mode(&self, mode_number: usize) -> Result<(usize, usize), Error> { let mut columns: usize = 0; let mut rows: usize = 0; (self.QueryMode)(self, mode_number, &mut columns, &mut rows)?; Ok((columns, rows)) } /// Sets the current mode of the output device. pub fn set_mode(&self, mode: usize) -> Result<(), Error> { (self.SetMode)(self, mode)?; Ok(()) } /// Sets the foreground and background color of the text that is output. pub fn set_attribute(&self, attribute: Color) -> Result<(), Error> { (self.SetAttribute)(self, attribute.0)?; Ok(()) } /// Clears the screen with the currently set background color. pub fn clear_screen(&self) -> Result<(), Error> { (self.ClearScreen)(self)?; Ok(()) } /// Sets the current cursor position. pub fn set_cursor_position(&self, column: usize, row: usize) -> Result<(), Error> { (self.SetCursorPosition)(self, column, row)?; Ok(()) } /// Turns the visibility of the cursor on/off. pub fn enable_cursor(&self, enable: bool) -> Result<(), Error> { (self.EnableCursor)(self, enable)?; Ok(()) } } impl<'a> fmt::Write for &'a TextOutput { fn write_str(&mut self, s: &str) -> fmt::Result { self.output_string(s).map_err(|_| fmt::Error).map(|_| ()) } } /// Executes the given function with the UTF16-encoded string. /// /// `function` will get a UTF16-encoded null-terminated string as its argument when its called. /// /// `function` may be called multiple times. This is because the string is converted /// to UTF16 in a fixed size buffer to avoid allocations. As a consequence, any string /// longer than the buffer needs the function to be called multiple times. fn with_utf16_str<FunctionType>(string: &str, function: FunctionType) -> Result<Warning, Error> where FunctionType: Fn(*const u16) -> Status, { const BUFFER_SIZE: usize = 256; let mut buffer = [0u16; BUFFER_SIZE]; let mut current_index = 0; let warning = Warning::Success; // Flushes the buffer let flush_buffer = |ref mut buffer: &mut [u16; BUFFER_SIZE], ref mut current_index, ref mut warning| -> Result<(), Error> { buffer[*current_index] = 0; *current_index = 0; if *warning == Warning::Success { *warning = function(buffer.as_ptr())?; } else { function(buffer.as_ptr())?; } Ok(()) }; for character in string.chars() { // If there is not enough space in the buffer, flush it if current_index + character.len_utf16() + 1 >= BUFFER_SIZE { flush_buffer(&mut buffer, current_index, warning)?; } character.encode_utf16(&mut buffer[current_index..]); current_index += character.len_utf16(); } flush_buffer(&mut buffer, current_index, warning)?; Ok(warning) } /// Represents color information for text. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct Color(usize); impl Color { /// Creates new color information from the foreground and background color. pub const fn new(foreground: ForegroundColor, background: BackgroundColor) -> Color { Color(foreground as usize | background as usize) } } /// Represents a foreground color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum Foregrou
// Represents the foreground color black. Black = 0x00, /// Represents the foreground color blue. Blue = 0x01, /// Represents the foreground color green. Green = 0x02, /// Represents the foreground color cyan. Cyan = 0x03, /// Represents the foreground color red. Red = 0x04, /// Represents the foreground color magenta. Magenta = 0x05, /// Represents the foreground color brown. Brown = 0x06, /// Represents the foreground color light gray. LightGray = 0x07, /// Represents the foreground color dark gray. DarkGray = 0x08, /// Represents the foreground color light blue. LightBlue = 0x09, /// Represents the foreground color light green. LightGreen = 0x0a, /// Represents the foreground color light cyan. LightCyan = 0x0b, /// Represents the foreground color light red. LightRed = 0x0c, /// Represents the foreground color light magenta. LightMagenta = 0x0d, /// Represents the foreground color yellow. Yellow = 0x0e, /// Represents the foreground color white. White = 0x0f, } /// Represents a background color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum BackgroundColor { /// Represents the background color black. Black = 0x00, /// Represents the background color blue. Blue = 0x10, /// Represents the background color green. Green = 0x20, /// Represents the background color cyan. Cyan = 0x30, /// Represents the background color red. Red = 0x40, /// Represents the background color magenta. Magenta = 0x50, /// Represents the background color brown. Brown = 0x60, /// Represents the background color light gray. LightGray = 0x70, }
ndColor { /
identifier_name
text.rs
//! This protocol is used to handle input and output of //! text-based information intended for the system user during the operation of code in the boot //! services environment. Also included here are the definitions of three console devices: one for input //! and one each for normal output and errors. use core::fmt; use crate::{ status::{Error, Status, Warning}, system::SystemTable, Event, }; /// Keystroke information for the key that was pressed. #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct TextInputKey { /// If there is a pending keystroke, then ScanCode is the EFI scan code defined in /// Table 104. pub ScanCode: u16, /// The UnicodeChar is the actual printable /// character or is zero if the key does not represent a printable /// character (control key, function key, etc.). pub UnicodeChar: u16, } /// This protocol is used to obtain input from the ConsoleIn device. The EFI specification requires that /// the EFI_SIMPLE_TEXT_INPUT_PROTOCOL supports the same languages as the corresponding /// EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL. #[repr(C)] pub struct TextInput { /// Reset the ConsoleIn device. pub Reset: extern "win64" fn(&TextInput, bool) -> Status, /// Returns the next input character. pub ReadKeyStroke: extern "win64" fn(&TextInput, &mut TextInputKey) -> Status, /// Event to use with EFI_BOOT_SERVICES.WaitForEvent() to wait for a key to be available. pub WaitForKey: Event, } impl TextInput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Returns the next input character, if it exists. pub fn try_read_key_stroke(&self) -> Result<TextInputKey, Error> { let mut key = TextInputKey::default(); (self.ReadKeyStroke)(self, &mut key)?; Ok(key) } /// Returns the next input character after waiting for it. pub fn read_key_stroke( &self, system_table: &'static SystemTable, ) -> Result<TextInputKey, Error> { system_table.BootServices.wait_for_event(&self.WaitForKey)?; self.try_read_key_stroke() } } /// The following data values in the SIMPLE_TEXT_OUTPUT_MODE interface are read-only and are /// changed by using the appropriate interface functions. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct TextOutputMode { /// The number of modes supported by QueryMode() and SetMode(). pub MaxMode: i32, /// The text mode of the output device(s). pub Mode: i32, /// The current character output attribute. pub Attribute: i32, /// The cursor’s column. pub CursorColumn: i32, /// The cursor’s row. pub CursorRow: i32, /// The cursor is currently visible or not. pub CursorVisible: bool, } /// This protocol is used to control text-based output devices. #[repr(C)] pub struct TextOutput { /// Reset the ConsoleOut device. pub Reset: extern "win64" fn(&TextOutput, bool) -> Status, /// Displays the string on the device at the current cursor location. pub OutputString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Tests to see if the ConsoleOut device supports this string. pub TestString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Queries information concerning the output device’s supported text mode. pub QueryMode: extern "win64" fn(&TextOutput, usize, &mut usize, &mut usize) -> Status, /// Sets the current mode of the output device. pub SetMode: extern "win64" fn(&TextOutput, usize) -> Status, /// Sets the foreground and background color of the text that is output. pub SetAttribute: extern "win64" fn(&TextOutput, usize) -> Status, /// Clears the screen with the currently set background color. pub ClearScreen: extern "win64" fn(&TextOutput) -> Status, /// Sets the current cursor position. pub SetCursorPosition: extern "win64" fn(&TextOutput, usize, usize) -> Status, /// Turns the visibility of the cursor on/off. pub EnableCursor: extern "win64" fn(&TextOutput, bool) -> Status, /// Reference to SIMPLE_TEXT_OUTPUT_MODE data. pub Mode: &'static TextOutputMode, } impl TextOutput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Displays the string on the device at the current cursor location. pub fn output_string(&self, string: &str) -> Result<Warning, Error> { with_utf16_str(string, |utf16| (self.OutputString)(self, utf16)) } /// Tests to see if the ConsoleOut device supports this string. pub fn test_string(&self, string: &str) -> Result<(), Error> { with_utf16_str(string, |utf16| (self.TestString)(self, utf16))?; Ok(()) } /// Queries information concerning the output device’s supported text mode. /// /// Returns the number of columns and rows, if successful. pub fn query_mode(&self, mode_number: usize) -> Result<(usize, usize), Error> { let mut columns: usize = 0; let mut rows: usize = 0; (self.QueryMode)(self, mode_number, &mut columns, &mut rows)?; Ok((columns, rows)) } /// Sets the current mode of the output device. pub fn set_mode(&self, mode: usize) -> Result<(), Error> { (self.SetMode)(self, mode)?; Ok(()) } /// Sets the foreground and background color of the text that is output. pub fn set_attribute(&self, attribute: Color) -> Result<(), Error> { (self.SetAttribute)(self, attribute.0)?; Ok(()) } /// Clears the screen with the currently set background color. pub fn clear_screen(&self) -> Result<(), Error> { (self.ClearScreen)(self)?; Ok(()) } /// Sets the current cursor position. pub fn set_cursor_position(&self, column: usize, row: usize) -> Result<(), Error> { (self.SetCursorPosition)(self, column, row)?; Ok(()) } /// Turns the visibility of the cursor on/off. pub fn enable_cursor(&self, enable: bool) -> Result<(), Error> { (self.EnableCursor)(self, enable)?; Ok(()) } } impl<'a> fmt::Write for &'a TextOutput { fn write_str(&mut self, s: &str) -> fmt::Result {
Executes the given function with the UTF16-encoded string. /// /// `function` will get a UTF16-encoded null-terminated string as its argument when its called. /// /// `function` may be called multiple times. This is because the string is converted /// to UTF16 in a fixed size buffer to avoid allocations. As a consequence, any string /// longer than the buffer needs the function to be called multiple times. fn with_utf16_str<FunctionType>(string: &str, function: FunctionType) -> Result<Warning, Error> where FunctionType: Fn(*const u16) -> Status, { const BUFFER_SIZE: usize = 256; let mut buffer = [0u16; BUFFER_SIZE]; let mut current_index = 0; let warning = Warning::Success; // Flushes the buffer let flush_buffer = |ref mut buffer: &mut [u16; BUFFER_SIZE], ref mut current_index, ref mut warning| -> Result<(), Error> { buffer[*current_index] = 0; *current_index = 0; if *warning == Warning::Success { *warning = function(buffer.as_ptr())?; } else { function(buffer.as_ptr())?; } Ok(()) }; for character in string.chars() { // If there is not enough space in the buffer, flush it if current_index + character.len_utf16() + 1 >= BUFFER_SIZE { flush_buffer(&mut buffer, current_index, warning)?; } character.encode_utf16(&mut buffer[current_index..]); current_index += character.len_utf16(); } flush_buffer(&mut buffer, current_index, warning)?; Ok(warning) } /// Represents color information for text. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct Color(usize); impl Color { /// Creates new color information from the foreground and background color. pub const fn new(foreground: ForegroundColor, background: BackgroundColor) -> Color { Color(foreground as usize | background as usize) } } /// Represents a foreground color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum ForegroundColor { /// Represents the foreground color black. Black = 0x00, /// Represents the foreground color blue. Blue = 0x01, /// Represents the foreground color green. Green = 0x02, /// Represents the foreground color cyan. Cyan = 0x03, /// Represents the foreground color red. Red = 0x04, /// Represents the foreground color magenta. Magenta = 0x05, /// Represents the foreground color brown. Brown = 0x06, /// Represents the foreground color light gray. LightGray = 0x07, /// Represents the foreground color dark gray. DarkGray = 0x08, /// Represents the foreground color light blue. LightBlue = 0x09, /// Represents the foreground color light green. LightGreen = 0x0a, /// Represents the foreground color light cyan. LightCyan = 0x0b, /// Represents the foreground color light red. LightRed = 0x0c, /// Represents the foreground color light magenta. LightMagenta = 0x0d, /// Represents the foreground color yellow. Yellow = 0x0e, /// Represents the foreground color white. White = 0x0f, } /// Represents a background color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum BackgroundColor { /// Represents the background color black. Black = 0x00, /// Represents the background color blue. Blue = 0x10, /// Represents the background color green. Green = 0x20, /// Represents the background color cyan. Cyan = 0x30, /// Represents the background color red. Red = 0x40, /// Represents the background color magenta. Magenta = 0x50, /// Represents the background color brown. Brown = 0x60, /// Represents the background color light gray. LightGray = 0x70, }
self.output_string(s).map_err(|_| fmt::Error).map(|_| ()) } } ///
identifier_body
text.rs
//! This protocol is used to handle input and output of //! text-based information intended for the system user during the operation of code in the boot //! services environment. Also included here are the definitions of three console devices: one for input //! and one each for normal output and errors. use core::fmt; use crate::{ status::{Error, Status, Warning}, system::SystemTable, Event, }; /// Keystroke information for the key that was pressed. #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct TextInputKey { /// If there is a pending keystroke, then ScanCode is the EFI scan code defined in /// Table 104. pub ScanCode: u16, /// The UnicodeChar is the actual printable /// character or is zero if the key does not represent a printable /// character (control key, function key, etc.). pub UnicodeChar: u16, } /// This protocol is used to obtain input from the ConsoleIn device. The EFI specification requires that /// the EFI_SIMPLE_TEXT_INPUT_PROTOCOL supports the same languages as the corresponding /// EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL. #[repr(C)] pub struct TextInput { /// Reset the ConsoleIn device. pub Reset: extern "win64" fn(&TextInput, bool) -> Status, /// Returns the next input character. pub ReadKeyStroke: extern "win64" fn(&TextInput, &mut TextInputKey) -> Status, /// Event to use with EFI_BOOT_SERVICES.WaitForEvent() to wait for a key to be available. pub WaitForKey: Event, } impl TextInput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Returns the next input character, if it exists. pub fn try_read_key_stroke(&self) -> Result<TextInputKey, Error> { let mut key = TextInputKey::default(); (self.ReadKeyStroke)(self, &mut key)?; Ok(key) } /// Returns the next input character after waiting for it. pub fn read_key_stroke( &self, system_table: &'static SystemTable, ) -> Result<TextInputKey, Error> { system_table.BootServices.wait_for_event(&self.WaitForKey)?; self.try_read_key_stroke() } } /// The following data values in the SIMPLE_TEXT_OUTPUT_MODE interface are read-only and are /// changed by using the appropriate interface functions. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct TextOutputMode { /// The number of modes supported by QueryMode() and SetMode(). pub MaxMode: i32, /// The text mode of the output device(s). pub Mode: i32, /// The current character output attribute. pub Attribute: i32, /// The cursor’s column. pub CursorColumn: i32, /// The cursor’s row. pub CursorRow: i32, /// The cursor is currently visible or not. pub CursorVisible: bool, } /// This protocol is used to control text-based output devices. #[repr(C)] pub struct TextOutput { /// Reset the ConsoleOut device. pub Reset: extern "win64" fn(&TextOutput, bool) -> Status, /// Displays the string on the device at the current cursor location. pub OutputString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Tests to see if the ConsoleOut device supports this string. pub TestString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Queries information concerning the output device’s supported text mode. pub QueryMode: extern "win64" fn(&TextOutput, usize, &mut usize, &mut usize) -> Status, /// Sets the current mode of the output device. pub SetMode: extern "win64" fn(&TextOutput, usize) -> Status, /// Sets the foreground and background color of the text that is output. pub SetAttribute: extern "win64" fn(&TextOutput, usize) -> Status, /// Clears the screen with the currently set background color. pub ClearScreen: extern "win64" fn(&TextOutput) -> Status, /// Sets the current cursor position. pub SetCursorPosition: extern "win64" fn(&TextOutput, usize, usize) -> Status, /// Turns the visibility of the cursor on/off. pub EnableCursor: extern "win64" fn(&TextOutput, bool) -> Status, /// Reference to SIMPLE_TEXT_OUTPUT_MODE data. pub Mode: &'static TextOutputMode, } impl TextOutput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Displays the string on the device at the current cursor location. pub fn output_string(&self, string: &str) -> Result<Warning, Error> { with_utf16_str(string, |utf16| (self.OutputString)(self, utf16)) } /// Tests to see if the ConsoleOut device supports this string. pub fn test_string(&self, string: &str) -> Result<(), Error> { with_utf16_str(string, |utf16| (self.TestString)(self, utf16))?; Ok(()) } /// Queries information concerning the output device’s supported text mode. /// /// Returns the number of columns and rows, if successful. pub fn query_mode(&self, mode_number: usize) -> Result<(usize, usize), Error> { let mut columns: usize = 0; let mut rows: usize = 0; (self.QueryMode)(self, mode_number, &mut columns, &mut rows)?; Ok((columns, rows)) } /// Sets the current mode of the output device. pub fn set_mode(&self, mode: usize) -> Result<(), Error> { (self.SetMode)(self, mode)?; Ok(()) } /// Sets the foreground and background color of the text that is output. pub fn set_attribute(&self, attribute: Color) -> Result<(), Error> { (self.SetAttribute)(self, attribute.0)?; Ok(()) } /// Clears the screen with the currently set background color. pub fn clear_screen(&self) -> Result<(), Error> { (self.ClearScreen)(self)?; Ok(()) } /// Sets the current cursor position. pub fn set_cursor_position(&self, column: usize, row: usize) -> Result<(), Error> { (self.SetCursorPosition)(self, column, row)?; Ok(()) } /// Turns the visibility of the cursor on/off. pub fn enable_cursor(&self, enable: bool) -> Result<(), Error> { (self.EnableCursor)(self, enable)?; Ok(()) } } impl<'a> fmt::Write for &'a TextOutput { fn write_str(&mut self, s: &str) -> fmt::Result { self.output_string(s).map_err(|_| fmt::Error).map(|_| ()) } } /// Executes the given function with the UTF16-encoded string. /// /// `function` will get a UTF16-encoded null-terminated string as its argument when its called. /// /// `function` may be called multiple times. This is because the string is converted /// to UTF16 in a fixed size buffer to avoid allocations. As a consequence, any string /// longer than the buffer needs the function to be called multiple times. fn with_utf16_str<FunctionType>(string: &str, function: FunctionType) -> Result<Warning, Error> where FunctionType: Fn(*const u16) -> Status, { const BUFFER_SIZE: usize = 256; let mut buffer = [0u16; BUFFER_SIZE]; let mut current_index = 0; let warning = Warning::Success; // Flushes the buffer let flush_buffer = |ref mut buffer: &mut [u16; BUFFER_SIZE], ref mut current_index, ref mut warning| -> Result<(), Error> { buffer[*current_index] = 0; *current_index = 0; if *warning == Warning::Success { *warning = function(buffer.as_ptr())?; } else { function(buffer.as_ptr())?; } Ok(()) }; for character in string.chars() { // If there is not enough space in the buffer, flush it if current_index + character.len_utf16() + 1 >= BUFFER_SIZE { flush_buffer(&mut buffer, current_index, warning)?; } character.encode_utf16(&mut buffer[current_index..]); current_index += character.len_utf16(); } flush_buffer(&mut buffer, current_index, warning)?; Ok(warning) } /// Represents color information for text. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct Color(usize); impl Color { /// Creates new color information from the foreground and background color. pub const fn new(foreground: ForegroundColor, background: BackgroundColor) -> Color { Color(foreground as usize | background as usize) } } /// Represents a foreground color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum ForegroundColor { /// Represents the foreground color black. Black = 0x00, /// Represents the foreground color blue. Blue = 0x01, /// Represents the foreground color green. Green = 0x02, /// Represents the foreground color cyan. Cyan = 0x03, /// Represents the foreground color red. Red = 0x04, /// Represents the foreground color magenta. Magenta = 0x05, /// Represents the foreground color brown. Brown = 0x06, /// Represents the foreground color light gray. LightGray = 0x07, /// Represents the foreground color dark gray. DarkGray = 0x08, /// Represents the foreground color light blue. LightBlue = 0x09, /// Represents the foreground color light green. LightGreen = 0x0a, /// Represents the foreground color light cyan. LightCyan = 0x0b, /// Represents the foreground color light red. LightRed = 0x0c, /// Represents the foreground color light magenta. LightMagenta = 0x0d, /// Represents the foreground color yellow. Yellow = 0x0e, /// Represents the foreground color white. White = 0x0f, } /// Represents a background color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum BackgroundColor { /// Represents the background color black. Black = 0x00,
/// Represents the background color blue. Blue = 0x10, /// Represents the background color green. Green = 0x20, /// Represents the background color cyan. Cyan = 0x30, /// Represents the background color red. Red = 0x40, /// Represents the background color magenta. Magenta = 0x50, /// Represents the background color brown. Brown = 0x60, /// Represents the background color light gray. LightGray = 0x70, }
random_line_split
text.rs
//! This protocol is used to handle input and output of //! text-based information intended for the system user during the operation of code in the boot //! services environment. Also included here are the definitions of three console devices: one for input //! and one each for normal output and errors. use core::fmt; use crate::{ status::{Error, Status, Warning}, system::SystemTable, Event, }; /// Keystroke information for the key that was pressed. #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct TextInputKey { /// If there is a pending keystroke, then ScanCode is the EFI scan code defined in /// Table 104. pub ScanCode: u16, /// The UnicodeChar is the actual printable /// character or is zero if the key does not represent a printable /// character (control key, function key, etc.). pub UnicodeChar: u16, } /// This protocol is used to obtain input from the ConsoleIn device. The EFI specification requires that /// the EFI_SIMPLE_TEXT_INPUT_PROTOCOL supports the same languages as the corresponding /// EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL. #[repr(C)] pub struct TextInput { /// Reset the ConsoleIn device. pub Reset: extern "win64" fn(&TextInput, bool) -> Status, /// Returns the next input character. pub ReadKeyStroke: extern "win64" fn(&TextInput, &mut TextInputKey) -> Status, /// Event to use with EFI_BOOT_SERVICES.WaitForEvent() to wait for a key to be available. pub WaitForKey: Event, } impl TextInput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Returns the next input character, if it exists. pub fn try_read_key_stroke(&self) -> Result<TextInputKey, Error> { let mut key = TextInputKey::default(); (self.ReadKeyStroke)(self, &mut key)?; Ok(key) } /// Returns the next input character after waiting for it. pub fn read_key_stroke( &self, system_table: &'static SystemTable, ) -> Result<TextInputKey, Error> { system_table.BootServices.wait_for_event(&self.WaitForKey)?; self.try_read_key_stroke() } } /// The following data values in the SIMPLE_TEXT_OUTPUT_MODE interface are read-only and are /// changed by using the appropriate interface functions. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct TextOutputMode { /// The number of modes supported by QueryMode() and SetMode(). pub MaxMode: i32, /// The text mode of the output device(s). pub Mode: i32, /// The current character output attribute. pub Attribute: i32, /// The cursor’s column. pub CursorColumn: i32, /// The cursor’s row. pub CursorRow: i32, /// The cursor is currently visible or not. pub CursorVisible: bool, } /// This protocol is used to control text-based output devices. #[repr(C)] pub struct TextOutput { /// Reset the ConsoleOut device. pub Reset: extern "win64" fn(&TextOutput, bool) -> Status, /// Displays the string on the device at the current cursor location. pub OutputString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Tests to see if the ConsoleOut device supports this string. pub TestString: extern "win64" fn(&TextOutput, *const u16) -> Status, /// Queries information concerning the output device’s supported text mode. pub QueryMode: extern "win64" fn(&TextOutput, usize, &mut usize, &mut usize) -> Status, /// Sets the current mode of the output device. pub SetMode: extern "win64" fn(&TextOutput, usize) -> Status, /// Sets the foreground and background color of the text that is output. pub SetAttribute: extern "win64" fn(&TextOutput, usize) -> Status, /// Clears the screen with the currently set background color. pub ClearScreen: extern "win64" fn(&TextOutput) -> Status, /// Sets the current cursor position. pub SetCursorPosition: extern "win64" fn(&TextOutput, usize, usize) -> Status, /// Turns the visibility of the cursor on/off. pub EnableCursor: extern "win64" fn(&TextOutput, bool) -> Status, /// Reference to SIMPLE_TEXT_OUTPUT_MODE data. pub Mode: &'static TextOutputMode, } impl TextOutput { /// Reset the ConsoleOut device. pub fn reset(&self, extended_verification: bool) -> Result<(), Error> { (self.Reset)(self, extended_verification)?; Ok(()) } /// Displays the string on the device at the current cursor location. pub fn output_string(&self, string: &str) -> Result<Warning, Error> { with_utf16_str(string, |utf16| (self.OutputString)(self, utf16)) } /// Tests to see if the ConsoleOut device supports this string. pub fn test_string(&self, string: &str) -> Result<(), Error> { with_utf16_str(string, |utf16| (self.TestString)(self, utf16))?; Ok(()) } /// Queries information concerning the output device’s supported text mode. /// /// Returns the number of columns and rows, if successful. pub fn query_mode(&self, mode_number: usize) -> Result<(usize, usize), Error> { let mut columns: usize = 0; let mut rows: usize = 0; (self.QueryMode)(self, mode_number, &mut columns, &mut rows)?; Ok((columns, rows)) } /// Sets the current mode of the output device. pub fn set_mode(&self, mode: usize) -> Result<(), Error> { (self.SetMode)(self, mode)?; Ok(()) } /// Sets the foreground and background color of the text that is output. pub fn set_attribute(&self, attribute: Color) -> Result<(), Error> { (self.SetAttribute)(self, attribute.0)?; Ok(()) } /// Clears the screen with the currently set background color. pub fn clear_screen(&self) -> Result<(), Error> { (self.ClearScreen)(self)?; Ok(()) } /// Sets the current cursor position. pub fn set_cursor_position(&self, column: usize, row: usize) -> Result<(), Error> { (self.SetCursorPosition)(self, column, row)?; Ok(()) } /// Turns the visibility of the cursor on/off. pub fn enable_cursor(&self, enable: bool) -> Result<(), Error> { (self.EnableCursor)(self, enable)?; Ok(()) } } impl<'a> fmt::Write for &'a TextOutput { fn write_str(&mut self, s: &str) -> fmt::Result { self.output_string(s).map_err(|_| fmt::Error).map(|_| ()) } } /// Executes the given function with the UTF16-encoded string. /// /// `function` will get a UTF16-encoded null-terminated string as its argument when its called. /// /// `function` may be called multiple times. This is because the string is converted /// to UTF16 in a fixed size buffer to avoid allocations. As a consequence, any string /// longer than the buffer needs the function to be called multiple times. fn with_utf16_str<FunctionType>(string: &str, function: FunctionType) -> Result<Warning, Error> where FunctionType: Fn(*const u16) -> Status, { const BUFFER_SIZE: usize = 256; let mut buffer = [0u16; BUFFER_SIZE]; let mut current_index = 0; let warning = Warning::Success; // Flushes the buffer let flush_buffer = |ref mut buffer: &mut [u16; BUFFER_SIZE], ref mut current_index, ref mut warning| -> Result<(), Error> { buffer[*current_index] = 0; *current_index = 0; if *warning == Warning::Success {
function(buffer.as_ptr())?; } Ok(()) }; for character in string.chars() { // If there is not enough space in the buffer, flush it if current_index + character.len_utf16() + 1 >= BUFFER_SIZE { flush_buffer(&mut buffer, current_index, warning)?; } character.encode_utf16(&mut buffer[current_index..]); current_index += character.len_utf16(); } flush_buffer(&mut buffer, current_index, warning)?; Ok(warning) } /// Represents color information for text. #[derive(Clone, Copy, Debug)] #[repr(C)] pub struct Color(usize); impl Color { /// Creates new color information from the foreground and background color. pub const fn new(foreground: ForegroundColor, background: BackgroundColor) -> Color { Color(foreground as usize | background as usize) } } /// Represents a foreground color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum ForegroundColor { /// Represents the foreground color black. Black = 0x00, /// Represents the foreground color blue. Blue = 0x01, /// Represents the foreground color green. Green = 0x02, /// Represents the foreground color cyan. Cyan = 0x03, /// Represents the foreground color red. Red = 0x04, /// Represents the foreground color magenta. Magenta = 0x05, /// Represents the foreground color brown. Brown = 0x06, /// Represents the foreground color light gray. LightGray = 0x07, /// Represents the foreground color dark gray. DarkGray = 0x08, /// Represents the foreground color light blue. LightBlue = 0x09, /// Represents the foreground color light green. LightGreen = 0x0a, /// Represents the foreground color light cyan. LightCyan = 0x0b, /// Represents the foreground color light red. LightRed = 0x0c, /// Represents the foreground color light magenta. LightMagenta = 0x0d, /// Represents the foreground color yellow. Yellow = 0x0e, /// Represents the foreground color white. White = 0x0f, } /// Represents a background color for text. #[derive(Clone, Copy, Debug)] #[repr(usize)] pub enum BackgroundColor { /// Represents the background color black. Black = 0x00, /// Represents the background color blue. Blue = 0x10, /// Represents the background color green. Green = 0x20, /// Represents the background color cyan. Cyan = 0x30, /// Represents the background color red. Red = 0x40, /// Represents the background color magenta. Magenta = 0x50, /// Represents the background color brown. Brown = 0x60, /// Represents the background color light gray. LightGray = 0x70, }
*warning = function(buffer.as_ptr())?; } else {
conditional_block
PubUtils.ts
import { Vec2, Prefab, instantiate, tween, Vec3, Node } from "cc"; //公用工具类 export class PubUtils { /** * 储存游戏数据 * @param game 游戏名字 * @param key 需要储存的key值 * @param data 数据 */ public static SetGameLocalData(game: string, key: string, data: any) { this.SetLocalData(game + key, data); } /** * 储存数据到本地 * @param key * @param data */ public static SetLocalData(key: string, data: any) { if (typeof data == "object") { data = JSON.stringify(data); } localStorage.setItem(key, data); } /** * 获取本地储存的数据 * @param key * @returns string */ public static GetLocalData(key: string): any { let data = localStorage.getItem(key); if (data == null || data == "" || typeof data == null || data == 'NaN') { return null; } data = JSON.parse(data); return data; } /** * 获取本地游戏数据 * @param game 游戏名字 * @param key */ public static GetGameLocalData(game: string, key: string) { return this.GetLocalData(game + key); } public static ClearLocalData(key: string) { if (key == null || key == "") return; localStorage.removeItem(key); } public static ClearGameLocalData(game: string, key: string) { this.ClearLocalData(game + key); } public static Range(min: number, max: number): number { return Math.floor(Math.random() * 100000) % (max - min) + min; } public static randomNum(maxNum, minNum, decimalNum): number { var max = 0, min = 0; minNum <= maxNum ? (min = minNum, max = maxNum) : (min = maxNum, max = minNum); switch (arguments.length) { case 1: return Math.floor(Math.random() * (max + 1)); case 2: return Math.floor(Math.random() * (max - min + 1) + min); case 3: return parseFloat((Math.random() * (max - min) + min).toFixed(decimalNum)); default: return Math.random(); } } // Interpolates between /a/ and /b/ by /t/. /t/ is clamped between 0 and 1. public static Lerp(a: number, b: number, t: number): number { return a + (b - a) * this.Clamp01(t); } // Clamps value between 0 and 1 and returns value public static Clamp01(value: number): number { if (value < 0) return 0; else if (value > 1) return 1; else return value; } public static EaseOutQuart(t) { t = this.Clamp(t, 0, 1); t--; return -(t * t * t * t - 1); } public static Clamp(value: number, min: number, max: number): number { if (value < min) value = min; else if (value > max) value = max; return value; } // Degrees-to-radians conversion constant (RO). public static Deg2Rad = Math.PI * 2 / 360; // Radians-to-degrees conversion constant (RO). public static get Rad2Deg() { return 1 / this.Deg2Rad; }; static MathMoveTowards(current: number, target: number, maxDelta: number) { if (Math.abs(target - current) <= maxDelta) return target; return current + Math.sign(target - current) * maxDelta; } //将一个点/当前点/直线移动到A/目标/点。 static MoveTowards(current, target, maxDistanceDelta) { // avoid vector ops because current scripting backends are terrible at inlining //避免使用向量操作,因为当前脚本后端在内联时非常糟糕 let toVector_x = target.x - current.x; let toVector_y = target.y - current.y; let toVector_z = target.z - current.z; let sqdist = toVector_x * toVector_x + toVector_y * toVector_y + toVector_z * toVector_z; if (sqdist == 0 || sqdist <= maxDistanceDelta * maxDistanceDelta) return target; let dist = Math.sqrt(sqdist); return new Vec3(current.x + toVector_x / dist * maxDistanceDelta, current.y + toVector_y / dist * maxDistanceDelta, current.z + toVector_z / dist * maxDistanceDelta); } /** * 解析json到model属性上 * @param model * @param json * @param types */ public static parseJsonToModel(model: any, json: any, types: any) { let keys = Object.keys(types); for (let i = 0; i < keys.length; i++) { let key = keys[i]; let type = types[key]; switch (type) { case "int": {
model[key] = parseFloat(json[key]); break; } case 'array-int': { let s = json[key] as string; let arry = s.split(','); for (let i = 0; i < arry.length; i++) { model[key].push(parseInt(arry[i])); } break; } case 'array-string': { let s = json[key] as string; let arry = s.split(','); for (let i = 0; i < arry.length; i++) { model[key].push(arry[i]); } break; } default: { model[key] = json[key]; break; } } } } public static copyObject(from_obj, to_obj) { let keys = Object.keys(from_obj); for (let key in keys) { let k = keys[key] if (from_obj[k] instanceof Array) { to_obj[k] = [].concat(from_obj[k]); } else { to_obj[k] = from_obj[k]; } } } // Gradually changes a value towards a desired goal over time. public static SmoothDamp(current, target, currentVelocity, smoothTime, maxSpeed: number = Number.POSITIVE_INFINITY, deltaTime) { // Based on Game Programming Gems 4 Chapter 1.10 smoothTime = Math.max(0.0001, smoothTime); let omega = 2 / smoothTime; let x = omega * deltaTime; let exp = 1 / (1 + x + 0.48 * x * x + 0.235 * x * x * x); let change = current - target; let originalTo = target; // Clamp maximum speed let maxChange = maxSpeed * smoothTime; change = PubUtils.Clamp(change, -maxChange, maxChange); target = current - change; let temp = (currentVelocity + omega * change) * deltaTime; currentVelocity = (currentVelocity - omega * temp) * exp; let output = target + (change + temp) * exp; if (originalTo - current > 0.0 == output > originalTo) { output = originalTo; currentVelocity = (output - originalTo) / deltaTime; } return output; } public static SmoothDampToSpeed(current, target, currentVelocity, smoothTime, deltaTime,) { return this.SmoothDamp(current, target, currentVelocity, smoothTime, Number.POSITIVE_INFINITY, deltaTime); } /** * 随机生成手机号 */ public static getMoble() { var prefixArray = new Array("130", "131", "132", "133", "135", "137", "138", "170", "187", "189"); var i = PubUtils.Range(0, prefixArray.length); var prefix = prefixArray[i]; for (var j = 0; j < 8; j++) { prefix = prefix + Math.floor(Math.random() * 10); } return prefix; } public static phoneNameToName(str: string) { let str1 = str.slice(0, 3); let str2 = str.slice(-2); return str1 + "****" + str2; } // public static getNumColor(color: string): Color { // let ns = this.getNums(color); // return new Color(ns[0] / 255, ns[1] / 255, ns[2] / 255); // } public static getNums(color: string): Array<number> { let a = color.split(","); let ary = []; for (let i = 0; i < a.length; i++) { ary.push(parseInt(a[i])); } return ary; } // /** // * 颜色rgb 转 颜色值 // * @param color // */ // public static colorRGBtoHex(color: Color) { // var hex = "#" + ((1 << 24) + ((color.r * 255) << 16) + ((color.g * 255) << 8) + (color.b * 255)).toString(16).slice(1); // return hex; // } public static coinNumToStr(coin: number): string { if (coin < 1000) { return coin.toString(); } else if (coin < 10000) { let c = (coin / 1000) c = this.toFixed(c, 2); return c + "K"; } else if (coin < 100000000) { let c = coin / 10000; let length = 0; if (coin < 100000) { length = 2; } else if (coin < 1000000) { length = 1; } return this.toFixed(c, length) + "W"; } else { return "9999W"; } } /** * 返回指定小数点后几位 向下取舍 * @param num 小数 * @param fixed_length 指定位数 * @param is_round */ public static toFixed(num: number, fixed_length: number) { return Math.floor(num * Math.pow(10, fixed_length)) / Math.pow(10, fixed_length); } public static UUID: number = 1; public static generateUUID(): string { let d = new Date().getTime(); if (window.performance && typeof window.performance.now === "function") { d += performance.now(); //use high-precision timer if available } let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); console.log(uuid); return uuid; // return (this.UUID++).toString(); } public static getUUID(): string { return (this.UUID++).toString(); } //全局调用 //srcPos:开始位置, //dstPos:目标位置 //radius:圆半径 //goldCount:切分多少块,多少个金币 //addGold:需要增加多少金币 //callBack:动画结束回调 static createGoldAnim(fabs: Prefab, parent: Node, srcPos: Vec3, dstPos: Vec3, srcNode: Node, radius: number, goldCount: number, addGold: number, callBack: Function) { var array = this.getPoint(radius, srcPos.x, srcPos.y, goldCount); var nodeArray = new Array(); for (var i = 0; i < array.length; i++) { let gold = instantiate(fabs) as Node; let randPos = new Vec3(array[i].x + this.Range(0, 50), array[i].y + this.Range(0, 50)); nodeArray.push({ gold: gold, randPos: randPos }); parent.addChild(gold); gold.setWorldPosition(srcPos); } nodeArray.sort(function (a, b) { var disa = Vec3.distance(a.randPos, dstPos); var disb = Vec3.distance(b.randPos, dstPos); return disa - disb; }); var notPlay = false; var targetGoldNode = srcNode; for (let i = 0; i < nodeArray.length; i++) { let pos = nodeArray[i].randPos; let node: Node = nodeArray[i].gold; tween(node).to(0.5, { worldPosition: pos }).delay(i * 0.03).to(0.5, { worldPosition: dstPos }).call(() => { if (!notPlay) { notPlay = true; tween(targetGoldNode).to(0.1, { scale: new Vec3(2, 2, 2) }).to(0.1, { scale: new Vec3(1, 1, 1) }).call(() => { notPlay = false; }).start(); } if (i == nodeArray.length - 1) { if (callBack != null) callBack(addGold); } node.destroy(); }).start() nodeArray[i].gold.id = i; } } /* * 求圆周上等分点的坐标 * ox,oy为圆心坐标 * r为半径 * count为等分个数 */ static getPoint(r, ox, oy, count) { var point = []; //结果 var radians = Math.PI / 180 * Math.round(360 / count), //弧度 i = 0; for (; i < count; i++) { var x = ox + r * Math.sin(radians * i), y = oy + r * Math.cos(radians * i); point.unshift({ x: x, y: y }); //为保持数据顺时针 } return point; } }
model[key] = parseInt(json[key]); break; } case "float": {
random_line_split
PubUtils.ts
import { Vec2, Prefab, instantiate, tween, Vec3, Node } from "cc"; //公用工具类 export class PubUtils { /** * 储存游戏数据 * @param game 游戏名字 * @param key 需要储存的key值 * @param data 数据 */ public static SetGameLocalData(game: string, key: string, data: any) { this.SetLocalData(game + key, data); } /** * 储存数据到本地 * @param key * @param data */ public static SetLocalData(key: string, data: any) { if (typeof data == "object") { data = JSON.stringify(data); } localStorage.setItem(key, data); } /** * 获取本地储存的数据 * @param key * @returns string */ public static GetLocalData(key: string): any { let data = localStorage.getItem(key); if (data == null || data == "" || typeof data == null || data == 'NaN') { return null; } data = JSON.parse(data); return data; } /** * 获取本地游戏数据 * @param game 游戏名字 * @param key */ public static GetGameLocalData(game: string, key: string) { return this.GetLocalData(game + key); } public static ClearLocalData(key: string) { if (key == null || key == "") return; localStorage.removeItem(key); } public static ClearGameLocalData(game: string, key: string) { this.ClearLocalData(game + key); } public static Range(min: number, max: number): number { return Math.floor(Math.random() * 100000) % (max - min) + min; } public static randomNum(maxNum, minNum, decimalNum): number { var max = 0, min = 0; minNum <= maxNum
minNum, max = maxNum) : (min = maxNum, max = minNum); switch (arguments.length) { case 1: return Math.floor(Math.random() * (max + 1)); case 2: return Math.floor(Math.random() * (max - min + 1) + min); case 3: return parseFloat((Math.random() * (max - min) + min).toFixed(decimalNum)); default: return Math.random(); } } // Interpolates between /a/ and /b/ by /t/. /t/ is clamped between 0 and 1. public static Lerp(a: number, b: number, t: number): number { return a + (b - a) * this.Clamp01(t); } // Clamps value between 0 and 1 and returns value public static Clamp01(value: number): number { if (value < 0) return 0; else if (value > 1) return 1; else return value; } public static EaseOutQuart(t) { t = this.Clamp(t, 0, 1); t--; return -(t * t * t * t - 1); } public static Clamp(value: number, min: number, max: number): number { if (value < min) value = min; else if (value > max) value = max; return value; } // Degrees-to-radians conversion constant (RO). public static Deg2Rad = Math.PI * 2 / 360; // Radians-to-degrees conversion constant (RO). public static get Rad2Deg() { return 1 / this.Deg2Rad; }; static MathMoveTowards(current: number, target: number, maxDelta: number) { if (Math.abs(target - current) <= maxDelta) return target; return current + Math.sign(target - current) * maxDelta; } //将一个点/当前点/直线移动到A/目标/点。 static MoveTowards(current, target, maxDistanceDelta) { // avoid vector ops because current scripting backends are terrible at inlining //避免使用向量操作,因为当前脚本后端在内联时非常糟糕 let toVector_x = target.x - current.x; let toVector_y = target.y - current.y; let toVector_z = target.z - current.z; let sqdist = toVector_x * toVector_x + toVector_y * toVector_y + toVector_z * toVector_z; if (sqdist == 0 || sqdist <= maxDistanceDelta * maxDistanceDelta) return target; let dist = Math.sqrt(sqdist); return new Vec3(current.x + toVector_x / dist * maxDistanceDelta, current.y + toVector_y / dist * maxDistanceDelta, current.z + toVector_z / dist * maxDistanceDelta); } /** * 解析json到model属性上 * @param model * @param json * @param types */ public static parseJsonToModel(model: any, json: any, types: any) { let keys = Object.keys(types); for (let i = 0; i < keys.length; i++) { let key = keys[i]; let type = types[key]; switch (type) { case "int": { model[key] = parseInt(json[key]); break; } case "float": { model[key] = parseFloat(json[key]); break; } case 'array-int': { let s = json[key] as string; let arry = s.split(','); for (let i = 0; i < arry.length; i++) { model[key].push(parseInt(arry[i])); } break; } case 'array-string': { let s = json[key] as string; let arry = s.split(','); for (let i = 0; i < arry.length; i++) { model[key].push(arry[i]); } break; } default: { model[key] = json[key]; break; } } } } public static copyObject(from_obj, to_obj) { let keys = Object.keys(from_obj); for (let key in keys) { let k = keys[key] if (from_obj[k] instanceof Array) { to_obj[k] = [].concat(from_obj[k]); } else { to_obj[k] = from_obj[k]; } } } // Gradually changes a value towards a desired goal over time. public static SmoothDamp(current, target, currentVelocity, smoothTime, maxSpeed: number = Number.POSITIVE_INFINITY, deltaTime) { // Based on Game Programming Gems 4 Chapter 1.10 smoothTime = Math.max(0.0001, smoothTime); let omega = 2 / smoothTime; let x = omega * deltaTime; let exp = 1 / (1 + x + 0.48 * x * x + 0.235 * x * x * x); let change = current - target; let originalTo = target; // Clamp maximum speed let maxChange = maxSpeed * smoothTime; change = PubUtils.Clamp(change, -maxChange, maxChange); target = current - change; let temp = (currentVelocity + omega * change) * deltaTime; currentVelocity = (currentVelocity - omega * temp) * exp; let output = target + (change + temp) * exp; if (originalTo - current > 0.0 == output > originalTo) { output = originalTo; currentVelocity = (output - originalTo) / deltaTime; } return output; } public static SmoothDampToSpeed(current, target, currentVelocity, smoothTime, deltaTime,) { return this.SmoothDamp(current, target, currentVelocity, smoothTime, Number.POSITIVE_INFINITY, deltaTime); } /** * 随机生成手机号 */ public static getMoble() { var prefixArray = new Array("130", "131", "132", "133", "135", "137", "138", "170", "187", "189"); var i = PubUtils.Range(0, prefixArray.length); var prefix = prefixArray[i]; for (var j = 0; j < 8; j++) { prefix = prefix + Math.floor(Math.random() * 10); } return prefix; } public static phoneNameToName(str: string) { let str1 = str.slice(0, 3); let str2 = str.slice(-2); return str1 + "****" + str2; } // public static getNumColor(color: string): Color { // let ns = this.getNums(color); // return new Color(ns[0] / 255, ns[1] / 255, ns[2] / 255); // } public static getNums(color: string): Array<number> { let a = color.split(","); let ary = []; for (let i = 0; i < a.length; i++) { ary.push(parseInt(a[i])); } return ary; } // /** // * 颜色rgb 转 颜色值 // * @param color // */ // public static colorRGBtoHex(color: Color) { // var hex = "#" + ((1 << 24) + ((color.r * 255) << 16) + ((color.g * 255) << 8) + (color.b * 255)).toString(16).slice(1); // return hex; // } public static coinNumToStr(coin: number): string { if (coin < 1000) { return coin.toString(); } else if (coin < 10000) { let c = (coin / 1000) c = this.toFixed(c, 2); return c + "K"; } else if (coin < 100000000) { let c = coin / 10000; let length = 0; if (coin < 100000) { length = 2; } else if (coin < 1000000) { length = 1; } return this.toFixed(c, length) + "W"; } else { return "9999W"; } } /** * 返回指定小数点后几位 向下取舍 * @param num 小数 * @param fixed_length 指定位数 * @param is_round */ public static toFixed(num: number, fixed_length: number) { return Math.floor(num * Math.pow(10, fixed_length)) / Math.pow(10, fixed_length); } public static UUID: number = 1; public static generateUUID(): string { let d = new Date().getTime(); if (window.performance && typeof window.performance.now === "function") { d += performance.now(); //use high-precision timer if available } let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); console.log(uuid); return uuid; // return (this.UUID++).toString(); } public static getUUID(): string { return (this.UUID++).toString(); } //全局调用 //srcPos:开始位置, //dstPos:目标位置 //radius:圆半径 //goldCount:切分多少块,多少个金币 //addGold:需要增加多少金币 //callBack:动画结束回调 static createGoldAnim(fabs: Prefab, parent: Node, srcPos: Vec3, dstPos: Vec3, srcNode: Node, radius: number, goldCount: number, addGold: number, callBack: Function) { var array = this.getPoint(radius, srcPos.x, srcPos.y, goldCount); var nodeArray = new Array(); for (var i = 0; i < array.length; i++) { let gold = instantiate(fabs) as Node; let randPos = new Vec3(array[i].x + this.Range(0, 50), array[i].y + this.Range(0, 50)); nodeArray.push({ gold: gold, randPos: randPos }); parent.addChild(gold); gold.setWorldPosition(srcPos); } nodeArray.sort(function (a, b) { var disa = Vec3.distance(a.randPos, dstPos); var disb = Vec3.distance(b.randPos, dstPos); return disa - disb; }); var notPlay = false; var targetGoldNode = srcNode; for (let i = 0; i < nodeArray.length; i++) { let pos = nodeArray[i].randPos; let node: Node = nodeArray[i].gold; tween(node).to(0.5, { worldPosition: pos }).delay(i * 0.03).to(0.5, { worldPosition: dstPos }).call(() => { if (!notPlay) { notPlay = true; tween(targetGoldNode).to(0.1, { scale: new Vec3(2, 2, 2) }).to(0.1, { scale: new Vec3(1, 1, 1) }).call(() => { notPlay = false; }).start(); } if (i == nodeArray.length - 1) { if (callBack != null) callBack(addGold); } node.destroy(); }).start() nodeArray[i].gold.id = i; } } /* * 求圆周上等分点的坐标 * ox,oy为圆心坐标 * r为半径 * count为等分个数 */ static getPoint(r, ox, oy, count) { var point = []; //结果 var radians = Math.PI / 180 * Math.round(360 / count), //弧度 i = 0; for (; i < count; i++) { var x = ox + r * Math.sin(radians * i), y = oy + r * Math.cos(radians * i); point.unshift({ x: x, y: y }); //为保持数据顺时针 } return point; } }
? (min =
identifier_name
PubUtils.ts
import { Vec2, Prefab, instantiate, tween, Vec3, Node } from "cc"; //公用工具类 export class PubUtils { /** * 储存游戏数据 * @param game 游戏名字 * @param key 需要储存的key值 * @param data 数据 */ public static SetGameLocalData(game: string, key: string, data: any) { this.SetLocalData(game + key, data); } /** * 储存数据到本地 * @param key * @param data */ public static SetLocalData(key: string, data: any) { if (typeof data == "object") { data = JSON.stringify(data); } localStorage.setItem(key, data); } /** * 获取本地储存的数据 * @param key * @returns string */ public static GetLocalData(key: string): any { let data = localStorage.getItem(key); if (data == null || data == "" || typeof data == null || data == 'NaN') { return null; } data = JSON.parse(data); return data; } /** * 获取本地游戏数据 * @param game 游戏名字 * @param key */ public static GetGameLocalData(game: string, key: string) { return this.GetLocalData(game + key); } public static ClearLocalData(key: string) {
localStorage.removeItem(key); } public static ClearGameLocalData(game: string, key: string) { this.ClearLocalData(game + key); } public static Range(min: number, max: number): number { return Math.floor(Math.random() * 100000) % (max - min) + min; } public static randomNum(maxNum, minNum, decimalNum): number { var max = 0, min = 0; minNum <= maxNum ? (min = minNum, max = maxNum) : (min = maxNum, max = minNum); switch (arguments.length) { case 1: return Math.floor(Math.random() * (max + 1)); case 2: return Math.floor(Math.random() * (max - min + 1) + min); case 3: return parseFloat((Math.random() * (max - min) + min).toFixed(decimalNum)); default: return Math.random(); } } // Interpolates between /a/ and /b/ by /t/. /t/ is clamped between 0 and 1. public static Lerp(a: number, b: number, t: number): number { return a + (b - a) * this.Clamp01(t); } // Clamps value between 0 and 1 and returns value public static Clamp01(value: number): number { if (value < 0) return 0; else if (value > 1) return 1; else return value; } public static EaseOutQuart(t) { t = this.Clamp(t, 0, 1); t--; return -(t * t * t * t - 1); } public static Clamp(value: number, min: number, max: number): number { if (value < min) value = min; else if (value > max) value = max; return value; } // Degrees-to-radians conversion constant (RO). public static Deg2Rad = Math.PI * 2 / 360; // Radians-to-degrees conversion constant (RO). public static get Rad2Deg() { return 1 / this.Deg2Rad; }; static MathMoveTowards(current: number, target: number, maxDelta: number) { if (Math.abs(target - current) <= maxDelta) return target; return current + Math.sign(target - current) * maxDelta; } //将一个点/当前点/直线移动到A/目标/点。 static MoveTowards(current, target, maxDistanceDelta) { // avoid vector ops because current scripting backends are terrible at inlining //避免使用向量操作,因为当前脚本后端在内联时非常糟糕 let toVector_x = target.x - current.x; let toVector_y = target.y - current.y; let toVector_z = target.z - current.z; let sqdist = toVector_x * toVector_x + toVector_y * toVector_y + toVector_z * toVector_z; if (sqdist == 0 || sqdist <= maxDistanceDelta * maxDistanceDelta) return target; let dist = Math.sqrt(sqdist); return new Vec3(current.x + toVector_x / dist * maxDistanceDelta, current.y + toVector_y / dist * maxDistanceDelta, current.z + toVector_z / dist * maxDistanceDelta); } /** * 解析json到model属性上 * @param model * @param json * @param types */ public static parseJsonToModel(model: any, json: any, types: any) { let keys = Object.keys(types); for (let i = 0; i < keys.length; i++) { let key = keys[i]; let type = types[key]; switch (type) { case "int": { model[key] = parseInt(json[key]); break; } case "float": { model[key] = parseFloat(json[key]); break; } case 'array-int': { let s = json[key] as string; let arry = s.split(','); for (let i = 0; i < arry.length; i++) { model[key].push(parseInt(arry[i])); } break; } case 'array-string': { let s = json[key] as string; let arry = s.split(','); for (let i = 0; i < arry.length; i++) { model[key].push(arry[i]); } break; } default: { model[key] = json[key]; break; } } } } public static copyObject(from_obj, to_obj) { let keys = Object.keys(from_obj); for (let key in keys) { let k = keys[key] if (from_obj[k] instanceof Array) { to_obj[k] = [].concat(from_obj[k]); } else { to_obj[k] = from_obj[k]; } } } // Gradually changes a value towards a desired goal over time. public static SmoothDamp(current, target, currentVelocity, smoothTime, maxSpeed: number = Number.POSITIVE_INFINITY, deltaTime) { // Based on Game Programming Gems 4 Chapter 1.10 smoothTime = Math.max(0.0001, smoothTime); let omega = 2 / smoothTime; let x = omega * deltaTime; let exp = 1 / (1 + x + 0.48 * x * x + 0.235 * x * x * x); let change = current - target; let originalTo = target; // Clamp maximum speed let maxChange = maxSpeed * smoothTime; change = PubUtils.Clamp(change, -maxChange, maxChange); target = current - change; let temp = (currentVelocity + omega * change) * deltaTime; currentVelocity = (currentVelocity - omega * temp) * exp; let output = target + (change + temp) * exp; if (originalTo - current > 0.0 == output > originalTo) { output = originalTo; currentVelocity = (output - originalTo) / deltaTime; } return output; } public static SmoothDampToSpeed(current, target, currentVelocity, smoothTime, deltaTime,) { return this.SmoothDamp(current, target, currentVelocity, smoothTime, Number.POSITIVE_INFINITY, deltaTime); } /** * 随机生成手机号 */ public static getMoble() { var prefixArray = new Array("130", "131", "132", "133", "135", "137", "138", "170", "187", "189"); var i = PubUtils.Range(0, prefixArray.length); var prefix = prefixArray[i]; for (var j = 0; j < 8; j++) { prefix = prefix + Math.floor(Math.random() * 10); } return prefix; } public static phoneNameToName(str: string) { let str1 = str.slice(0, 3); let str2 = str.slice(-2); return str1 + "****" + str2; } // public static getNumColor(color: string): Color { // let ns = this.getNums(color); // return new Color(ns[0] / 255, ns[1] / 255, ns[2] / 255); // } public static getNums(color: string): Array<number> { let a = color.split(","); let ary = []; for (let i = 0; i < a.length; i++) { ary.push(parseInt(a[i])); } return ary; } // /** // * 颜色rgb 转 颜色值 // * @param color // */ // public static colorRGBtoHex(color: Color) { // var hex = "#" + ((1 << 24) + ((color.r * 255) << 16) + ((color.g * 255) << 8) + (color.b * 255)).toString(16).slice(1); // return hex; // } public static coinNumToStr(coin: number): string { if (coin < 1000) { return coin.toString(); } else if (coin < 10000) { let c = (coin / 1000) c = this.toFixed(c, 2); return c + "K"; } else if (coin < 100000000) { let c = coin / 10000; let length = 0; if (coin < 100000) { length = 2; } else if (coin < 1000000) { length = 1; } return this.toFixed(c, length) + "W"; } else { return "9999W"; } } /** * 返回指定小数点后几位 向下取舍 * @param num 小数 * @param fixed_length 指定位数 * @param is_round */ public static toFixed(num: number, fixed_length: number) { return Math.floor(num * Math.pow(10, fixed_length)) / Math.pow(10, fixed_length); } public static UUID: number = 1; public static generateUUID(): string { let d = new Date().getTime(); if (window.performance && typeof window.performance.now === "function") { d += performance.now(); //use high-precision timer if available } let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); console.log(uuid); return uuid; // return (this.UUID++).toString(); } public static getUUID(): string { return (this.UUID++).toString(); } //全局调用 //srcPos:开始位置, //dstPos:目标位置 //radius:圆半径 //goldCount:切分多少块,多少个金币 //addGold:需要增加多少金币 //callBack:动画结束回调 static createGoldAnim(fabs: Prefab, parent: Node, srcPos: Vec3, dstPos: Vec3, srcNode: Node, radius: number, goldCount: number, addGold: number, callBack: Function) { var array = this.getPoint(radius, srcPos.x, srcPos.y, goldCount); var nodeArray = new Array(); for (var i = 0; i < array.length; i++) { let gold = instantiate(fabs) as Node; let randPos = new Vec3(array[i].x + this.Range(0, 50), array[i].y + this.Range(0, 50)); nodeArray.push({ gold: gold, randPos: randPos }); parent.addChild(gold); gold.setWorldPosition(srcPos); } nodeArray.sort(function (a, b) { var disa = Vec3.distance(a.randPos, dstPos); var disb = Vec3.distance(b.randPos, dstPos); return disa - disb; }); var notPlay = false; var targetGoldNode = srcNode; for (let i = 0; i < nodeArray.length; i++) { let pos = nodeArray[i].randPos; let node: Node = nodeArray[i].gold; tween(node).to(0.5, { worldPosition: pos }).delay(i * 0.03).to(0.5, { worldPosition: dstPos }).call(() => { if (!notPlay) { notPlay = true; tween(targetGoldNode).to(0.1, { scale: new Vec3(2, 2, 2) }).to(0.1, { scale: new Vec3(1, 1, 1) }).call(() => { notPlay = false; }).start(); } if (i == nodeArray.length - 1) { if (callBack != null) callBack(addGold); } node.destroy(); }).start() nodeArray[i].gold.id = i; } } /* * 求圆周上等分点的坐标 * ox,oy为圆心坐标 * r为半径 * count为等分个数 */ static getPoint(r, ox, oy, count) { var point = []; //结果 var radians = Math.PI / 180 * Math.round(360 / count), //弧度 i = 0; for (; i < count; i++) { var x = ox + r * Math.sin(radians * i), y = oy + r * Math.cos(radians * i); point.unshift({ x: x, y: y }); //为保持数据顺时针 } return point; } }
if (key == null || key == "") return;
identifier_body
context.rs
use std::{ alloc::Layout, cell::{Ref, RefMut}, marker::PhantomData, mem::size_of, panic::AssertUnwindSafe, ptr::NonNull, sync::atomic::{AtomicBool, Ordering}, }; use anyhow::anyhow; use bytemuck::{Pod, Zeroable}; use feather_common::Game; use feather_ecs::EntityBuilder; use quill_common::Component; use serde::de::DeserializeOwned; use vec_arena::Arena; use wasmer::{FromToNativeWasmType, Instance}; use crate::{host_function::WasmHostFunction, thread_pinned::ThreadPinned, PluginId}; mod native; mod wasm; /// Wraps a pointer into a plugin's memory space. #[derive(Copy, Clone, PartialEq, Eq, Zeroable)] #[repr(transparent)] pub struct PluginPtr<T> { pub ptr: u64, pub _marker: PhantomData<*const T>, } impl<T> PluginPtr<T> { pub fn as_native(&self) -> *const T { self.ptr as usize as *const T } /// # Safety /// Adding `n` to this pointer /// must produce a pointer within the same allocated /// object. #[must_use = "PluginPtr::add returns a new pointer"] pub unsafe fn add(self, n: usize) -> Self { Self { ptr: self.ptr + (n * size_of::<T>()) as u64, _marker: self._marker, } } /// # Safety /// The cast must be valid. pub unsafe fn cast<U>(self) -> PluginPtr<U> { PluginPtr { ptr: self.ptr, _marker: PhantomData, } } } unsafe impl<T: Copy + 'static> Pod for PluginPtr<T> {} /// Wraps a pointer into a plugin's memory space. #[derive(Copy, Clone, PartialEq, Eq, Zeroable)] #[repr(transparent)] pub struct PluginPtrMut<T> { pub ptr: u64, pub _marker: PhantomData<*mut T>, } impl<T> PluginPtrMut<T> { pub fn as_native(&self) -> *mut T { self.ptr as usize as *mut T } /// # Safety /// A null pointer must be valid in the context it is used. pub unsafe fn null() -> Self { Self { ptr: 0, _marker: PhantomData, } } /// # Safety /// Adding `n` to this pointer /// must produce a pointer within the same allocated /// object. #[must_use = "PluginPtrMut::add returns a new pointer"] pub unsafe fn add(self, n: usize) -> Self { Self { ptr: self.ptr + (n * size_of::<T>()) as u64, _marker: self._marker, } } /// # Safety /// The cast must be valid. pub unsafe fn cast<U>(self) -> PluginPtrMut<U> { PluginPtrMut { ptr: self.ptr, _marker: PhantomData, } } } unsafe impl<T: Copy + 'static> Pod for PluginPtrMut<T> {} unsafe impl<T: Copy> FromToNativeWasmType for PluginPtr<T> { type Native = i64; fn from_native(native: Self::Native) -> Self { Self { ptr: native as u64, _marker: PhantomData, } } fn to_native(self) -> Self::Native { self.ptr as i64 } } unsafe impl<T: Copy> FromToNativeWasmType for PluginPtrMut<T> { type Native = i64; fn from_native(native: Self::Native) -> Self { Self { ptr: native as u64, _marker: PhantomData, } } fn to_native(self) -> Self::Native { self.ptr as i64 } } /// Context of a running plugin. /// /// Provides methods to access plugin memory, /// invoke exported functions, and access the `Game`. /// /// This type abstracts over WASM or native plugins, /// providing the same interface for both. /// /// # Safety /// The `native` version of the plugin context /// dereferences raw pointers. We assume pointers /// passed by plugins are valid. Most functions /// will cause undefined behavior if these constraints /// are violated. /// /// We type-encode that a pointer originates from a plugin /// using the `PluginPtr` structs. Methods that /// dereference pointers take instances of these /// structs. Since creating a `PluginPtr` is unsafe, /// `PluginContext` methods don't have to be marked /// unsafe. /// /// On WASM targets, the plugin is never trusted, /// and pointer accesses are checked. Undefined behavior /// can never occur as a result of malicious plugin input. pub struct PluginContext { inner: Inner, /// Whether the plugin is currently being invoked /// on the main thread. /// If this is `true`, then plugin functions are on the call stack. invoking_on_main_thread: AtomicBool, /// The current `Game`. /// /// Set to `None` if `invoking_on_main_thread` is `false`. /// Otherwise, must point to a valid game. The pointer /// must be cleared after the plugin finishes executing /// or we risk a dangling reference. game: ThreadPinned<Option<NonNull<Game>>>, /// ID of the plugin. id: PluginId, /// Active entity builders for the plugin. pub entity_builders: ThreadPinned<Arena<EntityBuilder>>, } impl PluginContext { /// Creates a new WASM plugin context. pub fn new_wasm(id: PluginId) -> Self { Self { inner: Inner::Wasm(ThreadPinned::new(wasm::WasmPluginContext::new())), invoking_on_main_thread: AtomicBool::new(false), game: ThreadPinned::new(None), id, entity_builders: ThreadPinned::new(Arena::new()), } } /// Creates a new native plugin context. pub fn new_native(id: PluginId) -> Self { Self { inner: Inner::Native(native::NativePluginContext::new()), invoking_on_main_thread: AtomicBool::new(false), game: ThreadPinned::new(None), id, entity_builders: ThreadPinned::new(Arena::new()), } } pub fn init_with_instance(&self, instance: &Instance) -> anyhow::Result<()> { match &self.inner { Inner::Wasm(w) => w.borrow_mut().init_with_instance(instance), Inner::Native(_) => panic!("cannot initialize native plugin context"), } } /// Enters the plugin context, invoking a function inside the plugin. /// /// # Panics /// Panics if we are already inside the plugin context. /// Panics if not called on the main thread. pub fn enter<R>(&self, game: &mut Game, callback: impl FnOnce() -> R) -> R { let was_already_entered = self.invoking_on_main_thread.swap(true, Ordering::SeqCst); assert!(!was_already_entered, "cannot recursively invoke a plugin"); *self.game.borrow_mut() = Some(NonNull::from(game)); // If a panic occurs, we need to catch it so // we clear `self.game`. Otherwise, we get // a dangling pointer. let result = std::panic::catch_unwind(AssertUnwindSafe(callback)); self.invoking_on_main_thread.store(false, Ordering::SeqCst); *self.game.borrow_mut() = None; self.bump_reset(); result.unwrap() } /// Gets a mutable reference to the `Game`. /// /// # Panics /// Panics if the plugin is not currently being /// invoked on the main thread. pub fn game_mut(&self) -> RefMut<Game> { let ptr = self.game.borrow_mut(); RefMut::map(ptr, |ptr| { let game_ptr = ptr.expect("plugin is not exeuctugin"); assert!(self.invoking_on_main_thread.load(Ordering::Relaxed)); // SAFETY: `game_ptr` points to a valid `Game` whenever // the plugin is executing. If the plugin is not // executing, then we already panicked when unwrapping `ptr`. unsafe { &mut *game_ptr.as_ptr() } }) } /// Gets the plugin ID. pub fn plugin_id(&self) -> PluginId { self.id } /// Accesses a byte slice in the plugin's memory space. /// /// # Safety /// **WASM**: mutating plugin memory or invoking /// plugin functions while this byte slice is /// alive is undefined behavior. /// **Native**: `ptr` must be valid. pub unsafe fn deref_bytes(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<&[u8]> { match &self.inner { Inner::Wasm(w) => { let w = w.borrow(); let bytes = w.deref_bytes(ptr, len)?; Ok(unsafe { std::slice::from_raw_parts(bytes.as_ptr(), bytes.len()) }) } Inner::Native(n) => n.deref_bytes(ptr, len), } } /// Accesses a byte slice in the plugin's memory space. /// /// # Safety /// **WASM**: accessing plugin memory or invoking /// plugin functions while this byte slice is /// alive is undefined behavior. /// **Native**: `ptr` must be valid and the aliasing /// rules must not be violated. pub unsafe fn deref_bytes_mut( &self, ptr: PluginPtrMut<u8>, len: u32, ) -> anyhow::Result<&mut [u8]> { match &self.inner { Inner::Wasm(w) => { let w = w.borrow(); let bytes = w.deref_bytes_mut(ptr, len)?; Ok(unsafe { std::slice::from_raw_parts_mut(bytes.as_mut_ptr(), bytes.len()) }) } Inner::Native(n) => n.deref_bytes_mut(ptr, len), } } /// Accesses a `Pod` value in the plugin's memory space. pub fn read_pod<T: Pod>(&self, ptr: PluginPtr<T>) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), size_of::<T>() as u32)?; bytemuck::try_from_bytes(bytes) .map_err(|_| anyhow!("badly aligned data")) .map(|val| *val) } } /// Accesses a `bincode`-encoded value in the plugin's memory space. pub fn read_bincode<T: DeserializeOwned>( &self, ptr: PluginPtr<u8>, len: u32, ) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; bincode::deserialize(bytes).map_err(From::from) } } /// Accesses a `json`-encoded value in the plugin's memory space. pub fn read_json<T: DeserializeOwned>( &self, ptr: PluginPtr<u8>, len: u32, ) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; serde_json::from_slice(bytes).map_err(From::from) } } /// Deserializes a component value in the plugin's memory space. pub fn read_component<T: Component>(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; T::from_bytes(bytes) .ok_or_else(|| anyhow!("malformed component")) .map(|(component, _bytes_read)| component) } } /// Reads a string from the plugin's memory space. pub fn read_string(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<String> { // SAFETY: we do not return a reference to these bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; let string = std::str::from_utf8(bytes)?.to_owned(); Ok(string) } } /// Reads a `Vec<u8>` from the plugin's memory space. pub fn read_bytes(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<Vec<u8>> { // SAFETY: we do not return a reference to these bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; Ok(bytes.to_owned()) } } /// Allocates some memory within the plugin's bump /// allocator. /// /// The memory is reset after the plugin finishes /// executing the current system. pub fn bump_allocate(&self, layout: Layout) -> anyhow::Result<PluginPtrMut<u8>> { match &self.inner { Inner::Wasm(w) => w.borrow().bump_allocate(layout), Inner::Native(n) => n.bump_allocate(layout), } } /// Bump allocates some memory, then copies `data` into it. pub fn bump_allocate_and_write_bytes(&self, data: &[u8]) -> anyhow::Result<PluginPtrMut<u8>> { let layout = Layout::array::<u8>(data.len())?; let ptr = self.bump_allocate(layout)?; // SAFETY: our access to these bytes is isolated to the // current function. `ptr` is valid as it was just allocated. unsafe { self.write_bytes(ptr, data)?; }
Ok(ptr) } /// Writes `data` to `ptr`. /// /// # Safety /// **WASM**: No concerns. /// **NATIVE**: `ptr` must point to a slice /// of at least `len` valid bytes. pub unsafe fn write_bytes(&self, ptr: PluginPtrMut<u8>, data: &[u8]) -> anyhow::Result<()> { let bytes = self.deref_bytes_mut(ptr, data.len() as u32)?; bytes.copy_from_slice(data); Ok(()) } /// Writes a `Pod` type to `ptr`. pub fn write_pod<T: Pod>(&self, ptr: PluginPtrMut<T>, value: T) -> anyhow::Result<()> { // SAFETY: Unlike `write_bytes`, we know `ptr` is valid for values // of type `T` because of its type parameter. unsafe { self.write_bytes(ptr.cast(), bytemuck::bytes_of(&value)) } } /// Deallocates all bump-allocated memory. fn bump_reset(&self) { match &self.inner { Inner::Wasm(w) => w.borrow().bump_reset(), Inner::Native(n) => n.bump_reset(), } } } enum Inner { Wasm(ThreadPinned<wasm::WasmPluginContext>), Native(native::NativePluginContext), }
random_line_split
context.rs
use std::{ alloc::Layout, cell::{Ref, RefMut}, marker::PhantomData, mem::size_of, panic::AssertUnwindSafe, ptr::NonNull, sync::atomic::{AtomicBool, Ordering}, }; use anyhow::anyhow; use bytemuck::{Pod, Zeroable}; use feather_common::Game; use feather_ecs::EntityBuilder; use quill_common::Component; use serde::de::DeserializeOwned; use vec_arena::Arena; use wasmer::{FromToNativeWasmType, Instance}; use crate::{host_function::WasmHostFunction, thread_pinned::ThreadPinned, PluginId}; mod native; mod wasm; /// Wraps a pointer into a plugin's memory space. #[derive(Copy, Clone, PartialEq, Eq, Zeroable)] #[repr(transparent)] pub struct PluginPtr<T> { pub ptr: u64, pub _marker: PhantomData<*const T>, } impl<T> PluginPtr<T> { pub fn as_native(&self) -> *const T { self.ptr as usize as *const T } /// # Safety /// Adding `n` to this pointer /// must produce a pointer within the same allocated /// object. #[must_use = "PluginPtr::add returns a new pointer"] pub unsafe fn add(self, n: usize) -> Self { Self { ptr: self.ptr + (n * size_of::<T>()) as u64, _marker: self._marker, } } /// # Safety /// The cast must be valid. pub unsafe fn cast<U>(self) -> PluginPtr<U> { PluginPtr { ptr: self.ptr, _marker: PhantomData, } } } unsafe impl<T: Copy + 'static> Pod for PluginPtr<T> {} /// Wraps a pointer into a plugin's memory space. #[derive(Copy, Clone, PartialEq, Eq, Zeroable)] #[repr(transparent)] pub struct PluginPtrMut<T> { pub ptr: u64, pub _marker: PhantomData<*mut T>, } impl<T> PluginPtrMut<T> { pub fn as_native(&self) -> *mut T { self.ptr as usize as *mut T } /// # Safety /// A null pointer must be valid in the context it is used. pub unsafe fn null() -> Self { Self { ptr: 0, _marker: PhantomData, } } /// # Safety /// Adding `n` to this pointer /// must produce a pointer within the same allocated /// object. #[must_use = "PluginPtrMut::add returns a new pointer"] pub unsafe fn add(self, n: usize) -> Self { Self { ptr: self.ptr + (n * size_of::<T>()) as u64, _marker: self._marker, } } /// # Safety /// The cast must be valid. pub unsafe fn cast<U>(self) -> PluginPtrMut<U> { PluginPtrMut { ptr: self.ptr, _marker: PhantomData, } } } unsafe impl<T: Copy + 'static> Pod for PluginPtrMut<T> {} unsafe impl<T: Copy> FromToNativeWasmType for PluginPtr<T> { type Native = i64; fn from_native(native: Self::Native) -> Self { Self { ptr: native as u64, _marker: PhantomData, } } fn to_native(self) -> Self::Native { self.ptr as i64 } } unsafe impl<T: Copy> FromToNativeWasmType for PluginPtrMut<T> { type Native = i64; fn from_native(native: Self::Native) -> Self { Self { ptr: native as u64, _marker: PhantomData, } } fn to_native(self) -> Self::Native { self.ptr as i64 } } /// Context of a running plugin. /// /// Provides methods to access plugin memory, /// invoke exported functions, and access the `Game`. /// /// This type abstracts over WASM or native plugins, /// providing the same interface for both. /// /// # Safety /// The `native` version of the plugin context /// dereferences raw pointers. We assume pointers /// passed by plugins are valid. Most functions /// will cause undefined behavior if these constraints /// are violated. /// /// We type-encode that a pointer originates from a plugin /// using the `PluginPtr` structs. Methods that /// dereference pointers take instances of these /// structs. Since creating a `PluginPtr` is unsafe, /// `PluginContext` methods don't have to be marked /// unsafe. /// /// On WASM targets, the plugin is never trusted, /// and pointer accesses are checked. Undefined behavior /// can never occur as a result of malicious plugin input. pub struct PluginContext { inner: Inner, /// Whether the plugin is currently being invoked /// on the main thread. /// If this is `true`, then plugin functions are on the call stack. invoking_on_main_thread: AtomicBool, /// The current `Game`. /// /// Set to `None` if `invoking_on_main_thread` is `false`. /// Otherwise, must point to a valid game. The pointer /// must be cleared after the plugin finishes executing /// or we risk a dangling reference. game: ThreadPinned<Option<NonNull<Game>>>, /// ID of the plugin. id: PluginId, /// Active entity builders for the plugin. pub entity_builders: ThreadPinned<Arena<EntityBuilder>>, } impl PluginContext { /// Creates a new WASM plugin context. pub fn new_wasm(id: PluginId) -> Self { Self { inner: Inner::Wasm(ThreadPinned::new(wasm::WasmPluginContext::new())), invoking_on_main_thread: AtomicBool::new(false), game: ThreadPinned::new(None), id, entity_builders: ThreadPinned::new(Arena::new()), } } /// Creates a new native plugin context. pub fn new_native(id: PluginId) -> Self
pub fn init_with_instance(&self, instance: &Instance) -> anyhow::Result<()> { match &self.inner { Inner::Wasm(w) => w.borrow_mut().init_with_instance(instance), Inner::Native(_) => panic!("cannot initialize native plugin context"), } } /// Enters the plugin context, invoking a function inside the plugin. /// /// # Panics /// Panics if we are already inside the plugin context. /// Panics if not called on the main thread. pub fn enter<R>(&self, game: &mut Game, callback: impl FnOnce() -> R) -> R { let was_already_entered = self.invoking_on_main_thread.swap(true, Ordering::SeqCst); assert!(!was_already_entered, "cannot recursively invoke a plugin"); *self.game.borrow_mut() = Some(NonNull::from(game)); // If a panic occurs, we need to catch it so // we clear `self.game`. Otherwise, we get // a dangling pointer. let result = std::panic::catch_unwind(AssertUnwindSafe(callback)); self.invoking_on_main_thread.store(false, Ordering::SeqCst); *self.game.borrow_mut() = None; self.bump_reset(); result.unwrap() } /// Gets a mutable reference to the `Game`. /// /// # Panics /// Panics if the plugin is not currently being /// invoked on the main thread. pub fn game_mut(&self) -> RefMut<Game> { let ptr = self.game.borrow_mut(); RefMut::map(ptr, |ptr| { let game_ptr = ptr.expect("plugin is not exeuctugin"); assert!(self.invoking_on_main_thread.load(Ordering::Relaxed)); // SAFETY: `game_ptr` points to a valid `Game` whenever // the plugin is executing. If the plugin is not // executing, then we already panicked when unwrapping `ptr`. unsafe { &mut *game_ptr.as_ptr() } }) } /// Gets the plugin ID. pub fn plugin_id(&self) -> PluginId { self.id } /// Accesses a byte slice in the plugin's memory space. /// /// # Safety /// **WASM**: mutating plugin memory or invoking /// plugin functions while this byte slice is /// alive is undefined behavior. /// **Native**: `ptr` must be valid. pub unsafe fn deref_bytes(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<&[u8]> { match &self.inner { Inner::Wasm(w) => { let w = w.borrow(); let bytes = w.deref_bytes(ptr, len)?; Ok(unsafe { std::slice::from_raw_parts(bytes.as_ptr(), bytes.len()) }) } Inner::Native(n) => n.deref_bytes(ptr, len), } } /// Accesses a byte slice in the plugin's memory space. /// /// # Safety /// **WASM**: accessing plugin memory or invoking /// plugin functions while this byte slice is /// alive is undefined behavior. /// **Native**: `ptr` must be valid and the aliasing /// rules must not be violated. pub unsafe fn deref_bytes_mut( &self, ptr: PluginPtrMut<u8>, len: u32, ) -> anyhow::Result<&mut [u8]> { match &self.inner { Inner::Wasm(w) => { let w = w.borrow(); let bytes = w.deref_bytes_mut(ptr, len)?; Ok(unsafe { std::slice::from_raw_parts_mut(bytes.as_mut_ptr(), bytes.len()) }) } Inner::Native(n) => n.deref_bytes_mut(ptr, len), } } /// Accesses a `Pod` value in the plugin's memory space. pub fn read_pod<T: Pod>(&self, ptr: PluginPtr<T>) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), size_of::<T>() as u32)?; bytemuck::try_from_bytes(bytes) .map_err(|_| anyhow!("badly aligned data")) .map(|val| *val) } } /// Accesses a `bincode`-encoded value in the plugin's memory space. pub fn read_bincode<T: DeserializeOwned>( &self, ptr: PluginPtr<u8>, len: u32, ) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; bincode::deserialize(bytes).map_err(From::from) } } /// Accesses a `json`-encoded value in the plugin's memory space. pub fn read_json<T: DeserializeOwned>( &self, ptr: PluginPtr<u8>, len: u32, ) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; serde_json::from_slice(bytes).map_err(From::from) } } /// Deserializes a component value in the plugin's memory space. pub fn read_component<T: Component>(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; T::from_bytes(bytes) .ok_or_else(|| anyhow!("malformed component")) .map(|(component, _bytes_read)| component) } } /// Reads a string from the plugin's memory space. pub fn read_string(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<String> { // SAFETY: we do not return a reference to these bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; let string = std::str::from_utf8(bytes)?.to_owned(); Ok(string) } } /// Reads a `Vec<u8>` from the plugin's memory space. pub fn read_bytes(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<Vec<u8>> { // SAFETY: we do not return a reference to these bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; Ok(bytes.to_owned()) } } /// Allocates some memory within the plugin's bump /// allocator. /// /// The memory is reset after the plugin finishes /// executing the current system. pub fn bump_allocate(&self, layout: Layout) -> anyhow::Result<PluginPtrMut<u8>> { match &self.inner { Inner::Wasm(w) => w.borrow().bump_allocate(layout), Inner::Native(n) => n.bump_allocate(layout), } } /// Bump allocates some memory, then copies `data` into it. pub fn bump_allocate_and_write_bytes(&self, data: &[u8]) -> anyhow::Result<PluginPtrMut<u8>> { let layout = Layout::array::<u8>(data.len())?; let ptr = self.bump_allocate(layout)?; // SAFETY: our access to these bytes is isolated to the // current function. `ptr` is valid as it was just allocated. unsafe { self.write_bytes(ptr, data)?; } Ok(ptr) } /// Writes `data` to `ptr`. /// /// # Safety /// **WASM**: No concerns. /// **NATIVE**: `ptr` must point to a slice /// of at least `len` valid bytes. pub unsafe fn write_bytes(&self, ptr: PluginPtrMut<u8>, data: &[u8]) -> anyhow::Result<()> { let bytes = self.deref_bytes_mut(ptr, data.len() as u32)?; bytes.copy_from_slice(data); Ok(()) } /// Writes a `Pod` type to `ptr`. pub fn write_pod<T: Pod>(&self, ptr: PluginPtrMut<T>, value: T) -> anyhow::Result<()> { // SAFETY: Unlike `write_bytes`, we know `ptr` is valid for values // of type `T` because of its type parameter. unsafe { self.write_bytes(ptr.cast(), bytemuck::bytes_of(&value)) } } /// Deallocates all bump-allocated memory. fn bump_reset(&self) { match &self.inner { Inner::Wasm(w) => w.borrow().bump_reset(), Inner::Native(n) => n.bump_reset(), } } } enum Inner { Wasm(ThreadPinned<wasm::WasmPluginContext>), Native(native::NativePluginContext), }
{ Self { inner: Inner::Native(native::NativePluginContext::new()), invoking_on_main_thread: AtomicBool::new(false), game: ThreadPinned::new(None), id, entity_builders: ThreadPinned::new(Arena::new()), } }
identifier_body
context.rs
use std::{ alloc::Layout, cell::{Ref, RefMut}, marker::PhantomData, mem::size_of, panic::AssertUnwindSafe, ptr::NonNull, sync::atomic::{AtomicBool, Ordering}, }; use anyhow::anyhow; use bytemuck::{Pod, Zeroable}; use feather_common::Game; use feather_ecs::EntityBuilder; use quill_common::Component; use serde::de::DeserializeOwned; use vec_arena::Arena; use wasmer::{FromToNativeWasmType, Instance}; use crate::{host_function::WasmHostFunction, thread_pinned::ThreadPinned, PluginId}; mod native; mod wasm; /// Wraps a pointer into a plugin's memory space. #[derive(Copy, Clone, PartialEq, Eq, Zeroable)] #[repr(transparent)] pub struct PluginPtr<T> { pub ptr: u64, pub _marker: PhantomData<*const T>, } impl<T> PluginPtr<T> { pub fn as_native(&self) -> *const T { self.ptr as usize as *const T } /// # Safety /// Adding `n` to this pointer /// must produce a pointer within the same allocated /// object. #[must_use = "PluginPtr::add returns a new pointer"] pub unsafe fn add(self, n: usize) -> Self { Self { ptr: self.ptr + (n * size_of::<T>()) as u64, _marker: self._marker, } } /// # Safety /// The cast must be valid. pub unsafe fn cast<U>(self) -> PluginPtr<U> { PluginPtr { ptr: self.ptr, _marker: PhantomData, } } } unsafe impl<T: Copy + 'static> Pod for PluginPtr<T> {} /// Wraps a pointer into a plugin's memory space. #[derive(Copy, Clone, PartialEq, Eq, Zeroable)] #[repr(transparent)] pub struct PluginPtrMut<T> { pub ptr: u64, pub _marker: PhantomData<*mut T>, } impl<T> PluginPtrMut<T> { pub fn as_native(&self) -> *mut T { self.ptr as usize as *mut T } /// # Safety /// A null pointer must be valid in the context it is used. pub unsafe fn null() -> Self { Self { ptr: 0, _marker: PhantomData, } } /// # Safety /// Adding `n` to this pointer /// must produce a pointer within the same allocated /// object. #[must_use = "PluginPtrMut::add returns a new pointer"] pub unsafe fn add(self, n: usize) -> Self { Self { ptr: self.ptr + (n * size_of::<T>()) as u64, _marker: self._marker, } } /// # Safety /// The cast must be valid. pub unsafe fn cast<U>(self) -> PluginPtrMut<U> { PluginPtrMut { ptr: self.ptr, _marker: PhantomData, } } } unsafe impl<T: Copy + 'static> Pod for PluginPtrMut<T> {} unsafe impl<T: Copy> FromToNativeWasmType for PluginPtr<T> { type Native = i64; fn from_native(native: Self::Native) -> Self { Self { ptr: native as u64, _marker: PhantomData, } } fn to_native(self) -> Self::Native { self.ptr as i64 } } unsafe impl<T: Copy> FromToNativeWasmType for PluginPtrMut<T> { type Native = i64; fn from_native(native: Self::Native) -> Self { Self { ptr: native as u64, _marker: PhantomData, } } fn to_native(self) -> Self::Native { self.ptr as i64 } } /// Context of a running plugin. /// /// Provides methods to access plugin memory, /// invoke exported functions, and access the `Game`. /// /// This type abstracts over WASM or native plugins, /// providing the same interface for both. /// /// # Safety /// The `native` version of the plugin context /// dereferences raw pointers. We assume pointers /// passed by plugins are valid. Most functions /// will cause undefined behavior if these constraints /// are violated. /// /// We type-encode that a pointer originates from a plugin /// using the `PluginPtr` structs. Methods that /// dereference pointers take instances of these /// structs. Since creating a `PluginPtr` is unsafe, /// `PluginContext` methods don't have to be marked /// unsafe. /// /// On WASM targets, the plugin is never trusted, /// and pointer accesses are checked. Undefined behavior /// can never occur as a result of malicious plugin input. pub struct PluginContext { inner: Inner, /// Whether the plugin is currently being invoked /// on the main thread. /// If this is `true`, then plugin functions are on the call stack. invoking_on_main_thread: AtomicBool, /// The current `Game`. /// /// Set to `None` if `invoking_on_main_thread` is `false`. /// Otherwise, must point to a valid game. The pointer /// must be cleared after the plugin finishes executing /// or we risk a dangling reference. game: ThreadPinned<Option<NonNull<Game>>>, /// ID of the plugin. id: PluginId, /// Active entity builders for the plugin. pub entity_builders: ThreadPinned<Arena<EntityBuilder>>, } impl PluginContext { /// Creates a new WASM plugin context. pub fn new_wasm(id: PluginId) -> Self { Self { inner: Inner::Wasm(ThreadPinned::new(wasm::WasmPluginContext::new())), invoking_on_main_thread: AtomicBool::new(false), game: ThreadPinned::new(None), id, entity_builders: ThreadPinned::new(Arena::new()), } } /// Creates a new native plugin context. pub fn new_native(id: PluginId) -> Self { Self { inner: Inner::Native(native::NativePluginContext::new()), invoking_on_main_thread: AtomicBool::new(false), game: ThreadPinned::new(None), id, entity_builders: ThreadPinned::new(Arena::new()), } } pub fn init_with_instance(&self, instance: &Instance) -> anyhow::Result<()> { match &self.inner { Inner::Wasm(w) => w.borrow_mut().init_with_instance(instance), Inner::Native(_) => panic!("cannot initialize native plugin context"), } } /// Enters the plugin context, invoking a function inside the plugin. /// /// # Panics /// Panics if we are already inside the plugin context. /// Panics if not called on the main thread. pub fn enter<R>(&self, game: &mut Game, callback: impl FnOnce() -> R) -> R { let was_already_entered = self.invoking_on_main_thread.swap(true, Ordering::SeqCst); assert!(!was_already_entered, "cannot recursively invoke a plugin"); *self.game.borrow_mut() = Some(NonNull::from(game)); // If a panic occurs, we need to catch it so // we clear `self.game`. Otherwise, we get // a dangling pointer. let result = std::panic::catch_unwind(AssertUnwindSafe(callback)); self.invoking_on_main_thread.store(false, Ordering::SeqCst); *self.game.borrow_mut() = None; self.bump_reset(); result.unwrap() } /// Gets a mutable reference to the `Game`. /// /// # Panics /// Panics if the plugin is not currently being /// invoked on the main thread. pub fn game_mut(&self) -> RefMut<Game> { let ptr = self.game.borrow_mut(); RefMut::map(ptr, |ptr| { let game_ptr = ptr.expect("plugin is not exeuctugin"); assert!(self.invoking_on_main_thread.load(Ordering::Relaxed)); // SAFETY: `game_ptr` points to a valid `Game` whenever // the plugin is executing. If the plugin is not // executing, then we already panicked when unwrapping `ptr`. unsafe { &mut *game_ptr.as_ptr() } }) } /// Gets the plugin ID. pub fn plugin_id(&self) -> PluginId { self.id } /// Accesses a byte slice in the plugin's memory space. /// /// # Safety /// **WASM**: mutating plugin memory or invoking /// plugin functions while this byte slice is /// alive is undefined behavior. /// **Native**: `ptr` must be valid. pub unsafe fn deref_bytes(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<&[u8]> { match &self.inner { Inner::Wasm(w) => { let w = w.borrow(); let bytes = w.deref_bytes(ptr, len)?; Ok(unsafe { std::slice::from_raw_parts(bytes.as_ptr(), bytes.len()) }) } Inner::Native(n) => n.deref_bytes(ptr, len), } } /// Accesses a byte slice in the plugin's memory space. /// /// # Safety /// **WASM**: accessing plugin memory or invoking /// plugin functions while this byte slice is /// alive is undefined behavior. /// **Native**: `ptr` must be valid and the aliasing /// rules must not be violated. pub unsafe fn deref_bytes_mut( &self, ptr: PluginPtrMut<u8>, len: u32, ) -> anyhow::Result<&mut [u8]> { match &self.inner { Inner::Wasm(w) => { let w = w.borrow(); let bytes = w.deref_bytes_mut(ptr, len)?; Ok(unsafe { std::slice::from_raw_parts_mut(bytes.as_mut_ptr(), bytes.len()) }) } Inner::Native(n) => n.deref_bytes_mut(ptr, len), } } /// Accesses a `Pod` value in the plugin's memory space. pub fn read_pod<T: Pod>(&self, ptr: PluginPtr<T>) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), size_of::<T>() as u32)?; bytemuck::try_from_bytes(bytes) .map_err(|_| anyhow!("badly aligned data")) .map(|val| *val) } } /// Accesses a `bincode`-encoded value in the plugin's memory space. pub fn read_bincode<T: DeserializeOwned>( &self, ptr: PluginPtr<u8>, len: u32, ) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; bincode::deserialize(bytes).map_err(From::from) } } /// Accesses a `json`-encoded value in the plugin's memory space. pub fn
<T: DeserializeOwned>( &self, ptr: PluginPtr<u8>, len: u32, ) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; serde_json::from_slice(bytes).map_err(From::from) } } /// Deserializes a component value in the plugin's memory space. pub fn read_component<T: Component>(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<T> { // SAFETY: we do not return a reference to these // bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; T::from_bytes(bytes) .ok_or_else(|| anyhow!("malformed component")) .map(|(component, _bytes_read)| component) } } /// Reads a string from the plugin's memory space. pub fn read_string(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<String> { // SAFETY: we do not return a reference to these bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; let string = std::str::from_utf8(bytes)?.to_owned(); Ok(string) } } /// Reads a `Vec<u8>` from the plugin's memory space. pub fn read_bytes(&self, ptr: PluginPtr<u8>, len: u32) -> anyhow::Result<Vec<u8>> { // SAFETY: we do not return a reference to these bytes. unsafe { let bytes = self.deref_bytes(ptr.cast(), len)?; Ok(bytes.to_owned()) } } /// Allocates some memory within the plugin's bump /// allocator. /// /// The memory is reset after the plugin finishes /// executing the current system. pub fn bump_allocate(&self, layout: Layout) -> anyhow::Result<PluginPtrMut<u8>> { match &self.inner { Inner::Wasm(w) => w.borrow().bump_allocate(layout), Inner::Native(n) => n.bump_allocate(layout), } } /// Bump allocates some memory, then copies `data` into it. pub fn bump_allocate_and_write_bytes(&self, data: &[u8]) -> anyhow::Result<PluginPtrMut<u8>> { let layout = Layout::array::<u8>(data.len())?; let ptr = self.bump_allocate(layout)?; // SAFETY: our access to these bytes is isolated to the // current function. `ptr` is valid as it was just allocated. unsafe { self.write_bytes(ptr, data)?; } Ok(ptr) } /// Writes `data` to `ptr`. /// /// # Safety /// **WASM**: No concerns. /// **NATIVE**: `ptr` must point to a slice /// of at least `len` valid bytes. pub unsafe fn write_bytes(&self, ptr: PluginPtrMut<u8>, data: &[u8]) -> anyhow::Result<()> { let bytes = self.deref_bytes_mut(ptr, data.len() as u32)?; bytes.copy_from_slice(data); Ok(()) } /// Writes a `Pod` type to `ptr`. pub fn write_pod<T: Pod>(&self, ptr: PluginPtrMut<T>, value: T) -> anyhow::Result<()> { // SAFETY: Unlike `write_bytes`, we know `ptr` is valid for values // of type `T` because of its type parameter. unsafe { self.write_bytes(ptr.cast(), bytemuck::bytes_of(&value)) } } /// Deallocates all bump-allocated memory. fn bump_reset(&self) { match &self.inner { Inner::Wasm(w) => w.borrow().bump_reset(), Inner::Native(n) => n.bump_reset(), } } } enum Inner { Wasm(ThreadPinned<wasm::WasmPluginContext>), Native(native::NativePluginContext), }
read_json
identifier_name
main.py
import mlconfig import argparse import datetime import util import models import dataset import trades import madrys import mart import time import os import torch import shutil import numpy as np from trainer import Trainer from evaluator import Evaluator from torch.autograd import Variable from auto_attack.autoattack import AutoAttack from thop import profile mlconfig.register(trades.TradesLoss) mlconfig.register(madrys.MadrysLoss) mlconfig.register(mart.MartLoss) mlconfig.register(dataset.DatasetGenerator) parser = argparse.ArgumentParser(description='RobustArc') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--version', type=str, default="DARTS_Search") parser.add_argument('--exp_name', type=str, default="test_exp") parser.add_argument('--config_path', type=str, default='configs') parser.add_argument('--load_model', action='store_true', default=False) parser.add_argument('--load_best_model', action='store_true', default=False) parser.add_argument('--data_parallel', action='store_true', default=False) parser.add_argument('--train', action='store_true', default=False) parser.add_argument('--attack_choice', default='PGD', choices=['PGD', 'AA', 'GAMA', 'CW', 'none']) parser.add_argument('--epsilon', default=8, type=float, help='perturbation') parser.add_argument('--num_steps', default=20, type=int, help='perturb number of steps') parser.add_argument('--step_size', default=0.8, type=float, help='perturb step size') parser.add_argument('--train_eval_epoch', default=0.5, type=float, help='PGD Eval in training after this epoch') args = parser.parse_args() if args.epsilon > 1: args.epsilon = args.epsilon / 255 args.step_size = args.step_size / 255 # Set up if args.exp_name == '': args.exp_name = 'exp_' + datetime.datetime.now() exp_path = os.path.join(args.exp_name, args.version) log_file_path = os.path.join(exp_path, args.version) checkpoint_path = os.path.join(exp_path, 'checkpoints') search_results_checkpoint_file_name = None checkpoint_path_file = os.path.join(checkpoint_path, args.version) util.build_dirs(exp_path) util.build_dirs(checkpoint_path) logger = util.setup_logger(name=args.version, log_file=log_file_path + ".log") torch.manual_seed(args.seed) np.random.seed(args.seed) if torch.cuda.is_available(): torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark = True device = torch.device('cuda') device_list = [torch.cuda.get_device_name(i) for i in range(0, torch.cuda.device_count())] logger.info("GPU List: %s" % (device_list)) else: device = torch.device('cpu') config_file = os.path.join(args.config_path, args.version)+'.yaml' config = mlconfig.load(config_file) shutil.copyfile(config_file, os.path.join(exp_path, args.version+'.yaml')) def whitebox_eval(data_loader, model, evaluator, log=True): natural_count, pgd_count, total, stable_count = 0, 0, 0, 0 loss_meters = util.AverageMeter() lip_meters = util.AverageMeter() model.eval() for i, (images, labels) in enumerate(data_loader["test_dataset"]): images, labels = images.to(device), labels.to(device) # pgd attack images, labels = Variable(images, requires_grad=True), Variable(labels) if args.attack_choice == 'PGD': rs = evaluator._pgd_whitebox(model, images, labels, random_start=True, epsilon=args.epsilon, num_steps=args.num_steps, step_size=args.step_size) elif args.attack_choice == 'GAMA': rs = evaluator._gama_whitebox(model, images, labels, epsilon=args.epsilon, num_steps=args.num_steps, eps_iter=args.step_size) elif args.attack_choice == 'CW': rs = evaluator._cw_whitebox(model, images, labels, random_start=True, epsilon=args.epsilon, num_steps=args.num_steps, step_size=args.step_size) else: raise('Not implemented') acc, acc_pgd, loss, stable, X_pgd = rs total += images.size(0) natural_count += acc pgd_count += acc_pgd stable_count += stable local_lip = util.local_lip(model, images, X_pgd).item() lip_meters.update(local_lip) loss_meters.update(loss) if log: payload = 'LIP: %.4f\tStable Count: %d\tNatural Count: %d/%d\tNatural Acc: %.2f\tAdv Count: %d/%d\tAdv Acc: %.2f' % (local_lip, stable_count, natural_count, total, (natural_count/total) * 100, pgd_count, total, (pgd_count/total) * 100) logger.info(payload) natural_acc = (natural_count/total) * 100 pgd_acc = (pgd_count/total) * 100 payload = 'Natural Correct Count: %d/%d Acc: %.2f ' % (natural_count, total, natural_acc) logger.info(payload) payload = '%s Correct Count: %d/%d Acc: %.2f ' % (args.attack_choice, pgd_count, total, pgd_acc) logger.info(payload) payload = '%s Loss Avg: %.2f ' % (args.attack_choice, loss_meters.avg) logger.info(payload) payload = 'LIP Avg: %.4f ' % (lip_meters.avg) logger.info(payload) payload = 'Stable Count: %d/%d StableAcc: %.2f ' % (stable_count, total, stable_count * 100/total) logger.info(payload) return natural_acc, pgd_acc, stable_count*100/total, lip_meters.avg def adjust_learning_rate(optimizer, epoch): """decrease the learning rate""" lr = config.optimizer.lr schedule = config.lr_schedule if hasattr(config, 'lr_schedule') else 'fixed' if schedule == 'fixed': if epoch >= 0.75 * config.epochs: lr = config.optimizer.lr * 0.1 if epoch >= 0.9 * config.epochs: lr = config.optimizer.lr * 0.01 if epoch >= config.epochs: lr = config.optimizer.lr * 0.001 # cosine schedule elif schedule == 'cosine': lr = config.optimizer.lr * 0.5 * (1 + np.cos((epoch - 1) / config.epochs * np.pi)) elif schedule == 'search': if epoch >= 75: lr = 0.01 if epoch >= 90: lr = 0.001 else: raise ValueError('Unkown LR schedule %s' % schedule) for param_group in optimizer.param_groups: param_group['lr'] = lr return lr def adjust_eps(epoch, config): eps_min = 2/255 eps_max = 8/255 ratio = epoch / (config.epochs * 0.2) eps = (eps_min + 0.5 * (eps_max - eps_min) * (1 - np.cos(ratio * np.pi))) return eps def adjust_weight_decay(model, l2_value): conv, fc = [], [] for name, param in model.named_parameters(): print(name) if not param.requires_grad: # frozen weights continue if 'fc' in name: fc.append(param) else: conv.append(param) params = [{'params': conv, 'weight_decay': l2_value}, {'params': fc, 'weight_decay': 0.01}] print(fc) return params def train(starting_epoch, model, genotype, optimizer, scheduler, criterion, trainer, evaluator, ENV, data_loader): print(model) for epoch in range(starting_epoch, config.epochs): logger.info("="*20 + "Training Epoch %d" % (epoch) + "="*20) adjust_learning_rate(optimizer, epoch) # Update Drop Path Prob if isinstance(model, models.DARTS_model.NetworkCIFAR): drop_path_prob = config.model.drop_path_prob * epoch / config.epochs model.drop_path_prob = drop_path_prob logger.info('Drop Path Probability %.4f' % drop_path_prob) # Train ENV['global_step'] = trainer.train(epoch, model, criterion, optimizer) # Eval logger.info("="*20 + "Eval Epoch %d" % (epoch) + "="*20) evaluator.eval(epoch, model) payload = ('Eval Loss:%.4f\tEval acc: %.2f' % (evaluator.loss_meters.avg, evaluator.acc_meters.avg*100)) logger.info(payload) ENV['eval_history'].append(evaluator.acc_meters.avg*100) ENV['curren_acc'] = evaluator.acc_meters.avg*100 is_best = False if epoch >= config.epochs * args.train_eval_epoch and args.train_eval_epoch >= 0: # Reset Stats trainer._reset_stats() evaluator._reset_stats() for param in model.parameters(): param.requires_grad = False natural_acc, pgd_acc, stable_acc, lip = whitebox_eval(data_loader, model, evaluator, log=False) for param in model.parameters(): param.requires_grad = True is_best = True if pgd_acc > ENV['best_pgd_acc'] else False ENV['best_pgd_acc'] = max(ENV['best_pgd_acc'], pgd_acc) ENV['pgd_eval_history'].append((epoch, pgd_acc)) ENV['stable_acc_history'].append(stable_acc) ENV['lip_history'].append(lip) logger.info('Best PGD accuracy: %.2f' % (ENV['best_pgd_acc'])) # Reset Stats trainer._reset_stats() evaluator._reset_stats() # Save Model target_model = model.module if args.data_parallel else model filename = checkpoint_path_file + '.pth' util.save_model(ENV=ENV, epoch=epoch, model=target_model, optimizer=optimizer, alpha_optimizer=None, scheduler=None, genotype=genotype, save_best=is_best, filename=filename) logger.info('Model Saved at %s\n', filename) return def
(): # Load Search Version Genotype model = config.model().to(device) genotype = None # Setup ENV data_loader = config.dataset().getDataLoader() if hasattr(config, 'adjust_weight_decay') and config.adjust_weight_decay: params = adjust_weight_decay(model, config.optimizer.weight_decay) else: params = model.parameters() optimizer = config.optimizer(params) criterion = config.criterion() trainer = Trainer(criterion, data_loader, logger, config) evaluator = Evaluator(data_loader, logger, config) profile_inputs = (torch.randn([1, 3, 32, 32]).to(device),) flops, params = profile(model, inputs=profile_inputs, verbose=False) flops = flops / 1e6 starting_epoch = 0 config.set_immutable() for key in config: logger.info("%s: %s" % (key, config[key])) logger.info("param size = %fMB", util.count_parameters_in_MB(model)) logger.info("flops: %.4fM" % flops) logger.info("PyTorch Version: %s" % (torch.__version__)) if torch.cuda.is_available(): device_list = [torch.cuda.get_device_name(i) for i in range(0, torch.cuda.device_count())] logger.info("GPU List: %s" % (device_list)) ENV = {'global_step': 0, 'best_acc': 0.0, 'curren_acc': 0.0, 'best_pgd_acc': 0.0, 'flops': flops, 'train_history': [], 'eval_history': [], 'pgd_eval_history': [], 'stable_acc_history': [], 'lip_history': [], 'genotype_list': []} if args.load_model or args.load_best_model: filename = checkpoint_path_file + '_best.pth' if args.load_best_model else checkpoint_path_file + '.pth' checkpoint = util.load_model(filename=filename, model=model, optimizer=optimizer, alpha_optimizer=None, scheduler=None) starting_epoch = checkpoint['epoch'] + 1 ENV = checkpoint['ENV'] if 'stable_acc_history' not in ENV: ENV['stable_acc_history'] = [] if 'lip_history' not in ENV: ENV['lip_history'] = [] trainer.global_step = ENV['global_step'] logger.info("File %s loaded!" % (filename)) if args.data_parallel: print('data_parallel') model = torch.nn.DataParallel(model).to(device) logger.info("Starting Epoch: %d" % (starting_epoch)) if args.train: train(starting_epoch, model, genotype, optimizer, None, criterion, trainer, evaluator, ENV, data_loader) elif args.attack_choice in ['PGD', 'GAMA', 'CW']: for param in model.parameters(): param.requires_grad = False model.eval() natural_acc, adv_acc, stable_acc, lip = whitebox_eval(data_loader, model, evaluator) key = '%s_%d' % (args.attack_choice, args.num_steps) ENV['natural_acc'] = natural_acc ENV[key] = adv_acc ENV['%s_stable' % key] = stable_acc ENV['%s_lip' % key] = lip target_model = model.module if args.data_parallel else model filename = checkpoint_path_file + '_best.pth' if args.load_best_model else checkpoint_path_file + '.pth' util.save_model(ENV=ENV, epoch=starting_epoch-1, model=target_model, optimizer=optimizer, alpha_optimizer=None, scheduler=None, genotype=genotype, filename=filename) elif args.attack_choice == 'AA': for param in model.parameters(): param.requires_grad = False x_test = [x for (x, y) in data_loader['test_dataset']] x_test = torch.cat(x_test, dim=0) y_test = [y for (x, y) in data_loader['test_dataset']] y_test = torch.cat(y_test, dim=0) model.eval() adversary = AutoAttack(model, norm='Linf', eps=args.epsilon, logger=logger, verbose=True) adversary.plus = False logger.info('=' * 20 + 'AA Attack Eval' + '=' * 20) x_adv, robust_accuracy = adversary.run_standard_evaluation(x_test, y_test, bs=config.dataset.eval_batch_size) robust_accuracy = robust_accuracy * 100 logger.info('AA Accuracy: %.2f' % (robust_accuracy)) ENV['aa_attack'] = robust_accuracy target_model = model.module if args.data_parallel else model filename = checkpoint_path_file + '_best.pth' if args.load_best_model else checkpoint_path_file + '.pth' util.save_model(ENV=ENV, epoch=starting_epoch-1, model=target_model, optimizer=optimizer, alpha_optimizer=None, scheduler=None, genotype=genotype, filename=filename) return if __name__ == '__main__': for arg in vars(args): logger.info("%s: %s" % (arg, getattr(args, arg))) start = time.time() main() end = time.time() cost = (end - start) / 86400 payload = "Running Cost %.2f Days" % cost logger.info(payload)
main
identifier_name
main.py
import mlconfig import argparse import datetime import util import models import dataset import trades import madrys import mart import time import os import torch import shutil import numpy as np from trainer import Trainer from evaluator import Evaluator from torch.autograd import Variable from auto_attack.autoattack import AutoAttack from thop import profile mlconfig.register(trades.TradesLoss) mlconfig.register(madrys.MadrysLoss) mlconfig.register(mart.MartLoss) mlconfig.register(dataset.DatasetGenerator) parser = argparse.ArgumentParser(description='RobustArc') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--version', type=str, default="DARTS_Search") parser.add_argument('--exp_name', type=str, default="test_exp") parser.add_argument('--config_path', type=str, default='configs') parser.add_argument('--load_model', action='store_true', default=False) parser.add_argument('--load_best_model', action='store_true', default=False) parser.add_argument('--data_parallel', action='store_true', default=False) parser.add_argument('--train', action='store_true', default=False) parser.add_argument('--attack_choice', default='PGD', choices=['PGD', 'AA', 'GAMA', 'CW', 'none']) parser.add_argument('--epsilon', default=8, type=float, help='perturbation') parser.add_argument('--num_steps', default=20, type=int, help='perturb number of steps') parser.add_argument('--step_size', default=0.8, type=float, help='perturb step size') parser.add_argument('--train_eval_epoch', default=0.5, type=float, help='PGD Eval in training after this epoch') args = parser.parse_args() if args.epsilon > 1: args.epsilon = args.epsilon / 255 args.step_size = args.step_size / 255 # Set up if args.exp_name == '': args.exp_name = 'exp_' + datetime.datetime.now() exp_path = os.path.join(args.exp_name, args.version) log_file_path = os.path.join(exp_path, args.version) checkpoint_path = os.path.join(exp_path, 'checkpoints') search_results_checkpoint_file_name = None checkpoint_path_file = os.path.join(checkpoint_path, args.version) util.build_dirs(exp_path) util.build_dirs(checkpoint_path) logger = util.setup_logger(name=args.version, log_file=log_file_path + ".log") torch.manual_seed(args.seed) np.random.seed(args.seed) if torch.cuda.is_available(): torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark = True device = torch.device('cuda') device_list = [torch.cuda.get_device_name(i) for i in range(0, torch.cuda.device_count())] logger.info("GPU List: %s" % (device_list)) else: device = torch.device('cpu') config_file = os.path.join(args.config_path, args.version)+'.yaml' config = mlconfig.load(config_file) shutil.copyfile(config_file, os.path.join(exp_path, args.version+'.yaml')) def whitebox_eval(data_loader, model, evaluator, log=True): natural_count, pgd_count, total, stable_count = 0, 0, 0, 0 loss_meters = util.AverageMeter() lip_meters = util.AverageMeter() model.eval() for i, (images, labels) in enumerate(data_loader["test_dataset"]): images, labels = images.to(device), labels.to(device) # pgd attack images, labels = Variable(images, requires_grad=True), Variable(labels) if args.attack_choice == 'PGD': rs = evaluator._pgd_whitebox(model, images, labels, random_start=True, epsilon=args.epsilon, num_steps=args.num_steps, step_size=args.step_size) elif args.attack_choice == 'GAMA': rs = evaluator._gama_whitebox(model, images, labels, epsilon=args.epsilon, num_steps=args.num_steps, eps_iter=args.step_size) elif args.attack_choice == 'CW': rs = evaluator._cw_whitebox(model, images, labels, random_start=True, epsilon=args.epsilon, num_steps=args.num_steps, step_size=args.step_size) else: raise('Not implemented') acc, acc_pgd, loss, stable, X_pgd = rs total += images.size(0) natural_count += acc pgd_count += acc_pgd stable_count += stable local_lip = util.local_lip(model, images, X_pgd).item() lip_meters.update(local_lip) loss_meters.update(loss) if log: payload = 'LIP: %.4f\tStable Count: %d\tNatural Count: %d/%d\tNatural Acc: %.2f\tAdv Count: %d/%d\tAdv Acc: %.2f' % (local_lip, stable_count, natural_count, total, (natural_count/total) * 100, pgd_count, total, (pgd_count/total) * 100) logger.info(payload) natural_acc = (natural_count/total) * 100 pgd_acc = (pgd_count/total) * 100 payload = 'Natural Correct Count: %d/%d Acc: %.2f ' % (natural_count, total, natural_acc) logger.info(payload) payload = '%s Correct Count: %d/%d Acc: %.2f ' % (args.attack_choice, pgd_count, total, pgd_acc) logger.info(payload) payload = '%s Loss Avg: %.2f ' % (args.attack_choice, loss_meters.avg) logger.info(payload) payload = 'LIP Avg: %.4f ' % (lip_meters.avg) logger.info(payload) payload = 'Stable Count: %d/%d StableAcc: %.2f ' % (stable_count, total, stable_count * 100/total) logger.info(payload) return natural_acc, pgd_acc, stable_count*100/total, lip_meters.avg def adjust_learning_rate(optimizer, epoch): """decrease the learning rate""" lr = config.optimizer.lr schedule = config.lr_schedule if hasattr(config, 'lr_schedule') else 'fixed' if schedule == 'fixed': if epoch >= 0.75 * config.epochs: lr = config.optimizer.lr * 0.1 if epoch >= 0.9 * config.epochs: lr = config.optimizer.lr * 0.01 if epoch >= config.epochs: lr = config.optimizer.lr * 0.001 # cosine schedule elif schedule == 'cosine': lr = config.optimizer.lr * 0.5 * (1 + np.cos((epoch - 1) / config.epochs * np.pi)) elif schedule == 'search': if epoch >= 75: lr = 0.01 if epoch >= 90: lr = 0.001 else: raise ValueError('Unkown LR schedule %s' % schedule) for param_group in optimizer.param_groups: param_group['lr'] = lr return lr def adjust_eps(epoch, config): eps_min = 2/255 eps_max = 8/255 ratio = epoch / (config.epochs * 0.2) eps = (eps_min + 0.5 * (eps_max - eps_min) * (1 - np.cos(ratio * np.pi))) return eps def adjust_weight_decay(model, l2_value):
def train(starting_epoch, model, genotype, optimizer, scheduler, criterion, trainer, evaluator, ENV, data_loader): print(model) for epoch in range(starting_epoch, config.epochs): logger.info("="*20 + "Training Epoch %d" % (epoch) + "="*20) adjust_learning_rate(optimizer, epoch) # Update Drop Path Prob if isinstance(model, models.DARTS_model.NetworkCIFAR): drop_path_prob = config.model.drop_path_prob * epoch / config.epochs model.drop_path_prob = drop_path_prob logger.info('Drop Path Probability %.4f' % drop_path_prob) # Train ENV['global_step'] = trainer.train(epoch, model, criterion, optimizer) # Eval logger.info("="*20 + "Eval Epoch %d" % (epoch) + "="*20) evaluator.eval(epoch, model) payload = ('Eval Loss:%.4f\tEval acc: %.2f' % (evaluator.loss_meters.avg, evaluator.acc_meters.avg*100)) logger.info(payload) ENV['eval_history'].append(evaluator.acc_meters.avg*100) ENV['curren_acc'] = evaluator.acc_meters.avg*100 is_best = False if epoch >= config.epochs * args.train_eval_epoch and args.train_eval_epoch >= 0: # Reset Stats trainer._reset_stats() evaluator._reset_stats() for param in model.parameters(): param.requires_grad = False natural_acc, pgd_acc, stable_acc, lip = whitebox_eval(data_loader, model, evaluator, log=False) for param in model.parameters(): param.requires_grad = True is_best = True if pgd_acc > ENV['best_pgd_acc'] else False ENV['best_pgd_acc'] = max(ENV['best_pgd_acc'], pgd_acc) ENV['pgd_eval_history'].append((epoch, pgd_acc)) ENV['stable_acc_history'].append(stable_acc) ENV['lip_history'].append(lip) logger.info('Best PGD accuracy: %.2f' % (ENV['best_pgd_acc'])) # Reset Stats trainer._reset_stats() evaluator._reset_stats() # Save Model target_model = model.module if args.data_parallel else model filename = checkpoint_path_file + '.pth' util.save_model(ENV=ENV, epoch=epoch, model=target_model, optimizer=optimizer, alpha_optimizer=None, scheduler=None, genotype=genotype, save_best=is_best, filename=filename) logger.info('Model Saved at %s\n', filename) return def main(): # Load Search Version Genotype model = config.model().to(device) genotype = None # Setup ENV data_loader = config.dataset().getDataLoader() if hasattr(config, 'adjust_weight_decay') and config.adjust_weight_decay: params = adjust_weight_decay(model, config.optimizer.weight_decay) else: params = model.parameters() optimizer = config.optimizer(params) criterion = config.criterion() trainer = Trainer(criterion, data_loader, logger, config) evaluator = Evaluator(data_loader, logger, config) profile_inputs = (torch.randn([1, 3, 32, 32]).to(device),) flops, params = profile(model, inputs=profile_inputs, verbose=False) flops = flops / 1e6 starting_epoch = 0 config.set_immutable() for key in config: logger.info("%s: %s" % (key, config[key])) logger.info("param size = %fMB", util.count_parameters_in_MB(model)) logger.info("flops: %.4fM" % flops) logger.info("PyTorch Version: %s" % (torch.__version__)) if torch.cuda.is_available(): device_list = [torch.cuda.get_device_name(i) for i in range(0, torch.cuda.device_count())] logger.info("GPU List: %s" % (device_list)) ENV = {'global_step': 0, 'best_acc': 0.0, 'curren_acc': 0.0, 'best_pgd_acc': 0.0, 'flops': flops, 'train_history': [], 'eval_history': [], 'pgd_eval_history': [], 'stable_acc_history': [], 'lip_history': [], 'genotype_list': []} if args.load_model or args.load_best_model: filename = checkpoint_path_file + '_best.pth' if args.load_best_model else checkpoint_path_file + '.pth' checkpoint = util.load_model(filename=filename, model=model, optimizer=optimizer, alpha_optimizer=None, scheduler=None) starting_epoch = checkpoint['epoch'] + 1 ENV = checkpoint['ENV'] if 'stable_acc_history' not in ENV: ENV['stable_acc_history'] = [] if 'lip_history' not in ENV: ENV['lip_history'] = [] trainer.global_step = ENV['global_step'] logger.info("File %s loaded!" % (filename)) if args.data_parallel: print('data_parallel') model = torch.nn.DataParallel(model).to(device) logger.info("Starting Epoch: %d" % (starting_epoch)) if args.train: train(starting_epoch, model, genotype, optimizer, None, criterion, trainer, evaluator, ENV, data_loader) elif args.attack_choice in ['PGD', 'GAMA', 'CW']: for param in model.parameters(): param.requires_grad = False model.eval() natural_acc, adv_acc, stable_acc, lip = whitebox_eval(data_loader, model, evaluator) key = '%s_%d' % (args.attack_choice, args.num_steps) ENV['natural_acc'] = natural_acc ENV[key] = adv_acc ENV['%s_stable' % key] = stable_acc ENV['%s_lip' % key] = lip target_model = model.module if args.data_parallel else model filename = checkpoint_path_file + '_best.pth' if args.load_best_model else checkpoint_path_file + '.pth' util.save_model(ENV=ENV, epoch=starting_epoch-1, model=target_model, optimizer=optimizer, alpha_optimizer=None, scheduler=None, genotype=genotype, filename=filename) elif args.attack_choice == 'AA': for param in model.parameters(): param.requires_grad = False x_test = [x for (x, y) in data_loader['test_dataset']] x_test = torch.cat(x_test, dim=0) y_test = [y for (x, y) in data_loader['test_dataset']] y_test = torch.cat(y_test, dim=0) model.eval() adversary = AutoAttack(model, norm='Linf', eps=args.epsilon, logger=logger, verbose=True) adversary.plus = False logger.info('=' * 20 + 'AA Attack Eval' + '=' * 20) x_adv, robust_accuracy = adversary.run_standard_evaluation(x_test, y_test, bs=config.dataset.eval_batch_size) robust_accuracy = robust_accuracy * 100 logger.info('AA Accuracy: %.2f' % (robust_accuracy)) ENV['aa_attack'] = robust_accuracy target_model = model.module if args.data_parallel else model filename = checkpoint_path_file + '_best.pth' if args.load_best_model else checkpoint_path_file + '.pth' util.save_model(ENV=ENV, epoch=starting_epoch-1, model=target_model, optimizer=optimizer, alpha_optimizer=None, scheduler=None, genotype=genotype, filename=filename) return if __name__ == '__main__': for arg in vars(args): logger.info("%s: %s" % (arg, getattr(args, arg))) start = time.time() main() end = time.time() cost = (end - start) / 86400 payload = "Running Cost %.2f Days" % cost logger.info(payload)
conv, fc = [], [] for name, param in model.named_parameters(): print(name) if not param.requires_grad: # frozen weights continue if 'fc' in name: fc.append(param) else: conv.append(param) params = [{'params': conv, 'weight_decay': l2_value}, {'params': fc, 'weight_decay': 0.01}] print(fc) return params
identifier_body
main.py
import mlconfig import argparse import datetime import util import models import dataset import trades import madrys import mart import time import os import torch import shutil import numpy as np from trainer import Trainer from evaluator import Evaluator from torch.autograd import Variable from auto_attack.autoattack import AutoAttack from thop import profile mlconfig.register(trades.TradesLoss) mlconfig.register(madrys.MadrysLoss) mlconfig.register(mart.MartLoss) mlconfig.register(dataset.DatasetGenerator) parser = argparse.ArgumentParser(description='RobustArc') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--version', type=str, default="DARTS_Search") parser.add_argument('--exp_name', type=str, default="test_exp") parser.add_argument('--config_path', type=str, default='configs') parser.add_argument('--load_model', action='store_true', default=False) parser.add_argument('--load_best_model', action='store_true', default=False) parser.add_argument('--data_parallel', action='store_true', default=False)
parser.add_argument('--epsilon', default=8, type=float, help='perturbation') parser.add_argument('--num_steps', default=20, type=int, help='perturb number of steps') parser.add_argument('--step_size', default=0.8, type=float, help='perturb step size') parser.add_argument('--train_eval_epoch', default=0.5, type=float, help='PGD Eval in training after this epoch') args = parser.parse_args() if args.epsilon > 1: args.epsilon = args.epsilon / 255 args.step_size = args.step_size / 255 # Set up if args.exp_name == '': args.exp_name = 'exp_' + datetime.datetime.now() exp_path = os.path.join(args.exp_name, args.version) log_file_path = os.path.join(exp_path, args.version) checkpoint_path = os.path.join(exp_path, 'checkpoints') search_results_checkpoint_file_name = None checkpoint_path_file = os.path.join(checkpoint_path, args.version) util.build_dirs(exp_path) util.build_dirs(checkpoint_path) logger = util.setup_logger(name=args.version, log_file=log_file_path + ".log") torch.manual_seed(args.seed) np.random.seed(args.seed) if torch.cuda.is_available(): torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark = True device = torch.device('cuda') device_list = [torch.cuda.get_device_name(i) for i in range(0, torch.cuda.device_count())] logger.info("GPU List: %s" % (device_list)) else: device = torch.device('cpu') config_file = os.path.join(args.config_path, args.version)+'.yaml' config = mlconfig.load(config_file) shutil.copyfile(config_file, os.path.join(exp_path, args.version+'.yaml')) def whitebox_eval(data_loader, model, evaluator, log=True): natural_count, pgd_count, total, stable_count = 0, 0, 0, 0 loss_meters = util.AverageMeter() lip_meters = util.AverageMeter() model.eval() for i, (images, labels) in enumerate(data_loader["test_dataset"]): images, labels = images.to(device), labels.to(device) # pgd attack images, labels = Variable(images, requires_grad=True), Variable(labels) if args.attack_choice == 'PGD': rs = evaluator._pgd_whitebox(model, images, labels, random_start=True, epsilon=args.epsilon, num_steps=args.num_steps, step_size=args.step_size) elif args.attack_choice == 'GAMA': rs = evaluator._gama_whitebox(model, images, labels, epsilon=args.epsilon, num_steps=args.num_steps, eps_iter=args.step_size) elif args.attack_choice == 'CW': rs = evaluator._cw_whitebox(model, images, labels, random_start=True, epsilon=args.epsilon, num_steps=args.num_steps, step_size=args.step_size) else: raise('Not implemented') acc, acc_pgd, loss, stable, X_pgd = rs total += images.size(0) natural_count += acc pgd_count += acc_pgd stable_count += stable local_lip = util.local_lip(model, images, X_pgd).item() lip_meters.update(local_lip) loss_meters.update(loss) if log: payload = 'LIP: %.4f\tStable Count: %d\tNatural Count: %d/%d\tNatural Acc: %.2f\tAdv Count: %d/%d\tAdv Acc: %.2f' % (local_lip, stable_count, natural_count, total, (natural_count/total) * 100, pgd_count, total, (pgd_count/total) * 100) logger.info(payload) natural_acc = (natural_count/total) * 100 pgd_acc = (pgd_count/total) * 100 payload = 'Natural Correct Count: %d/%d Acc: %.2f ' % (natural_count, total, natural_acc) logger.info(payload) payload = '%s Correct Count: %d/%d Acc: %.2f ' % (args.attack_choice, pgd_count, total, pgd_acc) logger.info(payload) payload = '%s Loss Avg: %.2f ' % (args.attack_choice, loss_meters.avg) logger.info(payload) payload = 'LIP Avg: %.4f ' % (lip_meters.avg) logger.info(payload) payload = 'Stable Count: %d/%d StableAcc: %.2f ' % (stable_count, total, stable_count * 100/total) logger.info(payload) return natural_acc, pgd_acc, stable_count*100/total, lip_meters.avg def adjust_learning_rate(optimizer, epoch): """decrease the learning rate""" lr = config.optimizer.lr schedule = config.lr_schedule if hasattr(config, 'lr_schedule') else 'fixed' if schedule == 'fixed': if epoch >= 0.75 * config.epochs: lr = config.optimizer.lr * 0.1 if epoch >= 0.9 * config.epochs: lr = config.optimizer.lr * 0.01 if epoch >= config.epochs: lr = config.optimizer.lr * 0.001 # cosine schedule elif schedule == 'cosine': lr = config.optimizer.lr * 0.5 * (1 + np.cos((epoch - 1) / config.epochs * np.pi)) elif schedule == 'search': if epoch >= 75: lr = 0.01 if epoch >= 90: lr = 0.001 else: raise ValueError('Unkown LR schedule %s' % schedule) for param_group in optimizer.param_groups: param_group['lr'] = lr return lr def adjust_eps(epoch, config): eps_min = 2/255 eps_max = 8/255 ratio = epoch / (config.epochs * 0.2) eps = (eps_min + 0.5 * (eps_max - eps_min) * (1 - np.cos(ratio * np.pi))) return eps def adjust_weight_decay(model, l2_value): conv, fc = [], [] for name, param in model.named_parameters(): print(name) if not param.requires_grad: # frozen weights continue if 'fc' in name: fc.append(param) else: conv.append(param) params = [{'params': conv, 'weight_decay': l2_value}, {'params': fc, 'weight_decay': 0.01}] print(fc) return params def train(starting_epoch, model, genotype, optimizer, scheduler, criterion, trainer, evaluator, ENV, data_loader): print(model) for epoch in range(starting_epoch, config.epochs): logger.info("="*20 + "Training Epoch %d" % (epoch) + "="*20) adjust_learning_rate(optimizer, epoch) # Update Drop Path Prob if isinstance(model, models.DARTS_model.NetworkCIFAR): drop_path_prob = config.model.drop_path_prob * epoch / config.epochs model.drop_path_prob = drop_path_prob logger.info('Drop Path Probability %.4f' % drop_path_prob) # Train ENV['global_step'] = trainer.train(epoch, model, criterion, optimizer) # Eval logger.info("="*20 + "Eval Epoch %d" % (epoch) + "="*20) evaluator.eval(epoch, model) payload = ('Eval Loss:%.4f\tEval acc: %.2f' % (evaluator.loss_meters.avg, evaluator.acc_meters.avg*100)) logger.info(payload) ENV['eval_history'].append(evaluator.acc_meters.avg*100) ENV['curren_acc'] = evaluator.acc_meters.avg*100 is_best = False if epoch >= config.epochs * args.train_eval_epoch and args.train_eval_epoch >= 0: # Reset Stats trainer._reset_stats() evaluator._reset_stats() for param in model.parameters(): param.requires_grad = False natural_acc, pgd_acc, stable_acc, lip = whitebox_eval(data_loader, model, evaluator, log=False) for param in model.parameters(): param.requires_grad = True is_best = True if pgd_acc > ENV['best_pgd_acc'] else False ENV['best_pgd_acc'] = max(ENV['best_pgd_acc'], pgd_acc) ENV['pgd_eval_history'].append((epoch, pgd_acc)) ENV['stable_acc_history'].append(stable_acc) ENV['lip_history'].append(lip) logger.info('Best PGD accuracy: %.2f' % (ENV['best_pgd_acc'])) # Reset Stats trainer._reset_stats() evaluator._reset_stats() # Save Model target_model = model.module if args.data_parallel else model filename = checkpoint_path_file + '.pth' util.save_model(ENV=ENV, epoch=epoch, model=target_model, optimizer=optimizer, alpha_optimizer=None, scheduler=None, genotype=genotype, save_best=is_best, filename=filename) logger.info('Model Saved at %s\n', filename) return def main(): # Load Search Version Genotype model = config.model().to(device) genotype = None # Setup ENV data_loader = config.dataset().getDataLoader() if hasattr(config, 'adjust_weight_decay') and config.adjust_weight_decay: params = adjust_weight_decay(model, config.optimizer.weight_decay) else: params = model.parameters() optimizer = config.optimizer(params) criterion = config.criterion() trainer = Trainer(criterion, data_loader, logger, config) evaluator = Evaluator(data_loader, logger, config) profile_inputs = (torch.randn([1, 3, 32, 32]).to(device),) flops, params = profile(model, inputs=profile_inputs, verbose=False) flops = flops / 1e6 starting_epoch = 0 config.set_immutable() for key in config: logger.info("%s: %s" % (key, config[key])) logger.info("param size = %fMB", util.count_parameters_in_MB(model)) logger.info("flops: %.4fM" % flops) logger.info("PyTorch Version: %s" % (torch.__version__)) if torch.cuda.is_available(): device_list = [torch.cuda.get_device_name(i) for i in range(0, torch.cuda.device_count())] logger.info("GPU List: %s" % (device_list)) ENV = {'global_step': 0, 'best_acc': 0.0, 'curren_acc': 0.0, 'best_pgd_acc': 0.0, 'flops': flops, 'train_history': [], 'eval_history': [], 'pgd_eval_history': [], 'stable_acc_history': [], 'lip_history': [], 'genotype_list': []} if args.load_model or args.load_best_model: filename = checkpoint_path_file + '_best.pth' if args.load_best_model else checkpoint_path_file + '.pth' checkpoint = util.load_model(filename=filename, model=model, optimizer=optimizer, alpha_optimizer=None, scheduler=None) starting_epoch = checkpoint['epoch'] + 1 ENV = checkpoint['ENV'] if 'stable_acc_history' not in ENV: ENV['stable_acc_history'] = [] if 'lip_history' not in ENV: ENV['lip_history'] = [] trainer.global_step = ENV['global_step'] logger.info("File %s loaded!" % (filename)) if args.data_parallel: print('data_parallel') model = torch.nn.DataParallel(model).to(device) logger.info("Starting Epoch: %d" % (starting_epoch)) if args.train: train(starting_epoch, model, genotype, optimizer, None, criterion, trainer, evaluator, ENV, data_loader) elif args.attack_choice in ['PGD', 'GAMA', 'CW']: for param in model.parameters(): param.requires_grad = False model.eval() natural_acc, adv_acc, stable_acc, lip = whitebox_eval(data_loader, model, evaluator) key = '%s_%d' % (args.attack_choice, args.num_steps) ENV['natural_acc'] = natural_acc ENV[key] = adv_acc ENV['%s_stable' % key] = stable_acc ENV['%s_lip' % key] = lip target_model = model.module if args.data_parallel else model filename = checkpoint_path_file + '_best.pth' if args.load_best_model else checkpoint_path_file + '.pth' util.save_model(ENV=ENV, epoch=starting_epoch-1, model=target_model, optimizer=optimizer, alpha_optimizer=None, scheduler=None, genotype=genotype, filename=filename) elif args.attack_choice == 'AA': for param in model.parameters(): param.requires_grad = False x_test = [x for (x, y) in data_loader['test_dataset']] x_test = torch.cat(x_test, dim=0) y_test = [y for (x, y) in data_loader['test_dataset']] y_test = torch.cat(y_test, dim=0) model.eval() adversary = AutoAttack(model, norm='Linf', eps=args.epsilon, logger=logger, verbose=True) adversary.plus = False logger.info('=' * 20 + 'AA Attack Eval' + '=' * 20) x_adv, robust_accuracy = adversary.run_standard_evaluation(x_test, y_test, bs=config.dataset.eval_batch_size) robust_accuracy = robust_accuracy * 100 logger.info('AA Accuracy: %.2f' % (robust_accuracy)) ENV['aa_attack'] = robust_accuracy target_model = model.module if args.data_parallel else model filename = checkpoint_path_file + '_best.pth' if args.load_best_model else checkpoint_path_file + '.pth' util.save_model(ENV=ENV, epoch=starting_epoch-1, model=target_model, optimizer=optimizer, alpha_optimizer=None, scheduler=None, genotype=genotype, filename=filename) return if __name__ == '__main__': for arg in vars(args): logger.info("%s: %s" % (arg, getattr(args, arg))) start = time.time() main() end = time.time() cost = (end - start) / 86400 payload = "Running Cost %.2f Days" % cost logger.info(payload)
parser.add_argument('--train', action='store_true', default=False) parser.add_argument('--attack_choice', default='PGD', choices=['PGD', 'AA', 'GAMA', 'CW', 'none'])
random_line_split
main.py
import mlconfig import argparse import datetime import util import models import dataset import trades import madrys import mart import time import os import torch import shutil import numpy as np from trainer import Trainer from evaluator import Evaluator from torch.autograd import Variable from auto_attack.autoattack import AutoAttack from thop import profile mlconfig.register(trades.TradesLoss) mlconfig.register(madrys.MadrysLoss) mlconfig.register(mart.MartLoss) mlconfig.register(dataset.DatasetGenerator) parser = argparse.ArgumentParser(description='RobustArc') parser.add_argument('--seed', type=int, default=0) parser.add_argument('--version', type=str, default="DARTS_Search") parser.add_argument('--exp_name', type=str, default="test_exp") parser.add_argument('--config_path', type=str, default='configs') parser.add_argument('--load_model', action='store_true', default=False) parser.add_argument('--load_best_model', action='store_true', default=False) parser.add_argument('--data_parallel', action='store_true', default=False) parser.add_argument('--train', action='store_true', default=False) parser.add_argument('--attack_choice', default='PGD', choices=['PGD', 'AA', 'GAMA', 'CW', 'none']) parser.add_argument('--epsilon', default=8, type=float, help='perturbation') parser.add_argument('--num_steps', default=20, type=int, help='perturb number of steps') parser.add_argument('--step_size', default=0.8, type=float, help='perturb step size') parser.add_argument('--train_eval_epoch', default=0.5, type=float, help='PGD Eval in training after this epoch') args = parser.parse_args() if args.epsilon > 1: args.epsilon = args.epsilon / 255 args.step_size = args.step_size / 255 # Set up if args.exp_name == '': args.exp_name = 'exp_' + datetime.datetime.now() exp_path = os.path.join(args.exp_name, args.version) log_file_path = os.path.join(exp_path, args.version) checkpoint_path = os.path.join(exp_path, 'checkpoints') search_results_checkpoint_file_name = None checkpoint_path_file = os.path.join(checkpoint_path, args.version) util.build_dirs(exp_path) util.build_dirs(checkpoint_path) logger = util.setup_logger(name=args.version, log_file=log_file_path + ".log") torch.manual_seed(args.seed) np.random.seed(args.seed) if torch.cuda.is_available(): torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark = True device = torch.device('cuda') device_list = [torch.cuda.get_device_name(i) for i in range(0, torch.cuda.device_count())] logger.info("GPU List: %s" % (device_list)) else: device = torch.device('cpu') config_file = os.path.join(args.config_path, args.version)+'.yaml' config = mlconfig.load(config_file) shutil.copyfile(config_file, os.path.join(exp_path, args.version+'.yaml')) def whitebox_eval(data_loader, model, evaluator, log=True): natural_count, pgd_count, total, stable_count = 0, 0, 0, 0 loss_meters = util.AverageMeter() lip_meters = util.AverageMeter() model.eval() for i, (images, labels) in enumerate(data_loader["test_dataset"]): images, labels = images.to(device), labels.to(device) # pgd attack images, labels = Variable(images, requires_grad=True), Variable(labels) if args.attack_choice == 'PGD': rs = evaluator._pgd_whitebox(model, images, labels, random_start=True, epsilon=args.epsilon, num_steps=args.num_steps, step_size=args.step_size) elif args.attack_choice == 'GAMA': rs = evaluator._gama_whitebox(model, images, labels, epsilon=args.epsilon, num_steps=args.num_steps, eps_iter=args.step_size) elif args.attack_choice == 'CW': rs = evaluator._cw_whitebox(model, images, labels, random_start=True, epsilon=args.epsilon, num_steps=args.num_steps, step_size=args.step_size) else: raise('Not implemented') acc, acc_pgd, loss, stable, X_pgd = rs total += images.size(0) natural_count += acc pgd_count += acc_pgd stable_count += stable local_lip = util.local_lip(model, images, X_pgd).item() lip_meters.update(local_lip) loss_meters.update(loss) if log: payload = 'LIP: %.4f\tStable Count: %d\tNatural Count: %d/%d\tNatural Acc: %.2f\tAdv Count: %d/%d\tAdv Acc: %.2f' % (local_lip, stable_count, natural_count, total, (natural_count/total) * 100, pgd_count, total, (pgd_count/total) * 100) logger.info(payload) natural_acc = (natural_count/total) * 100 pgd_acc = (pgd_count/total) * 100 payload = 'Natural Correct Count: %d/%d Acc: %.2f ' % (natural_count, total, natural_acc) logger.info(payload) payload = '%s Correct Count: %d/%d Acc: %.2f ' % (args.attack_choice, pgd_count, total, pgd_acc) logger.info(payload) payload = '%s Loss Avg: %.2f ' % (args.attack_choice, loss_meters.avg) logger.info(payload) payload = 'LIP Avg: %.4f ' % (lip_meters.avg) logger.info(payload) payload = 'Stable Count: %d/%d StableAcc: %.2f ' % (stable_count, total, stable_count * 100/total) logger.info(payload) return natural_acc, pgd_acc, stable_count*100/total, lip_meters.avg def adjust_learning_rate(optimizer, epoch): """decrease the learning rate""" lr = config.optimizer.lr schedule = config.lr_schedule if hasattr(config, 'lr_schedule') else 'fixed' if schedule == 'fixed': if epoch >= 0.75 * config.epochs: lr = config.optimizer.lr * 0.1 if epoch >= 0.9 * config.epochs: lr = config.optimizer.lr * 0.01 if epoch >= config.epochs: lr = config.optimizer.lr * 0.001 # cosine schedule elif schedule == 'cosine': lr = config.optimizer.lr * 0.5 * (1 + np.cos((epoch - 1) / config.epochs * np.pi)) elif schedule == 'search': if epoch >= 75: lr = 0.01 if epoch >= 90: lr = 0.001 else: raise ValueError('Unkown LR schedule %s' % schedule) for param_group in optimizer.param_groups: param_group['lr'] = lr return lr def adjust_eps(epoch, config): eps_min = 2/255 eps_max = 8/255 ratio = epoch / (config.epochs * 0.2) eps = (eps_min + 0.5 * (eps_max - eps_min) * (1 - np.cos(ratio * np.pi))) return eps def adjust_weight_decay(model, l2_value): conv, fc = [], [] for name, param in model.named_parameters(): print(name) if not param.requires_grad: # frozen weights continue if 'fc' in name: fc.append(param) else: conv.append(param) params = [{'params': conv, 'weight_decay': l2_value}, {'params': fc, 'weight_decay': 0.01}] print(fc) return params def train(starting_epoch, model, genotype, optimizer, scheduler, criterion, trainer, evaluator, ENV, data_loader): print(model) for epoch in range(starting_epoch, config.epochs): logger.info("="*20 + "Training Epoch %d" % (epoch) + "="*20) adjust_learning_rate(optimizer, epoch) # Update Drop Path Prob if isinstance(model, models.DARTS_model.NetworkCIFAR): drop_path_prob = config.model.drop_path_prob * epoch / config.epochs model.drop_path_prob = drop_path_prob logger.info('Drop Path Probability %.4f' % drop_path_prob) # Train ENV['global_step'] = trainer.train(epoch, model, criterion, optimizer) # Eval logger.info("="*20 + "Eval Epoch %d" % (epoch) + "="*20) evaluator.eval(epoch, model) payload = ('Eval Loss:%.4f\tEval acc: %.2f' % (evaluator.loss_meters.avg, evaluator.acc_meters.avg*100)) logger.info(payload) ENV['eval_history'].append(evaluator.acc_meters.avg*100) ENV['curren_acc'] = evaluator.acc_meters.avg*100 is_best = False if epoch >= config.epochs * args.train_eval_epoch and args.train_eval_epoch >= 0: # Reset Stats trainer._reset_stats() evaluator._reset_stats() for param in model.parameters(): param.requires_grad = False natural_acc, pgd_acc, stable_acc, lip = whitebox_eval(data_loader, model, evaluator, log=False) for param in model.parameters(): param.requires_grad = True is_best = True if pgd_acc > ENV['best_pgd_acc'] else False ENV['best_pgd_acc'] = max(ENV['best_pgd_acc'], pgd_acc) ENV['pgd_eval_history'].append((epoch, pgd_acc)) ENV['stable_acc_history'].append(stable_acc) ENV['lip_history'].append(lip) logger.info('Best PGD accuracy: %.2f' % (ENV['best_pgd_acc'])) # Reset Stats trainer._reset_stats() evaluator._reset_stats() # Save Model target_model = model.module if args.data_parallel else model filename = checkpoint_path_file + '.pth' util.save_model(ENV=ENV, epoch=epoch, model=target_model, optimizer=optimizer, alpha_optimizer=None, scheduler=None, genotype=genotype, save_best=is_best, filename=filename) logger.info('Model Saved at %s\n', filename) return def main(): # Load Search Version Genotype model = config.model().to(device) genotype = None # Setup ENV data_loader = config.dataset().getDataLoader() if hasattr(config, 'adjust_weight_decay') and config.adjust_weight_decay: params = adjust_weight_decay(model, config.optimizer.weight_decay) else: params = model.parameters() optimizer = config.optimizer(params) criterion = config.criterion() trainer = Trainer(criterion, data_loader, logger, config) evaluator = Evaluator(data_loader, logger, config) profile_inputs = (torch.randn([1, 3, 32, 32]).to(device),) flops, params = profile(model, inputs=profile_inputs, verbose=False) flops = flops / 1e6 starting_epoch = 0 config.set_immutable() for key in config: logger.info("%s: %s" % (key, config[key])) logger.info("param size = %fMB", util.count_parameters_in_MB(model)) logger.info("flops: %.4fM" % flops) logger.info("PyTorch Version: %s" % (torch.__version__)) if torch.cuda.is_available(): device_list = [torch.cuda.get_device_name(i) for i in range(0, torch.cuda.device_count())] logger.info("GPU List: %s" % (device_list)) ENV = {'global_step': 0, 'best_acc': 0.0, 'curren_acc': 0.0, 'best_pgd_acc': 0.0, 'flops': flops, 'train_history': [], 'eval_history': [], 'pgd_eval_history': [], 'stable_acc_history': [], 'lip_history': [], 'genotype_list': []} if args.load_model or args.load_best_model: filename = checkpoint_path_file + '_best.pth' if args.load_best_model else checkpoint_path_file + '.pth' checkpoint = util.load_model(filename=filename, model=model, optimizer=optimizer, alpha_optimizer=None, scheduler=None) starting_epoch = checkpoint['epoch'] + 1 ENV = checkpoint['ENV'] if 'stable_acc_history' not in ENV:
if 'lip_history' not in ENV: ENV['lip_history'] = [] trainer.global_step = ENV['global_step'] logger.info("File %s loaded!" % (filename)) if args.data_parallel: print('data_parallel') model = torch.nn.DataParallel(model).to(device) logger.info("Starting Epoch: %d" % (starting_epoch)) if args.train: train(starting_epoch, model, genotype, optimizer, None, criterion, trainer, evaluator, ENV, data_loader) elif args.attack_choice in ['PGD', 'GAMA', 'CW']: for param in model.parameters(): param.requires_grad = False model.eval() natural_acc, adv_acc, stable_acc, lip = whitebox_eval(data_loader, model, evaluator) key = '%s_%d' % (args.attack_choice, args.num_steps) ENV['natural_acc'] = natural_acc ENV[key] = adv_acc ENV['%s_stable' % key] = stable_acc ENV['%s_lip' % key] = lip target_model = model.module if args.data_parallel else model filename = checkpoint_path_file + '_best.pth' if args.load_best_model else checkpoint_path_file + '.pth' util.save_model(ENV=ENV, epoch=starting_epoch-1, model=target_model, optimizer=optimizer, alpha_optimizer=None, scheduler=None, genotype=genotype, filename=filename) elif args.attack_choice == 'AA': for param in model.parameters(): param.requires_grad = False x_test = [x for (x, y) in data_loader['test_dataset']] x_test = torch.cat(x_test, dim=0) y_test = [y for (x, y) in data_loader['test_dataset']] y_test = torch.cat(y_test, dim=0) model.eval() adversary = AutoAttack(model, norm='Linf', eps=args.epsilon, logger=logger, verbose=True) adversary.plus = False logger.info('=' * 20 + 'AA Attack Eval' + '=' * 20) x_adv, robust_accuracy = adversary.run_standard_evaluation(x_test, y_test, bs=config.dataset.eval_batch_size) robust_accuracy = robust_accuracy * 100 logger.info('AA Accuracy: %.2f' % (robust_accuracy)) ENV['aa_attack'] = robust_accuracy target_model = model.module if args.data_parallel else model filename = checkpoint_path_file + '_best.pth' if args.load_best_model else checkpoint_path_file + '.pth' util.save_model(ENV=ENV, epoch=starting_epoch-1, model=target_model, optimizer=optimizer, alpha_optimizer=None, scheduler=None, genotype=genotype, filename=filename) return if __name__ == '__main__': for arg in vars(args): logger.info("%s: %s" % (arg, getattr(args, arg))) start = time.time() main() end = time.time() cost = (end - start) / 86400 payload = "Running Cost %.2f Days" % cost logger.info(payload)
ENV['stable_acc_history'] = []
conditional_block
printout7.js
for(var i1=0; i1<10; i1++) { console.log( i1 ); } console.log('i1 after loop: ' + i1); function counter()
// console.log('k after the loop ' + k); // conditional block if(true) { var i3 = 2; } console.log('i3: ' + i3); // anonymous block { var i4 = 3; } console.log('i4: ' + i4); { let i5 = 5; } // console.log('i5: ' + i5); if(true) { let i6 = 8; } // console.log('i6: ' + i6); for(let i7=0;i7<10;i7++) { console.log(i7); } // console.log(i7); // difference between const and var, let var i8 = 10; i8 = 15; console.log(i8); const i9 = 20; // i9 = 25; { const i10 = -1; } // creates a block scope console.log(i10); // expressions as arguments // unary operators +3 // returns 3 +'-3' // returns -3 +'3.14' // returns 3.14 +'3' // returns 3 +'0xFF' // returns 255 +true // returns 1 +'123e-5' // returns 0.00123 +false // returns 0 +null // returns 0 +'Infinity' // returns Infinity +'infinity' // returns NaN +function(val){ return val } // returns NaN !false // returns true !NaN // returns true !0 // returns true !null // returns true !undefined // returns true !"" // returns true !true // returns false !-3 // returns false !"-3" // returns false !42 // returns false !"42" // returns false !"foo" // returns false !"true" // returns false !"false" // returns false !{} // returns false ![] // returns false !function(){} // returns false !!'hi' === true // returns true !!1 === true // returns true !!0 === false // returns true !'hi' //returns false !false //returns true true === true //returns true x = 4 // x=4 y = x++ // y = 4 and x = 5 // y is set to the value before incrementing and it adds 1 to x // Be careful about resetting values when using postfix var a = 5 // a = 5 a = a++ // a = 5 // a is set to the value before incrementing x = 4 // x=4 y = ++x // y = 5 and x = 5 // y is set to the value after incrementing and it adds 1 to x var a = 5 // a = 5 a = ++a // a = 6 // a is set to the value after incrementing typeof 2 // returns 'number' typeof -3.14 // returns 'number' typeof 0xFF // returns 'number' typeof 123e-5 // returns 'number' typeof true // returns 'boolean' typeof false // returns 'boolean' typeof null // returns 'object' typeof Infinity // returns 'number' typeof '2' // returns 'string' typeof '-3' // returns 'string' typeof 'infinity' // returns 'string' typeof Date() // returns 'string' typeof [1,2,3] // returns 'object' typeof {hi: 'world'} // returns 'object' typeof function(val){ return val } // returns 'function' typeof { valueOf: function(){ return '0xFF' } } // returns 'object' typeof undefined // returns 'undefined' typeof hi // returns 'undefined' typeof NaN // returns 'number' typeof new Date() // returns 'object' typeof /ab+c/ // returns 'object' typeof new RegExp('ab+c') // returns 'object' typeof document // returns 'undefined' // Deleting a variable var hi = 1; delete hi; // returns false console.log(hi); // returns 1 // Deleting a function function yo(){ }; delete yo; // returns false console.log(yo); // returns function foo(){ } // Deleting an object var pub = {bar: '1'} delete pub // returns false console.log(pub); // returns {bar: '1'} //Deleting an array var code = [1,1,2,3,5] delete code // returns false console.log(code); // [1,1,2,3,5] // Deleting a property with the literal notation var fruits = {1: 'apple', 2: 'mango'} delete fruits[1] // returns true console.log(fruits); // returns { '2': 'mango' } console.log(fruits[1]); // returns undefined // Deleting a property with the dot notation var pub = { bar: "42" }; delete pub.bar; // returns true console.log(pub); // returns {} // Deleting a property that does not exist var lunch = { fries: 1 }; delete lunch.beans; // returns true console.log(lunch); // returns { fries: 1 } // Deleting a non-configurable property of a predefined object delete Math.PI; // returns false console.log(Math.PI); // returns 3.141592653589793 // When Non Configurable var Person = {}; Object.defineProperty(Person, 'name', { value: 'Scot', configurable: false }) // Defines an object property and sets it to non-configurable console.log(Person.value); // returns 'Scot' delete Person.value // returns false console.log(Person.value); // returns 'Scot' // When configurable var b = {}; Object.defineProperty(Person, 'name', { value: 'Scot', configurable: true }) console.log(b.value); // returns 'Scot' delete b.value // returns true console.log(b.value); // returns undefined function multiply(a, b=1) { return a * b; } console.log(multiply(5, 2)); console.log(multiply(5)); let i=0; function inc(p) { console.log(p); } inc(i=i+2); // FUNCTION CONSTRUCTORS var john = { name: 'John', yearOfBirth: 1990, job: 'teacher' }; // capital "P" !! var Person = function(name, yearOfBirth, job) { this.name = name; this.yearOfBirth = yearOfBirth; this.job = job; this.foo = null; this.calculateAge = function() { console.log(2016 - this.yearOfBirth); } } // instantiaton var john = new Person('John', 1990, 'teacher'); // new : this points to the empty object // NOT to the global Object // task var jane = new Person('Jane', 1991, 'designer'); var mark = new Person('Mark', 1948, 'retired'); // each person has the calculateAge method attached // so we saved a lot of time // imagine that we had 20 functions in each person // show prototypes that Person.prototype.calculateAge = function() { console.log(2016 - this.yearOfBirth); } Person.prototype.lastName = 'Smith'; // go to chrome console and show prototypes // ... // then do // john.__proto__ === Person.prototype // show until the proto is at Object // then tell every Object has a prototype john.hasOwnProperty('job'); // true john.hasOwnProperty('lastName'); // false john instanceof Person; // everything is an object var x = [2, 4, 6]; // show: // x. length // x.__proto__ // x.pop() // x.push() var personProto = { calculateAge: function () { console.log( 2016 - this.yearOfBirth ); } }; var john = Object.create( personProto ); john.yearOfBirth = 1990; john.job = 'teacher'; // lets do that for another person var jane = Object.create( personProto, { name: { value: 'Jane' }, yearOfBirth: { value: 1969 }, job: { value: 'designer' } }); // primitives vs objects // primitives var a = 23; var b = a; a = 46; console.log(a); console.log(b); // objects var obj1 = { name: 'John', age: 26 }; var obj2 = obj1; obj1.age = 30; console.log( obj1.age ); console.log( obj2.age ); // we did not create a new // object, we created a reference // that points to obj1 var age = 32; var obj = { name: 'Jan', city: 'Berlin' }; function change(a, b) { a = 30; b.city = 'New York'; } change(age, obj); console.log( age ); console.log( obj.city ); // passing functions as arguments // callback var years = [ 1998, 1965, 1937, 2005, 1998, 1985, 1991 ]; function arrayCalc(arr, fn) { var arrRes = []; for(var i=0; i<arr.length; i++) { arrRes.push( fn(arr[i]) ); } return arrRes; } function calculateAge( year ) { return 2017 - year; } var ages = arrayCalc(years, calculateAge); console.log( ages ); function isFullAge( year ) { return year >= 18; } var fullAges = arrayCalc( ages, isFullAge ); console.log( fullAges ); function maxHeartRate( age ) { if( age >= 18 && age <= 81 ) return Math.round(206.9 - (0.67 * age)); else return -1; } var rates = arrayCalc( ages, maxHeartRate ); console.log(rates); // functions returning functions function interviewQuestion( job ) { if(job === 'designer') { // anonymous function return function(name) { console.log(name + ', can you '+ 'please explain, what UX design is?'); } } else if(job === 'teacher') { return function(name) { console.log('What subject do you ' + 'teach, ' + name + '?'); } } else { return function(name) { console.log('Hello ' + name + ', what do you do?'); } } } var teacherQuestion = interviewQuestion('teacher'); teacherQuestion('John'); var designerQuestion = interviewQuestion('designer'); designerQuestion('Michelle'); // other usage interviewQuestion('teacher')('Mark'); /////////////////////////// // IIFE function game() { var score = Math.random() * 10; console.log( score >= 5); } game(); (function() { var score = Math.random() * 10; console.log( score >= 5 ); })(); // console.log( score ); (function(goodLuck) { var score = Math.random() * 10; console.log( score >= 5 - goodLuck ); })(5); // Closures function retirement(retirementAge) { var a = ' years left until retirement'; return function(year) { var age = 2016 - year; console.log((retirementAge - age) + a); } } var retirementUS = retirement(66); retirementUS(1990); retirement(66)(1990); // explain stuff here var retirementGermany = retirement(65); var retirementIceland = retirement(67); retirementGermany( 1990 ); retirementUS( 1990 ); retirementIceland( 1990 ); // mini coding challenge function interviewQuestion( job ) { var a = ' Do it!'; return function(name) { if (job === 'designer') { console.log( name + ', explain UXD!' + a); } else if( job === 'teacher' ) { console.log( name + ', subjects?' + a); } else { console.log( name + ', whatcha do?' + a); } } } interviewQuestion('designer')( 'Foofoo' );
{ for(var i2=0;i2<10;i2++) { console.log(i2); } }
identifier_body
printout7.js
for(var i1=0; i1<10; i1++) { console.log( i1 ); } console.log('i1 after loop: ' + i1); function counter() { for(var i2=0;i2<10;i2++) { console.log(i2); } } // console.log('k after the loop ' + k); // conditional block if(true) { var i3 = 2; } console.log('i3: ' + i3); // anonymous block { var i4 = 3; } console.log('i4: ' + i4); { let i5 = 5; } // console.log('i5: ' + i5); if(true) { let i6 = 8; } // console.log('i6: ' + i6); for(let i7=0;i7<10;i7++) { console.log(i7); } // console.log(i7); // difference between const and var, let var i8 = 10; i8 = 15; console.log(i8); const i9 = 20; // i9 = 25; { const i10 = -1; } // creates a block scope console.log(i10); // expressions as arguments // unary operators +3 // returns 3 +'-3' // returns -3 +'3.14' // returns 3.14 +'3' // returns 3 +'0xFF' // returns 255 +true // returns 1 +'123e-5' // returns 0.00123 +false // returns 0 +null // returns 0 +'Infinity' // returns Infinity +'infinity' // returns NaN +function(val){ return val } // returns NaN !false // returns true !NaN // returns true !0 // returns true !null // returns true !undefined // returns true !"" // returns true !true // returns false !-3 // returns false !"-3" // returns false !42 // returns false !"42" // returns false !"foo" // returns false !"true" // returns false !"false" // returns false !{} // returns false ![] // returns false !function(){} // returns false !!'hi' === true // returns true !!1 === true // returns true !!0 === false // returns true !'hi' //returns false !false //returns true true === true //returns true x = 4 // x=4 y = x++ // y = 4 and x = 5 // y is set to the value before incrementing and it adds 1 to x // Be careful about resetting values when using postfix var a = 5 // a = 5 a = a++ // a = 5 // a is set to the value before incrementing x = 4 // x=4 y = ++x // y = 5 and x = 5 // y is set to the value after incrementing and it adds 1 to x var a = 5 // a = 5 a = ++a // a = 6 // a is set to the value after incrementing typeof 2 // returns 'number' typeof -3.14 // returns 'number' typeof 0xFF // returns 'number' typeof 123e-5 // returns 'number' typeof true // returns 'boolean' typeof false // returns 'boolean' typeof null // returns 'object' typeof Infinity // returns 'number' typeof '2' // returns 'string' typeof '-3' // returns 'string' typeof 'infinity' // returns 'string' typeof Date() // returns 'string' typeof [1,2,3] // returns 'object' typeof {hi: 'world'} // returns 'object' typeof function(val){ return val } // returns 'function' typeof { valueOf: function(){ return '0xFF' } } // returns 'object' typeof undefined // returns 'undefined' typeof hi // returns 'undefined' typeof NaN // returns 'number' typeof new Date() // returns 'object' typeof /ab+c/ // returns 'object' typeof new RegExp('ab+c') // returns 'object' typeof document // returns 'undefined' // Deleting a variable var hi = 1; delete hi; // returns false console.log(hi); // returns 1 // Deleting a function function yo(){ }; delete yo; // returns false console.log(yo); // returns function foo(){ } // Deleting an object var pub = {bar: '1'} delete pub // returns false console.log(pub); // returns {bar: '1'} //Deleting an array var code = [1,1,2,3,5] delete code // returns false console.log(code); // [1,1,2,3,5] // Deleting a property with the literal notation var fruits = {1: 'apple', 2: 'mango'} delete fruits[1] // returns true console.log(fruits); // returns { '2': 'mango' } console.log(fruits[1]); // returns undefined // Deleting a property with the dot notation var pub = { bar: "42" }; delete pub.bar; // returns true console.log(pub); // returns {} // Deleting a property that does not exist var lunch = { fries: 1 }; delete lunch.beans; // returns true console.log(lunch); // returns { fries: 1 } // Deleting a non-configurable property of a predefined object delete Math.PI; // returns false console.log(Math.PI); // returns 3.141592653589793 // When Non Configurable var Person = {}; Object.defineProperty(Person, 'name', { value: 'Scot', configurable: false }) // Defines an object property and sets it to non-configurable console.log(Person.value); // returns 'Scot' delete Person.value // returns false console.log(Person.value); // returns 'Scot' // When configurable var b = {}; Object.defineProperty(Person, 'name', { value: 'Scot', configurable: true }) console.log(b.value); // returns 'Scot' delete b.value // returns true console.log(b.value); // returns undefined function multiply(a, b=1) { return a * b; } console.log(multiply(5, 2)); console.log(multiply(5)); let i=0; function inc(p) { console.log(p); } inc(i=i+2); // FUNCTION CONSTRUCTORS var john = { name: 'John', yearOfBirth: 1990, job: 'teacher' }; // capital "P" !! var Person = function(name, yearOfBirth, job) { this.name = name; this.yearOfBirth = yearOfBirth; this.job = job; this.foo = null; this.calculateAge = function() { console.log(2016 - this.yearOfBirth); } } // instantiaton var john = new Person('John', 1990, 'teacher'); // new : this points to the empty object // NOT to the global Object // task var jane = new Person('Jane', 1991, 'designer'); var mark = new Person('Mark', 1948, 'retired'); // each person has the calculateAge method attached // so we saved a lot of time // imagine that we had 20 functions in each person // show prototypes that Person.prototype.calculateAge = function() { console.log(2016 - this.yearOfBirth); } Person.prototype.lastName = 'Smith'; // go to chrome console and show prototypes // ... // then do // john.__proto__ === Person.prototype // show until the proto is at Object // then tell every Object has a prototype john.hasOwnProperty('job'); // true john.hasOwnProperty('lastName'); // false john instanceof Person; // everything is an object var x = [2, 4, 6]; // show: // x. length // x.__proto__ // x.pop() // x.push() var personProto = { calculateAge: function () { console.log( 2016 - this.yearOfBirth ); } }; var john = Object.create( personProto ); john.yearOfBirth = 1990; john.job = 'teacher'; // lets do that for another person var jane = Object.create( personProto, { name: { value: 'Jane' }, yearOfBirth: { value: 1969 }, job: { value: 'designer' } }); // primitives vs objects // primitives var a = 23; var b = a; a = 46; console.log(a); console.log(b); // objects var obj1 = { name: 'John', age: 26 }; var obj2 = obj1; obj1.age = 30; console.log( obj1.age ); console.log( obj2.age ); // we did not create a new // object, we created a reference // that points to obj1 var age = 32; var obj = { name: 'Jan', city: 'Berlin' }; function change(a, b) { a = 30; b.city = 'New York'; } change(age, obj); console.log( age ); console.log( obj.city ); // passing functions as arguments // callback var years = [ 1998, 1965, 1937, 2005, 1998, 1985, 1991 ]; function arrayCalc(arr, fn) { var arrRes = []; for(var i=0; i<arr.length; i++) { arrRes.push( fn(arr[i]) ); } return arrRes; } function calculateAge( year ) { return 2017 - year; } var ages = arrayCalc(years, calculateAge); console.log( ages ); function isFullAge( year ) { return year >= 18; } var fullAges = arrayCalc( ages, isFullAge ); console.log( fullAges ); function maxHeartRate( age ) { if( age >= 18 && age <= 81 ) return Math.round(206.9 - (0.67 * age)); else return -1; } var rates = arrayCalc( ages, maxHeartRate ); console.log(rates); // functions returning functions function interviewQuestion( job ) { if(job === 'designer') { // anonymous function return function(name) { console.log(name + ', can you '+ 'please explain, what UX design is?'); } } else if(job === 'teacher') { return function(name) { console.log('What subject do you ' + 'teach, ' + name + '?'); } } else { return function(name) { console.log('Hello ' + name + ', what do you do?'); } } } var teacherQuestion = interviewQuestion('teacher'); teacherQuestion('John'); var designerQuestion = interviewQuestion('designer'); designerQuestion('Michelle'); // other usage interviewQuestion('teacher')('Mark'); /////////////////////////// // IIFE function game() { var score = Math.random() * 10; console.log( score >= 5); } game(); (function() { var score = Math.random() * 10; console.log( score >= 5 ); })(); // console.log( score ); (function(goodLuck) { var score = Math.random() * 10; console.log( score >= 5 - goodLuck ); })(5); // Closures function retirement(retirementAge) { var a = ' years left until retirement'; return function(year) { var age = 2016 - year; console.log((retirementAge - age) + a); } } var retirementUS = retirement(66); retirementUS(1990); retirement(66)(1990); // explain stuff here var retirementGermany = retirement(65); var retirementIceland = retirement(67); retirementGermany( 1990 ); retirementUS( 1990 ); retirementIceland( 1990 ); // mini coding challenge function
( job ) { var a = ' Do it!'; return function(name) { if (job === 'designer') { console.log( name + ', explain UXD!' + a); } else if( job === 'teacher' ) { console.log( name + ', subjects?' + a); } else { console.log( name + ', whatcha do?' + a); } } } interviewQuestion('designer')( 'Foofoo' );
interviewQuestion
identifier_name
printout7.js
for(var i1=0; i1<10; i1++) { console.log( i1 ); } console.log('i1 after loop: ' + i1); function counter() { for(var i2=0;i2<10;i2++) { console.log(i2); } } // console.log('k after the loop ' + k); // conditional block if(true) { var i3 = 2; } console.log('i3: ' + i3); // anonymous block { var i4 = 3; } console.log('i4: ' + i4); { let i5 = 5; } // console.log('i5: ' + i5); if(true) { let i6 = 8; } // console.log('i6: ' + i6); for(let i7=0;i7<10;i7++) { console.log(i7); } // console.log(i7); // difference between const and var, let var i8 = 10; i8 = 15; console.log(i8); const i9 = 20; // i9 = 25; { const i10 = -1; } // creates a block scope console.log(i10); // expressions as arguments // unary operators +3 // returns 3 +'-3' // returns -3 +'3.14' // returns 3.14 +'3' // returns 3 +'0xFF' // returns 255 +true // returns 1 +'123e-5' // returns 0.00123 +false // returns 0 +null // returns 0 +'Infinity' // returns Infinity +'infinity' // returns NaN +function(val){ return val } // returns NaN !false // returns true !NaN // returns true !0 // returns true !null // returns true !undefined // returns true !"" // returns true !true // returns false !-3 // returns false !"-3" // returns false !42 // returns false !"42" // returns false !"foo" // returns false !"true" // returns false !"false" // returns false !{} // returns false ![] // returns false !function(){} // returns false !!'hi' === true // returns true !!1 === true // returns true !!0 === false // returns true !'hi' //returns false !false //returns true true === true //returns true x = 4 // x=4 y = x++ // y = 4 and x = 5 // y is set to the value before incrementing and it adds 1 to x // Be careful about resetting values when using postfix var a = 5 // a = 5 a = a++ // a = 5 // a is set to the value before incrementing x = 4 // x=4 y = ++x // y = 5 and x = 5 // y is set to the value after incrementing and it adds 1 to x var a = 5 // a = 5 a = ++a // a = 6 // a is set to the value after incrementing typeof 2 // returns 'number' typeof -3.14 // returns 'number' typeof 0xFF // returns 'number' typeof 123e-5 // returns 'number' typeof true // returns 'boolean' typeof false // returns 'boolean' typeof null // returns 'object' typeof Infinity // returns 'number' typeof '2' // returns 'string' typeof '-3' // returns 'string' typeof 'infinity' // returns 'string' typeof Date() // returns 'string' typeof [1,2,3] // returns 'object' typeof {hi: 'world'} // returns 'object' typeof function(val){ return val } // returns 'function' typeof { valueOf: function(){ return '0xFF' } } // returns 'object' typeof undefined // returns 'undefined' typeof hi // returns 'undefined' typeof NaN // returns 'number' typeof new Date() // returns 'object' typeof /ab+c/ // returns 'object' typeof new RegExp('ab+c') // returns 'object' typeof document // returns 'undefined' // Deleting a variable var hi = 1; delete hi; // returns false console.log(hi); // returns 1 // Deleting a function function yo(){ }; delete yo; // returns false console.log(yo); // returns function foo(){ } // Deleting an object var pub = {bar: '1'} delete pub // returns false console.log(pub); // returns {bar: '1'} //Deleting an array var code = [1,1,2,3,5] delete code // returns false console.log(code); // [1,1,2,3,5] // Deleting a property with the literal notation var fruits = {1: 'apple', 2: 'mango'} delete fruits[1] // returns true console.log(fruits); // returns { '2': 'mango' } console.log(fruits[1]); // returns undefined // Deleting a property with the dot notation var pub = { bar: "42" }; delete pub.bar; // returns true console.log(pub); // returns {} // Deleting a property that does not exist var lunch = { fries: 1 }; delete lunch.beans; // returns true console.log(lunch); // returns { fries: 1 } // Deleting a non-configurable property of a predefined object delete Math.PI; // returns false console.log(Math.PI); // returns 3.141592653589793 // When Non Configurable var Person = {}; Object.defineProperty(Person, 'name', { value: 'Scot', configurable: false }) // Defines an object property and sets it to non-configurable console.log(Person.value); // returns 'Scot' delete Person.value // returns false console.log(Person.value); // returns 'Scot' // When configurable var b = {}; Object.defineProperty(Person, 'name', { value: 'Scot', configurable: true }) console.log(b.value); // returns 'Scot' delete b.value // returns true console.log(b.value); // returns undefined function multiply(a, b=1) { return a * b; } console.log(multiply(5, 2)); console.log(multiply(5)); let i=0; function inc(p) { console.log(p); } inc(i=i+2); // FUNCTION CONSTRUCTORS var john = { name: 'John', yearOfBirth: 1990, job: 'teacher' }; // capital "P" !!
this.calculateAge = function() { console.log(2016 - this.yearOfBirth); } } // instantiaton var john = new Person('John', 1990, 'teacher'); // new : this points to the empty object // NOT to the global Object // task var jane = new Person('Jane', 1991, 'designer'); var mark = new Person('Mark', 1948, 'retired'); // each person has the calculateAge method attached // so we saved a lot of time // imagine that we had 20 functions in each person // show prototypes that Person.prototype.calculateAge = function() { console.log(2016 - this.yearOfBirth); } Person.prototype.lastName = 'Smith'; // go to chrome console and show prototypes // ... // then do // john.__proto__ === Person.prototype // show until the proto is at Object // then tell every Object has a prototype john.hasOwnProperty('job'); // true john.hasOwnProperty('lastName'); // false john instanceof Person; // everything is an object var x = [2, 4, 6]; // show: // x. length // x.__proto__ // x.pop() // x.push() var personProto = { calculateAge: function () { console.log( 2016 - this.yearOfBirth ); } }; var john = Object.create( personProto ); john.yearOfBirth = 1990; john.job = 'teacher'; // lets do that for another person var jane = Object.create( personProto, { name: { value: 'Jane' }, yearOfBirth: { value: 1969 }, job: { value: 'designer' } }); // primitives vs objects // primitives var a = 23; var b = a; a = 46; console.log(a); console.log(b); // objects var obj1 = { name: 'John', age: 26 }; var obj2 = obj1; obj1.age = 30; console.log( obj1.age ); console.log( obj2.age ); // we did not create a new // object, we created a reference // that points to obj1 var age = 32; var obj = { name: 'Jan', city: 'Berlin' }; function change(a, b) { a = 30; b.city = 'New York'; } change(age, obj); console.log( age ); console.log( obj.city ); // passing functions as arguments // callback var years = [ 1998, 1965, 1937, 2005, 1998, 1985, 1991 ]; function arrayCalc(arr, fn) { var arrRes = []; for(var i=0; i<arr.length; i++) { arrRes.push( fn(arr[i]) ); } return arrRes; } function calculateAge( year ) { return 2017 - year; } var ages = arrayCalc(years, calculateAge); console.log( ages ); function isFullAge( year ) { return year >= 18; } var fullAges = arrayCalc( ages, isFullAge ); console.log( fullAges ); function maxHeartRate( age ) { if( age >= 18 && age <= 81 ) return Math.round(206.9 - (0.67 * age)); else return -1; } var rates = arrayCalc( ages, maxHeartRate ); console.log(rates); // functions returning functions function interviewQuestion( job ) { if(job === 'designer') { // anonymous function return function(name) { console.log(name + ', can you '+ 'please explain, what UX design is?'); } } else if(job === 'teacher') { return function(name) { console.log('What subject do you ' + 'teach, ' + name + '?'); } } else { return function(name) { console.log('Hello ' + name + ', what do you do?'); } } } var teacherQuestion = interviewQuestion('teacher'); teacherQuestion('John'); var designerQuestion = interviewQuestion('designer'); designerQuestion('Michelle'); // other usage interviewQuestion('teacher')('Mark'); /////////////////////////// // IIFE function game() { var score = Math.random() * 10; console.log( score >= 5); } game(); (function() { var score = Math.random() * 10; console.log( score >= 5 ); })(); // console.log( score ); (function(goodLuck) { var score = Math.random() * 10; console.log( score >= 5 - goodLuck ); })(5); // Closures function retirement(retirementAge) { var a = ' years left until retirement'; return function(year) { var age = 2016 - year; console.log((retirementAge - age) + a); } } var retirementUS = retirement(66); retirementUS(1990); retirement(66)(1990); // explain stuff here var retirementGermany = retirement(65); var retirementIceland = retirement(67); retirementGermany( 1990 ); retirementUS( 1990 ); retirementIceland( 1990 ); // mini coding challenge function interviewQuestion( job ) { var a = ' Do it!'; return function(name) { if (job === 'designer') { console.log( name + ', explain UXD!' + a); } else if( job === 'teacher' ) { console.log( name + ', subjects?' + a); } else { console.log( name + ', whatcha do?' + a); } } } interviewQuestion('designer')( 'Foofoo' );
var Person = function(name, yearOfBirth, job) { this.name = name; this.yearOfBirth = yearOfBirth; this.job = job; this.foo = null;
random_line_split
printout7.js
for(var i1=0; i1<10; i1++)
console.log('i1 after loop: ' + i1); function counter() { for(var i2=0;i2<10;i2++) { console.log(i2); } } // console.log('k after the loop ' + k); // conditional block if(true) { var i3 = 2; } console.log('i3: ' + i3); // anonymous block { var i4 = 3; } console.log('i4: ' + i4); { let i5 = 5; } // console.log('i5: ' + i5); if(true) { let i6 = 8; } // console.log('i6: ' + i6); for(let i7=0;i7<10;i7++) { console.log(i7); } // console.log(i7); // difference between const and var, let var i8 = 10; i8 = 15; console.log(i8); const i9 = 20; // i9 = 25; { const i10 = -1; } // creates a block scope console.log(i10); // expressions as arguments // unary operators +3 // returns 3 +'-3' // returns -3 +'3.14' // returns 3.14 +'3' // returns 3 +'0xFF' // returns 255 +true // returns 1 +'123e-5' // returns 0.00123 +false // returns 0 +null // returns 0 +'Infinity' // returns Infinity +'infinity' // returns NaN +function(val){ return val } // returns NaN !false // returns true !NaN // returns true !0 // returns true !null // returns true !undefined // returns true !"" // returns true !true // returns false !-3 // returns false !"-3" // returns false !42 // returns false !"42" // returns false !"foo" // returns false !"true" // returns false !"false" // returns false !{} // returns false ![] // returns false !function(){} // returns false !!'hi' === true // returns true !!1 === true // returns true !!0 === false // returns true !'hi' //returns false !false //returns true true === true //returns true x = 4 // x=4 y = x++ // y = 4 and x = 5 // y is set to the value before incrementing and it adds 1 to x // Be careful about resetting values when using postfix var a = 5 // a = 5 a = a++ // a = 5 // a is set to the value before incrementing x = 4 // x=4 y = ++x // y = 5 and x = 5 // y is set to the value after incrementing and it adds 1 to x var a = 5 // a = 5 a = ++a // a = 6 // a is set to the value after incrementing typeof 2 // returns 'number' typeof -3.14 // returns 'number' typeof 0xFF // returns 'number' typeof 123e-5 // returns 'number' typeof true // returns 'boolean' typeof false // returns 'boolean' typeof null // returns 'object' typeof Infinity // returns 'number' typeof '2' // returns 'string' typeof '-3' // returns 'string' typeof 'infinity' // returns 'string' typeof Date() // returns 'string' typeof [1,2,3] // returns 'object' typeof {hi: 'world'} // returns 'object' typeof function(val){ return val } // returns 'function' typeof { valueOf: function(){ return '0xFF' } } // returns 'object' typeof undefined // returns 'undefined' typeof hi // returns 'undefined' typeof NaN // returns 'number' typeof new Date() // returns 'object' typeof /ab+c/ // returns 'object' typeof new RegExp('ab+c') // returns 'object' typeof document // returns 'undefined' // Deleting a variable var hi = 1; delete hi; // returns false console.log(hi); // returns 1 // Deleting a function function yo(){ }; delete yo; // returns false console.log(yo); // returns function foo(){ } // Deleting an object var pub = {bar: '1'} delete pub // returns false console.log(pub); // returns {bar: '1'} //Deleting an array var code = [1,1,2,3,5] delete code // returns false console.log(code); // [1,1,2,3,5] // Deleting a property with the literal notation var fruits = {1: 'apple', 2: 'mango'} delete fruits[1] // returns true console.log(fruits); // returns { '2': 'mango' } console.log(fruits[1]); // returns undefined // Deleting a property with the dot notation var pub = { bar: "42" }; delete pub.bar; // returns true console.log(pub); // returns {} // Deleting a property that does not exist var lunch = { fries: 1 }; delete lunch.beans; // returns true console.log(lunch); // returns { fries: 1 } // Deleting a non-configurable property of a predefined object delete Math.PI; // returns false console.log(Math.PI); // returns 3.141592653589793 // When Non Configurable var Person = {}; Object.defineProperty(Person, 'name', { value: 'Scot', configurable: false }) // Defines an object property and sets it to non-configurable console.log(Person.value); // returns 'Scot' delete Person.value // returns false console.log(Person.value); // returns 'Scot' // When configurable var b = {}; Object.defineProperty(Person, 'name', { value: 'Scot', configurable: true }) console.log(b.value); // returns 'Scot' delete b.value // returns true console.log(b.value); // returns undefined function multiply(a, b=1) { return a * b; } console.log(multiply(5, 2)); console.log(multiply(5)); let i=0; function inc(p) { console.log(p); } inc(i=i+2); // FUNCTION CONSTRUCTORS var john = { name: 'John', yearOfBirth: 1990, job: 'teacher' }; // capital "P" !! var Person = function(name, yearOfBirth, job) { this.name = name; this.yearOfBirth = yearOfBirth; this.job = job; this.foo = null; this.calculateAge = function() { console.log(2016 - this.yearOfBirth); } } // instantiaton var john = new Person('John', 1990, 'teacher'); // new : this points to the empty object // NOT to the global Object // task var jane = new Person('Jane', 1991, 'designer'); var mark = new Person('Mark', 1948, 'retired'); // each person has the calculateAge method attached // so we saved a lot of time // imagine that we had 20 functions in each person // show prototypes that Person.prototype.calculateAge = function() { console.log(2016 - this.yearOfBirth); } Person.prototype.lastName = 'Smith'; // go to chrome console and show prototypes // ... // then do // john.__proto__ === Person.prototype // show until the proto is at Object // then tell every Object has a prototype john.hasOwnProperty('job'); // true john.hasOwnProperty('lastName'); // false john instanceof Person; // everything is an object var x = [2, 4, 6]; // show: // x. length // x.__proto__ // x.pop() // x.push() var personProto = { calculateAge: function () { console.log( 2016 - this.yearOfBirth ); } }; var john = Object.create( personProto ); john.yearOfBirth = 1990; john.job = 'teacher'; // lets do that for another person var jane = Object.create( personProto, { name: { value: 'Jane' }, yearOfBirth: { value: 1969 }, job: { value: 'designer' } }); // primitives vs objects // primitives var a = 23; var b = a; a = 46; console.log(a); console.log(b); // objects var obj1 = { name: 'John', age: 26 }; var obj2 = obj1; obj1.age = 30; console.log( obj1.age ); console.log( obj2.age ); // we did not create a new // object, we created a reference // that points to obj1 var age = 32; var obj = { name: 'Jan', city: 'Berlin' }; function change(a, b) { a = 30; b.city = 'New York'; } change(age, obj); console.log( age ); console.log( obj.city ); // passing functions as arguments // callback var years = [ 1998, 1965, 1937, 2005, 1998, 1985, 1991 ]; function arrayCalc(arr, fn) { var arrRes = []; for(var i=0; i<arr.length; i++) { arrRes.push( fn(arr[i]) ); } return arrRes; } function calculateAge( year ) { return 2017 - year; } var ages = arrayCalc(years, calculateAge); console.log( ages ); function isFullAge( year ) { return year >= 18; } var fullAges = arrayCalc( ages, isFullAge ); console.log( fullAges ); function maxHeartRate( age ) { if( age >= 18 && age <= 81 ) return Math.round(206.9 - (0.67 * age)); else return -1; } var rates = arrayCalc( ages, maxHeartRate ); console.log(rates); // functions returning functions function interviewQuestion( job ) { if(job === 'designer') { // anonymous function return function(name) { console.log(name + ', can you '+ 'please explain, what UX design is?'); } } else if(job === 'teacher') { return function(name) { console.log('What subject do you ' + 'teach, ' + name + '?'); } } else { return function(name) { console.log('Hello ' + name + ', what do you do?'); } } } var teacherQuestion = interviewQuestion('teacher'); teacherQuestion('John'); var designerQuestion = interviewQuestion('designer'); designerQuestion('Michelle'); // other usage interviewQuestion('teacher')('Mark'); /////////////////////////// // IIFE function game() { var score = Math.random() * 10; console.log( score >= 5); } game(); (function() { var score = Math.random() * 10; console.log( score >= 5 ); })(); // console.log( score ); (function(goodLuck) { var score = Math.random() * 10; console.log( score >= 5 - goodLuck ); })(5); // Closures function retirement(retirementAge) { var a = ' years left until retirement'; return function(year) { var age = 2016 - year; console.log((retirementAge - age) + a); } } var retirementUS = retirement(66); retirementUS(1990); retirement(66)(1990); // explain stuff here var retirementGermany = retirement(65); var retirementIceland = retirement(67); retirementGermany( 1990 ); retirementUS( 1990 ); retirementIceland( 1990 ); // mini coding challenge function interviewQuestion( job ) { var a = ' Do it!'; return function(name) { if (job === 'designer') { console.log( name + ', explain UXD!' + a); } else if( job === 'teacher' ) { console.log( name + ', subjects?' + a); } else { console.log( name + ', whatcha do?' + a); } } } interviewQuestion('designer')( 'Foofoo' );
{ console.log( i1 ); }
conditional_block
watch.go
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. * */ package mongodb import ( "container/list" "context" "errors" "fmt" "reflect" "strings" "sync" "time" "bk-bcs/bcs-common/common/blog" "bk-bcs/bcs-services/bcs-storage/storage/operator" "gopkg.in/mgo.v2/bson" ) type watchHandler struct { opts *operator.WatchOptions event chan *operator.Event listenerName string dbName string cName string diffTree []string } func newWatchHandler(opts *operator.WatchOptions, tank *mongoTank) *watchHandler { wh := &watchHandler{ opts: opts, listenerName: tank.listenerName, dbName: tank.dbName, cName: tank.cName, } if opts.MustDiff != "" { wh.diffTree = strings.Split(opts.MustDiff, ".") } return wh } func (wh *watchHandler) isDiff(op *opLog) bool { if op.OP == opDeleteValue { return true } var d interface{} = op.O for _, t := range wh.diffTree { md, ok := d.(map[string]interface{}) if !ok { return false } if d = md[t]; d == nil { return false } } return true } func (wh *watchHandler) ns() string { return fmt.Sprintf("%s.%s", wh.dbName, wh.cName) } func (wh *watchHandler) watch() (event chan *operator.Event, cancel context.CancelFunc) { ctx, cancel := context.WithCancel(context.Background()) event = make(chan *operator.Event, 1000) wh.event = event go wh.watching(ctx) return } func (wh *watchHandler) watching(pCtx context.Context) { isValid := true listenerPoolLock.RLock() listener := listenerPool[wh.listenerName] listenerPoolLock.RUnlock() if listener == nil { blog.Errorf("mongodb watching | watcherName does not exists: %s", wh.listenerName) isValid = false } if wh.dbName == "" || wh.cName == "" { blog.Errorf("mongodb watching | dbName or cName is empty") isValid = false } if !isValid { wh.event <- operator.EventWatchBreak return } ns := wh.ns() we := listener.wr.subscribe(ns) blog.Infof("mongodb watching | begin to watch: %s", ns) var ctx context.Context var cancel context.CancelFunc var op *opLog var eventsNumber uint for { if wh.opts.Timeout > 0 { ctx, cancel = context.WithTimeout(pCtx, wh.opts.Timeout) } else { ctx, cancel = context.WithCancel(pCtx) //nolint } if (wh.opts.MaxEvents > 0) && (eventsNumber >= wh.opts.MaxEvents) { cancel() } select { case <-ctx.Done(): wh.event <- operator.EventWatchBreak listener.wr.unsubscribe(we) blog.Infof("mongodb watching | end watch: %s", ns) cancel() return //nolint case op = <-we.w: eventsNumber++ var eventType operator.EventType switch op.OP { case opNopValue: continue case opInsertValue: eventType = operator.Add case opDeleteValue: eventType = operator.Del case opUpdateValue: eventType = operator.Chg default: continue } // If SelfOnly is true means the watcher only concern the change of node itself, // and its eventType should be EventSelfChange. // Others such as children change, children add, children delete will be ignored. if wh.opts.SelfOnly && eventType != operator.SChg { continue } // If MustDiff is set and the change part does not contain the keys of diffTree, then continue if !wh.isDiff(op) { continue } wh.event <- &operator.Event{Type: eventType, Value: op.RAW} } } } type watcher chan *opLog type watcherElement struct { ns string w watcher l *watcherList e *list.Element } type watcherList struct { *list.List } func (wl *watcherList)
(f func(*list.Element)) { if wl == nil { return } for e := wl.Front(); e != nil; e = e.Next() { f(e) } } type watcherRouter struct { mutexLock sync.RWMutex routeLock sync.RWMutex mutex map[string]*sync.RWMutex route map[string]*watcherList } func (wr *watcherRouter) getMutex(ns string) *sync.RWMutex { wr.mutexLock.RLock() mutex := wr.mutex[ns] wr.mutexLock.RUnlock() if mutex == nil { return wr.newMutex(ns) } return mutex } func (wr *watcherRouter) getWL(ns string) *watcherList { wr.routeLock.RLock() wl := wr.route[ns] wr.routeLock.RUnlock() if wl == nil { return wr.newWL(ns) } return wl } func (wr *watcherRouter) newMutex(ns string) *sync.RWMutex { wr.mutexLock.Lock() defer wr.mutexLock.Unlock() if wr.mutex[ns] == nil { wr.mutex[ns] = new(sync.RWMutex) } return wr.mutex[ns] } func (wr *watcherRouter) newWL(ns string) *watcherList { wr.routeLock.Lock() defer wr.routeLock.Unlock() if wr.route[ns] == nil { mutex := wr.getMutex(ns) mutex.Lock() wr.route[ns] = &watcherList{list.New()} mutex.Unlock() } return wr.route[ns] } func (wr *watcherRouter) subscribe(ns string) (we *watcherElement) { w := make(watcher) wList := wr.getWL(ns) mutex := wr.getMutex(ns) mutex.Lock() defer mutex.Unlock() return &watcherElement{ ns: ns, w: w, l: wList, e: wList.PushBack(w), } } func (wr *watcherRouter) unsubscribe(we *watcherElement) { mutex := wr.getMutex(we.ns) mutex.Lock() defer mutex.Unlock() we.l.Remove(we.e) } const ( opLogTimestampKey = "ts" opNopValue = "n" opInsertValue = "i" opUpdateValue = "u" opDeleteValue = "d" opLogRetryGap = 5 * time.Second opIdKey = "_id" ) type opLogListener struct { name string wr *watcherRouter tank *mongoTank } func (ol *opLogListener) init(tank *mongoTank, name string) *opLogListener { ol.wr = &watcherRouter{route: make(map[string]*watcherList), mutex: make(map[string]*sync.RWMutex)} ol.tank = tank ol.name = name return ol } func (ol *opLogListener) listen() { blog.Infof(ol.sprint(fmt.Sprintf("get last timestamp of oplog"))) tank := ol.tank iter := tank.Copy().Filter(operator.BaseCondition.AddOp(operator.Gt, opLogTimestampKey, ol.getLastTimestamp()).AddOp(operator.Ne, "op", opNopValue)).(*mongoTank).Tail() for { var op *opLog for iter.Next(&op) { if strings.HasSuffix(op.OP, ".$cmd") { continue } if !op.preProcess(ol.tank.Copy()) { continue } wl := ol.wr.getWL(op.NS) mutex := ol.wr.getMutex(op.NS) mutex.RLock() op.RAW, _ = dotRecover([]interface{}{op.RAW})[0].(map[string]interface{}) wl.do(func(element *list.Element) { w, ok := element.Value.(watcher) if !ok { blog.Errorf(ol.sprint("watcher list value is not a chan *watcher")) return } subOp := &opLog{} *subOp = *op w <- subOp }) mutex.RUnlock() } if err := iter.Err(); err != nil { blog.Errorf(ol.sprint("get mongodb tail Next() failed: %v"), err) _ = iter.Close() time.Sleep(opLogRetryGap) } iter = tank.Copy().Filter(operator.BaseCondition.AddOp(operator.Gt, opLogTimestampKey, ol.getLastTimestamp()).AddOp(operator.Ne, "op", opNopValue)).(*mongoTank).Tail() } } // get the last timestamp of oplog func (ol *opLogListener) getLastTimestamp() bson.MongoTimestamp { tank := ol.tank.Copy().OrderBy("-" + opLogTimestampKey).Select(opLogTimestampKey).Limit(1) for ; ; time.Sleep(opLogRetryGap) { t := tank.Query() if err := t.GetError(); err != nil { blog.Errorf(ol.sprint(fmt.Sprintf("getLastTimestamp failed! %v", err))) continue } r := t.GetValue() if t.GetLen() == 0 { blog.Errorf(ol.sprint(fmt.Sprintf("getLastTimestamp failed! no oplog found."))) continue } op, err := ol.getOpLog(r[0]) if err != nil { blog.Errorf(ol.sprint(fmt.Sprintf("getLastTimestamp failed! %v", err))) continue } return bson.MongoTimestamp(op.TS) } } // get oplog func (ol *opLogListener) getOpLog(v interface{}) (*opLog, error) { vv, ok := v.(map[string]interface{}) if !ok { return nil, errors.New(ol.sprint(fmt.Sprintf("getLastTimestamp failed! oplog format error: %v", vv))) } op := &opLog{} if err := op.fillUp(vv); err != nil { return nil, err } return op, nil } func (ol *opLogListener) sprint(s string) string { return fmt.Sprintf("mongodb listener | %s | %s", ol.name, s) } type opLog struct { NS string OP string O map[string]interface{} O2 map[string]interface{} TS uint64 WALL time.Time H int64 V int64 RAW map[string]interface{} } func (opl *opLog) fillUp(value map[string]interface{}) error { for k, v := range value { err := setField(opl, k, v) if err != nil { return err } } return nil } func (opl *opLog) preProcess(tank operator.Tank) bool { defer tank.Close() if opl.OP == opNopValue { return false } var ok bool if opl.O["$set"] != nil { opl.O, ok = opl.O["$set"].(map[string]interface{}) if !ok { return false } } if opl.OP == opInsertValue || opl.OP == opDeleteValue { opl.RAW = opl.O return true } objectId, ok := opl.O2[opIdKey].(bson.ObjectId) if !ok { return false } ns := strings.Split(opl.NS, ".") if len(ns) < 2 { return false } defer func() { if r := recover(); r != nil { // prevent bson.ObjectIdHex() panic, return false } }() t := tank.Using(ns[0]).From(ns[1]).Filter(operator.BaseCondition.AddOp(operator.Eq, opIdKey, objectId)).Query() if t.GetError() != nil { return false } if v := t.GetValue(); len(v) > 0 { opl.RAW, ok = v[0].(map[string]interface{}) return ok } return false } func setField(obj interface{}, name string, value interface{}) error { name = strings.ToUpper(name) structValue := reflect.ValueOf(obj).Elem() structFieldValue := structValue.FieldByName(name) if !structFieldValue.IsValid() { return fmt.Errorf("no such field: %s in obj", name) } if !structFieldValue.CanSet() { return fmt.Errorf("cannot set %s field value", name) } structFieldType := structFieldValue.Type() val := reflect.ValueOf(value) if structFieldType != val.Type() { return errors.New("provided value type didn't match obj field type") } structFieldValue.Set(val) return nil } var ( listenerPool map[string]*opLogListener listenerPoolLock sync.RWMutex ) // StartWatch start storage operator unit watch func StartWatch(tank operator.Tank, name string) { t, ok := tank.(*mongoTank) if !ok { return } listenerPoolLock.Lock() listener := new(opLogListener).init(t, name) if listenerPool == nil { listenerPool = make(map[string]*opLogListener) } if listenerPool[name] != nil { blog.Errorf("watcherName duplicated: %s", name) listenerPoolLock.Unlock() return } listenerPool[name] = listener listenerPoolLock.Unlock() listener.listen() }
do
identifier_name
watch.go
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. * */ package mongodb import ( "container/list" "context" "errors" "fmt" "reflect" "strings" "sync" "time" "bk-bcs/bcs-common/common/blog" "bk-bcs/bcs-services/bcs-storage/storage/operator" "gopkg.in/mgo.v2/bson" ) type watchHandler struct { opts *operator.WatchOptions event chan *operator.Event listenerName string dbName string cName string diffTree []string } func newWatchHandler(opts *operator.WatchOptions, tank *mongoTank) *watchHandler { wh := &watchHandler{ opts: opts, listenerName: tank.listenerName, dbName: tank.dbName, cName: tank.cName, } if opts.MustDiff != "" { wh.diffTree = strings.Split(opts.MustDiff, ".") } return wh } func (wh *watchHandler) isDiff(op *opLog) bool { if op.OP == opDeleteValue { return true } var d interface{} = op.O for _, t := range wh.diffTree { md, ok := d.(map[string]interface{}) if !ok { return false } if d = md[t]; d == nil { return false } } return true } func (wh *watchHandler) ns() string { return fmt.Sprintf("%s.%s", wh.dbName, wh.cName) } func (wh *watchHandler) watch() (event chan *operator.Event, cancel context.CancelFunc) { ctx, cancel := context.WithCancel(context.Background()) event = make(chan *operator.Event, 1000) wh.event = event go wh.watching(ctx) return } func (wh *watchHandler) watching(pCtx context.Context) { isValid := true listenerPoolLock.RLock() listener := listenerPool[wh.listenerName] listenerPoolLock.RUnlock() if listener == nil { blog.Errorf("mongodb watching | watcherName does not exists: %s", wh.listenerName) isValid = false } if wh.dbName == "" || wh.cName == "" { blog.Errorf("mongodb watching | dbName or cName is empty") isValid = false } if !isValid { wh.event <- operator.EventWatchBreak return } ns := wh.ns() we := listener.wr.subscribe(ns) blog.Infof("mongodb watching | begin to watch: %s", ns) var ctx context.Context var cancel context.CancelFunc var op *opLog var eventsNumber uint for { if wh.opts.Timeout > 0 { ctx, cancel = context.WithTimeout(pCtx, wh.opts.Timeout) } else { ctx, cancel = context.WithCancel(pCtx) //nolint } if (wh.opts.MaxEvents > 0) && (eventsNumber >= wh.opts.MaxEvents) { cancel() } select { case <-ctx.Done(): wh.event <- operator.EventWatchBreak listener.wr.unsubscribe(we) blog.Infof("mongodb watching | end watch: %s", ns) cancel() return //nolint case op = <-we.w: eventsNumber++ var eventType operator.EventType switch op.OP { case opNopValue: continue case opInsertValue: eventType = operator.Add case opDeleteValue: eventType = operator.Del case opUpdateValue: eventType = operator.Chg default: continue } // If SelfOnly is true means the watcher only concern the change of node itself, // and its eventType should be EventSelfChange. // Others such as children change, children add, children delete will be ignored. if wh.opts.SelfOnly && eventType != operator.SChg { continue } // If MustDiff is set and the change part does not contain the keys of diffTree, then continue if !wh.isDiff(op) { continue } wh.event <- &operator.Event{Type: eventType, Value: op.RAW} } } } type watcher chan *opLog type watcherElement struct { ns string w watcher l *watcherList e *list.Element } type watcherList struct { *list.List } func (wl *watcherList) do(f func(*list.Element))
type watcherRouter struct { mutexLock sync.RWMutex routeLock sync.RWMutex mutex map[string]*sync.RWMutex route map[string]*watcherList } func (wr *watcherRouter) getMutex(ns string) *sync.RWMutex { wr.mutexLock.RLock() mutex := wr.mutex[ns] wr.mutexLock.RUnlock() if mutex == nil { return wr.newMutex(ns) } return mutex } func (wr *watcherRouter) getWL(ns string) *watcherList { wr.routeLock.RLock() wl := wr.route[ns] wr.routeLock.RUnlock() if wl == nil { return wr.newWL(ns) } return wl } func (wr *watcherRouter) newMutex(ns string) *sync.RWMutex { wr.mutexLock.Lock() defer wr.mutexLock.Unlock() if wr.mutex[ns] == nil { wr.mutex[ns] = new(sync.RWMutex) } return wr.mutex[ns] } func (wr *watcherRouter) newWL(ns string) *watcherList { wr.routeLock.Lock() defer wr.routeLock.Unlock() if wr.route[ns] == nil { mutex := wr.getMutex(ns) mutex.Lock() wr.route[ns] = &watcherList{list.New()} mutex.Unlock() } return wr.route[ns] } func (wr *watcherRouter) subscribe(ns string) (we *watcherElement) { w := make(watcher) wList := wr.getWL(ns) mutex := wr.getMutex(ns) mutex.Lock() defer mutex.Unlock() return &watcherElement{ ns: ns, w: w, l: wList, e: wList.PushBack(w), } } func (wr *watcherRouter) unsubscribe(we *watcherElement) { mutex := wr.getMutex(we.ns) mutex.Lock() defer mutex.Unlock() we.l.Remove(we.e) } const ( opLogTimestampKey = "ts" opNopValue = "n" opInsertValue = "i" opUpdateValue = "u" opDeleteValue = "d" opLogRetryGap = 5 * time.Second opIdKey = "_id" ) type opLogListener struct { name string wr *watcherRouter tank *mongoTank } func (ol *opLogListener) init(tank *mongoTank, name string) *opLogListener { ol.wr = &watcherRouter{route: make(map[string]*watcherList), mutex: make(map[string]*sync.RWMutex)} ol.tank = tank ol.name = name return ol } func (ol *opLogListener) listen() { blog.Infof(ol.sprint(fmt.Sprintf("get last timestamp of oplog"))) tank := ol.tank iter := tank.Copy().Filter(operator.BaseCondition.AddOp(operator.Gt, opLogTimestampKey, ol.getLastTimestamp()).AddOp(operator.Ne, "op", opNopValue)).(*mongoTank).Tail() for { var op *opLog for iter.Next(&op) { if strings.HasSuffix(op.OP, ".$cmd") { continue } if !op.preProcess(ol.tank.Copy()) { continue } wl := ol.wr.getWL(op.NS) mutex := ol.wr.getMutex(op.NS) mutex.RLock() op.RAW, _ = dotRecover([]interface{}{op.RAW})[0].(map[string]interface{}) wl.do(func(element *list.Element) { w, ok := element.Value.(watcher) if !ok { blog.Errorf(ol.sprint("watcher list value is not a chan *watcher")) return } subOp := &opLog{} *subOp = *op w <- subOp }) mutex.RUnlock() } if err := iter.Err(); err != nil { blog.Errorf(ol.sprint("get mongodb tail Next() failed: %v"), err) _ = iter.Close() time.Sleep(opLogRetryGap) } iter = tank.Copy().Filter(operator.BaseCondition.AddOp(operator.Gt, opLogTimestampKey, ol.getLastTimestamp()).AddOp(operator.Ne, "op", opNopValue)).(*mongoTank).Tail() } } // get the last timestamp of oplog func (ol *opLogListener) getLastTimestamp() bson.MongoTimestamp { tank := ol.tank.Copy().OrderBy("-" + opLogTimestampKey).Select(opLogTimestampKey).Limit(1) for ; ; time.Sleep(opLogRetryGap) { t := tank.Query() if err := t.GetError(); err != nil { blog.Errorf(ol.sprint(fmt.Sprintf("getLastTimestamp failed! %v", err))) continue } r := t.GetValue() if t.GetLen() == 0 { blog.Errorf(ol.sprint(fmt.Sprintf("getLastTimestamp failed! no oplog found."))) continue } op, err := ol.getOpLog(r[0]) if err != nil { blog.Errorf(ol.sprint(fmt.Sprintf("getLastTimestamp failed! %v", err))) continue } return bson.MongoTimestamp(op.TS) } } // get oplog func (ol *opLogListener) getOpLog(v interface{}) (*opLog, error) { vv, ok := v.(map[string]interface{}) if !ok { return nil, errors.New(ol.sprint(fmt.Sprintf("getLastTimestamp failed! oplog format error: %v", vv))) } op := &opLog{} if err := op.fillUp(vv); err != nil { return nil, err } return op, nil } func (ol *opLogListener) sprint(s string) string { return fmt.Sprintf("mongodb listener | %s | %s", ol.name, s) } type opLog struct { NS string OP string O map[string]interface{} O2 map[string]interface{} TS uint64 WALL time.Time H int64 V int64 RAW map[string]interface{} } func (opl *opLog) fillUp(value map[string]interface{}) error { for k, v := range value { err := setField(opl, k, v) if err != nil { return err } } return nil } func (opl *opLog) preProcess(tank operator.Tank) bool { defer tank.Close() if opl.OP == opNopValue { return false } var ok bool if opl.O["$set"] != nil { opl.O, ok = opl.O["$set"].(map[string]interface{}) if !ok { return false } } if opl.OP == opInsertValue || opl.OP == opDeleteValue { opl.RAW = opl.O return true } objectId, ok := opl.O2[opIdKey].(bson.ObjectId) if !ok { return false } ns := strings.Split(opl.NS, ".") if len(ns) < 2 { return false } defer func() { if r := recover(); r != nil { // prevent bson.ObjectIdHex() panic, return false } }() t := tank.Using(ns[0]).From(ns[1]).Filter(operator.BaseCondition.AddOp(operator.Eq, opIdKey, objectId)).Query() if t.GetError() != nil { return false } if v := t.GetValue(); len(v) > 0 { opl.RAW, ok = v[0].(map[string]interface{}) return ok } return false } func setField(obj interface{}, name string, value interface{}) error { name = strings.ToUpper(name) structValue := reflect.ValueOf(obj).Elem() structFieldValue := structValue.FieldByName(name) if !structFieldValue.IsValid() { return fmt.Errorf("no such field: %s in obj", name) } if !structFieldValue.CanSet() { return fmt.Errorf("cannot set %s field value", name) } structFieldType := structFieldValue.Type() val := reflect.ValueOf(value) if structFieldType != val.Type() { return errors.New("provided value type didn't match obj field type") } structFieldValue.Set(val) return nil } var ( listenerPool map[string]*opLogListener listenerPoolLock sync.RWMutex ) // StartWatch start storage operator unit watch func StartWatch(tank operator.Tank, name string) { t, ok := tank.(*mongoTank) if !ok { return } listenerPoolLock.Lock() listener := new(opLogListener).init(t, name) if listenerPool == nil { listenerPool = make(map[string]*opLogListener) } if listenerPool[name] != nil { blog.Errorf("watcherName duplicated: %s", name) listenerPoolLock.Unlock() return } listenerPool[name] = listener listenerPoolLock.Unlock() listener.listen() }
{ if wl == nil { return } for e := wl.Front(); e != nil; e = e.Next() { f(e) } }
identifier_body
watch.go
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. * */ package mongodb import ( "container/list" "context" "errors" "fmt" "reflect" "strings" "sync" "time" "bk-bcs/bcs-common/common/blog" "bk-bcs/bcs-services/bcs-storage/storage/operator" "gopkg.in/mgo.v2/bson" ) type watchHandler struct { opts *operator.WatchOptions event chan *operator.Event listenerName string dbName string cName string diffTree []string } func newWatchHandler(opts *operator.WatchOptions, tank *mongoTank) *watchHandler { wh := &watchHandler{ opts: opts, listenerName: tank.listenerName, dbName: tank.dbName, cName: tank.cName, } if opts.MustDiff != "" { wh.diffTree = strings.Split(opts.MustDiff, ".") } return wh } func (wh *watchHandler) isDiff(op *opLog) bool { if op.OP == opDeleteValue { return true } var d interface{} = op.O for _, t := range wh.diffTree { md, ok := d.(map[string]interface{}) if !ok { return false } if d = md[t]; d == nil { return false } } return true } func (wh *watchHandler) ns() string { return fmt.Sprintf("%s.%s", wh.dbName, wh.cName) } func (wh *watchHandler) watch() (event chan *operator.Event, cancel context.CancelFunc) { ctx, cancel := context.WithCancel(context.Background()) event = make(chan *operator.Event, 1000) wh.event = event go wh.watching(ctx) return } func (wh *watchHandler) watching(pCtx context.Context) { isValid := true listenerPoolLock.RLock() listener := listenerPool[wh.listenerName] listenerPoolLock.RUnlock() if listener == nil { blog.Errorf("mongodb watching | watcherName does not exists: %s", wh.listenerName) isValid = false } if wh.dbName == "" || wh.cName == "" { blog.Errorf("mongodb watching | dbName or cName is empty") isValid = false } if !isValid { wh.event <- operator.EventWatchBreak return } ns := wh.ns() we := listener.wr.subscribe(ns) blog.Infof("mongodb watching | begin to watch: %s", ns) var ctx context.Context var cancel context.CancelFunc var op *opLog var eventsNumber uint for { if wh.opts.Timeout > 0 { ctx, cancel = context.WithTimeout(pCtx, wh.opts.Timeout) } else { ctx, cancel = context.WithCancel(pCtx) //nolint } if (wh.opts.MaxEvents > 0) && (eventsNumber >= wh.opts.MaxEvents) { cancel() } select { case <-ctx.Done(): wh.event <- operator.EventWatchBreak listener.wr.unsubscribe(we) blog.Infof("mongodb watching | end watch: %s", ns) cancel() return //nolint case op = <-we.w: eventsNumber++ var eventType operator.EventType switch op.OP { case opNopValue: continue case opInsertValue: eventType = operator.Add case opDeleteValue: eventType = operator.Del case opUpdateValue: eventType = operator.Chg default: continue } // If SelfOnly is true means the watcher only concern the change of node itself, // and its eventType should be EventSelfChange. // Others such as children change, children add, children delete will be ignored. if wh.opts.SelfOnly && eventType != operator.SChg { continue } // If MustDiff is set and the change part does not contain the keys of diffTree, then continue if !wh.isDiff(op) { continue } wh.event <- &operator.Event{Type: eventType, Value: op.RAW} } } } type watcher chan *opLog type watcherElement struct { ns string w watcher l *watcherList e *list.Element } type watcherList struct { *list.List } func (wl *watcherList) do(f func(*list.Element)) { if wl == nil { return } for e := wl.Front(); e != nil; e = e.Next() { f(e) } } type watcherRouter struct { mutexLock sync.RWMutex routeLock sync.RWMutex mutex map[string]*sync.RWMutex route map[string]*watcherList } func (wr *watcherRouter) getMutex(ns string) *sync.RWMutex { wr.mutexLock.RLock() mutex := wr.mutex[ns] wr.mutexLock.RUnlock() if mutex == nil { return wr.newMutex(ns) } return mutex } func (wr *watcherRouter) getWL(ns string) *watcherList { wr.routeLock.RLock() wl := wr.route[ns] wr.routeLock.RUnlock() if wl == nil { return wr.newWL(ns) } return wl } func (wr *watcherRouter) newMutex(ns string) *sync.RWMutex { wr.mutexLock.Lock() defer wr.mutexLock.Unlock() if wr.mutex[ns] == nil { wr.mutex[ns] = new(sync.RWMutex) } return wr.mutex[ns] } func (wr *watcherRouter) newWL(ns string) *watcherList { wr.routeLock.Lock() defer wr.routeLock.Unlock() if wr.route[ns] == nil { mutex := wr.getMutex(ns) mutex.Lock() wr.route[ns] = &watcherList{list.New()} mutex.Unlock() } return wr.route[ns] } func (wr *watcherRouter) subscribe(ns string) (we *watcherElement) { w := make(watcher) wList := wr.getWL(ns) mutex := wr.getMutex(ns) mutex.Lock() defer mutex.Unlock() return &watcherElement{ ns: ns, w: w, l: wList, e: wList.PushBack(w), } } func (wr *watcherRouter) unsubscribe(we *watcherElement) { mutex := wr.getMutex(we.ns) mutex.Lock() defer mutex.Unlock() we.l.Remove(we.e) } const ( opLogTimestampKey = "ts" opNopValue = "n" opInsertValue = "i" opUpdateValue = "u" opDeleteValue = "d" opLogRetryGap = 5 * time.Second opIdKey = "_id" ) type opLogListener struct { name string wr *watcherRouter tank *mongoTank } func (ol *opLogListener) init(tank *mongoTank, name string) *opLogListener { ol.wr = &watcherRouter{route: make(map[string]*watcherList), mutex: make(map[string]*sync.RWMutex)} ol.tank = tank ol.name = name return ol } func (ol *opLogListener) listen() { blog.Infof(ol.sprint(fmt.Sprintf("get last timestamp of oplog"))) tank := ol.tank iter := tank.Copy().Filter(operator.BaseCondition.AddOp(operator.Gt, opLogTimestampKey, ol.getLastTimestamp()).AddOp(operator.Ne, "op", opNopValue)).(*mongoTank).Tail() for { var op *opLog for iter.Next(&op) { if strings.HasSuffix(op.OP, ".$cmd") { continue } if !op.preProcess(ol.tank.Copy()) { continue } wl := ol.wr.getWL(op.NS) mutex := ol.wr.getMutex(op.NS) mutex.RLock() op.RAW, _ = dotRecover([]interface{}{op.RAW})[0].(map[string]interface{}) wl.do(func(element *list.Element) { w, ok := element.Value.(watcher) if !ok { blog.Errorf(ol.sprint("watcher list value is not a chan *watcher")) return } subOp := &opLog{} *subOp = *op w <- subOp }) mutex.RUnlock() } if err := iter.Err(); err != nil { blog.Errorf(ol.sprint("get mongodb tail Next() failed: %v"), err) _ = iter.Close() time.Sleep(opLogRetryGap) } iter = tank.Copy().Filter(operator.BaseCondition.AddOp(operator.Gt, opLogTimestampKey, ol.getLastTimestamp()).AddOp(operator.Ne, "op", opNopValue)).(*mongoTank).Tail() } } // get the last timestamp of oplog func (ol *opLogListener) getLastTimestamp() bson.MongoTimestamp { tank := ol.tank.Copy().OrderBy("-" + opLogTimestampKey).Select(opLogTimestampKey).Limit(1) for ; ; time.Sleep(opLogRetryGap) { t := tank.Query() if err := t.GetError(); err != nil { blog.Errorf(ol.sprint(fmt.Sprintf("getLastTimestamp failed! %v", err))) continue } r := t.GetValue() if t.GetLen() == 0 { blog.Errorf(ol.sprint(fmt.Sprintf("getLastTimestamp failed! no oplog found."))) continue } op, err := ol.getOpLog(r[0]) if err != nil { blog.Errorf(ol.sprint(fmt.Sprintf("getLastTimestamp failed! %v", err))) continue } return bson.MongoTimestamp(op.TS) } } // get oplog func (ol *opLogListener) getOpLog(v interface{}) (*opLog, error) { vv, ok := v.(map[string]interface{}) if !ok { return nil, errors.New(ol.sprint(fmt.Sprintf("getLastTimestamp failed! oplog format error: %v", vv))) } op := &opLog{} if err := op.fillUp(vv); err != nil { return nil, err } return op, nil } func (ol *opLogListener) sprint(s string) string { return fmt.Sprintf("mongodb listener | %s | %s", ol.name, s) } type opLog struct { NS string OP string O map[string]interface{} O2 map[string]interface{} TS uint64 WALL time.Time H int64 V int64 RAW map[string]interface{} } func (opl *opLog) fillUp(value map[string]interface{}) error { for k, v := range value { err := setField(opl, k, v) if err != nil { return err } } return nil } func (opl *opLog) preProcess(tank operator.Tank) bool { defer tank.Close() if opl.OP == opNopValue { return false } var ok bool if opl.O["$set"] != nil { opl.O, ok = opl.O["$set"].(map[string]interface{}) if !ok { return false } } if opl.OP == opInsertValue || opl.OP == opDeleteValue { opl.RAW = opl.O return true } objectId, ok := opl.O2[opIdKey].(bson.ObjectId) if !ok { return false } ns := strings.Split(opl.NS, ".") if len(ns) < 2 { return false } defer func() { if r := recover(); r != nil { // prevent bson.ObjectIdHex() panic, return false } }() t := tank.Using(ns[0]).From(ns[1]).Filter(operator.BaseCondition.AddOp(operator.Eq, opIdKey, objectId)).Query() if t.GetError() != nil { return false } if v := t.GetValue(); len(v) > 0 { opl.RAW, ok = v[0].(map[string]interface{}) return ok } return false } func setField(obj interface{}, name string, value interface{}) error { name = strings.ToUpper(name) structValue := reflect.ValueOf(obj).Elem() structFieldValue := structValue.FieldByName(name) if !structFieldValue.IsValid() { return fmt.Errorf("no such field: %s in obj", name) } if !structFieldValue.CanSet()
structFieldType := structFieldValue.Type() val := reflect.ValueOf(value) if structFieldType != val.Type() { return errors.New("provided value type didn't match obj field type") } structFieldValue.Set(val) return nil } var ( listenerPool map[string]*opLogListener listenerPoolLock sync.RWMutex ) // StartWatch start storage operator unit watch func StartWatch(tank operator.Tank, name string) { t, ok := tank.(*mongoTank) if !ok { return } listenerPoolLock.Lock() listener := new(opLogListener).init(t, name) if listenerPool == nil { listenerPool = make(map[string]*opLogListener) } if listenerPool[name] != nil { blog.Errorf("watcherName duplicated: %s", name) listenerPoolLock.Unlock() return } listenerPool[name] = listener listenerPoolLock.Unlock() listener.listen() }
{ return fmt.Errorf("cannot set %s field value", name) }
conditional_block
watch.go
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. * */ package mongodb import ( "container/list" "context" "errors" "fmt" "reflect" "strings" "sync" "time" "bk-bcs/bcs-common/common/blog" "bk-bcs/bcs-services/bcs-storage/storage/operator" "gopkg.in/mgo.v2/bson" ) type watchHandler struct { opts *operator.WatchOptions event chan *operator.Event listenerName string dbName string cName string diffTree []string } func newWatchHandler(opts *operator.WatchOptions, tank *mongoTank) *watchHandler { wh := &watchHandler{ opts: opts, listenerName: tank.listenerName, dbName: tank.dbName, cName: tank.cName, } if opts.MustDiff != "" { wh.diffTree = strings.Split(opts.MustDiff, ".") } return wh } func (wh *watchHandler) isDiff(op *opLog) bool { if op.OP == opDeleteValue { return true } var d interface{} = op.O for _, t := range wh.diffTree { md, ok := d.(map[string]interface{}) if !ok { return false } if d = md[t]; d == nil { return false } } return true } func (wh *watchHandler) ns() string { return fmt.Sprintf("%s.%s", wh.dbName, wh.cName) } func (wh *watchHandler) watch() (event chan *operator.Event, cancel context.CancelFunc) { ctx, cancel := context.WithCancel(context.Background()) event = make(chan *operator.Event, 1000) wh.event = event go wh.watching(ctx) return } func (wh *watchHandler) watching(pCtx context.Context) { isValid := true listenerPoolLock.RLock() listener := listenerPool[wh.listenerName] listenerPoolLock.RUnlock() if listener == nil { blog.Errorf("mongodb watching | watcherName does not exists: %s", wh.listenerName) isValid = false } if wh.dbName == "" || wh.cName == "" { blog.Errorf("mongodb watching | dbName or cName is empty") isValid = false } if !isValid { wh.event <- operator.EventWatchBreak return } ns := wh.ns() we := listener.wr.subscribe(ns) blog.Infof("mongodb watching | begin to watch: %s", ns) var ctx context.Context var cancel context.CancelFunc var op *opLog var eventsNumber uint for { if wh.opts.Timeout > 0 { ctx, cancel = context.WithTimeout(pCtx, wh.opts.Timeout) } else { ctx, cancel = context.WithCancel(pCtx) //nolint } if (wh.opts.MaxEvents > 0) && (eventsNumber >= wh.opts.MaxEvents) { cancel() } select { case <-ctx.Done(): wh.event <- operator.EventWatchBreak listener.wr.unsubscribe(we) blog.Infof("mongodb watching | end watch: %s", ns) cancel() return //nolint case op = <-we.w: eventsNumber++ var eventType operator.EventType switch op.OP { case opNopValue: continue case opInsertValue: eventType = operator.Add case opDeleteValue: eventType = operator.Del case opUpdateValue: eventType = operator.Chg default: continue } // If SelfOnly is true means the watcher only concern the change of node itself, // and its eventType should be EventSelfChange. // Others such as children change, children add, children delete will be ignored. if wh.opts.SelfOnly && eventType != operator.SChg { continue } // If MustDiff is set and the change part does not contain the keys of diffTree, then continue if !wh.isDiff(op) { continue } wh.event <- &operator.Event{Type: eventType, Value: op.RAW} } } } type watcher chan *opLog type watcherElement struct { ns string w watcher l *watcherList e *list.Element } type watcherList struct { *list.List } func (wl *watcherList) do(f func(*list.Element)) { if wl == nil { return } for e := wl.Front(); e != nil; e = e.Next() { f(e) } } type watcherRouter struct { mutexLock sync.RWMutex routeLock sync.RWMutex mutex map[string]*sync.RWMutex route map[string]*watcherList } func (wr *watcherRouter) getMutex(ns string) *sync.RWMutex { wr.mutexLock.RLock() mutex := wr.mutex[ns] wr.mutexLock.RUnlock() if mutex == nil { return wr.newMutex(ns) } return mutex } func (wr *watcherRouter) getWL(ns string) *watcherList { wr.routeLock.RLock() wl := wr.route[ns] wr.routeLock.RUnlock() if wl == nil { return wr.newWL(ns) } return wl } func (wr *watcherRouter) newMutex(ns string) *sync.RWMutex { wr.mutexLock.Lock() defer wr.mutexLock.Unlock() if wr.mutex[ns] == nil { wr.mutex[ns] = new(sync.RWMutex) } return wr.mutex[ns] } func (wr *watcherRouter) newWL(ns string) *watcherList { wr.routeLock.Lock() defer wr.routeLock.Unlock() if wr.route[ns] == nil { mutex := wr.getMutex(ns) mutex.Lock() wr.route[ns] = &watcherList{list.New()} mutex.Unlock() } return wr.route[ns] } func (wr *watcherRouter) subscribe(ns string) (we *watcherElement) { w := make(watcher) wList := wr.getWL(ns) mutex := wr.getMutex(ns) mutex.Lock() defer mutex.Unlock() return &watcherElement{ ns: ns, w: w, l: wList, e: wList.PushBack(w), } } func (wr *watcherRouter) unsubscribe(we *watcherElement) { mutex := wr.getMutex(we.ns) mutex.Lock() defer mutex.Unlock() we.l.Remove(we.e) } const ( opLogTimestampKey = "ts" opNopValue = "n" opInsertValue = "i" opUpdateValue = "u" opDeleteValue = "d" opLogRetryGap = 5 * time.Second opIdKey = "_id" ) type opLogListener struct { name string wr *watcherRouter tank *mongoTank } func (ol *opLogListener) init(tank *mongoTank, name string) *opLogListener { ol.wr = &watcherRouter{route: make(map[string]*watcherList), mutex: make(map[string]*sync.RWMutex)} ol.tank = tank ol.name = name return ol } func (ol *opLogListener) listen() { blog.Infof(ol.sprint(fmt.Sprintf("get last timestamp of oplog"))) tank := ol.tank iter := tank.Copy().Filter(operator.BaseCondition.AddOp(operator.Gt, opLogTimestampKey, ol.getLastTimestamp()).AddOp(operator.Ne, "op", opNopValue)).(*mongoTank).Tail() for { var op *opLog for iter.Next(&op) { if strings.HasSuffix(op.OP, ".$cmd") { continue } if !op.preProcess(ol.tank.Copy()) { continue } wl := ol.wr.getWL(op.NS) mutex := ol.wr.getMutex(op.NS) mutex.RLock() op.RAW, _ = dotRecover([]interface{}{op.RAW})[0].(map[string]interface{}) wl.do(func(element *list.Element) { w, ok := element.Value.(watcher) if !ok { blog.Errorf(ol.sprint("watcher list value is not a chan *watcher")) return } subOp := &opLog{} *subOp = *op w <- subOp }) mutex.RUnlock() } if err := iter.Err(); err != nil { blog.Errorf(ol.sprint("get mongodb tail Next() failed: %v"), err) _ = iter.Close() time.Sleep(opLogRetryGap) } iter = tank.Copy().Filter(operator.BaseCondition.AddOp(operator.Gt, opLogTimestampKey, ol.getLastTimestamp()).AddOp(operator.Ne, "op", opNopValue)).(*mongoTank).Tail() } } // get the last timestamp of oplog func (ol *opLogListener) getLastTimestamp() bson.MongoTimestamp { tank := ol.tank.Copy().OrderBy("-" + opLogTimestampKey).Select(opLogTimestampKey).Limit(1) for ; ; time.Sleep(opLogRetryGap) { t := tank.Query() if err := t.GetError(); err != nil { blog.Errorf(ol.sprint(fmt.Sprintf("getLastTimestamp failed! %v", err))) continue } r := t.GetValue() if t.GetLen() == 0 { blog.Errorf(ol.sprint(fmt.Sprintf("getLastTimestamp failed! no oplog found."))) continue } op, err := ol.getOpLog(r[0]) if err != nil { blog.Errorf(ol.sprint(fmt.Sprintf("getLastTimestamp failed! %v", err))) continue } return bson.MongoTimestamp(op.TS) } } // get oplog func (ol *opLogListener) getOpLog(v interface{}) (*opLog, error) { vv, ok := v.(map[string]interface{}) if !ok { return nil, errors.New(ol.sprint(fmt.Sprintf("getLastTimestamp failed! oplog format error: %v", vv))) } op := &opLog{} if err := op.fillUp(vv); err != nil { return nil, err } return op, nil } func (ol *opLogListener) sprint(s string) string { return fmt.Sprintf("mongodb listener | %s | %s", ol.name, s) } type opLog struct { NS string OP string O map[string]interface{} O2 map[string]interface{} TS uint64 WALL time.Time H int64 V int64 RAW map[string]interface{} } func (opl *opLog) fillUp(value map[string]interface{}) error { for k, v := range value { err := setField(opl, k, v) if err != nil { return err } } return nil } func (opl *opLog) preProcess(tank operator.Tank) bool { defer tank.Close() if opl.OP == opNopValue { return false } var ok bool if opl.O["$set"] != nil { opl.O, ok = opl.O["$set"].(map[string]interface{}) if !ok { return false } } if opl.OP == opInsertValue || opl.OP == opDeleteValue { opl.RAW = opl.O return true }
ns := strings.Split(opl.NS, ".") if len(ns) < 2 { return false } defer func() { if r := recover(); r != nil { // prevent bson.ObjectIdHex() panic, return false } }() t := tank.Using(ns[0]).From(ns[1]).Filter(operator.BaseCondition.AddOp(operator.Eq, opIdKey, objectId)).Query() if t.GetError() != nil { return false } if v := t.GetValue(); len(v) > 0 { opl.RAW, ok = v[0].(map[string]interface{}) return ok } return false } func setField(obj interface{}, name string, value interface{}) error { name = strings.ToUpper(name) structValue := reflect.ValueOf(obj).Elem() structFieldValue := structValue.FieldByName(name) if !structFieldValue.IsValid() { return fmt.Errorf("no such field: %s in obj", name) } if !structFieldValue.CanSet() { return fmt.Errorf("cannot set %s field value", name) } structFieldType := structFieldValue.Type() val := reflect.ValueOf(value) if structFieldType != val.Type() { return errors.New("provided value type didn't match obj field type") } structFieldValue.Set(val) return nil } var ( listenerPool map[string]*opLogListener listenerPoolLock sync.RWMutex ) // StartWatch start storage operator unit watch func StartWatch(tank operator.Tank, name string) { t, ok := tank.(*mongoTank) if !ok { return } listenerPoolLock.Lock() listener := new(opLogListener).init(t, name) if listenerPool == nil { listenerPool = make(map[string]*opLogListener) } if listenerPool[name] != nil { blog.Errorf("watcherName duplicated: %s", name) listenerPoolLock.Unlock() return } listenerPool[name] = listener listenerPoolLock.Unlock() listener.listen() }
objectId, ok := opl.O2[opIdKey].(bson.ObjectId) if !ok { return false }
random_line_split
nodelib.py
"""Implementation of node listing, deployment and destruction""" from __future__ import absolute_import import datetime import itertools import json import os import re import string import libcloud.compute.providers import libcloud.compute.deployment import libcloud.compute.ssh from libcloud.compute.types import NodeState import provision.config as config from provision.collections import OrderedDict logger = config.logger def get_driver(secret_key=config.DEFAULT_SECRET_KEY, userid=config.DEFAULT_USERID, provider=config.DEFAULT_PROVIDER): """A driver represents successful authentication. They become stale, so obtain them as late as possible, and don't cache them.""" if hasattr(config, 'get_driver'): logger.debug('get_driver %s' % config.get_driver) return config.get_driver() else: logger.debug('get_driver {0}@{1}'.format(userid, provider)) return libcloud.compute.providers.get_driver( config.PROVIDERS[provider])(userid, secret_key) def list_nodes(driver): logger.debug('list_nodes') return [n for n in driver.list_nodes() if n.state != NodeState.TERMINATED] class NodeProxy(object): """Wrap a libcloud.base.Node object and add some functionality""" def __init__(self, node, image): self.node = node self.image = image def __getattr__(self, name): return getattr(self.node, name) def write_json(self, path): info = { 'id': self.node.id, 'name': self.node.name, 'state': self.node.state, 'public_ip': self.node.public_ip, 'private_ip': self.node.private_ip, 'image_id': self.image.id, 'image_name': self.image.name} with open(path, 'wb') as df: json.dump(info, df) df.close() def __repr__(self): s = self.node.__repr__() if hasattr(self.node, 'script_deployments') and self.node.script_deployments: ascii_deployments = [ # force script output to ascii encoding {'name':sd.name, 'exit_status':sd.exit_status, 'script':sd.script, 'stdout': sd.stdout.decode('ascii', 'ignore'), 'stderr': sd.stderr.decode('ascii', 'ignore')} for sd in self.node.script_deployments] s += '\n'.join( ['*{name}: {exit_status}\n{script}\n{stdout}\n{stderr}'.format(**sd) for sd in ascii_deployments]) return s def destroy(self): """Insure only destroyable nodes are destroyed""" node = self.node if not config.is_node_destroyable(node.name): logger.error('node %s has non-destroyable prefix' % node.name) return False logger.info('destroying node %s' % node) return node.destroy() def sum_exit_status(self): """Return the sum of all deployed scripts' exit_status""" return sum([sd.exit_status for sd in self.node.script_deployments]) def substitute(script, submap): """Check for presence of template indicator and if found, perform variable substition on script based on template type, returning script.""" match = config.TEMPLATE_RE.search(script) if match: template_type = match.groupdict()['type'] try: return config.TEMPLATE_TYPEMAP[template_type](script, submap) except KeyError: logger.error('Unsupported template type: %s' % template_type) raise return script def script_deployment(path, script, submap=None): """Return a ScriptDeployment from script with possible template substitutions.""" if submap is None: submap = {} script = substitute(script, submap) return libcloud.compute.deployment.ScriptDeployment(script, path) def merge(items, amap, load=False): """Merge list of tuples into dict amap, and optionally load source as value""" for target, source in items: if amap.get(target): logger.warn('overwriting {0}'.format(target)) if load: amap[target] = open(source).read() else: amap[target] = source def merge_keyvals_into_map(keyvals, amap): """Merge list of 'key=val' strings into dict amap, warning of duplicate keys""" for kv in keyvals: k,v = kv.split('=') if k in amap: logger.warn('overwriting {0} with {1}'.format(k, v)) amap[k] = v class Deployment(object): """Split the deployment process into two steps""" def __init__(self, name=None, bundles=[], pubkey=config.DEFAULT_PUBKEY, prefix=config.DEFAULT_NAME_PREFIX, image_name=config.DEFAULT_IMAGE_NAME, subvars=[]): """Initialize a node deployment. If name is not given, it will generate a random name using prefix. The node name is added to the global substitution map, which is used to parameterize templates in scripts containing the form {variable_name}. The list of bundle names is concatenated with any globally common bundle names from which result the set of files to be installed, and scripts to be run on the new node. The pubkey is concatented with any other public keys loaded during configuration and used as the first step in the multi-step deployment. Additional steps represent the scripts to be run. The image_name is used to determine which set of default bundles to install, as well as to actually get the image id in deploy().""" self.name = name or prefix + config.random_str() config.SUBMAP['node_name'] = self.name config.SUBMAP['node_shortname'] = self.name.split('.')[0] merge_keyvals_into_map(subvars, config.SUBMAP) logger.debug('substitution map {0}'.format(config.SUBMAP)) self.pubkeys = [pubkey] self.pubkeys.extend(config.PUBKEYS) self.image_name = image_name filemap = {} scriptmap = OrderedDict() # preserve script run order install_bundles = config.DEFAULT_BUNDLES[:] image_based_bundles = config.IMAGE_BUNDLES_MAP.get(image_name) if image_based_bundles: install_bundles.extend(image_based_bundles[:]) install_bundles.extend(bundles) for bundle in install_bundles: logger.debug('loading bundle {0}'.format(bundle)) merge(config.BUNDLEMAP[bundle].filemap.items(), filemap) merge(config.BUNDLEMAP[bundle].scriptmap.items(), scriptmap, load=True) logger.debug('files {0}'.format(filemap.keys())) logger.debug('scripts {0}'.format(scriptmap.keys())) file_deployments = [libcloud.compute.deployment.FileDeployment( source, target) for target, source in filemap.items()] logger.debug('len(file_deployments) = {0}'.format(len(file_deployments))) self.script_deployments = [script_deployment(path, script, config.SUBMAP) for path, script in scriptmap.items()] logger.debug('len(script_deployments) = {0}'.format(len(self.script_deployments))) steps = [libcloud.compute.deployment.SSHKeyDeployment(''.join(self.pubkeys))] steps.extend(file_deployments) steps.extend(self.script_deployments) self.deployment = libcloud.compute.deployment.MultiStepDeployment(steps) def deploy(self, driver, location_id=config.DEFAULT_LOCATION_ID, size=config.DEFAULT_SIZE): """Use driver to deploy node, with optional ability to specify location id and size id. First, obtain location object from driver. Next, get the size. Then, get the image. Finally, deploy node, and return NodeProxy. """ logger.debug('deploying node %s using driver %s' % (self.name, driver)) args = {'name': self.name} if hasattr(config, 'SSH_KEY_NAME'): args['ex_keyname'] = config.SSH_KEY_NAME if hasattr(config, 'EX_USERDATA'): args['ex_userdata'] = config.EX_USERDATA args['location'] = driver.list_locations()[location_id] logger.debug('location %s' % args['location']) args['size'] = size_from_name(size, driver.list_sizes()) logger.debug('size %s' % args['size']) logger.debug('image name %s' % config.IMAGE_NAMES[self.image_name]) args['image'] = image_from_name( config.IMAGE_NAMES[self.image_name], driver.list_images()) logger.debug('image %s' % args['image']) logger.debug('creating node with args: %s' % args) node = driver.create_node(**args) logger.debug('node created') # password must be extracted before _wait_until_running(), where it goes away logger.debug('driver.features %s' % driver.features) password = node.extra.get('password') \ if 'generates_password' in driver.features['create_node'] else None logger.debug('waiting for node to obtain %s' % config.SSH_INTERFACE) node, ip_addresses = driver._wait_until_running( node, timeout=1200, ssh_interface=config.SSH_INTERFACE) ssh_args = {'hostname': ip_addresses[0], 'port': 22, 'timeout': 10} if password: ssh_args['password'] = password else: ssh_args['key'] = config.SSH_KEY_PATH if hasattr(config, 'SSH_KEY_PATH') else None logger.debug('initializing ssh client with %s' % ssh_args) ssh_client = libcloud.compute.ssh.SSHClient(**ssh_args) logger.debug('ssh client attempting to connect') ssh_client = driver._ssh_client_connect(ssh_client) logger.debug('ssh client connected') logger.debug('starting node deployment with %s steps' % len(self.deployment.steps)) driver._run_deployment_script(self.deployment, node, ssh_client) node.script_deployments = self.script_deployments # retain exit_status, stdout, stderr logger.debug('node.extra["imageId"] %s' % node.extra['imageId']) return NodeProxy(node, args['image']) def size_from_name(size, sizes): """Return a size from a list of sizes.""" by_name = [s for s in sizes if s.name == size] if len(by_name) > 1: raise Exception('more than one image named %s exists' % size) return by_name[0] def image_from_name(name, images): """Return an image from a list of images. If the name is an exact match, return the last exactly matching image. Otherwise, sort images by 'natural' order, using decorate-sort-undecorate, and return the largest. see: http://code.activestate.com/recipes/285264-natural-string-sorting/ """ prefixed_images = [i for i in images if i.name.startswith(name)] if name in [i.name for i in prefixed_images]: return [i for i in prefixed_images if i.name == name][-1] decorated = sorted( [(int(re.search('\d+', i.name).group(0)), i) for i in prefixed_images]) return [i[1] for i in decorated][-1] def destroy_by_name(name, driver):
"""Destroy all nodes matching specified name""" matches = [node for node in list_nodes(driver) if node.name == name] if len(matches) == 0: logger.warn('no node named %s' % name) return False else: return all([node.destroy() for node in matches])
identifier_body
nodelib.py
"""Implementation of node listing, deployment and destruction""" from __future__ import absolute_import import datetime import itertools import json import os import re import string import libcloud.compute.providers import libcloud.compute.deployment import libcloud.compute.ssh from libcloud.compute.types import NodeState import provision.config as config from provision.collections import OrderedDict logger = config.logger def get_driver(secret_key=config.DEFAULT_SECRET_KEY, userid=config.DEFAULT_USERID, provider=config.DEFAULT_PROVIDER): """A driver represents successful authentication. They become stale, so obtain them as late as possible, and don't cache them.""" if hasattr(config, 'get_driver'): logger.debug('get_driver %s' % config.get_driver) return config.get_driver() else: logger.debug('get_driver {0}@{1}'.format(userid, provider)) return libcloud.compute.providers.get_driver( config.PROVIDERS[provider])(userid, secret_key) def list_nodes(driver): logger.debug('list_nodes') return [n for n in driver.list_nodes() if n.state != NodeState.TERMINATED] class NodeProxy(object): """Wrap a libcloud.base.Node object and add some functionality""" def __init__(self, node, image): self.node = node self.image = image def __getattr__(self, name): return getattr(self.node, name) def write_json(self, path): info = { 'id': self.node.id, 'name': self.node.name, 'state': self.node.state, 'public_ip': self.node.public_ip, 'private_ip': self.node.private_ip, 'image_id': self.image.id, 'image_name': self.image.name} with open(path, 'wb') as df: json.dump(info, df) df.close() def __repr__(self): s = self.node.__repr__() if hasattr(self.node, 'script_deployments') and self.node.script_deployments: ascii_deployments = [ # force script output to ascii encoding {'name':sd.name, 'exit_status':sd.exit_status, 'script':sd.script, 'stdout': sd.stdout.decode('ascii', 'ignore'), 'stderr': sd.stderr.decode('ascii', 'ignore')} for sd in self.node.script_deployments] s += '\n'.join( ['*{name}: {exit_status}\n{script}\n{stdout}\n{stderr}'.format(**sd) for sd in ascii_deployments]) return s def destroy(self): """Insure only destroyable nodes are destroyed""" node = self.node if not config.is_node_destroyable(node.name): logger.error('node %s has non-destroyable prefix' % node.name) return False logger.info('destroying node %s' % node) return node.destroy() def sum_exit_status(self): """Return the sum of all deployed scripts' exit_status""" return sum([sd.exit_status for sd in self.node.script_deployments]) def substitute(script, submap): """Check for presence of template indicator and if found, perform variable substition on script based on template type, returning script.""" match = config.TEMPLATE_RE.search(script) if match: template_type = match.groupdict()['type'] try: return config.TEMPLATE_TYPEMAP[template_type](script, submap) except KeyError: logger.error('Unsupported template type: %s' % template_type) raise return script def script_deployment(path, script, submap=None): """Return a ScriptDeployment from script with possible template substitutions.""" if submap is None: submap = {} script = substitute(script, submap) return libcloud.compute.deployment.ScriptDeployment(script, path) def merge(items, amap, load=False): """Merge list of tuples into dict amap, and optionally load source as value""" for target, source in items: if amap.get(target): logger.warn('overwriting {0}'.format(target)) if load: amap[target] = open(source).read() else:
def merge_keyvals_into_map(keyvals, amap): """Merge list of 'key=val' strings into dict amap, warning of duplicate keys""" for kv in keyvals: k,v = kv.split('=') if k in amap: logger.warn('overwriting {0} with {1}'.format(k, v)) amap[k] = v class Deployment(object): """Split the deployment process into two steps""" def __init__(self, name=None, bundles=[], pubkey=config.DEFAULT_PUBKEY, prefix=config.DEFAULT_NAME_PREFIX, image_name=config.DEFAULT_IMAGE_NAME, subvars=[]): """Initialize a node deployment. If name is not given, it will generate a random name using prefix. The node name is added to the global substitution map, which is used to parameterize templates in scripts containing the form {variable_name}. The list of bundle names is concatenated with any globally common bundle names from which result the set of files to be installed, and scripts to be run on the new node. The pubkey is concatented with any other public keys loaded during configuration and used as the first step in the multi-step deployment. Additional steps represent the scripts to be run. The image_name is used to determine which set of default bundles to install, as well as to actually get the image id in deploy().""" self.name = name or prefix + config.random_str() config.SUBMAP['node_name'] = self.name config.SUBMAP['node_shortname'] = self.name.split('.')[0] merge_keyvals_into_map(subvars, config.SUBMAP) logger.debug('substitution map {0}'.format(config.SUBMAP)) self.pubkeys = [pubkey] self.pubkeys.extend(config.PUBKEYS) self.image_name = image_name filemap = {} scriptmap = OrderedDict() # preserve script run order install_bundles = config.DEFAULT_BUNDLES[:] image_based_bundles = config.IMAGE_BUNDLES_MAP.get(image_name) if image_based_bundles: install_bundles.extend(image_based_bundles[:]) install_bundles.extend(bundles) for bundle in install_bundles: logger.debug('loading bundle {0}'.format(bundle)) merge(config.BUNDLEMAP[bundle].filemap.items(), filemap) merge(config.BUNDLEMAP[bundle].scriptmap.items(), scriptmap, load=True) logger.debug('files {0}'.format(filemap.keys())) logger.debug('scripts {0}'.format(scriptmap.keys())) file_deployments = [libcloud.compute.deployment.FileDeployment( source, target) for target, source in filemap.items()] logger.debug('len(file_deployments) = {0}'.format(len(file_deployments))) self.script_deployments = [script_deployment(path, script, config.SUBMAP) for path, script in scriptmap.items()] logger.debug('len(script_deployments) = {0}'.format(len(self.script_deployments))) steps = [libcloud.compute.deployment.SSHKeyDeployment(''.join(self.pubkeys))] steps.extend(file_deployments) steps.extend(self.script_deployments) self.deployment = libcloud.compute.deployment.MultiStepDeployment(steps) def deploy(self, driver, location_id=config.DEFAULT_LOCATION_ID, size=config.DEFAULT_SIZE): """Use driver to deploy node, with optional ability to specify location id and size id. First, obtain location object from driver. Next, get the size. Then, get the image. Finally, deploy node, and return NodeProxy. """ logger.debug('deploying node %s using driver %s' % (self.name, driver)) args = {'name': self.name} if hasattr(config, 'SSH_KEY_NAME'): args['ex_keyname'] = config.SSH_KEY_NAME if hasattr(config, 'EX_USERDATA'): args['ex_userdata'] = config.EX_USERDATA args['location'] = driver.list_locations()[location_id] logger.debug('location %s' % args['location']) args['size'] = size_from_name(size, driver.list_sizes()) logger.debug('size %s' % args['size']) logger.debug('image name %s' % config.IMAGE_NAMES[self.image_name]) args['image'] = image_from_name( config.IMAGE_NAMES[self.image_name], driver.list_images()) logger.debug('image %s' % args['image']) logger.debug('creating node with args: %s' % args) node = driver.create_node(**args) logger.debug('node created') # password must be extracted before _wait_until_running(), where it goes away logger.debug('driver.features %s' % driver.features) password = node.extra.get('password') \ if 'generates_password' in driver.features['create_node'] else None logger.debug('waiting for node to obtain %s' % config.SSH_INTERFACE) node, ip_addresses = driver._wait_until_running( node, timeout=1200, ssh_interface=config.SSH_INTERFACE) ssh_args = {'hostname': ip_addresses[0], 'port': 22, 'timeout': 10} if password: ssh_args['password'] = password else: ssh_args['key'] = config.SSH_KEY_PATH if hasattr(config, 'SSH_KEY_PATH') else None logger.debug('initializing ssh client with %s' % ssh_args) ssh_client = libcloud.compute.ssh.SSHClient(**ssh_args) logger.debug('ssh client attempting to connect') ssh_client = driver._ssh_client_connect(ssh_client) logger.debug('ssh client connected') logger.debug('starting node deployment with %s steps' % len(self.deployment.steps)) driver._run_deployment_script(self.deployment, node, ssh_client) node.script_deployments = self.script_deployments # retain exit_status, stdout, stderr logger.debug('node.extra["imageId"] %s' % node.extra['imageId']) return NodeProxy(node, args['image']) def size_from_name(size, sizes): """Return a size from a list of sizes.""" by_name = [s for s in sizes if s.name == size] if len(by_name) > 1: raise Exception('more than one image named %s exists' % size) return by_name[0] def image_from_name(name, images): """Return an image from a list of images. If the name is an exact match, return the last exactly matching image. Otherwise, sort images by 'natural' order, using decorate-sort-undecorate, and return the largest. see: http://code.activestate.com/recipes/285264-natural-string-sorting/ """ prefixed_images = [i for i in images if i.name.startswith(name)] if name in [i.name for i in prefixed_images]: return [i for i in prefixed_images if i.name == name][-1] decorated = sorted( [(int(re.search('\d+', i.name).group(0)), i) for i in prefixed_images]) return [i[1] for i in decorated][-1] def destroy_by_name(name, driver): """Destroy all nodes matching specified name""" matches = [node for node in list_nodes(driver) if node.name == name] if len(matches) == 0: logger.warn('no node named %s' % name) return False else: return all([node.destroy() for node in matches])
amap[target] = source
conditional_block
nodelib.py
"""Implementation of node listing, deployment and destruction""" from __future__ import absolute_import import datetime import itertools import json import os import re import string
import libcloud.compute.providers import libcloud.compute.deployment import libcloud.compute.ssh from libcloud.compute.types import NodeState import provision.config as config from provision.collections import OrderedDict logger = config.logger def get_driver(secret_key=config.DEFAULT_SECRET_KEY, userid=config.DEFAULT_USERID, provider=config.DEFAULT_PROVIDER): """A driver represents successful authentication. They become stale, so obtain them as late as possible, and don't cache them.""" if hasattr(config, 'get_driver'): logger.debug('get_driver %s' % config.get_driver) return config.get_driver() else: logger.debug('get_driver {0}@{1}'.format(userid, provider)) return libcloud.compute.providers.get_driver( config.PROVIDERS[provider])(userid, secret_key) def list_nodes(driver): logger.debug('list_nodes') return [n for n in driver.list_nodes() if n.state != NodeState.TERMINATED] class NodeProxy(object): """Wrap a libcloud.base.Node object and add some functionality""" def __init__(self, node, image): self.node = node self.image = image def __getattr__(self, name): return getattr(self.node, name) def write_json(self, path): info = { 'id': self.node.id, 'name': self.node.name, 'state': self.node.state, 'public_ip': self.node.public_ip, 'private_ip': self.node.private_ip, 'image_id': self.image.id, 'image_name': self.image.name} with open(path, 'wb') as df: json.dump(info, df) df.close() def __repr__(self): s = self.node.__repr__() if hasattr(self.node, 'script_deployments') and self.node.script_deployments: ascii_deployments = [ # force script output to ascii encoding {'name':sd.name, 'exit_status':sd.exit_status, 'script':sd.script, 'stdout': sd.stdout.decode('ascii', 'ignore'), 'stderr': sd.stderr.decode('ascii', 'ignore')} for sd in self.node.script_deployments] s += '\n'.join( ['*{name}: {exit_status}\n{script}\n{stdout}\n{stderr}'.format(**sd) for sd in ascii_deployments]) return s def destroy(self): """Insure only destroyable nodes are destroyed""" node = self.node if not config.is_node_destroyable(node.name): logger.error('node %s has non-destroyable prefix' % node.name) return False logger.info('destroying node %s' % node) return node.destroy() def sum_exit_status(self): """Return the sum of all deployed scripts' exit_status""" return sum([sd.exit_status for sd in self.node.script_deployments]) def substitute(script, submap): """Check for presence of template indicator and if found, perform variable substition on script based on template type, returning script.""" match = config.TEMPLATE_RE.search(script) if match: template_type = match.groupdict()['type'] try: return config.TEMPLATE_TYPEMAP[template_type](script, submap) except KeyError: logger.error('Unsupported template type: %s' % template_type) raise return script def script_deployment(path, script, submap=None): """Return a ScriptDeployment from script with possible template substitutions.""" if submap is None: submap = {} script = substitute(script, submap) return libcloud.compute.deployment.ScriptDeployment(script, path) def merge(items, amap, load=False): """Merge list of tuples into dict amap, and optionally load source as value""" for target, source in items: if amap.get(target): logger.warn('overwriting {0}'.format(target)) if load: amap[target] = open(source).read() else: amap[target] = source def merge_keyvals_into_map(keyvals, amap): """Merge list of 'key=val' strings into dict amap, warning of duplicate keys""" for kv in keyvals: k,v = kv.split('=') if k in amap: logger.warn('overwriting {0} with {1}'.format(k, v)) amap[k] = v class Deployment(object): """Split the deployment process into two steps""" def __init__(self, name=None, bundles=[], pubkey=config.DEFAULT_PUBKEY, prefix=config.DEFAULT_NAME_PREFIX, image_name=config.DEFAULT_IMAGE_NAME, subvars=[]): """Initialize a node deployment. If name is not given, it will generate a random name using prefix. The node name is added to the global substitution map, which is used to parameterize templates in scripts containing the form {variable_name}. The list of bundle names is concatenated with any globally common bundle names from which result the set of files to be installed, and scripts to be run on the new node. The pubkey is concatented with any other public keys loaded during configuration and used as the first step in the multi-step deployment. Additional steps represent the scripts to be run. The image_name is used to determine which set of default bundles to install, as well as to actually get the image id in deploy().""" self.name = name or prefix + config.random_str() config.SUBMAP['node_name'] = self.name config.SUBMAP['node_shortname'] = self.name.split('.')[0] merge_keyvals_into_map(subvars, config.SUBMAP) logger.debug('substitution map {0}'.format(config.SUBMAP)) self.pubkeys = [pubkey] self.pubkeys.extend(config.PUBKEYS) self.image_name = image_name filemap = {} scriptmap = OrderedDict() # preserve script run order install_bundles = config.DEFAULT_BUNDLES[:] image_based_bundles = config.IMAGE_BUNDLES_MAP.get(image_name) if image_based_bundles: install_bundles.extend(image_based_bundles[:]) install_bundles.extend(bundles) for bundle in install_bundles: logger.debug('loading bundle {0}'.format(bundle)) merge(config.BUNDLEMAP[bundle].filemap.items(), filemap) merge(config.BUNDLEMAP[bundle].scriptmap.items(), scriptmap, load=True) logger.debug('files {0}'.format(filemap.keys())) logger.debug('scripts {0}'.format(scriptmap.keys())) file_deployments = [libcloud.compute.deployment.FileDeployment( source, target) for target, source in filemap.items()] logger.debug('len(file_deployments) = {0}'.format(len(file_deployments))) self.script_deployments = [script_deployment(path, script, config.SUBMAP) for path, script in scriptmap.items()] logger.debug('len(script_deployments) = {0}'.format(len(self.script_deployments))) steps = [libcloud.compute.deployment.SSHKeyDeployment(''.join(self.pubkeys))] steps.extend(file_deployments) steps.extend(self.script_deployments) self.deployment = libcloud.compute.deployment.MultiStepDeployment(steps) def deploy(self, driver, location_id=config.DEFAULT_LOCATION_ID, size=config.DEFAULT_SIZE): """Use driver to deploy node, with optional ability to specify location id and size id. First, obtain location object from driver. Next, get the size. Then, get the image. Finally, deploy node, and return NodeProxy. """ logger.debug('deploying node %s using driver %s' % (self.name, driver)) args = {'name': self.name} if hasattr(config, 'SSH_KEY_NAME'): args['ex_keyname'] = config.SSH_KEY_NAME if hasattr(config, 'EX_USERDATA'): args['ex_userdata'] = config.EX_USERDATA args['location'] = driver.list_locations()[location_id] logger.debug('location %s' % args['location']) args['size'] = size_from_name(size, driver.list_sizes()) logger.debug('size %s' % args['size']) logger.debug('image name %s' % config.IMAGE_NAMES[self.image_name]) args['image'] = image_from_name( config.IMAGE_NAMES[self.image_name], driver.list_images()) logger.debug('image %s' % args['image']) logger.debug('creating node with args: %s' % args) node = driver.create_node(**args) logger.debug('node created') # password must be extracted before _wait_until_running(), where it goes away logger.debug('driver.features %s' % driver.features) password = node.extra.get('password') \ if 'generates_password' in driver.features['create_node'] else None logger.debug('waiting for node to obtain %s' % config.SSH_INTERFACE) node, ip_addresses = driver._wait_until_running( node, timeout=1200, ssh_interface=config.SSH_INTERFACE) ssh_args = {'hostname': ip_addresses[0], 'port': 22, 'timeout': 10} if password: ssh_args['password'] = password else: ssh_args['key'] = config.SSH_KEY_PATH if hasattr(config, 'SSH_KEY_PATH') else None logger.debug('initializing ssh client with %s' % ssh_args) ssh_client = libcloud.compute.ssh.SSHClient(**ssh_args) logger.debug('ssh client attempting to connect') ssh_client = driver._ssh_client_connect(ssh_client) logger.debug('ssh client connected') logger.debug('starting node deployment with %s steps' % len(self.deployment.steps)) driver._run_deployment_script(self.deployment, node, ssh_client) node.script_deployments = self.script_deployments # retain exit_status, stdout, stderr logger.debug('node.extra["imageId"] %s' % node.extra['imageId']) return NodeProxy(node, args['image']) def size_from_name(size, sizes): """Return a size from a list of sizes.""" by_name = [s for s in sizes if s.name == size] if len(by_name) > 1: raise Exception('more than one image named %s exists' % size) return by_name[0] def image_from_name(name, images): """Return an image from a list of images. If the name is an exact match, return the last exactly matching image. Otherwise, sort images by 'natural' order, using decorate-sort-undecorate, and return the largest. see: http://code.activestate.com/recipes/285264-natural-string-sorting/ """ prefixed_images = [i for i in images if i.name.startswith(name)] if name in [i.name for i in prefixed_images]: return [i for i in prefixed_images if i.name == name][-1] decorated = sorted( [(int(re.search('\d+', i.name).group(0)), i) for i in prefixed_images]) return [i[1] for i in decorated][-1] def destroy_by_name(name, driver): """Destroy all nodes matching specified name""" matches = [node for node in list_nodes(driver) if node.name == name] if len(matches) == 0: logger.warn('no node named %s' % name) return False else: return all([node.destroy() for node in matches])
random_line_split
nodelib.py
"""Implementation of node listing, deployment and destruction""" from __future__ import absolute_import import datetime import itertools import json import os import re import string import libcloud.compute.providers import libcloud.compute.deployment import libcloud.compute.ssh from libcloud.compute.types import NodeState import provision.config as config from provision.collections import OrderedDict logger = config.logger def get_driver(secret_key=config.DEFAULT_SECRET_KEY, userid=config.DEFAULT_USERID, provider=config.DEFAULT_PROVIDER): """A driver represents successful authentication. They become stale, so obtain them as late as possible, and don't cache them.""" if hasattr(config, 'get_driver'): logger.debug('get_driver %s' % config.get_driver) return config.get_driver() else: logger.debug('get_driver {0}@{1}'.format(userid, provider)) return libcloud.compute.providers.get_driver( config.PROVIDERS[provider])(userid, secret_key) def list_nodes(driver): logger.debug('list_nodes') return [n for n in driver.list_nodes() if n.state != NodeState.TERMINATED] class NodeProxy(object): """Wrap a libcloud.base.Node object and add some functionality""" def __init__(self, node, image): self.node = node self.image = image def __getattr__(self, name): return getattr(self.node, name) def write_json(self, path): info = { 'id': self.node.id, 'name': self.node.name, 'state': self.node.state, 'public_ip': self.node.public_ip, 'private_ip': self.node.private_ip, 'image_id': self.image.id, 'image_name': self.image.name} with open(path, 'wb') as df: json.dump(info, df) df.close() def __repr__(self): s = self.node.__repr__() if hasattr(self.node, 'script_deployments') and self.node.script_deployments: ascii_deployments = [ # force script output to ascii encoding {'name':sd.name, 'exit_status':sd.exit_status, 'script':sd.script, 'stdout': sd.stdout.decode('ascii', 'ignore'), 'stderr': sd.stderr.decode('ascii', 'ignore')} for sd in self.node.script_deployments] s += '\n'.join( ['*{name}: {exit_status}\n{script}\n{stdout}\n{stderr}'.format(**sd) for sd in ascii_deployments]) return s def destroy(self): """Insure only destroyable nodes are destroyed""" node = self.node if not config.is_node_destroyable(node.name): logger.error('node %s has non-destroyable prefix' % node.name) return False logger.info('destroying node %s' % node) return node.destroy() def sum_exit_status(self): """Return the sum of all deployed scripts' exit_status""" return sum([sd.exit_status for sd in self.node.script_deployments]) def substitute(script, submap): """Check for presence of template indicator and if found, perform variable substition on script based on template type, returning script.""" match = config.TEMPLATE_RE.search(script) if match: template_type = match.groupdict()['type'] try: return config.TEMPLATE_TYPEMAP[template_type](script, submap) except KeyError: logger.error('Unsupported template type: %s' % template_type) raise return script def script_deployment(path, script, submap=None): """Return a ScriptDeployment from script with possible template substitutions.""" if submap is None: submap = {} script = substitute(script, submap) return libcloud.compute.deployment.ScriptDeployment(script, path) def merge(items, amap, load=False): """Merge list of tuples into dict amap, and optionally load source as value""" for target, source in items: if amap.get(target): logger.warn('overwriting {0}'.format(target)) if load: amap[target] = open(source).read() else: amap[target] = source def merge_keyvals_into_map(keyvals, amap): """Merge list of 'key=val' strings into dict amap, warning of duplicate keys""" for kv in keyvals: k,v = kv.split('=') if k in amap: logger.warn('overwriting {0} with {1}'.format(k, v)) amap[k] = v class Deployment(object): """Split the deployment process into two steps""" def __init__(self, name=None, bundles=[], pubkey=config.DEFAULT_PUBKEY, prefix=config.DEFAULT_NAME_PREFIX, image_name=config.DEFAULT_IMAGE_NAME, subvars=[]): """Initialize a node deployment. If name is not given, it will generate a random name using prefix. The node name is added to the global substitution map, which is used to parameterize templates in scripts containing the form {variable_name}. The list of bundle names is concatenated with any globally common bundle names from which result the set of files to be installed, and scripts to be run on the new node. The pubkey is concatented with any other public keys loaded during configuration and used as the first step in the multi-step deployment. Additional steps represent the scripts to be run. The image_name is used to determine which set of default bundles to install, as well as to actually get the image id in deploy().""" self.name = name or prefix + config.random_str() config.SUBMAP['node_name'] = self.name config.SUBMAP['node_shortname'] = self.name.split('.')[0] merge_keyvals_into_map(subvars, config.SUBMAP) logger.debug('substitution map {0}'.format(config.SUBMAP)) self.pubkeys = [pubkey] self.pubkeys.extend(config.PUBKEYS) self.image_name = image_name filemap = {} scriptmap = OrderedDict() # preserve script run order install_bundles = config.DEFAULT_BUNDLES[:] image_based_bundles = config.IMAGE_BUNDLES_MAP.get(image_name) if image_based_bundles: install_bundles.extend(image_based_bundles[:]) install_bundles.extend(bundles) for bundle in install_bundles: logger.debug('loading bundle {0}'.format(bundle)) merge(config.BUNDLEMAP[bundle].filemap.items(), filemap) merge(config.BUNDLEMAP[bundle].scriptmap.items(), scriptmap, load=True) logger.debug('files {0}'.format(filemap.keys())) logger.debug('scripts {0}'.format(scriptmap.keys())) file_deployments = [libcloud.compute.deployment.FileDeployment( source, target) for target, source in filemap.items()] logger.debug('len(file_deployments) = {0}'.format(len(file_deployments))) self.script_deployments = [script_deployment(path, script, config.SUBMAP) for path, script in scriptmap.items()] logger.debug('len(script_deployments) = {0}'.format(len(self.script_deployments))) steps = [libcloud.compute.deployment.SSHKeyDeployment(''.join(self.pubkeys))] steps.extend(file_deployments) steps.extend(self.script_deployments) self.deployment = libcloud.compute.deployment.MultiStepDeployment(steps) def deploy(self, driver, location_id=config.DEFAULT_LOCATION_ID, size=config.DEFAULT_SIZE): """Use driver to deploy node, with optional ability to specify location id and size id. First, obtain location object from driver. Next, get the size. Then, get the image. Finally, deploy node, and return NodeProxy. """ logger.debug('deploying node %s using driver %s' % (self.name, driver)) args = {'name': self.name} if hasattr(config, 'SSH_KEY_NAME'): args['ex_keyname'] = config.SSH_KEY_NAME if hasattr(config, 'EX_USERDATA'): args['ex_userdata'] = config.EX_USERDATA args['location'] = driver.list_locations()[location_id] logger.debug('location %s' % args['location']) args['size'] = size_from_name(size, driver.list_sizes()) logger.debug('size %s' % args['size']) logger.debug('image name %s' % config.IMAGE_NAMES[self.image_name]) args['image'] = image_from_name( config.IMAGE_NAMES[self.image_name], driver.list_images()) logger.debug('image %s' % args['image']) logger.debug('creating node with args: %s' % args) node = driver.create_node(**args) logger.debug('node created') # password must be extracted before _wait_until_running(), where it goes away logger.debug('driver.features %s' % driver.features) password = node.extra.get('password') \ if 'generates_password' in driver.features['create_node'] else None logger.debug('waiting for node to obtain %s' % config.SSH_INTERFACE) node, ip_addresses = driver._wait_until_running( node, timeout=1200, ssh_interface=config.SSH_INTERFACE) ssh_args = {'hostname': ip_addresses[0], 'port': 22, 'timeout': 10} if password: ssh_args['password'] = password else: ssh_args['key'] = config.SSH_KEY_PATH if hasattr(config, 'SSH_KEY_PATH') else None logger.debug('initializing ssh client with %s' % ssh_args) ssh_client = libcloud.compute.ssh.SSHClient(**ssh_args) logger.debug('ssh client attempting to connect') ssh_client = driver._ssh_client_connect(ssh_client) logger.debug('ssh client connected') logger.debug('starting node deployment with %s steps' % len(self.deployment.steps)) driver._run_deployment_script(self.deployment, node, ssh_client) node.script_deployments = self.script_deployments # retain exit_status, stdout, stderr logger.debug('node.extra["imageId"] %s' % node.extra['imageId']) return NodeProxy(node, args['image']) def
(size, sizes): """Return a size from a list of sizes.""" by_name = [s for s in sizes if s.name == size] if len(by_name) > 1: raise Exception('more than one image named %s exists' % size) return by_name[0] def image_from_name(name, images): """Return an image from a list of images. If the name is an exact match, return the last exactly matching image. Otherwise, sort images by 'natural' order, using decorate-sort-undecorate, and return the largest. see: http://code.activestate.com/recipes/285264-natural-string-sorting/ """ prefixed_images = [i for i in images if i.name.startswith(name)] if name in [i.name for i in prefixed_images]: return [i for i in prefixed_images if i.name == name][-1] decorated = sorted( [(int(re.search('\d+', i.name).group(0)), i) for i in prefixed_images]) return [i[1] for i in decorated][-1] def destroy_by_name(name, driver): """Destroy all nodes matching specified name""" matches = [node for node in list_nodes(driver) if node.name == name] if len(matches) == 0: logger.warn('no node named %s' % name) return False else: return all([node.destroy() for node in matches])
size_from_name
identifier_name
skipmap.go
// Package skipmap is a high-performance, scalable, concurrent-safe map based on skip-list. // In the typical pattern(100000 operations, 90%LOAD 9%STORE 1%DELETE, 8C16T), the skipmap // up to 10x faster than the built-in sync.Map. package skipmap import ( "sync" "sync/atomic" "unsafe" ) // Int64Map represents a map based on skip list in ascending order. type Int64Map struct { header *int64Node length int64 } type int64Node struct { key int64 value unsafe.Pointer next []*int64Node mu sync.Mutex flags bitflag } func newInt64Node(key int64, value interface{}, level int) *int64Node { n := &int64Node{ key: key, next: make([]*int64Node, level), } n.storeVal(value) return n } func (n *int64Node) storeVal(value interface{}) { atomic.StorePointer(&n.value, unsafe.Pointer(&value)) } func (n *int64Node) loadVal() interface{} { return *(*interface{})(atomic.LoadPointer(&n.value)) } // loadNext return `n.next[i]`(atomic) func (n *int64Node) loadNext(i int) *int64Node { return (*int64Node)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&n.next[i])))) } // storeNext same with `n.next[i] = value`(atomic) func (n *int64Node) storeNext(i int, value *int64Node) { atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&n.next[i])), unsafe.Pointer(value)) } func (n *int64Node) lessthan(key int64) bool { return n.key < key } func (n *int64Node) equal(key int64) bool { return n.key == key } // NewInt64 return an empty int64 skipmap. func NewInt64() *Int64Map { h := newInt64Node(0, "", maxLevel) h.flags.SetTrue(fullyLinked) return &Int64Map{ header: h, } } // findNode takes a key and two maximal-height arrays then searches exactly as in a sequential skipmap. // The returned preds and succs always satisfy preds[i] > key >= succs[i]. // (without fullpath, if find the node will return immediately) func (s *Int64Map) findNode(key int64, preds *[maxLevel]*int64Node, succs *[maxLevel]*int64Node) *int64Node { x := s.header for i := maxLevel - 1; i >= 0; i-- { succ := x.loadNext(i) for succ != nil && succ.lessthan(key) { x = succ succ = x.loadNext(i) } preds[i] = x succs[i] = succ // Check if the key already in the skipmap. if succ != nil && succ.equal(key) { return succ } } return nil } // findNodeDelete takes a key and two maximal-height arrays then searches exactly as in a sequential skip-list. // The returned preds and succs always satisfy preds[i] > key >= succs[i]. func (s *Int64Map) findNodeDelete(key int64, preds *[maxLevel]*int64Node, succs *[maxLevel]*int64Node) int { // lFound represents the index of the first layer at which it found a node. lFound, x := -1, s.header for i := maxLevel - 1; i >= 0; i-- { succ := x.loadNext(i) for succ != nil && succ.lessthan(key) { x = succ succ = x.loadNext(i) } preds[i] = x succs[i] = succ // Check if the key already in the skip list. if lFound == -1 && succ != nil && succ.equal(key) { lFound = i } } return lFound } func unlockInt64(preds [maxLevel]*int64Node, highestLevel int) { var prevPred *int64Node for i := highestLevel; i >= 0; i-- { if preds[i] != prevPred { // the node could be unlocked by previous loop preds[i].mu.Unlock() prevPred = preds[i] } } } // Store sets the value for a key. func (s *Int64Map)
(key int64, value interface{}) { level := randomLevel() var preds, succs [maxLevel]*int64Node for { nodeFound := s.findNode(key, &preds, &succs) if nodeFound != nil { // indicating the key is already in the skip-list if !nodeFound.flags.Get(marked) { // We don't need to care about whether or not the node is fully linked, // just replace the value. nodeFound.storeVal(value) return } // If the node is marked, represents some other goroutines is in the process of deleting this node, // we need to add this node in next loop. continue } // Add this node into skip list. var ( highestLocked = -1 // the highest level being locked by this process valid = true pred, succ, prevPred *int64Node ) for layer := 0; valid && layer < level; layer++ { pred = preds[layer] // target node's previous node succ = succs[layer] // target node's next node if pred != prevPred { // the node in this layer could be locked by previous loop pred.mu.Lock() highestLocked = layer prevPred = pred } // valid check if there is another node has inserted into the skip list in this layer during this process. // It is valid if: // 1. The previous node and next node both are not marked. // 2. The previous node's next node is succ in this layer. valid = !pred.flags.Get(marked) && (succ == nil || !succ.flags.Get(marked)) && pred.next[layer] == succ } if !valid { unlockInt64(preds, highestLocked) continue } nn := newInt64Node(key, value, level) for layer := 0; layer < level; layer++ { nn.next[layer] = succs[layer] preds[layer].storeNext(layer, nn) } nn.flags.SetTrue(fullyLinked) unlockInt64(preds, highestLocked) atomic.AddInt64(&s.length, 1) } } // Load returns the value stored in the map for a key, or nil if no // value is present. // The ok result indicates whether value was found in the map. func (s *Int64Map) Load(key int64) (value interface{}, ok bool) { x := s.header for i := maxLevel - 1; i >= 0; i-- { nex := x.loadNext(i) for nex != nil && nex.lessthan(key) { x = nex nex = x.loadNext(i) } // Check if the key already in the skip list. if nex != nil && nex.equal(key) { if nex.flags.MGet(fullyLinked|marked, fullyLinked) { return nex.loadVal(), true } return nil, false } } return nil, false } // LoadAndDelete deletes the value for a key, returning the previous value if any. // The loaded result reports whether the key was present. func (s *Int64Map) LoadAndDelete(key int64) (value interface{}, loaded bool) { var ( nodeToDelete *int64Node isMarked bool // represents if this operation mark the node topLayer = -1 preds, succs [maxLevel]*int64Node ) for { lFound := s.findNodeDelete(key, &preds, &succs) if isMarked || // this process mark this node or we can find this node in the skip list lFound != -1 && succs[lFound].flags.MGet(fullyLinked|marked, fullyLinked) && (len(succs[lFound].next)-1) == lFound { if !isMarked { // we don't mark this node for now nodeToDelete = succs[lFound] topLayer = lFound nodeToDelete.mu.Lock() if nodeToDelete.flags.Get(marked) { // The node is marked by another process, // the physical deletion will be accomplished by another process. nodeToDelete.mu.Unlock() return nil, false } nodeToDelete.flags.SetTrue(marked) isMarked = true } // Accomplish the physical deletion. var ( highestLocked = -1 // the highest level being locked by this process valid = true pred, succ, prevPred *int64Node ) for layer := 0; valid && (layer <= topLayer); layer++ { pred, succ = preds[layer], succs[layer] if pred != prevPred { // the node in this layer could be locked by previous loop pred.mu.Lock() highestLocked = layer prevPred = pred } // valid check if there is another node has inserted into the skip list in this layer // during this process, or the previous is deleted by another process. // It is valid if: // 1. the previous node exists. // 2. no another node has inserted into the skip list in this layer. valid = !pred.flags.Get(marked) && pred.next[layer] == succ } if !valid { unlockInt64(preds, highestLocked) continue } for i := topLayer; i >= 0; i-- { // Now we own the `nodeToDelete`, no other goroutine will modify it. // So we don't need `nodeToDelete.loadNext` preds[i].storeNext(i, nodeToDelete.next[i]) } nodeToDelete.mu.Unlock() unlockInt64(preds, highestLocked) atomic.AddInt64(&s.length, -1) return nodeToDelete.loadVal(), true } return nil, false } } // LoadOrStore returns the existing value for the key if present. // Otherwise, it stores and returns the given value. // The loaded result is true if the value was loaded, false if stored. func (s *Int64Map) LoadOrStore(key int64, value interface{}) (actual interface{}, loaded bool) { loadedval, ok := s.Load(key) if !ok { s.Store(key, value) return value, false } return loadedval, true } // Delete deletes the value for a key. func (s *Int64Map) Delete(key int64) { var ( nodeToDelete *int64Node isMarked bool // represents if this operation mark the node topLayer = -1 preds, succs [maxLevel]*int64Node ) for { lFound := s.findNodeDelete(key, &preds, &succs) if isMarked || // this process mark this node or we can find this node in the skip list lFound != -1 && succs[lFound].flags.MGet(fullyLinked|marked, fullyLinked) && (len(succs[lFound].next)-1) == lFound { if !isMarked { // we don't mark this node for now nodeToDelete = succs[lFound] topLayer = lFound nodeToDelete.mu.Lock() if nodeToDelete.flags.Get(marked) { // The node is marked by another process, // the physical deletion will be accomplished by another process. nodeToDelete.mu.Unlock() return // false } nodeToDelete.flags.SetTrue(marked) isMarked = true } // Accomplish the physical deletion. var ( highestLocked = -1 // the highest level being locked by this process valid = true pred, succ, prevPred *int64Node ) for layer := 0; valid && (layer <= topLayer); layer++ { pred, succ = preds[layer], succs[layer] if pred != prevPred { // the node in this layer could be locked by previous loop pred.mu.Lock() highestLocked = layer prevPred = pred } // valid check if there is another node has inserted into the skip list in this layer // during this process, or the previous is deleted by another process. // It is valid if: // 1. the previous node exists. // 2. no another node has inserted into the skip list in this layer. valid = !pred.flags.Get(marked) && pred.loadNext(layer) == succ } if !valid { unlockInt64(preds, highestLocked) continue } for i := topLayer; i >= 0; i-- { // Now we own the `nodeToDelete`, no other goroutine will modify it. // So we don't need `nodeToDelete.loadNext` preds[i].storeNext(i, nodeToDelete.next[i]) } nodeToDelete.mu.Unlock() unlockInt64(preds, highestLocked) atomic.AddInt64(&s.length, -1) return // true } return // false } } // Range calls f sequentially for each key and value present in the skipmap. // If f returns false, range stops the iteration. // // Range does not necessarily correspond to any consistent snapshot of the Map's // contents: no key will be visited more than once, but if the value for any key // is stored or deleted concurrently, Range may reflect any mapping for that key // from any point during the Range call. func (s *Int64Map) Range(f func(key int64, value interface{}) bool) { x := s.header.loadNext(0) for x != nil { if !x.flags.MGet(fullyLinked|marked, fullyLinked) { x = x.loadNext(0) continue } if !f(x.key, x.loadVal()) { break } x = x.loadNext(0) } } // Len return the length of this skipmap. // Keep in sync with types_gen.go:lengthFunction // Special case for code generation, Must in the tail of skipmap.go. func (s *Int64Map) Len() int { return int(atomic.LoadInt64(&s.length)) }
Store
identifier_name
skipmap.go
// Package skipmap is a high-performance, scalable, concurrent-safe map based on skip-list. // In the typical pattern(100000 operations, 90%LOAD 9%STORE 1%DELETE, 8C16T), the skipmap // up to 10x faster than the built-in sync.Map. package skipmap import ( "sync" "sync/atomic" "unsafe" ) // Int64Map represents a map based on skip list in ascending order. type Int64Map struct { header *int64Node length int64 } type int64Node struct { key int64 value unsafe.Pointer next []*int64Node mu sync.Mutex flags bitflag } func newInt64Node(key int64, value interface{}, level int) *int64Node { n := &int64Node{ key: key, next: make([]*int64Node, level), } n.storeVal(value) return n } func (n *int64Node) storeVal(value interface{}) { atomic.StorePointer(&n.value, unsafe.Pointer(&value)) } func (n *int64Node) loadVal() interface{} { return *(*interface{})(atomic.LoadPointer(&n.value)) } // loadNext return `n.next[i]`(atomic) func (n *int64Node) loadNext(i int) *int64Node { return (*int64Node)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&n.next[i])))) } // storeNext same with `n.next[i] = value`(atomic) func (n *int64Node) storeNext(i int, value *int64Node) { atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&n.next[i])), unsafe.Pointer(value)) } func (n *int64Node) lessthan(key int64) bool { return n.key < key } func (n *int64Node) equal(key int64) bool { return n.key == key } // NewInt64 return an empty int64 skipmap. func NewInt64() *Int64Map { h := newInt64Node(0, "", maxLevel) h.flags.SetTrue(fullyLinked) return &Int64Map{ header: h, } } // findNode takes a key and two maximal-height arrays then searches exactly as in a sequential skipmap. // The returned preds and succs always satisfy preds[i] > key >= succs[i]. // (without fullpath, if find the node will return immediately) func (s *Int64Map) findNode(key int64, preds *[maxLevel]*int64Node, succs *[maxLevel]*int64Node) *int64Node
// findNodeDelete takes a key and two maximal-height arrays then searches exactly as in a sequential skip-list. // The returned preds and succs always satisfy preds[i] > key >= succs[i]. func (s *Int64Map) findNodeDelete(key int64, preds *[maxLevel]*int64Node, succs *[maxLevel]*int64Node) int { // lFound represents the index of the first layer at which it found a node. lFound, x := -1, s.header for i := maxLevel - 1; i >= 0; i-- { succ := x.loadNext(i) for succ != nil && succ.lessthan(key) { x = succ succ = x.loadNext(i) } preds[i] = x succs[i] = succ // Check if the key already in the skip list. if lFound == -1 && succ != nil && succ.equal(key) { lFound = i } } return lFound } func unlockInt64(preds [maxLevel]*int64Node, highestLevel int) { var prevPred *int64Node for i := highestLevel; i >= 0; i-- { if preds[i] != prevPred { // the node could be unlocked by previous loop preds[i].mu.Unlock() prevPred = preds[i] } } } // Store sets the value for a key. func (s *Int64Map) Store(key int64, value interface{}) { level := randomLevel() var preds, succs [maxLevel]*int64Node for { nodeFound := s.findNode(key, &preds, &succs) if nodeFound != nil { // indicating the key is already in the skip-list if !nodeFound.flags.Get(marked) { // We don't need to care about whether or not the node is fully linked, // just replace the value. nodeFound.storeVal(value) return } // If the node is marked, represents some other goroutines is in the process of deleting this node, // we need to add this node in next loop. continue } // Add this node into skip list. var ( highestLocked = -1 // the highest level being locked by this process valid = true pred, succ, prevPred *int64Node ) for layer := 0; valid && layer < level; layer++ { pred = preds[layer] // target node's previous node succ = succs[layer] // target node's next node if pred != prevPred { // the node in this layer could be locked by previous loop pred.mu.Lock() highestLocked = layer prevPred = pred } // valid check if there is another node has inserted into the skip list in this layer during this process. // It is valid if: // 1. The previous node and next node both are not marked. // 2. The previous node's next node is succ in this layer. valid = !pred.flags.Get(marked) && (succ == nil || !succ.flags.Get(marked)) && pred.next[layer] == succ } if !valid { unlockInt64(preds, highestLocked) continue } nn := newInt64Node(key, value, level) for layer := 0; layer < level; layer++ { nn.next[layer] = succs[layer] preds[layer].storeNext(layer, nn) } nn.flags.SetTrue(fullyLinked) unlockInt64(preds, highestLocked) atomic.AddInt64(&s.length, 1) } } // Load returns the value stored in the map for a key, or nil if no // value is present. // The ok result indicates whether value was found in the map. func (s *Int64Map) Load(key int64) (value interface{}, ok bool) { x := s.header for i := maxLevel - 1; i >= 0; i-- { nex := x.loadNext(i) for nex != nil && nex.lessthan(key) { x = nex nex = x.loadNext(i) } // Check if the key already in the skip list. if nex != nil && nex.equal(key) { if nex.flags.MGet(fullyLinked|marked, fullyLinked) { return nex.loadVal(), true } return nil, false } } return nil, false } // LoadAndDelete deletes the value for a key, returning the previous value if any. // The loaded result reports whether the key was present. func (s *Int64Map) LoadAndDelete(key int64) (value interface{}, loaded bool) { var ( nodeToDelete *int64Node isMarked bool // represents if this operation mark the node topLayer = -1 preds, succs [maxLevel]*int64Node ) for { lFound := s.findNodeDelete(key, &preds, &succs) if isMarked || // this process mark this node or we can find this node in the skip list lFound != -1 && succs[lFound].flags.MGet(fullyLinked|marked, fullyLinked) && (len(succs[lFound].next)-1) == lFound { if !isMarked { // we don't mark this node for now nodeToDelete = succs[lFound] topLayer = lFound nodeToDelete.mu.Lock() if nodeToDelete.flags.Get(marked) { // The node is marked by another process, // the physical deletion will be accomplished by another process. nodeToDelete.mu.Unlock() return nil, false } nodeToDelete.flags.SetTrue(marked) isMarked = true } // Accomplish the physical deletion. var ( highestLocked = -1 // the highest level being locked by this process valid = true pred, succ, prevPred *int64Node ) for layer := 0; valid && (layer <= topLayer); layer++ { pred, succ = preds[layer], succs[layer] if pred != prevPred { // the node in this layer could be locked by previous loop pred.mu.Lock() highestLocked = layer prevPred = pred } // valid check if there is another node has inserted into the skip list in this layer // during this process, or the previous is deleted by another process. // It is valid if: // 1. the previous node exists. // 2. no another node has inserted into the skip list in this layer. valid = !pred.flags.Get(marked) && pred.next[layer] == succ } if !valid { unlockInt64(preds, highestLocked) continue } for i := topLayer; i >= 0; i-- { // Now we own the `nodeToDelete`, no other goroutine will modify it. // So we don't need `nodeToDelete.loadNext` preds[i].storeNext(i, nodeToDelete.next[i]) } nodeToDelete.mu.Unlock() unlockInt64(preds, highestLocked) atomic.AddInt64(&s.length, -1) return nodeToDelete.loadVal(), true } return nil, false } } // LoadOrStore returns the existing value for the key if present. // Otherwise, it stores and returns the given value. // The loaded result is true if the value was loaded, false if stored. func (s *Int64Map) LoadOrStore(key int64, value interface{}) (actual interface{}, loaded bool) { loadedval, ok := s.Load(key) if !ok { s.Store(key, value) return value, false } return loadedval, true } // Delete deletes the value for a key. func (s *Int64Map) Delete(key int64) { var ( nodeToDelete *int64Node isMarked bool // represents if this operation mark the node topLayer = -1 preds, succs [maxLevel]*int64Node ) for { lFound := s.findNodeDelete(key, &preds, &succs) if isMarked || // this process mark this node or we can find this node in the skip list lFound != -1 && succs[lFound].flags.MGet(fullyLinked|marked, fullyLinked) && (len(succs[lFound].next)-1) == lFound { if !isMarked { // we don't mark this node for now nodeToDelete = succs[lFound] topLayer = lFound nodeToDelete.mu.Lock() if nodeToDelete.flags.Get(marked) { // The node is marked by another process, // the physical deletion will be accomplished by another process. nodeToDelete.mu.Unlock() return // false } nodeToDelete.flags.SetTrue(marked) isMarked = true } // Accomplish the physical deletion. var ( highestLocked = -1 // the highest level being locked by this process valid = true pred, succ, prevPred *int64Node ) for layer := 0; valid && (layer <= topLayer); layer++ { pred, succ = preds[layer], succs[layer] if pred != prevPred { // the node in this layer could be locked by previous loop pred.mu.Lock() highestLocked = layer prevPred = pred } // valid check if there is another node has inserted into the skip list in this layer // during this process, or the previous is deleted by another process. // It is valid if: // 1. the previous node exists. // 2. no another node has inserted into the skip list in this layer. valid = !pred.flags.Get(marked) && pred.loadNext(layer) == succ } if !valid { unlockInt64(preds, highestLocked) continue } for i := topLayer; i >= 0; i-- { // Now we own the `nodeToDelete`, no other goroutine will modify it. // So we don't need `nodeToDelete.loadNext` preds[i].storeNext(i, nodeToDelete.next[i]) } nodeToDelete.mu.Unlock() unlockInt64(preds, highestLocked) atomic.AddInt64(&s.length, -1) return // true } return // false } } // Range calls f sequentially for each key and value present in the skipmap. // If f returns false, range stops the iteration. // // Range does not necessarily correspond to any consistent snapshot of the Map's // contents: no key will be visited more than once, but if the value for any key // is stored or deleted concurrently, Range may reflect any mapping for that key // from any point during the Range call. func (s *Int64Map) Range(f func(key int64, value interface{}) bool) { x := s.header.loadNext(0) for x != nil { if !x.flags.MGet(fullyLinked|marked, fullyLinked) { x = x.loadNext(0) continue } if !f(x.key, x.loadVal()) { break } x = x.loadNext(0) } } // Len return the length of this skipmap. // Keep in sync with types_gen.go:lengthFunction // Special case for code generation, Must in the tail of skipmap.go. func (s *Int64Map) Len() int { return int(atomic.LoadInt64(&s.length)) }
{ x := s.header for i := maxLevel - 1; i >= 0; i-- { succ := x.loadNext(i) for succ != nil && succ.lessthan(key) { x = succ succ = x.loadNext(i) } preds[i] = x succs[i] = succ // Check if the key already in the skipmap. if succ != nil && succ.equal(key) { return succ } } return nil }
identifier_body
skipmap.go
// Package skipmap is a high-performance, scalable, concurrent-safe map based on skip-list. // In the typical pattern(100000 operations, 90%LOAD 9%STORE 1%DELETE, 8C16T), the skipmap // up to 10x faster than the built-in sync.Map. package skipmap import ( "sync" "sync/atomic" "unsafe" ) // Int64Map represents a map based on skip list in ascending order. type Int64Map struct { header *int64Node length int64 } type int64Node struct { key int64 value unsafe.Pointer next []*int64Node mu sync.Mutex flags bitflag } func newInt64Node(key int64, value interface{}, level int) *int64Node { n := &int64Node{ key: key, next: make([]*int64Node, level), } n.storeVal(value) return n } func (n *int64Node) storeVal(value interface{}) { atomic.StorePointer(&n.value, unsafe.Pointer(&value)) } func (n *int64Node) loadVal() interface{} { return *(*interface{})(atomic.LoadPointer(&n.value)) } // loadNext return `n.next[i]`(atomic) func (n *int64Node) loadNext(i int) *int64Node { return (*int64Node)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&n.next[i])))) } // storeNext same with `n.next[i] = value`(atomic) func (n *int64Node) storeNext(i int, value *int64Node) { atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&n.next[i])), unsafe.Pointer(value)) } func (n *int64Node) lessthan(key int64) bool { return n.key < key } func (n *int64Node) equal(key int64) bool { return n.key == key } // NewInt64 return an empty int64 skipmap. func NewInt64() *Int64Map { h := newInt64Node(0, "", maxLevel) h.flags.SetTrue(fullyLinked) return &Int64Map{ header: h, } } // findNode takes a key and two maximal-height arrays then searches exactly as in a sequential skipmap. // The returned preds and succs always satisfy preds[i] > key >= succs[i]. // (without fullpath, if find the node will return immediately) func (s *Int64Map) findNode(key int64, preds *[maxLevel]*int64Node, succs *[maxLevel]*int64Node) *int64Node { x := s.header for i := maxLevel - 1; i >= 0; i-- { succ := x.loadNext(i) for succ != nil && succ.lessthan(key) { x = succ succ = x.loadNext(i) } preds[i] = x succs[i] = succ // Check if the key already in the skipmap. if succ != nil && succ.equal(key) { return succ } } return nil } // findNodeDelete takes a key and two maximal-height arrays then searches exactly as in a sequential skip-list. // The returned preds and succs always satisfy preds[i] > key >= succs[i]. func (s *Int64Map) findNodeDelete(key int64, preds *[maxLevel]*int64Node, succs *[maxLevel]*int64Node) int { // lFound represents the index of the first layer at which it found a node. lFound, x := -1, s.header for i := maxLevel - 1; i >= 0; i-- { succ := x.loadNext(i) for succ != nil && succ.lessthan(key) { x = succ succ = x.loadNext(i) } preds[i] = x succs[i] = succ // Check if the key already in the skip list. if lFound == -1 && succ != nil && succ.equal(key) { lFound = i } } return lFound } func unlockInt64(preds [maxLevel]*int64Node, highestLevel int) { var prevPred *int64Node for i := highestLevel; i >= 0; i-- { if preds[i] != prevPred { // the node could be unlocked by previous loop preds[i].mu.Unlock() prevPred = preds[i] } } } // Store sets the value for a key. func (s *Int64Map) Store(key int64, value interface{}) { level := randomLevel() var preds, succs [maxLevel]*int64Node for { nodeFound := s.findNode(key, &preds, &succs) if nodeFound != nil { // indicating the key is already in the skip-list if !nodeFound.flags.Get(marked) { // We don't need to care about whether or not the node is fully linked, // just replace the value. nodeFound.storeVal(value) return } // If the node is marked, represents some other goroutines is in the process of deleting this node, // we need to add this node in next loop. continue } // Add this node into skip list. var ( highestLocked = -1 // the highest level being locked by this process valid = true pred, succ, prevPred *int64Node ) for layer := 0; valid && layer < level; layer++ { pred = preds[layer] // target node's previous node succ = succs[layer] // target node's next node if pred != prevPred { // the node in this layer could be locked by previous loop pred.mu.Lock() highestLocked = layer prevPred = pred } // valid check if there is another node has inserted into the skip list in this layer during this process. // It is valid if: // 1. The previous node and next node both are not marked. // 2. The previous node's next node is succ in this layer. valid = !pred.flags.Get(marked) && (succ == nil || !succ.flags.Get(marked)) && pred.next[layer] == succ } if !valid { unlockInt64(preds, highestLocked) continue } nn := newInt64Node(key, value, level) for layer := 0; layer < level; layer++ { nn.next[layer] = succs[layer] preds[layer].storeNext(layer, nn) } nn.flags.SetTrue(fullyLinked) unlockInt64(preds, highestLocked) atomic.AddInt64(&s.length, 1) } } // Load returns the value stored in the map for a key, or nil if no // value is present. // The ok result indicates whether value was found in the map. func (s *Int64Map) Load(key int64) (value interface{}, ok bool) { x := s.header for i := maxLevel - 1; i >= 0; i-- { nex := x.loadNext(i) for nex != nil && nex.lessthan(key) { x = nex nex = x.loadNext(i) } // Check if the key already in the skip list. if nex != nil && nex.equal(key) { if nex.flags.MGet(fullyLinked|marked, fullyLinked) { return nex.loadVal(), true } return nil, false } } return nil, false } // LoadAndDelete deletes the value for a key, returning the previous value if any. // The loaded result reports whether the key was present. func (s *Int64Map) LoadAndDelete(key int64) (value interface{}, loaded bool) { var ( nodeToDelete *int64Node isMarked bool // represents if this operation mark the node topLayer = -1 preds, succs [maxLevel]*int64Node ) for { lFound := s.findNodeDelete(key, &preds, &succs) if isMarked || // this process mark this node or we can find this node in the skip list lFound != -1 && succs[lFound].flags.MGet(fullyLinked|marked, fullyLinked) && (len(succs[lFound].next)-1) == lFound { if !isMarked { // we don't mark this node for now nodeToDelete = succs[lFound] topLayer = lFound nodeToDelete.mu.Lock() if nodeToDelete.flags.Get(marked)
nodeToDelete.flags.SetTrue(marked) isMarked = true } // Accomplish the physical deletion. var ( highestLocked = -1 // the highest level being locked by this process valid = true pred, succ, prevPred *int64Node ) for layer := 0; valid && (layer <= topLayer); layer++ { pred, succ = preds[layer], succs[layer] if pred != prevPred { // the node in this layer could be locked by previous loop pred.mu.Lock() highestLocked = layer prevPred = pred } // valid check if there is another node has inserted into the skip list in this layer // during this process, or the previous is deleted by another process. // It is valid if: // 1. the previous node exists. // 2. no another node has inserted into the skip list in this layer. valid = !pred.flags.Get(marked) && pred.next[layer] == succ } if !valid { unlockInt64(preds, highestLocked) continue } for i := topLayer; i >= 0; i-- { // Now we own the `nodeToDelete`, no other goroutine will modify it. // So we don't need `nodeToDelete.loadNext` preds[i].storeNext(i, nodeToDelete.next[i]) } nodeToDelete.mu.Unlock() unlockInt64(preds, highestLocked) atomic.AddInt64(&s.length, -1) return nodeToDelete.loadVal(), true } return nil, false } } // LoadOrStore returns the existing value for the key if present. // Otherwise, it stores and returns the given value. // The loaded result is true if the value was loaded, false if stored. func (s *Int64Map) LoadOrStore(key int64, value interface{}) (actual interface{}, loaded bool) { loadedval, ok := s.Load(key) if !ok { s.Store(key, value) return value, false } return loadedval, true } // Delete deletes the value for a key. func (s *Int64Map) Delete(key int64) { var ( nodeToDelete *int64Node isMarked bool // represents if this operation mark the node topLayer = -1 preds, succs [maxLevel]*int64Node ) for { lFound := s.findNodeDelete(key, &preds, &succs) if isMarked || // this process mark this node or we can find this node in the skip list lFound != -1 && succs[lFound].flags.MGet(fullyLinked|marked, fullyLinked) && (len(succs[lFound].next)-1) == lFound { if !isMarked { // we don't mark this node for now nodeToDelete = succs[lFound] topLayer = lFound nodeToDelete.mu.Lock() if nodeToDelete.flags.Get(marked) { // The node is marked by another process, // the physical deletion will be accomplished by another process. nodeToDelete.mu.Unlock() return // false } nodeToDelete.flags.SetTrue(marked) isMarked = true } // Accomplish the physical deletion. var ( highestLocked = -1 // the highest level being locked by this process valid = true pred, succ, prevPred *int64Node ) for layer := 0; valid && (layer <= topLayer); layer++ { pred, succ = preds[layer], succs[layer] if pred != prevPred { // the node in this layer could be locked by previous loop pred.mu.Lock() highestLocked = layer prevPred = pred } // valid check if there is another node has inserted into the skip list in this layer // during this process, or the previous is deleted by another process. // It is valid if: // 1. the previous node exists. // 2. no another node has inserted into the skip list in this layer. valid = !pred.flags.Get(marked) && pred.loadNext(layer) == succ } if !valid { unlockInt64(preds, highestLocked) continue } for i := topLayer; i >= 0; i-- { // Now we own the `nodeToDelete`, no other goroutine will modify it. // So we don't need `nodeToDelete.loadNext` preds[i].storeNext(i, nodeToDelete.next[i]) } nodeToDelete.mu.Unlock() unlockInt64(preds, highestLocked) atomic.AddInt64(&s.length, -1) return // true } return // false } } // Range calls f sequentially for each key and value present in the skipmap. // If f returns false, range stops the iteration. // // Range does not necessarily correspond to any consistent snapshot of the Map's // contents: no key will be visited more than once, but if the value for any key // is stored or deleted concurrently, Range may reflect any mapping for that key // from any point during the Range call. func (s *Int64Map) Range(f func(key int64, value interface{}) bool) { x := s.header.loadNext(0) for x != nil { if !x.flags.MGet(fullyLinked|marked, fullyLinked) { x = x.loadNext(0) continue } if !f(x.key, x.loadVal()) { break } x = x.loadNext(0) } } // Len return the length of this skipmap. // Keep in sync with types_gen.go:lengthFunction // Special case for code generation, Must in the tail of skipmap.go. func (s *Int64Map) Len() int { return int(atomic.LoadInt64(&s.length)) }
{ // The node is marked by another process, // the physical deletion will be accomplished by another process. nodeToDelete.mu.Unlock() return nil, false }
conditional_block
skipmap.go
// Package skipmap is a high-performance, scalable, concurrent-safe map based on skip-list. // In the typical pattern(100000 operations, 90%LOAD 9%STORE 1%DELETE, 8C16T), the skipmap // up to 10x faster than the built-in sync.Map. package skipmap import ( "sync" "sync/atomic" "unsafe" ) // Int64Map represents a map based on skip list in ascending order. type Int64Map struct { header *int64Node length int64 } type int64Node struct { key int64 value unsafe.Pointer next []*int64Node mu sync.Mutex flags bitflag }
next: make([]*int64Node, level), } n.storeVal(value) return n } func (n *int64Node) storeVal(value interface{}) { atomic.StorePointer(&n.value, unsafe.Pointer(&value)) } func (n *int64Node) loadVal() interface{} { return *(*interface{})(atomic.LoadPointer(&n.value)) } // loadNext return `n.next[i]`(atomic) func (n *int64Node) loadNext(i int) *int64Node { return (*int64Node)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&n.next[i])))) } // storeNext same with `n.next[i] = value`(atomic) func (n *int64Node) storeNext(i int, value *int64Node) { atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&n.next[i])), unsafe.Pointer(value)) } func (n *int64Node) lessthan(key int64) bool { return n.key < key } func (n *int64Node) equal(key int64) bool { return n.key == key } // NewInt64 return an empty int64 skipmap. func NewInt64() *Int64Map { h := newInt64Node(0, "", maxLevel) h.flags.SetTrue(fullyLinked) return &Int64Map{ header: h, } } // findNode takes a key and two maximal-height arrays then searches exactly as in a sequential skipmap. // The returned preds and succs always satisfy preds[i] > key >= succs[i]. // (without fullpath, if find the node will return immediately) func (s *Int64Map) findNode(key int64, preds *[maxLevel]*int64Node, succs *[maxLevel]*int64Node) *int64Node { x := s.header for i := maxLevel - 1; i >= 0; i-- { succ := x.loadNext(i) for succ != nil && succ.lessthan(key) { x = succ succ = x.loadNext(i) } preds[i] = x succs[i] = succ // Check if the key already in the skipmap. if succ != nil && succ.equal(key) { return succ } } return nil } // findNodeDelete takes a key and two maximal-height arrays then searches exactly as in a sequential skip-list. // The returned preds and succs always satisfy preds[i] > key >= succs[i]. func (s *Int64Map) findNodeDelete(key int64, preds *[maxLevel]*int64Node, succs *[maxLevel]*int64Node) int { // lFound represents the index of the first layer at which it found a node. lFound, x := -1, s.header for i := maxLevel - 1; i >= 0; i-- { succ := x.loadNext(i) for succ != nil && succ.lessthan(key) { x = succ succ = x.loadNext(i) } preds[i] = x succs[i] = succ // Check if the key already in the skip list. if lFound == -1 && succ != nil && succ.equal(key) { lFound = i } } return lFound } func unlockInt64(preds [maxLevel]*int64Node, highestLevel int) { var prevPred *int64Node for i := highestLevel; i >= 0; i-- { if preds[i] != prevPred { // the node could be unlocked by previous loop preds[i].mu.Unlock() prevPred = preds[i] } } } // Store sets the value for a key. func (s *Int64Map) Store(key int64, value interface{}) { level := randomLevel() var preds, succs [maxLevel]*int64Node for { nodeFound := s.findNode(key, &preds, &succs) if nodeFound != nil { // indicating the key is already in the skip-list if !nodeFound.flags.Get(marked) { // We don't need to care about whether or not the node is fully linked, // just replace the value. nodeFound.storeVal(value) return } // If the node is marked, represents some other goroutines is in the process of deleting this node, // we need to add this node in next loop. continue } // Add this node into skip list. var ( highestLocked = -1 // the highest level being locked by this process valid = true pred, succ, prevPred *int64Node ) for layer := 0; valid && layer < level; layer++ { pred = preds[layer] // target node's previous node succ = succs[layer] // target node's next node if pred != prevPred { // the node in this layer could be locked by previous loop pred.mu.Lock() highestLocked = layer prevPred = pred } // valid check if there is another node has inserted into the skip list in this layer during this process. // It is valid if: // 1. The previous node and next node both are not marked. // 2. The previous node's next node is succ in this layer. valid = !pred.flags.Get(marked) && (succ == nil || !succ.flags.Get(marked)) && pred.next[layer] == succ } if !valid { unlockInt64(preds, highestLocked) continue } nn := newInt64Node(key, value, level) for layer := 0; layer < level; layer++ { nn.next[layer] = succs[layer] preds[layer].storeNext(layer, nn) } nn.flags.SetTrue(fullyLinked) unlockInt64(preds, highestLocked) atomic.AddInt64(&s.length, 1) } } // Load returns the value stored in the map for a key, or nil if no // value is present. // The ok result indicates whether value was found in the map. func (s *Int64Map) Load(key int64) (value interface{}, ok bool) { x := s.header for i := maxLevel - 1; i >= 0; i-- { nex := x.loadNext(i) for nex != nil && nex.lessthan(key) { x = nex nex = x.loadNext(i) } // Check if the key already in the skip list. if nex != nil && nex.equal(key) { if nex.flags.MGet(fullyLinked|marked, fullyLinked) { return nex.loadVal(), true } return nil, false } } return nil, false } // LoadAndDelete deletes the value for a key, returning the previous value if any. // The loaded result reports whether the key was present. func (s *Int64Map) LoadAndDelete(key int64) (value interface{}, loaded bool) { var ( nodeToDelete *int64Node isMarked bool // represents if this operation mark the node topLayer = -1 preds, succs [maxLevel]*int64Node ) for { lFound := s.findNodeDelete(key, &preds, &succs) if isMarked || // this process mark this node or we can find this node in the skip list lFound != -1 && succs[lFound].flags.MGet(fullyLinked|marked, fullyLinked) && (len(succs[lFound].next)-1) == lFound { if !isMarked { // we don't mark this node for now nodeToDelete = succs[lFound] topLayer = lFound nodeToDelete.mu.Lock() if nodeToDelete.flags.Get(marked) { // The node is marked by another process, // the physical deletion will be accomplished by another process. nodeToDelete.mu.Unlock() return nil, false } nodeToDelete.flags.SetTrue(marked) isMarked = true } // Accomplish the physical deletion. var ( highestLocked = -1 // the highest level being locked by this process valid = true pred, succ, prevPred *int64Node ) for layer := 0; valid && (layer <= topLayer); layer++ { pred, succ = preds[layer], succs[layer] if pred != prevPred { // the node in this layer could be locked by previous loop pred.mu.Lock() highestLocked = layer prevPred = pred } // valid check if there is another node has inserted into the skip list in this layer // during this process, or the previous is deleted by another process. // It is valid if: // 1. the previous node exists. // 2. no another node has inserted into the skip list in this layer. valid = !pred.flags.Get(marked) && pred.next[layer] == succ } if !valid { unlockInt64(preds, highestLocked) continue } for i := topLayer; i >= 0; i-- { // Now we own the `nodeToDelete`, no other goroutine will modify it. // So we don't need `nodeToDelete.loadNext` preds[i].storeNext(i, nodeToDelete.next[i]) } nodeToDelete.mu.Unlock() unlockInt64(preds, highestLocked) atomic.AddInt64(&s.length, -1) return nodeToDelete.loadVal(), true } return nil, false } } // LoadOrStore returns the existing value for the key if present. // Otherwise, it stores and returns the given value. // The loaded result is true if the value was loaded, false if stored. func (s *Int64Map) LoadOrStore(key int64, value interface{}) (actual interface{}, loaded bool) { loadedval, ok := s.Load(key) if !ok { s.Store(key, value) return value, false } return loadedval, true } // Delete deletes the value for a key. func (s *Int64Map) Delete(key int64) { var ( nodeToDelete *int64Node isMarked bool // represents if this operation mark the node topLayer = -1 preds, succs [maxLevel]*int64Node ) for { lFound := s.findNodeDelete(key, &preds, &succs) if isMarked || // this process mark this node or we can find this node in the skip list lFound != -1 && succs[lFound].flags.MGet(fullyLinked|marked, fullyLinked) && (len(succs[lFound].next)-1) == lFound { if !isMarked { // we don't mark this node for now nodeToDelete = succs[lFound] topLayer = lFound nodeToDelete.mu.Lock() if nodeToDelete.flags.Get(marked) { // The node is marked by another process, // the physical deletion will be accomplished by another process. nodeToDelete.mu.Unlock() return // false } nodeToDelete.flags.SetTrue(marked) isMarked = true } // Accomplish the physical deletion. var ( highestLocked = -1 // the highest level being locked by this process valid = true pred, succ, prevPred *int64Node ) for layer := 0; valid && (layer <= topLayer); layer++ { pred, succ = preds[layer], succs[layer] if pred != prevPred { // the node in this layer could be locked by previous loop pred.mu.Lock() highestLocked = layer prevPred = pred } // valid check if there is another node has inserted into the skip list in this layer // during this process, or the previous is deleted by another process. // It is valid if: // 1. the previous node exists. // 2. no another node has inserted into the skip list in this layer. valid = !pred.flags.Get(marked) && pred.loadNext(layer) == succ } if !valid { unlockInt64(preds, highestLocked) continue } for i := topLayer; i >= 0; i-- { // Now we own the `nodeToDelete`, no other goroutine will modify it. // So we don't need `nodeToDelete.loadNext` preds[i].storeNext(i, nodeToDelete.next[i]) } nodeToDelete.mu.Unlock() unlockInt64(preds, highestLocked) atomic.AddInt64(&s.length, -1) return // true } return // false } } // Range calls f sequentially for each key and value present in the skipmap. // If f returns false, range stops the iteration. // // Range does not necessarily correspond to any consistent snapshot of the Map's // contents: no key will be visited more than once, but if the value for any key // is stored or deleted concurrently, Range may reflect any mapping for that key // from any point during the Range call. func (s *Int64Map) Range(f func(key int64, value interface{}) bool) { x := s.header.loadNext(0) for x != nil { if !x.flags.MGet(fullyLinked|marked, fullyLinked) { x = x.loadNext(0) continue } if !f(x.key, x.loadVal()) { break } x = x.loadNext(0) } } // Len return the length of this skipmap. // Keep in sync with types_gen.go:lengthFunction // Special case for code generation, Must in the tail of skipmap.go. func (s *Int64Map) Len() int { return int(atomic.LoadInt64(&s.length)) }
func newInt64Node(key int64, value interface{}, level int) *int64Node { n := &int64Node{ key: key,
random_line_split
lib.rs
// This component uses Sciter Engine, // copyright Terra Informatica Software, Inc. // (http://terrainformatica.com/). /*! # Rust bindings library for Sciter engine. [Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine with GPU accelerated rendering designed to render modern desktop application UI. It's a compact, single dll/dylib/so file (4-8 mb) engine without any additional dependencies. Check the [screenshot gallery](https://github.com/oskca/sciter#sciter-desktop-ui-examples) of the desktop UI examples. Sciter supports all standard elements defined in HTML5 specification [with some additions](https://sciter.com/developers/for-web-programmers/). CSS is extended to better support the Desktop UI development, e.g. flow and flex units, vertical and horizontal alignment, OS theming. [Sciter SDK](https://sciter.com/download/) comes with a demo "browser" with builtin DOM inspector, script debugger and documentation viewer: ![Sciter tools](https://sciter.com/images/sciter-tools.png) Check <https://sciter.com> website and its [documentation resources](https://sciter.com/developers/) for engine principles, architecture and more. ## Brief look: Here is a minimal sciter app: ```no_run extern crate sciter; fn main() { let mut frame = sciter::Window::new(); frame.load_file("minimal.htm"); frame.run_app(); } ``` It looks similar like this: ![Minimal sciter sample](https://i.imgur.com/ojcM5JJ.png) Check [rust-sciter/examples](https://github.com/sciter-sdk/rust-sciter/tree/master/examples) folder for more complex usage and module-level sections for the guides about: * [Window](window/index.html) creation. * [Behaviors](dom/event/index.html) and event handling. * [DOM](dom/index.html) access methods. * Sciter [Value](value/index.html) interface. */ #![doc(html_logo_url = "https://sciter.com/screenshots/slide-sciter-osx.png", html_favicon_url = "https://sciter.com/wp-content/themes/sciter/!images/favicon.ico")] // documentation test: // #![warn(missing_docs)] /* Clippy lints */ #![allow(clippy::needless_return, clippy::let_and_return)] // past habits #![allow(clippy::redundant_field_names)] // since Rust 1.17 and less readable #![allow(clippy::unreadable_literal)] // C++ SDK constants #![allow(clippy::upper_case_acronyms)]// C++ SDK constants #![allow(clippy::deprecated_semver)] // `#[deprecated(since="Sciter 4.4.3.24")]` is not a semver format. #![allow(clippy::result_unit_err)] // Sciter returns BOOL, but `Result<(), ()>` is more strict even without error description. // #![allow(clippy::cast_ptr_alignment)] // 0.0.195 only /* Macros */ #[cfg(target_os = "macos")] #[macro_use] extern crate objc; #[macro_use] extern crate lazy_static; #[macro_use] pub mod macros; mod capi; #[doc(hidden)] pub use capi::scdom::{HELEMENT}; pub use capi::scdef::{GFX_LAYER, SCRIPT_RUNTIME_FEATURES}; /* Rust interface */ mod platform; mod eventhandler; pub mod dom; pub mod graphics; pub mod host; pub mod om; pub mod request; pub mod types; pub mod utf; pub mod value; pub mod video; pub mod window; pub mod windowless; pub use dom::Element; pub use dom::event::EventHandler; pub use host::{Archive, Host, HostHandler}; pub use value::{Value, FromValue}; pub use window::Window; /// Builder pattern for window creation. See [`window::Builder`](window/struct.Builder.html) documentation. /// /// For example, /// /// ```rust,no_run /// let mut frame = sciter::WindowBuilder::main_window() /// .with_size((800,600)) /// .glassy() /// .fixed() /// .create(); /// ``` pub type WindowBuilder = window::Builder; /* Loader */ pub use capi::scapi::{ISciterAPI}; use capi::scgraphics::SciterGraphicsAPI; use capi::screquest::SciterRequestAPI; #[cfg(windows)] mod ext { // Note: // Sciter 4.x shipped with universal "sciter.dll" library for different builds: // bin/32, bin/64, bin/skia32, bin/skia64 // However it is quite inconvenient now (e.g. we can not put x64 and x86 builds in %PATH%) // #![allow(non_snake_case, non_camel_case_types)] use capi::scapi::{ISciterAPI}; use capi::sctypes::{LPCSTR, LPCVOID, BOOL}; type ApiType = *const ISciterAPI; type FuncType = extern "system" fn () -> *const ISciterAPI; pub static mut CUSTOM_DLL_PATH: Option<String> = None; extern "system" { fn LoadLibraryA(lpFileName: LPCSTR) -> LPCVOID; fn FreeLibrary(dll: LPCVOID) -> BOOL; fn GetProcAddress(hModule: LPCVOID, lpProcName: LPCSTR) -> LPCVOID; } pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::path::Path; fn try_load(path: &Path) -> Option<LPCVOID> { let path = CString::new(format!("{}", path.display())).expect("invalid library path"); let dll = unsafe { LoadLibraryA(path.as_ptr()) }; if !dll.is_null() { Some(dll) } else { None } } fn in_global() -> Option<LPCVOID> { // modern dll name let mut dll = unsafe { LoadLibraryA(b"sciter.dll\0".as_ptr() as LPCSTR) }; if dll.is_null() { // try to load with old names let alternate = if cfg!(target_arch = "x86_64") { b"sciter64.dll\0" } else { b"sciter32.dll\0" }; dll = unsafe { LoadLibraryA(alternate.as_ptr() as LPCSTR) }; } if !dll.is_null() { Some(dll) } else { None } } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_global() }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { GetProcAddress(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if !permanent { unsafe { FreeLibrary(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_arch = "x86_64") { "bin/64" } else { "bin/32" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from SDK/{}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", "sciter.dll", msg)) } pub unsafe fn SciterAPI() -> *const ISciterAPI { match try_load_library(true) { Ok(api) => api, Err(error) => panic!("{}", error), } } } #[cfg(all(feature = "dynamic", unix))] mod ext { #![allow(non_snake_case, non_camel_case_types)] extern crate libc; pub static mut CUSTOM_DLL_PATH: Option<String> = None; #[cfg(target_os = "linux")] const DLL_NAMES: &[&str] = &[ "libsciter-gtk.so" ]; // "libsciter.dylib" since Sciter 4.4.6.3. #[cfg(target_os = "macos")] const DLL_NAMES: &[&str] = &[ "libsciter.dylib", "sciter-osx-64.dylib" ]; use capi::scapi::ISciterAPI; use capi::sctypes::{LPVOID, LPCSTR}; type FuncType = extern "system" fn () -> *const ISciterAPI; type ApiType = *const ISciterAPI; pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::os::unix::ffi::OsStrExt; use std::path::{Path}; // Try to load the library from a specified absolute path. fn try_load(path: &Path) -> Option<LPVOID> { let bytes = path.as_os_str().as_bytes(); if let Ok(cstr) = CString::new(bytes) { let dll = unsafe { libc::dlopen(cstr.as_ptr(), libc::RTLD_LOCAL | libc::RTLD_LAZY) }; if !dll.is_null() { return Some(dll) } } None } // Try to find a library (by one of its names) in a specified path. fn try_load_from(dir: Option<&Path>) -> Option<LPVOID> { let dll = DLL_NAMES.iter() .map(|name| { let mut path = dir.map(Path::to_owned).unwrap_or_default(); path.push(name); path }) .map(|path| try_load(&path)) .find(|dll| dll.is_some()) .map(|o| o.unwrap()); if dll.is_some() { return dll; } None } // Try to load from the current directory. fn in_current_dir() -> Option<LPVOID> { if let Ok(dir) = ::std::env::current_exe() { if let Some(dir) = dir.parent() { let dll = try_load_from(Some(dir)); if dll.is_some() { return dll; } if cfg!(target_os = "macos") { // "(bundle folder)/Contents/Frameworks/" let mut path = dir.to_owned(); path.push("../Frameworks/libsciter.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } let mut path = dir.to_owned(); path.push("../Frameworks/sciter-osx-64.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } } } } None } // Try to load indirectly via `dlopen("dll.so")`. fn in_global() -> Option<LPVOID> { try_load_from(None) } // Try to find in $PATH. fn in_paths() -> Option<LPVOID> { use std::env; if let Some(paths) = env::var_os("PATH") { for path in env::split_paths(&paths) { if let Some(dll) = try_load_from(Some(&path)) { return Some(dll); } } } None } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_current_dir().or_else(in_paths).or_else(in_global) }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { libc::dlsym(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if !permanent { unsafe { libc::dlclose(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_os = "macos") { "bin.osx" } else { "bin.lnx" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from {}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", DLL_NAMES[0], msg)) } pub fn SciterAPI() -> *const ISciterAPI { match try_load_library(true) { Ok(api) => api, Err(error) => panic!("{}", error), } } } #[cfg(all(target_os = "linux", not(feature = "dynamic")))] mod ext { // Note: // Since 4.1.4 library name has been changed to "libsciter-gtk" (without 32/64 suffix). // Since 3.3.1.6 library name was changed to "libsciter". // However CC requires `-l sciter` form. #[link(name = "sciter-gtk")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } #[cfg(all(target_os = "macos", target_arch = "x86_64", not(feature = "dynamic")))] mod ext { #[link(name = "libsciter", kind = "dylib")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } /// Getting ISciterAPI reference, can be used for manual API calling. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { // TODO: it's not good to raise a panic inside `lazy_static!`, // because it wents into recursive panicing. // // Somehow, `cargo test --all` tests all the features, // also sometimes it comes even without `cfg!(test)`. // Well, the culprit is "examples/extensions" which uses the "extension" feature, // but how on earth it builds without `cfg(test)`? // if cfg!(test) { &*ext::SciterAPI() } else { EXT_API //.or_else(|| Some(&*ext::SciterAPI())) .expect("Sciter API is not available yet, call `sciter::set_api()` first.") } } else { &*ext::SciterAPI() } }; let abi_version = ap.version; if cfg!(feature = "windowless") { assert!(abi_version >= 0x0001_0001, "Incompatible Sciter build and \"windowless\" feature"); } if cfg!(not(feature = "windowless"))
return ap; } /// Getting ISciterAPI reference, can be used for manual API calling. /// /// Bypasses ABI compatability checks. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI_unchecked<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { EXT_API.expect("Sciter API is not available yet, call `sciter::set_api()` first.") } else { &*ext::SciterAPI() } }; return ap; } lazy_static! { static ref _API: &'static ISciterAPI = SciterAPI(); static ref _GAPI: &'static SciterGraphicsAPI = { if version_num() < 0x0401_0A00 { panic!("Graphics API is incompatible since 4.1.10 (your version is {})", version()); } unsafe { &*(SciterAPI().GetSciterGraphicsAPI)() } }; static ref _RAPI: &'static SciterRequestAPI = unsafe { &*(SciterAPI().GetSciterRequestAPI)() }; } /// Set a custom path to the Sciter dynamic library. /// /// Note: Must be called first before any other function. /// /// Returns error if the specified library can not be loaded. /// /// # Example /// /// ```rust /// if sciter::set_library("~/lib/sciter/bin.gtk/x64/libsciter-gtk.so").is_ok() { /// println!("loaded Sciter version {}", sciter::version()); /// } /// ``` pub fn set_library(custom_path: &str) -> ::std::result::Result<(), String> { #[cfg(not(feature = "dynamic"))] fn set_impl(_: &str) -> ::std::result::Result<(), String> { Err("Don't use `sciter::set_library()` in static builds.\n Build with the feature \"dynamic\" instead.".to_owned()) } #[cfg(feature = "dynamic")] fn set_impl(path: &str) -> ::std::result::Result<(), String> { unsafe { ext::CUSTOM_DLL_PATH = Some(path.to_owned()); } ext::try_load_library(false).map(|_| ()) } set_impl(custom_path) } static mut EXT_API: Option<&'static ISciterAPI> = None; /// Set the Sciter API coming from `SciterLibraryInit`. /// /// Note: Must be called first before any other function. pub fn set_host_api(api: &'static ISciterAPI) { if cfg!(feature="extension") { unsafe { EXT_API.replace(api); } } } /// Sciter engine version number (e.g. `0x03030200`). /// /// Note: does not return the `build` part because it doesn't fit in `0..255` byte range. /// Use [`sciter::version()`](fn.version.html) instead which returns the complete version string. pub fn version_num() -> u32 { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let (major, minor, revision, _build) = (v1 >> 16 & 0xFF, v1 & 0xFF, v2 >> 16 & 0xFF, v2 & 0xFF); let num = (major << 24) | (minor << 16) | (revision << 8); // let num = ((v1 >> 16) << 24) | ((v1 & 0xFFFF) << 16) | ((v2 >> 16) << 8) | (v2 & 0xFFFF); return num; } /// Sciter engine version string (e.g. "`3.3.2.0`"). pub fn version() -> String { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let num = [v1 >> 16, v1 & 0xFFFF, v2 >> 16, v2 & 0xFFFF]; let version = format!("{}.{}.{}.{}", num[0], num[1], num[2], num[3]); return version; } /// Sciter API version. /// /// Returns: /// /// * `0x0000_0001` for regular builds, `0x0001_0001` for windowless builds. /// * `0x0000_0002` since 4.4.2.14 (a breaking change in assets with [SOM builds](https://sciter.com/native-code-exposure-to-script/)) /// * `0x0000_0003` since 4.4.2.16 /// * `0x0000_0004` since 4.4.2.17 (a breaking change in SOM passport) /// * `0x0000_0005` since 4.4.3.20 (a breaking change in `INITIALIZATION_PARAMS`, SOM in event handlers fix) /// * `0x0000_0006` since 4.4.3.24 (TIScript native API is gone, use SOM instead) /// * `0x0000_0007` since 4.4.5.4 (DOM-Value conversion functions were added, no breaking change) /// * `0x0000_0008` since 4.4.6.7 (Sciter and Sciter.Lite are unified in ISciterAPI) /// * `0x0000_0009` since 4.4.7.0 (ISciterAPI unification between all platforms) /// /// Since 4.4.0.3. pub fn api_version() -> u32 { _API.version } /// Returns true for windowless builds. pub fn is_windowless() -> bool { api_version() >= 0x0001_0001 } /// Various global Sciter engine options. /// /// Used by [`sciter::set_options()`](fn.set_options.html). /// /// See also [per-window options](window/enum.Options.html). #[derive(Copy, Clone)] pub enum RuntimeOptions<'a> { /// global; value: the full path to the Sciter dynamic library (dll/dylib/so), /// must be called before any other Sciter function. LibraryPath(&'a str), /// global; value: [`GFX_LAYER`](enum.GFX_LAYER.html), must be called before any window creation. GfxLayer(GFX_LAYER), /// global; value: `true` - the engine will use a "unisex" theme that is common for all platforms. /// That UX theme is not using OS primitives for rendering input elements. /// Use it if you want exactly the same (modulo fonts) look-n-feel on all platforms. UxTheming(bool), /// global or per-window; enables Sciter Inspector for all windows, must be called before any window creation. DebugMode(bool), /// global or per-window; value: combination of [`SCRIPT_RUNTIME_FEATURES`](enum.SCRIPT_RUNTIME_FEATURES.html) flags. /// /// Note that these features have been disabled by default /// since [4.2.5.0](https://rawgit.com/c-smile/sciter-sdk/7036a9c7912ac30d9f369d9abb87b278d2d54c6d/logfile.htm). ScriptFeatures(u8), /// global; value: milliseconds, connection timeout of http client. ConnectionTimeout(u32), /// global; value: `0` - drop connection, `1` - use builtin dialog, `2` - accept connection silently. OnHttpsError(u8), // global; value: json with GPU black list, see the `gpu-blacklist.json` resource. // Not used in Sciter 4, in fact: https://sciter.com/forums/topic/how-to-use-the-gpu-blacklist/#post-59338 // GpuBlacklist(&'a str), /// global; value: script source to be loaded into each view before any other script execution. InitScript(&'a str), /// global; value - max request length in megabytes (1024*1024 bytes), since 4.3.0.15. MaxHttpDataLength(usize), /// global or per-window; value: `true` - `1px` in CSS is treated as `1dip`, otherwise `1px` is a physical pixel (by default). /// /// since [4.4.5.0](https://rawgit.com/c-smile/sciter-sdk/aafb625bb0bc317d79c0a14d02b5730f6a02b48a/logfile.htm). LogicalPixel(bool), } /// Set various global Sciter engine options, see the [`RuntimeOptions`](enum.RuntimeOptions.html). pub fn set_options(options: RuntimeOptions) -> std::result::Result<(), ()> { use RuntimeOptions::*; use capi::scdef::SCITER_RT_OPTIONS::*; let (option, value) = match options { ConnectionTimeout(ms) => (SCITER_CONNECTION_TIMEOUT, ms as usize), OnHttpsError(behavior) => (SCITER_HTTPS_ERROR, behavior as usize), // GpuBlacklist(json) => (SCITER_SET_GPU_BLACKLIST, json.as_bytes().as_ptr() as usize), InitScript(script) => (SCITER_SET_INIT_SCRIPT, script.as_bytes().as_ptr() as usize), ScriptFeatures(mask) => (SCITER_SET_SCRIPT_RUNTIME_FEATURES, mask as usize), GfxLayer(backend) => (SCITER_SET_GFX_LAYER, backend as usize), DebugMode(enable) => (SCITER_SET_DEBUG_MODE, enable as usize), UxTheming(enable) => (SCITER_SET_UX_THEMING, enable as usize), MaxHttpDataLength(value) => (SCITER_SET_MAX_HTTP_DATA_LENGTH, value), LogicalPixel(enable) => (SCITER_SET_PX_AS_DIP, enable as usize), LibraryPath(path) => { return set_library(path).map_err(|_|()); } }; let ok = (_API.SciterSetOption)(std::ptr::null_mut(), option, value); if ok != 0 { Ok(()) } else { Err(()) } } /// Set a global variable by its path to all windows. /// /// This variable will be accessible in all windows via `globalThis[path]` or just `path`. /// /// Note that this call affects only _new_ windows, /// so it's preferred to call it before the main window creation. /// /// See also per-window [`Window::set_variable`](window/struct.Window.html#method.set_variable) /// to assign a global to a single window only. pub fn set_variable(path: &str, value: Value) -> dom::Result<()> { let ws = s2u!(path); let ok = (_API.SciterSetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_cptr()); if ok == dom::SCDOM_RESULT::OK { Ok(()) } else { Err(ok) } } /// Get a global variable by its path. /// /// See the per-window [`Window::get_variable`](window/struct.Window.html#method.get_variable). #[doc(hidden)] pub fn get_variable(path: &str) -> dom::Result<Value> { let ws = s2u!(path); let mut value = Value::new(); let ok = (_API.SciterGetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_mut_ptr()); if ok == dom::SCDOM_RESULT::OK { Ok(value) } else { Err(ok) } }
{ assert!(abi_version < 0x0001_0000, "Incompatible Sciter build and \"windowless\" feature"); }
conditional_block
lib.rs
// This component uses Sciter Engine, // copyright Terra Informatica Software, Inc. // (http://terrainformatica.com/). /*! # Rust bindings library for Sciter engine. [Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine with GPU accelerated rendering designed to render modern desktop application UI. It's a compact, single dll/dylib/so file (4-8 mb) engine without any additional dependencies. Check the [screenshot gallery](https://github.com/oskca/sciter#sciter-desktop-ui-examples) of the desktop UI examples. Sciter supports all standard elements defined in HTML5 specification [with some additions](https://sciter.com/developers/for-web-programmers/). CSS is extended to better support the Desktop UI development, e.g. flow and flex units, vertical and horizontal alignment, OS theming. [Sciter SDK](https://sciter.com/download/) comes with a demo "browser" with builtin DOM inspector, script debugger and documentation viewer: ![Sciter tools](https://sciter.com/images/sciter-tools.png) Check <https://sciter.com> website and its [documentation resources](https://sciter.com/developers/) for engine principles, architecture and more. ## Brief look: Here is a minimal sciter app: ```no_run extern crate sciter; fn main() { let mut frame = sciter::Window::new(); frame.load_file("minimal.htm"); frame.run_app(); } ``` It looks similar like this: ![Minimal sciter sample](https://i.imgur.com/ojcM5JJ.png) Check [rust-sciter/examples](https://github.com/sciter-sdk/rust-sciter/tree/master/examples) folder for more complex usage and module-level sections for the guides about: * [Window](window/index.html) creation. * [Behaviors](dom/event/index.html) and event handling. * [DOM](dom/index.html) access methods. * Sciter [Value](value/index.html) interface. */ #![doc(html_logo_url = "https://sciter.com/screenshots/slide-sciter-osx.png", html_favicon_url = "https://sciter.com/wp-content/themes/sciter/!images/favicon.ico")] // documentation test: // #![warn(missing_docs)] /* Clippy lints */ #![allow(clippy::needless_return, clippy::let_and_return)] // past habits #![allow(clippy::redundant_field_names)] // since Rust 1.17 and less readable #![allow(clippy::unreadable_literal)] // C++ SDK constants #![allow(clippy::upper_case_acronyms)]// C++ SDK constants #![allow(clippy::deprecated_semver)] // `#[deprecated(since="Sciter 4.4.3.24")]` is not a semver format. #![allow(clippy::result_unit_err)] // Sciter returns BOOL, but `Result<(), ()>` is more strict even without error description. // #![allow(clippy::cast_ptr_alignment)] // 0.0.195 only /* Macros */ #[cfg(target_os = "macos")] #[macro_use] extern crate objc; #[macro_use] extern crate lazy_static; #[macro_use] pub mod macros; mod capi; #[doc(hidden)] pub use capi::scdom::{HELEMENT}; pub use capi::scdef::{GFX_LAYER, SCRIPT_RUNTIME_FEATURES}; /* Rust interface */ mod platform; mod eventhandler; pub mod dom; pub mod graphics; pub mod host; pub mod om; pub mod request; pub mod types; pub mod utf; pub mod value; pub mod video; pub mod window; pub mod windowless; pub use dom::Element; pub use dom::event::EventHandler; pub use host::{Archive, Host, HostHandler}; pub use value::{Value, FromValue}; pub use window::Window; /// Builder pattern for window creation. See [`window::Builder`](window/struct.Builder.html) documentation. /// /// For example, /// /// ```rust,no_run /// let mut frame = sciter::WindowBuilder::main_window() /// .with_size((800,600)) /// .glassy() /// .fixed() /// .create(); /// ``` pub type WindowBuilder = window::Builder; /* Loader */ pub use capi::scapi::{ISciterAPI}; use capi::scgraphics::SciterGraphicsAPI; use capi::screquest::SciterRequestAPI; #[cfg(windows)] mod ext { // Note: // Sciter 4.x shipped with universal "sciter.dll" library for different builds: // bin/32, bin/64, bin/skia32, bin/skia64 // However it is quite inconvenient now (e.g. we can not put x64 and x86 builds in %PATH%) // #![allow(non_snake_case, non_camel_case_types)] use capi::scapi::{ISciterAPI}; use capi::sctypes::{LPCSTR, LPCVOID, BOOL}; type ApiType = *const ISciterAPI; type FuncType = extern "system" fn () -> *const ISciterAPI; pub static mut CUSTOM_DLL_PATH: Option<String> = None; extern "system" { fn LoadLibraryA(lpFileName: LPCSTR) -> LPCVOID; fn FreeLibrary(dll: LPCVOID) -> BOOL; fn GetProcAddress(hModule: LPCVOID, lpProcName: LPCSTR) -> LPCVOID; } pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::path::Path; fn try_load(path: &Path) -> Option<LPCVOID> { let path = CString::new(format!("{}", path.display())).expect("invalid library path"); let dll = unsafe { LoadLibraryA(path.as_ptr()) }; if !dll.is_null() { Some(dll) } else { None } } fn in_global() -> Option<LPCVOID> { // modern dll name let mut dll = unsafe { LoadLibraryA(b"sciter.dll\0".as_ptr() as LPCSTR) }; if dll.is_null() { // try to load with old names let alternate = if cfg!(target_arch = "x86_64") { b"sciter64.dll\0" } else { b"sciter32.dll\0" }; dll = unsafe { LoadLibraryA(alternate.as_ptr() as LPCSTR) }; } if !dll.is_null() { Some(dll) } else { None } } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_global() }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { GetProcAddress(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if !permanent { unsafe { FreeLibrary(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_arch = "x86_64") { "bin/64" } else { "bin/32" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from SDK/{}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", "sciter.dll", msg)) } pub unsafe fn SciterAPI() -> *const ISciterAPI { match try_load_library(true) { Ok(api) => api, Err(error) => panic!("{}", error), } } } #[cfg(all(feature = "dynamic", unix))] mod ext { #![allow(non_snake_case, non_camel_case_types)] extern crate libc; pub static mut CUSTOM_DLL_PATH: Option<String> = None; #[cfg(target_os = "linux")] const DLL_NAMES: &[&str] = &[ "libsciter-gtk.so" ]; // "libsciter.dylib" since Sciter 4.4.6.3. #[cfg(target_os = "macos")] const DLL_NAMES: &[&str] = &[ "libsciter.dylib", "sciter-osx-64.dylib" ]; use capi::scapi::ISciterAPI; use capi::sctypes::{LPVOID, LPCSTR}; type FuncType = extern "system" fn () -> *const ISciterAPI; type ApiType = *const ISciterAPI; pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::os::unix::ffi::OsStrExt; use std::path::{Path}; // Try to load the library from a specified absolute path. fn try_load(path: &Path) -> Option<LPVOID> { let bytes = path.as_os_str().as_bytes(); if let Ok(cstr) = CString::new(bytes) { let dll = unsafe { libc::dlopen(cstr.as_ptr(), libc::RTLD_LOCAL | libc::RTLD_LAZY) }; if !dll.is_null() { return Some(dll) } } None } // Try to find a library (by one of its names) in a specified path. fn try_load_from(dir: Option<&Path>) -> Option<LPVOID> { let dll = DLL_NAMES.iter() .map(|name| { let mut path = dir.map(Path::to_owned).unwrap_or_default(); path.push(name); path }) .map(|path| try_load(&path)) .find(|dll| dll.is_some()) .map(|o| o.unwrap()); if dll.is_some() { return dll; } None } // Try to load from the current directory. fn in_current_dir() -> Option<LPVOID> { if let Ok(dir) = ::std::env::current_exe() { if let Some(dir) = dir.parent() { let dll = try_load_from(Some(dir)); if dll.is_some() { return dll; } if cfg!(target_os = "macos") { // "(bundle folder)/Contents/Frameworks/" let mut path = dir.to_owned(); path.push("../Frameworks/libsciter.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } let mut path = dir.to_owned(); path.push("../Frameworks/sciter-osx-64.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } } } } None } // Try to load indirectly via `dlopen("dll.so")`. fn in_global() -> Option<LPVOID> { try_load_from(None) } // Try to find in $PATH. fn in_paths() -> Option<LPVOID> { use std::env; if let Some(paths) = env::var_os("PATH") { for path in env::split_paths(&paths) { if let Some(dll) = try_load_from(Some(&path)) { return Some(dll); } } } None } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_current_dir().or_else(in_paths).or_else(in_global) }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { libc::dlsym(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if !permanent { unsafe { libc::dlclose(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_os = "macos") { "bin.osx" } else { "bin.lnx" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from {}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", DLL_NAMES[0], msg)) } pub fn SciterAPI() -> *const ISciterAPI { match try_load_library(true) { Ok(api) => api, Err(error) => panic!("{}", error), } } } #[cfg(all(target_os = "linux", not(feature = "dynamic")))] mod ext { // Note: // Since 4.1.4 library name has been changed to "libsciter-gtk" (without 32/64 suffix). // Since 3.3.1.6 library name was changed to "libsciter". // However CC requires `-l sciter` form. #[link(name = "sciter-gtk")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } #[cfg(all(target_os = "macos", target_arch = "x86_64", not(feature = "dynamic")))] mod ext { #[link(name = "libsciter", kind = "dylib")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } /// Getting ISciterAPI reference, can be used for manual API calling. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { // TODO: it's not good to raise a panic inside `lazy_static!`, // because it wents into recursive panicing. // // Somehow, `cargo test --all` tests all the features, // also sometimes it comes even without `cfg!(test)`. // Well, the culprit is "examples/extensions" which uses the "extension" feature, // but how on earth it builds without `cfg(test)`? // if cfg!(test) { &*ext::SciterAPI() } else { EXT_API //.or_else(|| Some(&*ext::SciterAPI())) .expect("Sciter API is not available yet, call `sciter::set_api()` first.") } } else { &*ext::SciterAPI() } }; let abi_version = ap.version; if cfg!(feature = "windowless") { assert!(abi_version >= 0x0001_0001, "Incompatible Sciter build and \"windowless\" feature"); } if cfg!(not(feature = "windowless")) { assert!(abi_version < 0x0001_0000, "Incompatible Sciter build and \"windowless\" feature"); } return ap; } /// Getting ISciterAPI reference, can be used for manual API calling. /// /// Bypasses ABI compatability checks. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI_unchecked<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { EXT_API.expect("Sciter API is not available yet, call `sciter::set_api()` first.") } else { &*ext::SciterAPI() } }; return ap; } lazy_static! { static ref _API: &'static ISciterAPI = SciterAPI(); static ref _GAPI: &'static SciterGraphicsAPI = { if version_num() < 0x0401_0A00 { panic!("Graphics API is incompatible since 4.1.10 (your version is {})", version()); } unsafe { &*(SciterAPI().GetSciterGraphicsAPI)() } }; static ref _RAPI: &'static SciterRequestAPI = unsafe { &*(SciterAPI().GetSciterRequestAPI)() }; } /// Set a custom path to the Sciter dynamic library. /// /// Note: Must be called first before any other function. /// /// Returns error if the specified library can not be loaded. /// /// # Example /// /// ```rust /// if sciter::set_library("~/lib/sciter/bin.gtk/x64/libsciter-gtk.so").is_ok() { /// println!("loaded Sciter version {}", sciter::version()); /// } /// ``` pub fn set_library(custom_path: &str) -> ::std::result::Result<(), String> { #[cfg(not(feature = "dynamic"))] fn set_impl(_: &str) -> ::std::result::Result<(), String> { Err("Don't use `sciter::set_library()` in static builds.\n Build with the feature \"dynamic\" instead.".to_owned()) } #[cfg(feature = "dynamic")] fn set_impl(path: &str) -> ::std::result::Result<(), String> { unsafe { ext::CUSTOM_DLL_PATH = Some(path.to_owned()); } ext::try_load_library(false).map(|_| ()) } set_impl(custom_path) } static mut EXT_API: Option<&'static ISciterAPI> = None; /// Set the Sciter API coming from `SciterLibraryInit`. /// /// Note: Must be called first before any other function. pub fn set_host_api(api: &'static ISciterAPI) { if cfg!(feature="extension") { unsafe { EXT_API.replace(api); } } } /// Sciter engine version number (e.g. `0x03030200`). /// /// Note: does not return the `build` part because it doesn't fit in `0..255` byte range. /// Use [`sciter::version()`](fn.version.html) instead which returns the complete version string. pub fn version_num() -> u32 { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let (major, minor, revision, _build) = (v1 >> 16 & 0xFF, v1 & 0xFF, v2 >> 16 & 0xFF, v2 & 0xFF); let num = (major << 24) | (minor << 16) | (revision << 8); // let num = ((v1 >> 16) << 24) | ((v1 & 0xFFFF) << 16) | ((v2 >> 16) << 8) | (v2 & 0xFFFF); return num; } /// Sciter engine version string (e.g. "`3.3.2.0`"). pub fn version() -> String { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let num = [v1 >> 16, v1 & 0xFFFF, v2 >> 16, v2 & 0xFFFF]; let version = format!("{}.{}.{}.{}", num[0], num[1], num[2], num[3]); return version; } /// Sciter API version. /// /// Returns: /// /// * `0x0000_0001` for regular builds, `0x0001_0001` for windowless builds. /// * `0x0000_0002` since 4.4.2.14 (a breaking change in assets with [SOM builds](https://sciter.com/native-code-exposure-to-script/)) /// * `0x0000_0003` since 4.4.2.16 /// * `0x0000_0004` since 4.4.2.17 (a breaking change in SOM passport) /// * `0x0000_0005` since 4.4.3.20 (a breaking change in `INITIALIZATION_PARAMS`, SOM in event handlers fix) /// * `0x0000_0006` since 4.4.3.24 (TIScript native API is gone, use SOM instead) /// * `0x0000_0007` since 4.4.5.4 (DOM-Value conversion functions were added, no breaking change) /// * `0x0000_0008` since 4.4.6.7 (Sciter and Sciter.Lite are unified in ISciterAPI) /// * `0x0000_0009` since 4.4.7.0 (ISciterAPI unification between all platforms) /// /// Since 4.4.0.3. pub fn api_version() -> u32 { _API.version } /// Returns true for windowless builds. pub fn is_windowless() -> bool { api_version() >= 0x0001_0001 } /// Various global Sciter engine options. /// /// Used by [`sciter::set_options()`](fn.set_options.html). /// /// See also [per-window options](window/enum.Options.html). #[derive(Copy, Clone)] pub enum RuntimeOptions<'a> { /// global; value: the full path to the Sciter dynamic library (dll/dylib/so), /// must be called before any other Sciter function. LibraryPath(&'a str), /// global; value: [`GFX_LAYER`](enum.GFX_LAYER.html), must be called before any window creation. GfxLayer(GFX_LAYER), /// global; value: `true` - the engine will use a "unisex" theme that is common for all platforms. /// That UX theme is not using OS primitives for rendering input elements. /// Use it if you want exactly the same (modulo fonts) look-n-feel on all platforms. UxTheming(bool), /// global or per-window; enables Sciter Inspector for all windows, must be called before any window creation. DebugMode(bool), /// global or per-window; value: combination of [`SCRIPT_RUNTIME_FEATURES`](enum.SCRIPT_RUNTIME_FEATURES.html) flags. /// /// Note that these features have been disabled by default /// since [4.2.5.0](https://rawgit.com/c-smile/sciter-sdk/7036a9c7912ac30d9f369d9abb87b278d2d54c6d/logfile.htm). ScriptFeatures(u8), /// global; value: milliseconds, connection timeout of http client. ConnectionTimeout(u32), /// global; value: `0` - drop connection, `1` - use builtin dialog, `2` - accept connection silently. OnHttpsError(u8), // global; value: json with GPU black list, see the `gpu-blacklist.json` resource. // Not used in Sciter 4, in fact: https://sciter.com/forums/topic/how-to-use-the-gpu-blacklist/#post-59338 // GpuBlacklist(&'a str), /// global; value: script source to be loaded into each view before any other script execution. InitScript(&'a str), /// global; value - max request length in megabytes (1024*1024 bytes), since 4.3.0.15. MaxHttpDataLength(usize), /// global or per-window; value: `true` - `1px` in CSS is treated as `1dip`, otherwise `1px` is a physical pixel (by default). /// /// since [4.4.5.0](https://rawgit.com/c-smile/sciter-sdk/aafb625bb0bc317d79c0a14d02b5730f6a02b48a/logfile.htm). LogicalPixel(bool), } /// Set various global Sciter engine options, see the [`RuntimeOptions`](enum.RuntimeOptions.html). pub fn set_options(options: RuntimeOptions) -> std::result::Result<(), ()> { use RuntimeOptions::*; use capi::scdef::SCITER_RT_OPTIONS::*; let (option, value) = match options { ConnectionTimeout(ms) => (SCITER_CONNECTION_TIMEOUT, ms as usize), OnHttpsError(behavior) => (SCITER_HTTPS_ERROR, behavior as usize), // GpuBlacklist(json) => (SCITER_SET_GPU_BLACKLIST, json.as_bytes().as_ptr() as usize), InitScript(script) => (SCITER_SET_INIT_SCRIPT, script.as_bytes().as_ptr() as usize), ScriptFeatures(mask) => (SCITER_SET_SCRIPT_RUNTIME_FEATURES, mask as usize), GfxLayer(backend) => (SCITER_SET_GFX_LAYER, backend as usize), DebugMode(enable) => (SCITER_SET_DEBUG_MODE, enable as usize), UxTheming(enable) => (SCITER_SET_UX_THEMING, enable as usize), MaxHttpDataLength(value) => (SCITER_SET_MAX_HTTP_DATA_LENGTH, value), LogicalPixel(enable) => (SCITER_SET_PX_AS_DIP, enable as usize), LibraryPath(path) => { return set_library(path).map_err(|_|()); } }; let ok = (_API.SciterSetOption)(std::ptr::null_mut(), option, value); if ok != 0 { Ok(()) } else { Err(()) } } /// Set a global variable by its path to all windows. /// /// This variable will be accessible in all windows via `globalThis[path]` or just `path`. /// /// Note that this call affects only _new_ windows, /// so it's preferred to call it before the main window creation. /// /// See also per-window [`Window::set_variable`](window/struct.Window.html#method.set_variable) /// to assign a global to a single window only. pub fn set_variable(path: &str, value: Value) -> dom::Result<()>
/// Get a global variable by its path. /// /// See the per-window [`Window::get_variable`](window/struct.Window.html#method.get_variable). #[doc(hidden)] pub fn get_variable(path: &str) -> dom::Result<Value> { let ws = s2u!(path); let mut value = Value::new(); let ok = (_API.SciterGetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_mut_ptr()); if ok == dom::SCDOM_RESULT::OK { Ok(value) } else { Err(ok) } }
{ let ws = s2u!(path); let ok = (_API.SciterSetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_cptr()); if ok == dom::SCDOM_RESULT::OK { Ok(()) } else { Err(ok) } }
identifier_body
lib.rs
// This component uses Sciter Engine, // copyright Terra Informatica Software, Inc. // (http://terrainformatica.com/). /*! # Rust bindings library for Sciter engine. [Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine with GPU accelerated rendering designed to render modern desktop application UI. It's a compact, single dll/dylib/so file (4-8 mb) engine without any additional dependencies. Check the [screenshot gallery](https://github.com/oskca/sciter#sciter-desktop-ui-examples) of the desktop UI examples. Sciter supports all standard elements defined in HTML5 specification [with some additions](https://sciter.com/developers/for-web-programmers/). CSS is extended to better support the Desktop UI development, e.g. flow and flex units, vertical and horizontal alignment, OS theming. [Sciter SDK](https://sciter.com/download/) comes with a demo "browser" with builtin DOM inspector, script debugger and documentation viewer: ![Sciter tools](https://sciter.com/images/sciter-tools.png) Check <https://sciter.com> website and its [documentation resources](https://sciter.com/developers/) for engine principles, architecture and more. ## Brief look: Here is a minimal sciter app: ```no_run extern crate sciter; fn main() { let mut frame = sciter::Window::new(); frame.load_file("minimal.htm"); frame.run_app(); } ``` It looks similar like this: ![Minimal sciter sample](https://i.imgur.com/ojcM5JJ.png) Check [rust-sciter/examples](https://github.com/sciter-sdk/rust-sciter/tree/master/examples) folder for more complex usage and module-level sections for the guides about: * [Window](window/index.html) creation. * [Behaviors](dom/event/index.html) and event handling. * [DOM](dom/index.html) access methods. * Sciter [Value](value/index.html) interface. */ #![doc(html_logo_url = "https://sciter.com/screenshots/slide-sciter-osx.png", html_favicon_url = "https://sciter.com/wp-content/themes/sciter/!images/favicon.ico")] // documentation test: // #![warn(missing_docs)] /* Clippy lints */ #![allow(clippy::needless_return, clippy::let_and_return)] // past habits #![allow(clippy::redundant_field_names)] // since Rust 1.17 and less readable #![allow(clippy::unreadable_literal)] // C++ SDK constants #![allow(clippy::upper_case_acronyms)]// C++ SDK constants #![allow(clippy::deprecated_semver)] // `#[deprecated(since="Sciter 4.4.3.24")]` is not a semver format. #![allow(clippy::result_unit_err)] // Sciter returns BOOL, but `Result<(), ()>` is more strict even without error description. // #![allow(clippy::cast_ptr_alignment)] // 0.0.195 only /* Macros */ #[cfg(target_os = "macos")] #[macro_use] extern crate objc; #[macro_use] extern crate lazy_static; #[macro_use] pub mod macros; mod capi; #[doc(hidden)] pub use capi::scdom::{HELEMENT}; pub use capi::scdef::{GFX_LAYER, SCRIPT_RUNTIME_FEATURES}; /* Rust interface */ mod platform; mod eventhandler; pub mod dom; pub mod graphics; pub mod host; pub mod om; pub mod request; pub mod types; pub mod utf; pub mod value; pub mod video; pub mod window; pub mod windowless; pub use dom::Element; pub use dom::event::EventHandler; pub use host::{Archive, Host, HostHandler}; pub use value::{Value, FromValue}; pub use window::Window; /// Builder pattern for window creation. See [`window::Builder`](window/struct.Builder.html) documentation. /// /// For example, /// /// ```rust,no_run /// let mut frame = sciter::WindowBuilder::main_window() /// .with_size((800,600)) /// .glassy() /// .fixed() /// .create(); /// ``` pub type WindowBuilder = window::Builder; /* Loader */ pub use capi::scapi::{ISciterAPI}; use capi::scgraphics::SciterGraphicsAPI; use capi::screquest::SciterRequestAPI; #[cfg(windows)] mod ext { // Note: // Sciter 4.x shipped with universal "sciter.dll" library for different builds: // bin/32, bin/64, bin/skia32, bin/skia64 // However it is quite inconvenient now (e.g. we can not put x64 and x86 builds in %PATH%) // #![allow(non_snake_case, non_camel_case_types)] use capi::scapi::{ISciterAPI}; use capi::sctypes::{LPCSTR, LPCVOID, BOOL}; type ApiType = *const ISciterAPI; type FuncType = extern "system" fn () -> *const ISciterAPI; pub static mut CUSTOM_DLL_PATH: Option<String> = None; extern "system" { fn LoadLibraryA(lpFileName: LPCSTR) -> LPCVOID; fn FreeLibrary(dll: LPCVOID) -> BOOL; fn GetProcAddress(hModule: LPCVOID, lpProcName: LPCSTR) -> LPCVOID; } pub fn
(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::path::Path; fn try_load(path: &Path) -> Option<LPCVOID> { let path = CString::new(format!("{}", path.display())).expect("invalid library path"); let dll = unsafe { LoadLibraryA(path.as_ptr()) }; if !dll.is_null() { Some(dll) } else { None } } fn in_global() -> Option<LPCVOID> { // modern dll name let mut dll = unsafe { LoadLibraryA(b"sciter.dll\0".as_ptr() as LPCSTR) }; if dll.is_null() { // try to load with old names let alternate = if cfg!(target_arch = "x86_64") { b"sciter64.dll\0" } else { b"sciter32.dll\0" }; dll = unsafe { LoadLibraryA(alternate.as_ptr() as LPCSTR) }; } if !dll.is_null() { Some(dll) } else { None } } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_global() }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { GetProcAddress(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if !permanent { unsafe { FreeLibrary(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_arch = "x86_64") { "bin/64" } else { "bin/32" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from SDK/{}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", "sciter.dll", msg)) } pub unsafe fn SciterAPI() -> *const ISciterAPI { match try_load_library(true) { Ok(api) => api, Err(error) => panic!("{}", error), } } } #[cfg(all(feature = "dynamic", unix))] mod ext { #![allow(non_snake_case, non_camel_case_types)] extern crate libc; pub static mut CUSTOM_DLL_PATH: Option<String> = None; #[cfg(target_os = "linux")] const DLL_NAMES: &[&str] = &[ "libsciter-gtk.so" ]; // "libsciter.dylib" since Sciter 4.4.6.3. #[cfg(target_os = "macos")] const DLL_NAMES: &[&str] = &[ "libsciter.dylib", "sciter-osx-64.dylib" ]; use capi::scapi::ISciterAPI; use capi::sctypes::{LPVOID, LPCSTR}; type FuncType = extern "system" fn () -> *const ISciterAPI; type ApiType = *const ISciterAPI; pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::os::unix::ffi::OsStrExt; use std::path::{Path}; // Try to load the library from a specified absolute path. fn try_load(path: &Path) -> Option<LPVOID> { let bytes = path.as_os_str().as_bytes(); if let Ok(cstr) = CString::new(bytes) { let dll = unsafe { libc::dlopen(cstr.as_ptr(), libc::RTLD_LOCAL | libc::RTLD_LAZY) }; if !dll.is_null() { return Some(dll) } } None } // Try to find a library (by one of its names) in a specified path. fn try_load_from(dir: Option<&Path>) -> Option<LPVOID> { let dll = DLL_NAMES.iter() .map(|name| { let mut path = dir.map(Path::to_owned).unwrap_or_default(); path.push(name); path }) .map(|path| try_load(&path)) .find(|dll| dll.is_some()) .map(|o| o.unwrap()); if dll.is_some() { return dll; } None } // Try to load from the current directory. fn in_current_dir() -> Option<LPVOID> { if let Ok(dir) = ::std::env::current_exe() { if let Some(dir) = dir.parent() { let dll = try_load_from(Some(dir)); if dll.is_some() { return dll; } if cfg!(target_os = "macos") { // "(bundle folder)/Contents/Frameworks/" let mut path = dir.to_owned(); path.push("../Frameworks/libsciter.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } let mut path = dir.to_owned(); path.push("../Frameworks/sciter-osx-64.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } } } } None } // Try to load indirectly via `dlopen("dll.so")`. fn in_global() -> Option<LPVOID> { try_load_from(None) } // Try to find in $PATH. fn in_paths() -> Option<LPVOID> { use std::env; if let Some(paths) = env::var_os("PATH") { for path in env::split_paths(&paths) { if let Some(dll) = try_load_from(Some(&path)) { return Some(dll); } } } None } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_current_dir().or_else(in_paths).or_else(in_global) }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { libc::dlsym(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if !permanent { unsafe { libc::dlclose(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_os = "macos") { "bin.osx" } else { "bin.lnx" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from {}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", DLL_NAMES[0], msg)) } pub fn SciterAPI() -> *const ISciterAPI { match try_load_library(true) { Ok(api) => api, Err(error) => panic!("{}", error), } } } #[cfg(all(target_os = "linux", not(feature = "dynamic")))] mod ext { // Note: // Since 4.1.4 library name has been changed to "libsciter-gtk" (without 32/64 suffix). // Since 3.3.1.6 library name was changed to "libsciter". // However CC requires `-l sciter` form. #[link(name = "sciter-gtk")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } #[cfg(all(target_os = "macos", target_arch = "x86_64", not(feature = "dynamic")))] mod ext { #[link(name = "libsciter", kind = "dylib")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } /// Getting ISciterAPI reference, can be used for manual API calling. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { // TODO: it's not good to raise a panic inside `lazy_static!`, // because it wents into recursive panicing. // // Somehow, `cargo test --all` tests all the features, // also sometimes it comes even without `cfg!(test)`. // Well, the culprit is "examples/extensions" which uses the "extension" feature, // but how on earth it builds without `cfg(test)`? // if cfg!(test) { &*ext::SciterAPI() } else { EXT_API //.or_else(|| Some(&*ext::SciterAPI())) .expect("Sciter API is not available yet, call `sciter::set_api()` first.") } } else { &*ext::SciterAPI() } }; let abi_version = ap.version; if cfg!(feature = "windowless") { assert!(abi_version >= 0x0001_0001, "Incompatible Sciter build and \"windowless\" feature"); } if cfg!(not(feature = "windowless")) { assert!(abi_version < 0x0001_0000, "Incompatible Sciter build and \"windowless\" feature"); } return ap; } /// Getting ISciterAPI reference, can be used for manual API calling. /// /// Bypasses ABI compatability checks. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI_unchecked<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { EXT_API.expect("Sciter API is not available yet, call `sciter::set_api()` first.") } else { &*ext::SciterAPI() } }; return ap; } lazy_static! { static ref _API: &'static ISciterAPI = SciterAPI(); static ref _GAPI: &'static SciterGraphicsAPI = { if version_num() < 0x0401_0A00 { panic!("Graphics API is incompatible since 4.1.10 (your version is {})", version()); } unsafe { &*(SciterAPI().GetSciterGraphicsAPI)() } }; static ref _RAPI: &'static SciterRequestAPI = unsafe { &*(SciterAPI().GetSciterRequestAPI)() }; } /// Set a custom path to the Sciter dynamic library. /// /// Note: Must be called first before any other function. /// /// Returns error if the specified library can not be loaded. /// /// # Example /// /// ```rust /// if sciter::set_library("~/lib/sciter/bin.gtk/x64/libsciter-gtk.so").is_ok() { /// println!("loaded Sciter version {}", sciter::version()); /// } /// ``` pub fn set_library(custom_path: &str) -> ::std::result::Result<(), String> { #[cfg(not(feature = "dynamic"))] fn set_impl(_: &str) -> ::std::result::Result<(), String> { Err("Don't use `sciter::set_library()` in static builds.\n Build with the feature \"dynamic\" instead.".to_owned()) } #[cfg(feature = "dynamic")] fn set_impl(path: &str) -> ::std::result::Result<(), String> { unsafe { ext::CUSTOM_DLL_PATH = Some(path.to_owned()); } ext::try_load_library(false).map(|_| ()) } set_impl(custom_path) } static mut EXT_API: Option<&'static ISciterAPI> = None; /// Set the Sciter API coming from `SciterLibraryInit`. /// /// Note: Must be called first before any other function. pub fn set_host_api(api: &'static ISciterAPI) { if cfg!(feature="extension") { unsafe { EXT_API.replace(api); } } } /// Sciter engine version number (e.g. `0x03030200`). /// /// Note: does not return the `build` part because it doesn't fit in `0..255` byte range. /// Use [`sciter::version()`](fn.version.html) instead which returns the complete version string. pub fn version_num() -> u32 { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let (major, minor, revision, _build) = (v1 >> 16 & 0xFF, v1 & 0xFF, v2 >> 16 & 0xFF, v2 & 0xFF); let num = (major << 24) | (minor << 16) | (revision << 8); // let num = ((v1 >> 16) << 24) | ((v1 & 0xFFFF) << 16) | ((v2 >> 16) << 8) | (v2 & 0xFFFF); return num; } /// Sciter engine version string (e.g. "`3.3.2.0`"). pub fn version() -> String { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let num = [v1 >> 16, v1 & 0xFFFF, v2 >> 16, v2 & 0xFFFF]; let version = format!("{}.{}.{}.{}", num[0], num[1], num[2], num[3]); return version; } /// Sciter API version. /// /// Returns: /// /// * `0x0000_0001` for regular builds, `0x0001_0001` for windowless builds. /// * `0x0000_0002` since 4.4.2.14 (a breaking change in assets with [SOM builds](https://sciter.com/native-code-exposure-to-script/)) /// * `0x0000_0003` since 4.4.2.16 /// * `0x0000_0004` since 4.4.2.17 (a breaking change in SOM passport) /// * `0x0000_0005` since 4.4.3.20 (a breaking change in `INITIALIZATION_PARAMS`, SOM in event handlers fix) /// * `0x0000_0006` since 4.4.3.24 (TIScript native API is gone, use SOM instead) /// * `0x0000_0007` since 4.4.5.4 (DOM-Value conversion functions were added, no breaking change) /// * `0x0000_0008` since 4.4.6.7 (Sciter and Sciter.Lite are unified in ISciterAPI) /// * `0x0000_0009` since 4.4.7.0 (ISciterAPI unification between all platforms) /// /// Since 4.4.0.3. pub fn api_version() -> u32 { _API.version } /// Returns true for windowless builds. pub fn is_windowless() -> bool { api_version() >= 0x0001_0001 } /// Various global Sciter engine options. /// /// Used by [`sciter::set_options()`](fn.set_options.html). /// /// See also [per-window options](window/enum.Options.html). #[derive(Copy, Clone)] pub enum RuntimeOptions<'a> { /// global; value: the full path to the Sciter dynamic library (dll/dylib/so), /// must be called before any other Sciter function. LibraryPath(&'a str), /// global; value: [`GFX_LAYER`](enum.GFX_LAYER.html), must be called before any window creation. GfxLayer(GFX_LAYER), /// global; value: `true` - the engine will use a "unisex" theme that is common for all platforms. /// That UX theme is not using OS primitives for rendering input elements. /// Use it if you want exactly the same (modulo fonts) look-n-feel on all platforms. UxTheming(bool), /// global or per-window; enables Sciter Inspector for all windows, must be called before any window creation. DebugMode(bool), /// global or per-window; value: combination of [`SCRIPT_RUNTIME_FEATURES`](enum.SCRIPT_RUNTIME_FEATURES.html) flags. /// /// Note that these features have been disabled by default /// since [4.2.5.0](https://rawgit.com/c-smile/sciter-sdk/7036a9c7912ac30d9f369d9abb87b278d2d54c6d/logfile.htm). ScriptFeatures(u8), /// global; value: milliseconds, connection timeout of http client. ConnectionTimeout(u32), /// global; value: `0` - drop connection, `1` - use builtin dialog, `2` - accept connection silently. OnHttpsError(u8), // global; value: json with GPU black list, see the `gpu-blacklist.json` resource. // Not used in Sciter 4, in fact: https://sciter.com/forums/topic/how-to-use-the-gpu-blacklist/#post-59338 // GpuBlacklist(&'a str), /// global; value: script source to be loaded into each view before any other script execution. InitScript(&'a str), /// global; value - max request length in megabytes (1024*1024 bytes), since 4.3.0.15. MaxHttpDataLength(usize), /// global or per-window; value: `true` - `1px` in CSS is treated as `1dip`, otherwise `1px` is a physical pixel (by default). /// /// since [4.4.5.0](https://rawgit.com/c-smile/sciter-sdk/aafb625bb0bc317d79c0a14d02b5730f6a02b48a/logfile.htm). LogicalPixel(bool), } /// Set various global Sciter engine options, see the [`RuntimeOptions`](enum.RuntimeOptions.html). pub fn set_options(options: RuntimeOptions) -> std::result::Result<(), ()> { use RuntimeOptions::*; use capi::scdef::SCITER_RT_OPTIONS::*; let (option, value) = match options { ConnectionTimeout(ms) => (SCITER_CONNECTION_TIMEOUT, ms as usize), OnHttpsError(behavior) => (SCITER_HTTPS_ERROR, behavior as usize), // GpuBlacklist(json) => (SCITER_SET_GPU_BLACKLIST, json.as_bytes().as_ptr() as usize), InitScript(script) => (SCITER_SET_INIT_SCRIPT, script.as_bytes().as_ptr() as usize), ScriptFeatures(mask) => (SCITER_SET_SCRIPT_RUNTIME_FEATURES, mask as usize), GfxLayer(backend) => (SCITER_SET_GFX_LAYER, backend as usize), DebugMode(enable) => (SCITER_SET_DEBUG_MODE, enable as usize), UxTheming(enable) => (SCITER_SET_UX_THEMING, enable as usize), MaxHttpDataLength(value) => (SCITER_SET_MAX_HTTP_DATA_LENGTH, value), LogicalPixel(enable) => (SCITER_SET_PX_AS_DIP, enable as usize), LibraryPath(path) => { return set_library(path).map_err(|_|()); } }; let ok = (_API.SciterSetOption)(std::ptr::null_mut(), option, value); if ok != 0 { Ok(()) } else { Err(()) } } /// Set a global variable by its path to all windows. /// /// This variable will be accessible in all windows via `globalThis[path]` or just `path`. /// /// Note that this call affects only _new_ windows, /// so it's preferred to call it before the main window creation. /// /// See also per-window [`Window::set_variable`](window/struct.Window.html#method.set_variable) /// to assign a global to a single window only. pub fn set_variable(path: &str, value: Value) -> dom::Result<()> { let ws = s2u!(path); let ok = (_API.SciterSetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_cptr()); if ok == dom::SCDOM_RESULT::OK { Ok(()) } else { Err(ok) } } /// Get a global variable by its path. /// /// See the per-window [`Window::get_variable`](window/struct.Window.html#method.get_variable). #[doc(hidden)] pub fn get_variable(path: &str) -> dom::Result<Value> { let ws = s2u!(path); let mut value = Value::new(); let ok = (_API.SciterGetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_mut_ptr()); if ok == dom::SCDOM_RESULT::OK { Ok(value) } else { Err(ok) } }
try_load_library
identifier_name
lib.rs
// This component uses Sciter Engine, // copyright Terra Informatica Software, Inc. // (http://terrainformatica.com/). /*! # Rust bindings library for Sciter engine. [Sciter](http://sciter.com) is an embeddable [multiplatform](https://sciter.com/sciter/crossplatform/) HTML/CSS/script engine with GPU accelerated rendering designed to render modern desktop application UI. It's a compact, single dll/dylib/so file (4-8 mb) engine without any additional dependencies. Check the [screenshot gallery](https://github.com/oskca/sciter#sciter-desktop-ui-examples) of the desktop UI examples. Sciter supports all standard elements defined in HTML5 specification [with some additions](https://sciter.com/developers/for-web-programmers/). CSS is extended to better support the Desktop UI development, e.g. flow and flex units, vertical and horizontal alignment, OS theming. [Sciter SDK](https://sciter.com/download/) comes with a demo "browser" with builtin DOM inspector, script debugger and documentation viewer: ![Sciter tools](https://sciter.com/images/sciter-tools.png) Check <https://sciter.com> website and its [documentation resources](https://sciter.com/developers/) for engine principles, architecture and more. ## Brief look: Here is a minimal sciter app: ```no_run extern crate sciter; fn main() { let mut frame = sciter::Window::new(); frame.load_file("minimal.htm"); frame.run_app(); } ``` It looks similar like this: ![Minimal sciter sample](https://i.imgur.com/ojcM5JJ.png) Check [rust-sciter/examples](https://github.com/sciter-sdk/rust-sciter/tree/master/examples) folder for more complex usage and module-level sections for the guides about: * [Window](window/index.html) creation. * [Behaviors](dom/event/index.html) and event handling. * [DOM](dom/index.html) access methods. * Sciter [Value](value/index.html) interface. */ #![doc(html_logo_url = "https://sciter.com/screenshots/slide-sciter-osx.png", html_favicon_url = "https://sciter.com/wp-content/themes/sciter/!images/favicon.ico")] // documentation test: // #![warn(missing_docs)] /* Clippy lints */ #![allow(clippy::needless_return, clippy::let_and_return)] // past habits #![allow(clippy::redundant_field_names)] // since Rust 1.17 and less readable #![allow(clippy::unreadable_literal)] // C++ SDK constants #![allow(clippy::upper_case_acronyms)]// C++ SDK constants #![allow(clippy::deprecated_semver)] // `#[deprecated(since="Sciter 4.4.3.24")]` is not a semver format. #![allow(clippy::result_unit_err)] // Sciter returns BOOL, but `Result<(), ()>` is more strict even without error description. // #![allow(clippy::cast_ptr_alignment)] // 0.0.195 only /* Macros */ #[cfg(target_os = "macos")] #[macro_use] extern crate objc; #[macro_use] extern crate lazy_static; #[macro_use] pub mod macros; mod capi; #[doc(hidden)] pub use capi::scdom::{HELEMENT}; pub use capi::scdef::{GFX_LAYER, SCRIPT_RUNTIME_FEATURES}; /* Rust interface */ mod platform; mod eventhandler; pub mod dom; pub mod graphics; pub mod host; pub mod om; pub mod request; pub mod types; pub mod utf; pub mod value; pub mod video; pub mod window; pub mod windowless; pub use dom::Element; pub use dom::event::EventHandler; pub use host::{Archive, Host, HostHandler}; pub use value::{Value, FromValue}; pub use window::Window; /// Builder pattern for window creation. See [`window::Builder`](window/struct.Builder.html) documentation. /// /// For example, /// /// ```rust,no_run /// let mut frame = sciter::WindowBuilder::main_window() /// .with_size((800,600)) /// .glassy() /// .fixed() /// .create(); /// ``` pub type WindowBuilder = window::Builder; /* Loader */ pub use capi::scapi::{ISciterAPI}; use capi::scgraphics::SciterGraphicsAPI; use capi::screquest::SciterRequestAPI; #[cfg(windows)] mod ext { // Note: // Sciter 4.x shipped with universal "sciter.dll" library for different builds: // bin/32, bin/64, bin/skia32, bin/skia64 // However it is quite inconvenient now (e.g. we can not put x64 and x86 builds in %PATH%) // #![allow(non_snake_case, non_camel_case_types)] use capi::scapi::{ISciterAPI}; use capi::sctypes::{LPCSTR, LPCVOID, BOOL}; type ApiType = *const ISciterAPI; type FuncType = extern "system" fn () -> *const ISciterAPI; pub static mut CUSTOM_DLL_PATH: Option<String> = None; extern "system" { fn LoadLibraryA(lpFileName: LPCSTR) -> LPCVOID; fn FreeLibrary(dll: LPCVOID) -> BOOL; fn GetProcAddress(hModule: LPCVOID, lpProcName: LPCSTR) -> LPCVOID; } pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::path::Path; fn try_load(path: &Path) -> Option<LPCVOID> { let path = CString::new(format!("{}", path.display())).expect("invalid library path"); let dll = unsafe { LoadLibraryA(path.as_ptr()) }; if !dll.is_null() { Some(dll) } else { None } } fn in_global() -> Option<LPCVOID> { // modern dll name let mut dll = unsafe { LoadLibraryA(b"sciter.dll\0".as_ptr() as LPCSTR) }; if dll.is_null() { // try to load with old names let alternate = if cfg!(target_arch = "x86_64") { b"sciter64.dll\0" } else { b"sciter32.dll\0" }; dll = unsafe { LoadLibraryA(alternate.as_ptr() as LPCSTR) }; } if !dll.is_null() { Some(dll) } else { None } } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_global() }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { GetProcAddress(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if !permanent { unsafe { FreeLibrary(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_arch = "x86_64") { "bin/64" } else { "bin/32" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from SDK/{}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", "sciter.dll", msg)) } pub unsafe fn SciterAPI() -> *const ISciterAPI {
Err(error) => panic!("{}", error), } } } #[cfg(all(feature = "dynamic", unix))] mod ext { #![allow(non_snake_case, non_camel_case_types)] extern crate libc; pub static mut CUSTOM_DLL_PATH: Option<String> = None; #[cfg(target_os = "linux")] const DLL_NAMES: &[&str] = &[ "libsciter-gtk.so" ]; // "libsciter.dylib" since Sciter 4.4.6.3. #[cfg(target_os = "macos")] const DLL_NAMES: &[&str] = &[ "libsciter.dylib", "sciter-osx-64.dylib" ]; use capi::scapi::ISciterAPI; use capi::sctypes::{LPVOID, LPCSTR}; type FuncType = extern "system" fn () -> *const ISciterAPI; type ApiType = *const ISciterAPI; pub fn try_load_library(permanent: bool) -> ::std::result::Result<ApiType, String> { use std::ffi::CString; use std::os::unix::ffi::OsStrExt; use std::path::{Path}; // Try to load the library from a specified absolute path. fn try_load(path: &Path) -> Option<LPVOID> { let bytes = path.as_os_str().as_bytes(); if let Ok(cstr) = CString::new(bytes) { let dll = unsafe { libc::dlopen(cstr.as_ptr(), libc::RTLD_LOCAL | libc::RTLD_LAZY) }; if !dll.is_null() { return Some(dll) } } None } // Try to find a library (by one of its names) in a specified path. fn try_load_from(dir: Option<&Path>) -> Option<LPVOID> { let dll = DLL_NAMES.iter() .map(|name| { let mut path = dir.map(Path::to_owned).unwrap_or_default(); path.push(name); path }) .map(|path| try_load(&path)) .find(|dll| dll.is_some()) .map(|o| o.unwrap()); if dll.is_some() { return dll; } None } // Try to load from the current directory. fn in_current_dir() -> Option<LPVOID> { if let Ok(dir) = ::std::env::current_exe() { if let Some(dir) = dir.parent() { let dll = try_load_from(Some(dir)); if dll.is_some() { return dll; } if cfg!(target_os = "macos") { // "(bundle folder)/Contents/Frameworks/" let mut path = dir.to_owned(); path.push("../Frameworks/libsciter.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } let mut path = dir.to_owned(); path.push("../Frameworks/sciter-osx-64.dylib"); let dll = try_load(&path); if dll.is_some() { return dll; } } } } None } // Try to load indirectly via `dlopen("dll.so")`. fn in_global() -> Option<LPVOID> { try_load_from(None) } // Try to find in $PATH. fn in_paths() -> Option<LPVOID> { use std::env; if let Some(paths) = env::var_os("PATH") { for path in env::split_paths(&paths) { if let Some(dll) = try_load_from(Some(&path)) { return Some(dll); } } } None } // try specified path first (and only if present) // and several paths to lookup then let dll = if let Some(path) = unsafe { CUSTOM_DLL_PATH.as_ref() } { try_load(Path::new(path)) } else { in_current_dir().or_else(in_paths).or_else(in_global) }; if let Some(dll) = dll { // get the "SciterAPI" exported symbol let sym = unsafe { libc::dlsym(dll, b"SciterAPI\0".as_ptr() as LPCSTR) }; if sym.is_null() { return Err("\"SciterAPI\" function was expected in the loaded library.".to_owned()); } if !permanent { unsafe { libc::dlclose(dll) }; return Ok(0 as ApiType); } let get_api: FuncType = unsafe { std::mem::transmute(sym) }; return Ok(get_api()); } let sdkbin = if cfg!(target_os = "macos") { "bin.osx" } else { "bin.lnx" }; let msg = format!("Please verify that Sciter SDK is installed and its binaries (from {}) are available in PATH.", sdkbin); Err(format!("error: '{}' was not found neither in PATH nor near the current executable.\n {}", DLL_NAMES[0], msg)) } pub fn SciterAPI() -> *const ISciterAPI { match try_load_library(true) { Ok(api) => api, Err(error) => panic!("{}", error), } } } #[cfg(all(target_os = "linux", not(feature = "dynamic")))] mod ext { // Note: // Since 4.1.4 library name has been changed to "libsciter-gtk" (without 32/64 suffix). // Since 3.3.1.6 library name was changed to "libsciter". // However CC requires `-l sciter` form. #[link(name = "sciter-gtk")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } #[cfg(all(target_os = "macos", target_arch = "x86_64", not(feature = "dynamic")))] mod ext { #[link(name = "libsciter", kind = "dylib")] extern "system" { pub fn SciterAPI() -> *const ::capi::scapi::ISciterAPI; } } /// Getting ISciterAPI reference, can be used for manual API calling. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { // TODO: it's not good to raise a panic inside `lazy_static!`, // because it wents into recursive panicing. // // Somehow, `cargo test --all` tests all the features, // also sometimes it comes even without `cfg!(test)`. // Well, the culprit is "examples/extensions" which uses the "extension" feature, // but how on earth it builds without `cfg(test)`? // if cfg!(test) { &*ext::SciterAPI() } else { EXT_API //.or_else(|| Some(&*ext::SciterAPI())) .expect("Sciter API is not available yet, call `sciter::set_api()` first.") } } else { &*ext::SciterAPI() } }; let abi_version = ap.version; if cfg!(feature = "windowless") { assert!(abi_version >= 0x0001_0001, "Incompatible Sciter build and \"windowless\" feature"); } if cfg!(not(feature = "windowless")) { assert!(abi_version < 0x0001_0000, "Incompatible Sciter build and \"windowless\" feature"); } return ap; } /// Getting ISciterAPI reference, can be used for manual API calling. /// /// Bypasses ABI compatability checks. #[doc(hidden)] #[allow(non_snake_case)] pub fn SciterAPI_unchecked<'a>() -> &'a ISciterAPI { let ap = unsafe { if cfg!(feature="extension") { EXT_API.expect("Sciter API is not available yet, call `sciter::set_api()` first.") } else { &*ext::SciterAPI() } }; return ap; } lazy_static! { static ref _API: &'static ISciterAPI = SciterAPI(); static ref _GAPI: &'static SciterGraphicsAPI = { if version_num() < 0x0401_0A00 { panic!("Graphics API is incompatible since 4.1.10 (your version is {})", version()); } unsafe { &*(SciterAPI().GetSciterGraphicsAPI)() } }; static ref _RAPI: &'static SciterRequestAPI = unsafe { &*(SciterAPI().GetSciterRequestAPI)() }; } /// Set a custom path to the Sciter dynamic library. /// /// Note: Must be called first before any other function. /// /// Returns error if the specified library can not be loaded. /// /// # Example /// /// ```rust /// if sciter::set_library("~/lib/sciter/bin.gtk/x64/libsciter-gtk.so").is_ok() { /// println!("loaded Sciter version {}", sciter::version()); /// } /// ``` pub fn set_library(custom_path: &str) -> ::std::result::Result<(), String> { #[cfg(not(feature = "dynamic"))] fn set_impl(_: &str) -> ::std::result::Result<(), String> { Err("Don't use `sciter::set_library()` in static builds.\n Build with the feature \"dynamic\" instead.".to_owned()) } #[cfg(feature = "dynamic")] fn set_impl(path: &str) -> ::std::result::Result<(), String> { unsafe { ext::CUSTOM_DLL_PATH = Some(path.to_owned()); } ext::try_load_library(false).map(|_| ()) } set_impl(custom_path) } static mut EXT_API: Option<&'static ISciterAPI> = None; /// Set the Sciter API coming from `SciterLibraryInit`. /// /// Note: Must be called first before any other function. pub fn set_host_api(api: &'static ISciterAPI) { if cfg!(feature="extension") { unsafe { EXT_API.replace(api); } } } /// Sciter engine version number (e.g. `0x03030200`). /// /// Note: does not return the `build` part because it doesn't fit in `0..255` byte range. /// Use [`sciter::version()`](fn.version.html) instead which returns the complete version string. pub fn version_num() -> u32 { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let (major, minor, revision, _build) = (v1 >> 16 & 0xFF, v1 & 0xFF, v2 >> 16 & 0xFF, v2 & 0xFF); let num = (major << 24) | (minor << 16) | (revision << 8); // let num = ((v1 >> 16) << 24) | ((v1 & 0xFFFF) << 16) | ((v2 >> 16) << 8) | (v2 & 0xFFFF); return num; } /// Sciter engine version string (e.g. "`3.3.2.0`"). pub fn version() -> String { use types::BOOL; let v1 = (_API.SciterVersion)(true as BOOL); let v2 = (_API.SciterVersion)(false as BOOL); let num = [v1 >> 16, v1 & 0xFFFF, v2 >> 16, v2 & 0xFFFF]; let version = format!("{}.{}.{}.{}", num[0], num[1], num[2], num[3]); return version; } /// Sciter API version. /// /// Returns: /// /// * `0x0000_0001` for regular builds, `0x0001_0001` for windowless builds. /// * `0x0000_0002` since 4.4.2.14 (a breaking change in assets with [SOM builds](https://sciter.com/native-code-exposure-to-script/)) /// * `0x0000_0003` since 4.4.2.16 /// * `0x0000_0004` since 4.4.2.17 (a breaking change in SOM passport) /// * `0x0000_0005` since 4.4.3.20 (a breaking change in `INITIALIZATION_PARAMS`, SOM in event handlers fix) /// * `0x0000_0006` since 4.4.3.24 (TIScript native API is gone, use SOM instead) /// * `0x0000_0007` since 4.4.5.4 (DOM-Value conversion functions were added, no breaking change) /// * `0x0000_0008` since 4.4.6.7 (Sciter and Sciter.Lite are unified in ISciterAPI) /// * `0x0000_0009` since 4.4.7.0 (ISciterAPI unification between all platforms) /// /// Since 4.4.0.3. pub fn api_version() -> u32 { _API.version } /// Returns true for windowless builds. pub fn is_windowless() -> bool { api_version() >= 0x0001_0001 } /// Various global Sciter engine options. /// /// Used by [`sciter::set_options()`](fn.set_options.html). /// /// See also [per-window options](window/enum.Options.html). #[derive(Copy, Clone)] pub enum RuntimeOptions<'a> { /// global; value: the full path to the Sciter dynamic library (dll/dylib/so), /// must be called before any other Sciter function. LibraryPath(&'a str), /// global; value: [`GFX_LAYER`](enum.GFX_LAYER.html), must be called before any window creation. GfxLayer(GFX_LAYER), /// global; value: `true` - the engine will use a "unisex" theme that is common for all platforms. /// That UX theme is not using OS primitives for rendering input elements. /// Use it if you want exactly the same (modulo fonts) look-n-feel on all platforms. UxTheming(bool), /// global or per-window; enables Sciter Inspector for all windows, must be called before any window creation. DebugMode(bool), /// global or per-window; value: combination of [`SCRIPT_RUNTIME_FEATURES`](enum.SCRIPT_RUNTIME_FEATURES.html) flags. /// /// Note that these features have been disabled by default /// since [4.2.5.0](https://rawgit.com/c-smile/sciter-sdk/7036a9c7912ac30d9f369d9abb87b278d2d54c6d/logfile.htm). ScriptFeatures(u8), /// global; value: milliseconds, connection timeout of http client. ConnectionTimeout(u32), /// global; value: `0` - drop connection, `1` - use builtin dialog, `2` - accept connection silently. OnHttpsError(u8), // global; value: json with GPU black list, see the `gpu-blacklist.json` resource. // Not used in Sciter 4, in fact: https://sciter.com/forums/topic/how-to-use-the-gpu-blacklist/#post-59338 // GpuBlacklist(&'a str), /// global; value: script source to be loaded into each view before any other script execution. InitScript(&'a str), /// global; value - max request length in megabytes (1024*1024 bytes), since 4.3.0.15. MaxHttpDataLength(usize), /// global or per-window; value: `true` - `1px` in CSS is treated as `1dip`, otherwise `1px` is a physical pixel (by default). /// /// since [4.4.5.0](https://rawgit.com/c-smile/sciter-sdk/aafb625bb0bc317d79c0a14d02b5730f6a02b48a/logfile.htm). LogicalPixel(bool), } /// Set various global Sciter engine options, see the [`RuntimeOptions`](enum.RuntimeOptions.html). pub fn set_options(options: RuntimeOptions) -> std::result::Result<(), ()> { use RuntimeOptions::*; use capi::scdef::SCITER_RT_OPTIONS::*; let (option, value) = match options { ConnectionTimeout(ms) => (SCITER_CONNECTION_TIMEOUT, ms as usize), OnHttpsError(behavior) => (SCITER_HTTPS_ERROR, behavior as usize), // GpuBlacklist(json) => (SCITER_SET_GPU_BLACKLIST, json.as_bytes().as_ptr() as usize), InitScript(script) => (SCITER_SET_INIT_SCRIPT, script.as_bytes().as_ptr() as usize), ScriptFeatures(mask) => (SCITER_SET_SCRIPT_RUNTIME_FEATURES, mask as usize), GfxLayer(backend) => (SCITER_SET_GFX_LAYER, backend as usize), DebugMode(enable) => (SCITER_SET_DEBUG_MODE, enable as usize), UxTheming(enable) => (SCITER_SET_UX_THEMING, enable as usize), MaxHttpDataLength(value) => (SCITER_SET_MAX_HTTP_DATA_LENGTH, value), LogicalPixel(enable) => (SCITER_SET_PX_AS_DIP, enable as usize), LibraryPath(path) => { return set_library(path).map_err(|_|()); } }; let ok = (_API.SciterSetOption)(std::ptr::null_mut(), option, value); if ok != 0 { Ok(()) } else { Err(()) } } /// Set a global variable by its path to all windows. /// /// This variable will be accessible in all windows via `globalThis[path]` or just `path`. /// /// Note that this call affects only _new_ windows, /// so it's preferred to call it before the main window creation. /// /// See also per-window [`Window::set_variable`](window/struct.Window.html#method.set_variable) /// to assign a global to a single window only. pub fn set_variable(path: &str, value: Value) -> dom::Result<()> { let ws = s2u!(path); let ok = (_API.SciterSetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_cptr()); if ok == dom::SCDOM_RESULT::OK { Ok(()) } else { Err(ok) } } /// Get a global variable by its path. /// /// See the per-window [`Window::get_variable`](window/struct.Window.html#method.get_variable). #[doc(hidden)] pub fn get_variable(path: &str) -> dom::Result<Value> { let ws = s2u!(path); let mut value = Value::new(); let ok = (_API.SciterGetVariable)(std::ptr::null_mut(), ws.as_ptr(), value.as_mut_ptr()); if ok == dom::SCDOM_RESULT::OK { Ok(value) } else { Err(ok) } }
match try_load_library(true) { Ok(api) => api,
random_line_split
heatmiser_wifi.py
#!/usr/bin/env python # coding=utf-8 # ############################################################################### # - heatmiser_wifi - # # Copyright 2020 by Joel Midstjärna (joel.midstjarna@gmail.com) # # A Heatmiser WiFi Thermostat communication library. # # Supported Heatmiser Thermostats are DT, DT-E, PRT and PRT-E. # # It is also possible to run this file as a command line executable. # # All rights reserved. # This file is part of the heatmiser_wifi python library and is # released under the "MIT License Agreement". Please see the LICENSE # file that should have been included as part of this package. ############################################################################### import socket, time, sys from optparse import OptionParser from collections import OrderedDict class CRC16: CRC16_LookupHigh = [0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1] CRC16_LookupLow = [0x00, 0x21, 0x42, 0x63, 0x84, 0xA5, 0xC6, 0xE7, 0x08, 0x29, 0x4A, 0x6B, 0x8C, 0xAD, 0xCE, 0xEF] CRC16_High = 0xff CRC16_Low = 0xff def _CRC16_Update4Bits(self, val): t = (self.CRC16_High >> 4) & 0xff t = (t ^ val) & 0xff self.CRC16_High = ((self.CRC16_High << 4)|(self.CRC16_Low >> 4)) & 0xff self.CRC16_Low = (self.CRC16_Low << 4) & 0xff self.CRC16_High = (self.CRC16_High ^ self.CRC16_LookupHigh[t]) & 0xff self.CRC16_Low = (self.CRC16_Low ^ self.CRC16_LookupLow[t]) & 0xff def _CRC16_Update(self, val): self._CRC16_Update4Bits((val >> 4) & 0x0f) self._CRC16_Update4Bits(val & 0x0f) def CRC16(self,bytes): self.CRC16_High = 0xff self.CRC16_Low = 0xff for byte in bytes: self._CRC16_Update(byte) return (self.CRC16_Low, self.CRC16_High) class HeatmiserTransport: ''' This class handles the Heatmiser transport protocol ''' def __init__(self, host, port, pin): self.host = host self.port = port self.crc16 = CRC16() self.pin = pin def connect(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.host,self.port)) self.sock.settimeout(5) def disconnect(self): self.sock.close() def _
self, dcb_start = 0x0, dcb_length = 0xffff): ''' dcb_length = 0xffff means the whole DCB. The Heatmiser v3 protocol specification recommends that the whole DCB shall be read at once. It seems that dcb_start > 0x0 has no effect. ''' frame_list = [ 0x93, # Operation 0x93=Read, 0xa3=Write 0x0b, # Frame length low byte inc CRC (0xb if no data) 0x00, # Frame length high byte inc CRC (0 if no data) int(self.pin) & 0xff, # PIN code low byte int(self.pin) >> 8, # PIN code high byte dcb_start & 0xff, # DCB start low byte dcb_start >> 8, # DCB start high byte dcb_length & 0xff, # DCB length low byte (0xff for whole DCB) dcb_length >> 8] # DCB length high byte (0xff for whole DCB) frame = bytearray(frame_list) # Add CRC16 to the frame (16 bytes) (crc16_low, crc16_high) = self.crc16.CRC16(frame) frame.append(crc16_low) frame.append(crc16_high) self.sock.send(frame) def _send_write_request(self, dcb_address, dcb_data): ''' dcb_address is address in DCB block (not index) ''' dcb_length = len(dcb_data) length = dcb_length + 11 frame_list = [ 0xa3, # Operation 0x93=Read, 0xa3=Write length & 0xff, # Frame length low byte inc CRC (11+dcb_data) length >> 8, # Frame length high byte inc CRC (11+dcb_data) self.pin & 0xff, # PIN code low byte self.pin >> 8, # PIN code high byte 1, # Nbr of items (only 1 in this impl) dcb_address & 0xff,# DCB address low byte dcb_address >> 8, # DCB address high byte dcb_length] # DCB length frame = bytearray(frame_list) + dcb_data # Add CRC16 to the frame (16 bytes) (crc16_low, crc16_high) = self.crc16.CRC16(frame) frame.append(crc16_low) frame.append(crc16_high) self.sock.send(frame) def _receive_dcb(self): data = self.sock.recv(1024) frame = bytearray(data) # Validate the CRC (two last bytes) and remove from frame received_crc16_high = frame.pop() received_crc16_low = frame.pop() (crc16_low, crc16_high) = self.crc16.CRC16(frame) if((received_crc16_high != crc16_high) or (received_crc16_low != crc16_low)): raise Exception("CRC16 mismatch in received data from Thermostat") # Validate frame head if(frame[0] != 0x94): raise Exception("Unknown type of message received from Thermostat") # Read out and validate the frame length frame_length = (frame[2] << 8) | frame[1] if(frame_length != (len(frame) + 2)): #+2 since CRC has been removed raise Exception("Invalid frame length in data received from Thermostat") # Read out DCB start address dcb_start = (frame[4] << 8) | frame[3] # Read out and validate DCB content length dcb_length = (frame[6] << 8) | frame[5] if(dcb_length == 0): raise Exception("Thermostat connected but reports wrong PIN code") if(dcb_length != (frame_length - 9)): #Overhead in frame is 9 bytes raise Exception("Invalid DCB length in data received from Thermostat") # Read out DCB data dcb_data = frame[7:] return (dcb_start, dcb_data) def get_dcb(self): ''' Get whole DCB ''' self._send_read_request() (dcb_start, dcb_data) = self._receive_dcb() return dcb_data def set_dcb(self, dcb_address, dcb_data): self._send_write_request(dcb_address, dcb_data) # Just get an ACK from the Thermostat (don't use the result) dcb = self._receive_dcb() class Heatmiser(HeatmiserTransport): ''' This class handles the Heatmiser application (DCB) protocol ''' def _get_info_time_triggers(self, dcb, first_index): index = first_index info = OrderedDict() for i in range (1,5): trigger = OrderedDict() trigger['hour'] = dcb[index] index = index + 1 trigger['minute'] = dcb[index] index = index + 1 trigger['set_temp'] = dcb[index] index = index + 1 info['time'+str(i)] = trigger return info def get_info(self): ''' Returns an ordered dictionary with all Thermostat values ''' dcb = self.get_dcb() if(len(dcb) < 41): raise Exception("Size of DCB received from Thermostat is too small") info = OrderedDict() if(dcb[2] == 0): info["vendor_id"] = "HEATMISER" else: info["vendor_id"] = "OEM" info["version"] = dcb[3] & 0x7F info["in_floor_limit_state"] = ((dcb[3] & 0x8F) > 0) if(dcb[4] == 0): info["model"] = "DT" elif(dcb[4] == 1): info["model"] = "DT-E" elif(dcb[4] == 2): info["model"] = "PRT" elif(dcb[4] == 3): info["model"] = "PRT-E" else: info["model"] = "Unknown" if(dcb[5] == 0): info["temperature_format"] = "Celsius" else: info["temperature_format"] = "Fahrenheit" info["switch_differential"] = dcb[6] info["frost_protection_enable"] = (dcb[7] == 1) info["calibration_offset"] = ((dcb[8] << 8) | dcb[9]) info["output_delay_in_minutes"] = dcb[10] # dcb[11] = address (not used) info['up_down_key_limit'] = dcb[12] if(dcb[13] == 0): info['sensor_selection'] = "Built in air sensor only" elif(dcb[13] == 1): info['sensor_selection'] = "Remote air sensor only" elif(dcb[13] == 2): info['sensor_selection'] = "Floor sensor only" elif(dcb[13] == 3): info['sensor_selection'] = "Built in air and floor sensor" elif(dcb[13] == 4): info['sensor_selection'] = "Remote air and floor sensor" else: info['sensor_selection'] = "Unknown" info['optimum_start'] = dcb[14] info['rate_of_change'] = dcb[15] if(dcb[16] == 0): info['program_mode'] = "2/5 mode" else: info['program_mode'] = "7 day mode" info['frost_protect_temperature'] = dcb[17] info['set_room_temp'] = dcb[18] info['floor_max_limit'] = dcb[19] info['floor_max_limit_enable'] = (dcb[20] == 1) if(dcb[21] == 1): info['on_off'] = "On" else: info['on_off'] = "Off" if(dcb[22] == 0): info['key_lock'] = "Unlock" else: info['key_lock'] = "Lock" if(dcb[23] == 0): info['run_mode'] = "Heating mode (normal mode)" else: info['run_mode'] = "Frost protection mode" # dcb[24] = away mode (not used) info['holiday_return_date_year'] = 2000 + dcb[25] info['holiday_return_date_month'] = dcb[26] info['holiday_return_date_day_of_month'] = dcb[27] info['holiday_return_date_hour'] = dcb[28] info['holiday_return_date_minute'] = dcb[29] info['holiday_enable'] = (dcb[30] == 1) info['temp_hold_minutes'] = ((dcb[31] << 8) | dcb[32]) if((dcb[13] == 1) or (dcb[13] == 4)): info['air_temp'] = (float((dcb[34] << 8) | dcb[33]) / 10.0) if((dcb[13] == 2) or (dcb[13] == 3) or (dcb[13] == 4)): info['floor_temp'] = (float((dcb[36] << 8) | dcb[35]) / 10.0) if((dcb[13] == 0) or (dcb[13] == 3)): info['air_temp'] = (float((dcb[38] << 8) | dcb[37]) / 10.0) info['error_code'] = dcb[39] info['heating_is_currently_on'] = (dcb[40] == 1) # Model DT and DT-E stops here if(dcb[4] <= 1): return info if(len(dcb) < 72): raise Exception("Size of DCB received from Thermostat is too small") info['year'] = 2000 + dcb[41] info['month'] = dcb[42] info['day_of_month'] = dcb[43] info['weekday'] = dcb[44] info['hour'] = dcb[45] info['minute'] = dcb[46] info['second'] = dcb[47] info['weekday_triggers'] = self._get_info_time_triggers(dcb, 48) info['weekend_triggers'] = self._get_info_time_triggers(dcb, 60) # If mode is 5/2 stop here if(dcb[16] == 0): return info if(len(dcb) < 156): raise Exception("Size of DCB received from Thermostat is too small") info['mon_triggers'] = self._get_info_time_triggers(dcb, 72) info['tue_triggers'] = self._get_info_time_triggers(dcb, 84) info['wed_triggers'] = self._get_info_time_triggers(dcb, 96) info['thu_triggers'] = self._get_info_time_triggers(dcb, 108) info['fri_triggers'] = self._get_info_time_triggers(dcb, 120) info['sat_triggers'] = self._get_info_time_triggers(dcb, 132) info['sun_triggers'] = self._get_info_time_triggers(dcb, 144) return info def set_value(self, name, value): ''' Use the same name and value as returned in get_info. Only a few name/keys are supported in this implementation. Use the set_dcb method to set any value. ''' if(name == "switch_differential"): self.set_dcb(6,bytearray([int(value)])) elif(name == "frost_protect_temperature"): self.set_dcb(17,bytearray([int(value)])) elif(name == "set_room_temp"): self.set_dcb(18,bytearray([int(value)])) elif(name == "floor_max_limit"): self.set_dcb(19,bytearray([int(value)])) elif(name == "floor_max_limit_enable"): if((value == True) or (value == "True") or (value == "1") or (value == 1)): value = 1 elif((value == False) or (value == "False") or (value == "0") or (value == 0)): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: True, 1, False or 0") self.set_dcb(20,bytearray([value])) elif(name == "on_off"): if(value == "On"): value = 1 elif(value == "Off"): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: 'On' or 'Off'") self.set_dcb(21,bytearray([value])) elif(name == "key_lock"): if(value == "Lock"): value = 1 elif(value == "Unlock"): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: 'Lock' or 'Unlock'") self.set_dcb(22,bytearray([value])) elif(name == "run_mode"): if(value == "Frost protection mode"): value = 1 elif(value == "Heating mode (normal mode)"): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: 'Frost protection mode' or " + "'Heating mode (normal mode)'") self.set_dcb(23,bytearray([value])) else: raise Exception("'"+name+"' not supported to be set") ############################################################################### # Below is a command line tool for reading and setting parameters of a # Heatmiser Wifi thermostat. It can also be seen as an example on how to use # the library. def print_dict(dict, level=""): for i in dict.items(): if(isinstance(i[1],OrderedDict)): print(level+i[0]+":") print_dict(i[1],level + " ") else: print(level+str(i[0])+" = "+str(i[1])) def main(): # This function shows how to use the Heatmiser class. parser = OptionParser("Usage: %prog [options] <Heatmiser Thermostat address>") parser.add_option("-p", "--port", dest="port", type="int", help="Port of HeatMiser Thermostat (default 8068)", default=8068) parser.add_option("-c", "--pin", dest="pin", type="int", help="Pin code of HeatMiser Thermostat (default 0000)", default=0) parser.add_option("-l", "--list", action="store_true", dest="list_all", help="List all parameters in Thermostat", default=False) parser.add_option("-r", "--read", dest="parameter", help="Read one parameter in Thermostat (-r param)", default="") parser.add_option("-w", "--write", dest="param_value", nargs=2, help="Write value to parameter in Thermostat (-w param value)") (options, args) = parser.parse_args() if (len(args) != 1): parser.error("Wrong number of arguments") host = args[0] # Create a new Heatmiser object heatmiser = Heatmiser(host,options.port,options.pin) # Connect to Thermostat heatmiser.connect() # Read all parameters info = heatmiser.get_info() # Print all parameters in Thermostat if(options.list_all): print_dict(info) # Print one parameter in Thermostat if(options.parameter != ""): if (options.parameter in info): print(options.parameter + " = " + str(info[options.parameter])) else: sys.stderr.write("Error!\n"+ "Parameter '"+options.parameter+"' does not exist\n") # Write value to one parameter in Thermostat if(options.param_value != None): param = options.param_value[0] value = options.param_value[1] if (param in info): try: heatmiser.set_value(param,value) info2 = heatmiser.get_info() print("Before change: " + param + " = " + str(info[param])) print("After change: " + param + " = " + str(info2[param])) except Exception as e: sys.stderr.write(e.args[0]+"\n") else: sys.stderr.write("Error!\n"+ "Parameter '"+param+"' does not exist\n") heatmiser.disconnect() if __name__ == '__main__': main()
send_read_request(
identifier_name
heatmiser_wifi.py
#!/usr/bin/env python # coding=utf-8 # ############################################################################### # - heatmiser_wifi - # # Copyright 2020 by Joel Midstjärna (joel.midstjarna@gmail.com) # # A Heatmiser WiFi Thermostat communication library. # # Supported Heatmiser Thermostats are DT, DT-E, PRT and PRT-E. # # It is also possible to run this file as a command line executable. # # All rights reserved. # This file is part of the heatmiser_wifi python library and is # released under the "MIT License Agreement". Please see the LICENSE # file that should have been included as part of this package. ############################################################################### import socket, time, sys from optparse import OptionParser from collections import OrderedDict class CRC16: CRC16_LookupHigh = [0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1] CRC16_LookupLow = [0x00, 0x21, 0x42, 0x63, 0x84, 0xA5, 0xC6, 0xE7, 0x08, 0x29, 0x4A, 0x6B, 0x8C, 0xAD, 0xCE, 0xEF] CRC16_High = 0xff CRC16_Low = 0xff def _CRC16_Update4Bits(self, val): t = (self.CRC16_High >> 4) & 0xff t = (t ^ val) & 0xff self.CRC16_High = ((self.CRC16_High << 4)|(self.CRC16_Low >> 4)) & 0xff self.CRC16_Low = (self.CRC16_Low << 4) & 0xff self.CRC16_High = (self.CRC16_High ^ self.CRC16_LookupHigh[t]) & 0xff self.CRC16_Low = (self.CRC16_Low ^ self.CRC16_LookupLow[t]) & 0xff def _CRC16_Update(self, val): self._CRC16_Update4Bits((val >> 4) & 0x0f) self._CRC16_Update4Bits(val & 0x0f) def CRC16(self,bytes): self.CRC16_High = 0xff self.CRC16_Low = 0xff for byte in bytes: self._CRC16_Update(byte) return (self.CRC16_Low, self.CRC16_High) class HeatmiserTransport: ''' This class handles the Heatmiser transport protocol ''' def __init__(self, host, port, pin): self.host = host self.port = port self.crc16 = CRC16() self.pin = pin def connect(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.host,self.port)) self.sock.settimeout(5) def disconnect(self): self.sock.close() def _send_read_request(self, dcb_start = 0x0, dcb_length = 0xffff): ''' dcb_length = 0xffff means the whole DCB. The Heatmiser v3 protocol specification recommends that the whole DCB shall be read at once. It seems that dcb_start > 0x0 has no effect. ''' frame_list = [ 0x93, # Operation 0x93=Read, 0xa3=Write 0x0b, # Frame length low byte inc CRC (0xb if no data) 0x00, # Frame length high byte inc CRC (0 if no data) int(self.pin) & 0xff, # PIN code low byte int(self.pin) >> 8, # PIN code high byte dcb_start & 0xff, # DCB start low byte dcb_start >> 8, # DCB start high byte dcb_length & 0xff, # DCB length low byte (0xff for whole DCB) dcb_length >> 8] # DCB length high byte (0xff for whole DCB) frame = bytearray(frame_list) # Add CRC16 to the frame (16 bytes) (crc16_low, crc16_high) = self.crc16.CRC16(frame) frame.append(crc16_low) frame.append(crc16_high) self.sock.send(frame) def _send_write_request(self, dcb_address, dcb_data): ''' dcb_address is address in DCB block (not index) ''' dcb_length = len(dcb_data) length = dcb_length + 11 frame_list = [ 0xa3, # Operation 0x93=Read, 0xa3=Write length & 0xff, # Frame length low byte inc CRC (11+dcb_data) length >> 8, # Frame length high byte inc CRC (11+dcb_data) self.pin & 0xff, # PIN code low byte self.pin >> 8, # PIN code high byte 1, # Nbr of items (only 1 in this impl) dcb_address & 0xff,# DCB address low byte dcb_address >> 8, # DCB address high byte dcb_length] # DCB length frame = bytearray(frame_list) + dcb_data # Add CRC16 to the frame (16 bytes) (crc16_low, crc16_high) = self.crc16.CRC16(frame) frame.append(crc16_low) frame.append(crc16_high) self.sock.send(frame) def _receive_dcb(self): data = self.sock.recv(1024) frame = bytearray(data) # Validate the CRC (two last bytes) and remove from frame received_crc16_high = frame.pop() received_crc16_low = frame.pop() (crc16_low, crc16_high) = self.crc16.CRC16(frame) if((received_crc16_high != crc16_high) or (received_crc16_low != crc16_low)): raise Exception("CRC16 mismatch in received data from Thermostat") # Validate frame head if(frame[0] != 0x94): r
# Read out and validate the frame length frame_length = (frame[2] << 8) | frame[1] if(frame_length != (len(frame) + 2)): #+2 since CRC has been removed raise Exception("Invalid frame length in data received from Thermostat") # Read out DCB start address dcb_start = (frame[4] << 8) | frame[3] # Read out and validate DCB content length dcb_length = (frame[6] << 8) | frame[5] if(dcb_length == 0): raise Exception("Thermostat connected but reports wrong PIN code") if(dcb_length != (frame_length - 9)): #Overhead in frame is 9 bytes raise Exception("Invalid DCB length in data received from Thermostat") # Read out DCB data dcb_data = frame[7:] return (dcb_start, dcb_data) def get_dcb(self): ''' Get whole DCB ''' self._send_read_request() (dcb_start, dcb_data) = self._receive_dcb() return dcb_data def set_dcb(self, dcb_address, dcb_data): self._send_write_request(dcb_address, dcb_data) # Just get an ACK from the Thermostat (don't use the result) dcb = self._receive_dcb() class Heatmiser(HeatmiserTransport): ''' This class handles the Heatmiser application (DCB) protocol ''' def _get_info_time_triggers(self, dcb, first_index): index = first_index info = OrderedDict() for i in range (1,5): trigger = OrderedDict() trigger['hour'] = dcb[index] index = index + 1 trigger['minute'] = dcb[index] index = index + 1 trigger['set_temp'] = dcb[index] index = index + 1 info['time'+str(i)] = trigger return info def get_info(self): ''' Returns an ordered dictionary with all Thermostat values ''' dcb = self.get_dcb() if(len(dcb) < 41): raise Exception("Size of DCB received from Thermostat is too small") info = OrderedDict() if(dcb[2] == 0): info["vendor_id"] = "HEATMISER" else: info["vendor_id"] = "OEM" info["version"] = dcb[3] & 0x7F info["in_floor_limit_state"] = ((dcb[3] & 0x8F) > 0) if(dcb[4] == 0): info["model"] = "DT" elif(dcb[4] == 1): info["model"] = "DT-E" elif(dcb[4] == 2): info["model"] = "PRT" elif(dcb[4] == 3): info["model"] = "PRT-E" else: info["model"] = "Unknown" if(dcb[5] == 0): info["temperature_format"] = "Celsius" else: info["temperature_format"] = "Fahrenheit" info["switch_differential"] = dcb[6] info["frost_protection_enable"] = (dcb[7] == 1) info["calibration_offset"] = ((dcb[8] << 8) | dcb[9]) info["output_delay_in_minutes"] = dcb[10] # dcb[11] = address (not used) info['up_down_key_limit'] = dcb[12] if(dcb[13] == 0): info['sensor_selection'] = "Built in air sensor only" elif(dcb[13] == 1): info['sensor_selection'] = "Remote air sensor only" elif(dcb[13] == 2): info['sensor_selection'] = "Floor sensor only" elif(dcb[13] == 3): info['sensor_selection'] = "Built in air and floor sensor" elif(dcb[13] == 4): info['sensor_selection'] = "Remote air and floor sensor" else: info['sensor_selection'] = "Unknown" info['optimum_start'] = dcb[14] info['rate_of_change'] = dcb[15] if(dcb[16] == 0): info['program_mode'] = "2/5 mode" else: info['program_mode'] = "7 day mode" info['frost_protect_temperature'] = dcb[17] info['set_room_temp'] = dcb[18] info['floor_max_limit'] = dcb[19] info['floor_max_limit_enable'] = (dcb[20] == 1) if(dcb[21] == 1): info['on_off'] = "On" else: info['on_off'] = "Off" if(dcb[22] == 0): info['key_lock'] = "Unlock" else: info['key_lock'] = "Lock" if(dcb[23] == 0): info['run_mode'] = "Heating mode (normal mode)" else: info['run_mode'] = "Frost protection mode" # dcb[24] = away mode (not used) info['holiday_return_date_year'] = 2000 + dcb[25] info['holiday_return_date_month'] = dcb[26] info['holiday_return_date_day_of_month'] = dcb[27] info['holiday_return_date_hour'] = dcb[28] info['holiday_return_date_minute'] = dcb[29] info['holiday_enable'] = (dcb[30] == 1) info['temp_hold_minutes'] = ((dcb[31] << 8) | dcb[32]) if((dcb[13] == 1) or (dcb[13] == 4)): info['air_temp'] = (float((dcb[34] << 8) | dcb[33]) / 10.0) if((dcb[13] == 2) or (dcb[13] == 3) or (dcb[13] == 4)): info['floor_temp'] = (float((dcb[36] << 8) | dcb[35]) / 10.0) if((dcb[13] == 0) or (dcb[13] == 3)): info['air_temp'] = (float((dcb[38] << 8) | dcb[37]) / 10.0) info['error_code'] = dcb[39] info['heating_is_currently_on'] = (dcb[40] == 1) # Model DT and DT-E stops here if(dcb[4] <= 1): return info if(len(dcb) < 72): raise Exception("Size of DCB received from Thermostat is too small") info['year'] = 2000 + dcb[41] info['month'] = dcb[42] info['day_of_month'] = dcb[43] info['weekday'] = dcb[44] info['hour'] = dcb[45] info['minute'] = dcb[46] info['second'] = dcb[47] info['weekday_triggers'] = self._get_info_time_triggers(dcb, 48) info['weekend_triggers'] = self._get_info_time_triggers(dcb, 60) # If mode is 5/2 stop here if(dcb[16] == 0): return info if(len(dcb) < 156): raise Exception("Size of DCB received from Thermostat is too small") info['mon_triggers'] = self._get_info_time_triggers(dcb, 72) info['tue_triggers'] = self._get_info_time_triggers(dcb, 84) info['wed_triggers'] = self._get_info_time_triggers(dcb, 96) info['thu_triggers'] = self._get_info_time_triggers(dcb, 108) info['fri_triggers'] = self._get_info_time_triggers(dcb, 120) info['sat_triggers'] = self._get_info_time_triggers(dcb, 132) info['sun_triggers'] = self._get_info_time_triggers(dcb, 144) return info def set_value(self, name, value): ''' Use the same name and value as returned in get_info. Only a few name/keys are supported in this implementation. Use the set_dcb method to set any value. ''' if(name == "switch_differential"): self.set_dcb(6,bytearray([int(value)])) elif(name == "frost_protect_temperature"): self.set_dcb(17,bytearray([int(value)])) elif(name == "set_room_temp"): self.set_dcb(18,bytearray([int(value)])) elif(name == "floor_max_limit"): self.set_dcb(19,bytearray([int(value)])) elif(name == "floor_max_limit_enable"): if((value == True) or (value == "True") or (value == "1") or (value == 1)): value = 1 elif((value == False) or (value == "False") or (value == "0") or (value == 0)): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: True, 1, False or 0") self.set_dcb(20,bytearray([value])) elif(name == "on_off"): if(value == "On"): value = 1 elif(value == "Off"): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: 'On' or 'Off'") self.set_dcb(21,bytearray([value])) elif(name == "key_lock"): if(value == "Lock"): value = 1 elif(value == "Unlock"): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: 'Lock' or 'Unlock'") self.set_dcb(22,bytearray([value])) elif(name == "run_mode"): if(value == "Frost protection mode"): value = 1 elif(value == "Heating mode (normal mode)"): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: 'Frost protection mode' or " + "'Heating mode (normal mode)'") self.set_dcb(23,bytearray([value])) else: raise Exception("'"+name+"' not supported to be set") ############################################################################### # Below is a command line tool for reading and setting parameters of a # Heatmiser Wifi thermostat. It can also be seen as an example on how to use # the library. def print_dict(dict, level=""): for i in dict.items(): if(isinstance(i[1],OrderedDict)): print(level+i[0]+":") print_dict(i[1],level + " ") else: print(level+str(i[0])+" = "+str(i[1])) def main(): # This function shows how to use the Heatmiser class. parser = OptionParser("Usage: %prog [options] <Heatmiser Thermostat address>") parser.add_option("-p", "--port", dest="port", type="int", help="Port of HeatMiser Thermostat (default 8068)", default=8068) parser.add_option("-c", "--pin", dest="pin", type="int", help="Pin code of HeatMiser Thermostat (default 0000)", default=0) parser.add_option("-l", "--list", action="store_true", dest="list_all", help="List all parameters in Thermostat", default=False) parser.add_option("-r", "--read", dest="parameter", help="Read one parameter in Thermostat (-r param)", default="") parser.add_option("-w", "--write", dest="param_value", nargs=2, help="Write value to parameter in Thermostat (-w param value)") (options, args) = parser.parse_args() if (len(args) != 1): parser.error("Wrong number of arguments") host = args[0] # Create a new Heatmiser object heatmiser = Heatmiser(host,options.port,options.pin) # Connect to Thermostat heatmiser.connect() # Read all parameters info = heatmiser.get_info() # Print all parameters in Thermostat if(options.list_all): print_dict(info) # Print one parameter in Thermostat if(options.parameter != ""): if (options.parameter in info): print(options.parameter + " = " + str(info[options.parameter])) else: sys.stderr.write("Error!\n"+ "Parameter '"+options.parameter+"' does not exist\n") # Write value to one parameter in Thermostat if(options.param_value != None): param = options.param_value[0] value = options.param_value[1] if (param in info): try: heatmiser.set_value(param,value) info2 = heatmiser.get_info() print("Before change: " + param + " = " + str(info[param])) print("After change: " + param + " = " + str(info2[param])) except Exception as e: sys.stderr.write(e.args[0]+"\n") else: sys.stderr.write("Error!\n"+ "Parameter '"+param+"' does not exist\n") heatmiser.disconnect() if __name__ == '__main__': main()
aise Exception("Unknown type of message received from Thermostat")
conditional_block
heatmiser_wifi.py
#!/usr/bin/env python # coding=utf-8 # ############################################################################### # - heatmiser_wifi - # # Copyright 2020 by Joel Midstjärna (joel.midstjarna@gmail.com) # # A Heatmiser WiFi Thermostat communication library. # # Supported Heatmiser Thermostats are DT, DT-E, PRT and PRT-E. # # It is also possible to run this file as a command line executable. # # All rights reserved. # This file is part of the heatmiser_wifi python library and is # released under the "MIT License Agreement". Please see the LICENSE # file that should have been included as part of this package. ############################################################################### import socket, time, sys from optparse import OptionParser from collections import OrderedDict class CRC16: CRC16_LookupHigh = [0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1] CRC16_LookupLow = [0x00, 0x21, 0x42, 0x63, 0x84, 0xA5, 0xC6, 0xE7, 0x08, 0x29, 0x4A, 0x6B, 0x8C, 0xAD, 0xCE, 0xEF] CRC16_High = 0xff CRC16_Low = 0xff def _CRC16_Update4Bits(self, val): t = (self.CRC16_High >> 4) & 0xff t = (t ^ val) & 0xff self.CRC16_High = ((self.CRC16_High << 4)|(self.CRC16_Low >> 4)) & 0xff self.CRC16_Low = (self.CRC16_Low << 4) & 0xff self.CRC16_High = (self.CRC16_High ^ self.CRC16_LookupHigh[t]) & 0xff self.CRC16_Low = (self.CRC16_Low ^ self.CRC16_LookupLow[t]) & 0xff def _CRC16_Update(self, val): self._CRC16_Update4Bits((val >> 4) & 0x0f) self._CRC16_Update4Bits(val & 0x0f) def CRC16(self,bytes): self.CRC16_High = 0xff self.CRC16_Low = 0xff for byte in bytes: self._CRC16_Update(byte) return (self.CRC16_Low, self.CRC16_High) class HeatmiserTransport: ''' This class handles the Heatmiser transport protocol ''' def __init__(self, host, port, pin): self.host = host self.port = port self.crc16 = CRC16() self.pin = pin def connect(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.host,self.port)) self.sock.settimeout(5) def disconnect(self): s
def _send_read_request(self, dcb_start = 0x0, dcb_length = 0xffff): ''' dcb_length = 0xffff means the whole DCB. The Heatmiser v3 protocol specification recommends that the whole DCB shall be read at once. It seems that dcb_start > 0x0 has no effect. ''' frame_list = [ 0x93, # Operation 0x93=Read, 0xa3=Write 0x0b, # Frame length low byte inc CRC (0xb if no data) 0x00, # Frame length high byte inc CRC (0 if no data) int(self.pin) & 0xff, # PIN code low byte int(self.pin) >> 8, # PIN code high byte dcb_start & 0xff, # DCB start low byte dcb_start >> 8, # DCB start high byte dcb_length & 0xff, # DCB length low byte (0xff for whole DCB) dcb_length >> 8] # DCB length high byte (0xff for whole DCB) frame = bytearray(frame_list) # Add CRC16 to the frame (16 bytes) (crc16_low, crc16_high) = self.crc16.CRC16(frame) frame.append(crc16_low) frame.append(crc16_high) self.sock.send(frame) def _send_write_request(self, dcb_address, dcb_data): ''' dcb_address is address in DCB block (not index) ''' dcb_length = len(dcb_data) length = dcb_length + 11 frame_list = [ 0xa3, # Operation 0x93=Read, 0xa3=Write length & 0xff, # Frame length low byte inc CRC (11+dcb_data) length >> 8, # Frame length high byte inc CRC (11+dcb_data) self.pin & 0xff, # PIN code low byte self.pin >> 8, # PIN code high byte 1, # Nbr of items (only 1 in this impl) dcb_address & 0xff,# DCB address low byte dcb_address >> 8, # DCB address high byte dcb_length] # DCB length frame = bytearray(frame_list) + dcb_data # Add CRC16 to the frame (16 bytes) (crc16_low, crc16_high) = self.crc16.CRC16(frame) frame.append(crc16_low) frame.append(crc16_high) self.sock.send(frame) def _receive_dcb(self): data = self.sock.recv(1024) frame = bytearray(data) # Validate the CRC (two last bytes) and remove from frame received_crc16_high = frame.pop() received_crc16_low = frame.pop() (crc16_low, crc16_high) = self.crc16.CRC16(frame) if((received_crc16_high != crc16_high) or (received_crc16_low != crc16_low)): raise Exception("CRC16 mismatch in received data from Thermostat") # Validate frame head if(frame[0] != 0x94): raise Exception("Unknown type of message received from Thermostat") # Read out and validate the frame length frame_length = (frame[2] << 8) | frame[1] if(frame_length != (len(frame) + 2)): #+2 since CRC has been removed raise Exception("Invalid frame length in data received from Thermostat") # Read out DCB start address dcb_start = (frame[4] << 8) | frame[3] # Read out and validate DCB content length dcb_length = (frame[6] << 8) | frame[5] if(dcb_length == 0): raise Exception("Thermostat connected but reports wrong PIN code") if(dcb_length != (frame_length - 9)): #Overhead in frame is 9 bytes raise Exception("Invalid DCB length in data received from Thermostat") # Read out DCB data dcb_data = frame[7:] return (dcb_start, dcb_data) def get_dcb(self): ''' Get whole DCB ''' self._send_read_request() (dcb_start, dcb_data) = self._receive_dcb() return dcb_data def set_dcb(self, dcb_address, dcb_data): self._send_write_request(dcb_address, dcb_data) # Just get an ACK from the Thermostat (don't use the result) dcb = self._receive_dcb() class Heatmiser(HeatmiserTransport): ''' This class handles the Heatmiser application (DCB) protocol ''' def _get_info_time_triggers(self, dcb, first_index): index = first_index info = OrderedDict() for i in range (1,5): trigger = OrderedDict() trigger['hour'] = dcb[index] index = index + 1 trigger['minute'] = dcb[index] index = index + 1 trigger['set_temp'] = dcb[index] index = index + 1 info['time'+str(i)] = trigger return info def get_info(self): ''' Returns an ordered dictionary with all Thermostat values ''' dcb = self.get_dcb() if(len(dcb) < 41): raise Exception("Size of DCB received from Thermostat is too small") info = OrderedDict() if(dcb[2] == 0): info["vendor_id"] = "HEATMISER" else: info["vendor_id"] = "OEM" info["version"] = dcb[3] & 0x7F info["in_floor_limit_state"] = ((dcb[3] & 0x8F) > 0) if(dcb[4] == 0): info["model"] = "DT" elif(dcb[4] == 1): info["model"] = "DT-E" elif(dcb[4] == 2): info["model"] = "PRT" elif(dcb[4] == 3): info["model"] = "PRT-E" else: info["model"] = "Unknown" if(dcb[5] == 0): info["temperature_format"] = "Celsius" else: info["temperature_format"] = "Fahrenheit" info["switch_differential"] = dcb[6] info["frost_protection_enable"] = (dcb[7] == 1) info["calibration_offset"] = ((dcb[8] << 8) | dcb[9]) info["output_delay_in_minutes"] = dcb[10] # dcb[11] = address (not used) info['up_down_key_limit'] = dcb[12] if(dcb[13] == 0): info['sensor_selection'] = "Built in air sensor only" elif(dcb[13] == 1): info['sensor_selection'] = "Remote air sensor only" elif(dcb[13] == 2): info['sensor_selection'] = "Floor sensor only" elif(dcb[13] == 3): info['sensor_selection'] = "Built in air and floor sensor" elif(dcb[13] == 4): info['sensor_selection'] = "Remote air and floor sensor" else: info['sensor_selection'] = "Unknown" info['optimum_start'] = dcb[14] info['rate_of_change'] = dcb[15] if(dcb[16] == 0): info['program_mode'] = "2/5 mode" else: info['program_mode'] = "7 day mode" info['frost_protect_temperature'] = dcb[17] info['set_room_temp'] = dcb[18] info['floor_max_limit'] = dcb[19] info['floor_max_limit_enable'] = (dcb[20] == 1) if(dcb[21] == 1): info['on_off'] = "On" else: info['on_off'] = "Off" if(dcb[22] == 0): info['key_lock'] = "Unlock" else: info['key_lock'] = "Lock" if(dcb[23] == 0): info['run_mode'] = "Heating mode (normal mode)" else: info['run_mode'] = "Frost protection mode" # dcb[24] = away mode (not used) info['holiday_return_date_year'] = 2000 + dcb[25] info['holiday_return_date_month'] = dcb[26] info['holiday_return_date_day_of_month'] = dcb[27] info['holiday_return_date_hour'] = dcb[28] info['holiday_return_date_minute'] = dcb[29] info['holiday_enable'] = (dcb[30] == 1) info['temp_hold_minutes'] = ((dcb[31] << 8) | dcb[32]) if((dcb[13] == 1) or (dcb[13] == 4)): info['air_temp'] = (float((dcb[34] << 8) | dcb[33]) / 10.0) if((dcb[13] == 2) or (dcb[13] == 3) or (dcb[13] == 4)): info['floor_temp'] = (float((dcb[36] << 8) | dcb[35]) / 10.0) if((dcb[13] == 0) or (dcb[13] == 3)): info['air_temp'] = (float((dcb[38] << 8) | dcb[37]) / 10.0) info['error_code'] = dcb[39] info['heating_is_currently_on'] = (dcb[40] == 1) # Model DT and DT-E stops here if(dcb[4] <= 1): return info if(len(dcb) < 72): raise Exception("Size of DCB received from Thermostat is too small") info['year'] = 2000 + dcb[41] info['month'] = dcb[42] info['day_of_month'] = dcb[43] info['weekday'] = dcb[44] info['hour'] = dcb[45] info['minute'] = dcb[46] info['second'] = dcb[47] info['weekday_triggers'] = self._get_info_time_triggers(dcb, 48) info['weekend_triggers'] = self._get_info_time_triggers(dcb, 60) # If mode is 5/2 stop here if(dcb[16] == 0): return info if(len(dcb) < 156): raise Exception("Size of DCB received from Thermostat is too small") info['mon_triggers'] = self._get_info_time_triggers(dcb, 72) info['tue_triggers'] = self._get_info_time_triggers(dcb, 84) info['wed_triggers'] = self._get_info_time_triggers(dcb, 96) info['thu_triggers'] = self._get_info_time_triggers(dcb, 108) info['fri_triggers'] = self._get_info_time_triggers(dcb, 120) info['sat_triggers'] = self._get_info_time_triggers(dcb, 132) info['sun_triggers'] = self._get_info_time_triggers(dcb, 144) return info def set_value(self, name, value): ''' Use the same name and value as returned in get_info. Only a few name/keys are supported in this implementation. Use the set_dcb method to set any value. ''' if(name == "switch_differential"): self.set_dcb(6,bytearray([int(value)])) elif(name == "frost_protect_temperature"): self.set_dcb(17,bytearray([int(value)])) elif(name == "set_room_temp"): self.set_dcb(18,bytearray([int(value)])) elif(name == "floor_max_limit"): self.set_dcb(19,bytearray([int(value)])) elif(name == "floor_max_limit_enable"): if((value == True) or (value == "True") or (value == "1") or (value == 1)): value = 1 elif((value == False) or (value == "False") or (value == "0") or (value == 0)): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: True, 1, False or 0") self.set_dcb(20,bytearray([value])) elif(name == "on_off"): if(value == "On"): value = 1 elif(value == "Off"): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: 'On' or 'Off'") self.set_dcb(21,bytearray([value])) elif(name == "key_lock"): if(value == "Lock"): value = 1 elif(value == "Unlock"): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: 'Lock' or 'Unlock'") self.set_dcb(22,bytearray([value])) elif(name == "run_mode"): if(value == "Frost protection mode"): value = 1 elif(value == "Heating mode (normal mode)"): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: 'Frost protection mode' or " + "'Heating mode (normal mode)'") self.set_dcb(23,bytearray([value])) else: raise Exception("'"+name+"' not supported to be set") ############################################################################### # Below is a command line tool for reading and setting parameters of a # Heatmiser Wifi thermostat. It can also be seen as an example on how to use # the library. def print_dict(dict, level=""): for i in dict.items(): if(isinstance(i[1],OrderedDict)): print(level+i[0]+":") print_dict(i[1],level + " ") else: print(level+str(i[0])+" = "+str(i[1])) def main(): # This function shows how to use the Heatmiser class. parser = OptionParser("Usage: %prog [options] <Heatmiser Thermostat address>") parser.add_option("-p", "--port", dest="port", type="int", help="Port of HeatMiser Thermostat (default 8068)", default=8068) parser.add_option("-c", "--pin", dest="pin", type="int", help="Pin code of HeatMiser Thermostat (default 0000)", default=0) parser.add_option("-l", "--list", action="store_true", dest="list_all", help="List all parameters in Thermostat", default=False) parser.add_option("-r", "--read", dest="parameter", help="Read one parameter in Thermostat (-r param)", default="") parser.add_option("-w", "--write", dest="param_value", nargs=2, help="Write value to parameter in Thermostat (-w param value)") (options, args) = parser.parse_args() if (len(args) != 1): parser.error("Wrong number of arguments") host = args[0] # Create a new Heatmiser object heatmiser = Heatmiser(host,options.port,options.pin) # Connect to Thermostat heatmiser.connect() # Read all parameters info = heatmiser.get_info() # Print all parameters in Thermostat if(options.list_all): print_dict(info) # Print one parameter in Thermostat if(options.parameter != ""): if (options.parameter in info): print(options.parameter + " = " + str(info[options.parameter])) else: sys.stderr.write("Error!\n"+ "Parameter '"+options.parameter+"' does not exist\n") # Write value to one parameter in Thermostat if(options.param_value != None): param = options.param_value[0] value = options.param_value[1] if (param in info): try: heatmiser.set_value(param,value) info2 = heatmiser.get_info() print("Before change: " + param + " = " + str(info[param])) print("After change: " + param + " = " + str(info2[param])) except Exception as e: sys.stderr.write(e.args[0]+"\n") else: sys.stderr.write("Error!\n"+ "Parameter '"+param+"' does not exist\n") heatmiser.disconnect() if __name__ == '__main__': main()
elf.sock.close()
identifier_body
heatmiser_wifi.py
#!/usr/bin/env python # coding=utf-8 # ############################################################################### # - heatmiser_wifi - # # Copyright 2020 by Joel Midstjärna (joel.midstjarna@gmail.com) # # A Heatmiser WiFi Thermostat communication library. # # Supported Heatmiser Thermostats are DT, DT-E, PRT and PRT-E. # # It is also possible to run this file as a command line executable. # # All rights reserved. # This file is part of the heatmiser_wifi python library and is # released under the "MIT License Agreement". Please see the LICENSE # file that should have been included as part of this package. ############################################################################### import socket, time, sys from optparse import OptionParser from collections import OrderedDict class CRC16: CRC16_LookupHigh = [0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1] CRC16_LookupLow = [0x00, 0x21, 0x42, 0x63, 0x84, 0xA5, 0xC6, 0xE7, 0x08, 0x29, 0x4A, 0x6B, 0x8C, 0xAD, 0xCE, 0xEF] CRC16_High = 0xff CRC16_Low = 0xff def _CRC16_Update4Bits(self, val): t = (self.CRC16_High >> 4) & 0xff t = (t ^ val) & 0xff self.CRC16_High = ((self.CRC16_High << 4)|(self.CRC16_Low >> 4)) & 0xff self.CRC16_Low = (self.CRC16_Low << 4) & 0xff self.CRC16_High = (self.CRC16_High ^ self.CRC16_LookupHigh[t]) & 0xff self.CRC16_Low = (self.CRC16_Low ^ self.CRC16_LookupLow[t]) & 0xff def _CRC16_Update(self, val): self._CRC16_Update4Bits((val >> 4) & 0x0f) self._CRC16_Update4Bits(val & 0x0f) def CRC16(self,bytes): self.CRC16_High = 0xff self.CRC16_Low = 0xff for byte in bytes: self._CRC16_Update(byte) return (self.CRC16_Low, self.CRC16_High) class HeatmiserTransport: ''' This class handles the Heatmiser transport protocol ''' def __init__(self, host, port, pin): self.host = host self.port = port self.crc16 = CRC16() self.pin = pin def connect(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.host,self.port)) self.sock.settimeout(5) def disconnect(self): self.sock.close() def _send_read_request(self, dcb_start = 0x0, dcb_length = 0xffff): ''' dcb_length = 0xffff means the whole DCB. The Heatmiser v3 protocol specification recommends that the whole DCB shall be read at once. It seems that dcb_start > 0x0 has no effect. ''' frame_list = [ 0x93, # Operation 0x93=Read, 0xa3=Write 0x0b, # Frame length low byte inc CRC (0xb if no data) 0x00, # Frame length high byte inc CRC (0 if no data) int(self.pin) & 0xff, # PIN code low byte int(self.pin) >> 8, # PIN code high byte dcb_start & 0xff, # DCB start low byte dcb_start >> 8, # DCB start high byte dcb_length & 0xff, # DCB length low byte (0xff for whole DCB) dcb_length >> 8] # DCB length high byte (0xff for whole DCB) frame = bytearray(frame_list) # Add CRC16 to the frame (16 bytes) (crc16_low, crc16_high) = self.crc16.CRC16(frame) frame.append(crc16_low) frame.append(crc16_high) self.sock.send(frame) def _send_write_request(self, dcb_address, dcb_data): ''' dcb_address is address in DCB block (not index) ''' dcb_length = len(dcb_data) length = dcb_length + 11 frame_list = [ 0xa3, # Operation 0x93=Read, 0xa3=Write length & 0xff, # Frame length low byte inc CRC (11+dcb_data) length >> 8, # Frame length high byte inc CRC (11+dcb_data) self.pin & 0xff, # PIN code low byte self.pin >> 8, # PIN code high byte 1, # Nbr of items (only 1 in this impl) dcb_address & 0xff,# DCB address low byte dcb_address >> 8, # DCB address high byte dcb_length] # DCB length frame = bytearray(frame_list) + dcb_data # Add CRC16 to the frame (16 bytes) (crc16_low, crc16_high) = self.crc16.CRC16(frame) frame.append(crc16_low) frame.append(crc16_high) self.sock.send(frame) def _receive_dcb(self): data = self.sock.recv(1024) frame = bytearray(data) # Validate the CRC (two last bytes) and remove from frame received_crc16_high = frame.pop() received_crc16_low = frame.pop() (crc16_low, crc16_high) = self.crc16.CRC16(frame) if((received_crc16_high != crc16_high) or (received_crc16_low != crc16_low)): raise Exception("CRC16 mismatch in received data from Thermostat") # Validate frame head if(frame[0] != 0x94): raise Exception("Unknown type of message received from Thermostat") # Read out and validate the frame length frame_length = (frame[2] << 8) | frame[1] if(frame_length != (len(frame) + 2)): #+2 since CRC has been removed raise Exception("Invalid frame length in data received from Thermostat") # Read out DCB start address dcb_start = (frame[4] << 8) | frame[3] # Read out and validate DCB content length dcb_length = (frame[6] << 8) | frame[5] if(dcb_length == 0): raise Exception("Thermostat connected but reports wrong PIN code") if(dcb_length != (frame_length - 9)): #Overhead in frame is 9 bytes raise Exception("Invalid DCB length in data received from Thermostat") # Read out DCB data dcb_data = frame[7:] return (dcb_start, dcb_data) def get_dcb(self): ''' Get whole DCB ''' self._send_read_request() (dcb_start, dcb_data) = self._receive_dcb() return dcb_data def set_dcb(self, dcb_address, dcb_data): self._send_write_request(dcb_address, dcb_data) # Just get an ACK from the Thermostat (don't use the result) dcb = self._receive_dcb() class Heatmiser(HeatmiserTransport): ''' This class handles the Heatmiser application (DCB) protocol ''' def _get_info_time_triggers(self, dcb, first_index): index = first_index info = OrderedDict() for i in range (1,5): trigger = OrderedDict() trigger['hour'] = dcb[index] index = index + 1 trigger['minute'] = dcb[index] index = index + 1 trigger['set_temp'] = dcb[index] index = index + 1 info['time'+str(i)] = trigger return info def get_info(self): ''' Returns an ordered dictionary with all Thermostat values ''' dcb = self.get_dcb() if(len(dcb) < 41): raise Exception("Size of DCB received from Thermostat is too small") info = OrderedDict() if(dcb[2] == 0): info["vendor_id"] = "HEATMISER" else: info["vendor_id"] = "OEM" info["version"] = dcb[3] & 0x7F info["in_floor_limit_state"] = ((dcb[3] & 0x8F) > 0) if(dcb[4] == 0): info["model"] = "DT" elif(dcb[4] == 1): info["model"] = "DT-E" elif(dcb[4] == 2): info["model"] = "PRT" elif(dcb[4] == 3): info["model"] = "PRT-E" else: info["model"] = "Unknown" if(dcb[5] == 0): info["temperature_format"] = "Celsius" else: info["temperature_format"] = "Fahrenheit" info["switch_differential"] = dcb[6] info["frost_protection_enable"] = (dcb[7] == 1) info["calibration_offset"] = ((dcb[8] << 8) | dcb[9]) info["output_delay_in_minutes"] = dcb[10] # dcb[11] = address (not used) info['up_down_key_limit'] = dcb[12] if(dcb[13] == 0): info['sensor_selection'] = "Built in air sensor only" elif(dcb[13] == 1): info['sensor_selection'] = "Remote air sensor only" elif(dcb[13] == 2): info['sensor_selection'] = "Floor sensor only" elif(dcb[13] == 3): info['sensor_selection'] = "Built in air and floor sensor" elif(dcb[13] == 4): info['sensor_selection'] = "Remote air and floor sensor" else: info['sensor_selection'] = "Unknown" info['optimum_start'] = dcb[14] info['rate_of_change'] = dcb[15] if(dcb[16] == 0): info['program_mode'] = "2/5 mode" else: info['program_mode'] = "7 day mode" info['frost_protect_temperature'] = dcb[17] info['set_room_temp'] = dcb[18] info['floor_max_limit'] = dcb[19] info['floor_max_limit_enable'] = (dcb[20] == 1) if(dcb[21] == 1): info['on_off'] = "On" else: info['on_off'] = "Off" if(dcb[22] == 0): info['key_lock'] = "Unlock" else: info['key_lock'] = "Lock" if(dcb[23] == 0): info['run_mode'] = "Heating mode (normal mode)" else: info['run_mode'] = "Frost protection mode" # dcb[24] = away mode (not used) info['holiday_return_date_year'] = 2000 + dcb[25] info['holiday_return_date_month'] = dcb[26] info['holiday_return_date_day_of_month'] = dcb[27] info['holiday_return_date_hour'] = dcb[28] info['holiday_return_date_minute'] = dcb[29] info['holiday_enable'] = (dcb[30] == 1) info['temp_hold_minutes'] = ((dcb[31] << 8) | dcb[32]) if((dcb[13] == 1) or (dcb[13] == 4)): info['air_temp'] = (float((dcb[34] << 8) | dcb[33]) / 10.0) if((dcb[13] == 2) or (dcb[13] == 3) or (dcb[13] == 4)): info['floor_temp'] = (float((dcb[36] << 8) | dcb[35]) / 10.0) if((dcb[13] == 0) or (dcb[13] == 3)): info['air_temp'] = (float((dcb[38] << 8) | dcb[37]) / 10.0) info['error_code'] = dcb[39] info['heating_is_currently_on'] = (dcb[40] == 1) # Model DT and DT-E stops here if(dcb[4] <= 1): return info if(len(dcb) < 72): raise Exception("Size of DCB received from Thermostat is too small") info['year'] = 2000 + dcb[41] info['month'] = dcb[42] info['day_of_month'] = dcb[43] info['weekday'] = dcb[44] info['hour'] = dcb[45] info['minute'] = dcb[46] info['second'] = dcb[47] info['weekday_triggers'] = self._get_info_time_triggers(dcb, 48) info['weekend_triggers'] = self._get_info_time_triggers(dcb, 60) # If mode is 5/2 stop here if(dcb[16] == 0): return info if(len(dcb) < 156): raise Exception("Size of DCB received from Thermostat is too small") info['mon_triggers'] = self._get_info_time_triggers(dcb, 72) info['tue_triggers'] = self._get_info_time_triggers(dcb, 84) info['wed_triggers'] = self._get_info_time_triggers(dcb, 96) info['thu_triggers'] = self._get_info_time_triggers(dcb, 108) info['fri_triggers'] = self._get_info_time_triggers(dcb, 120) info['sat_triggers'] = self._get_info_time_triggers(dcb, 132) info['sun_triggers'] = self._get_info_time_triggers(dcb, 144) return info def set_value(self, name, value): ''' Use the same name and value as returned in get_info. Only a few name/keys are supported in this implementation. Use the set_dcb method to set any value. ''' if(name == "switch_differential"): self.set_dcb(6,bytearray([int(value)])) elif(name == "frost_protect_temperature"): self.set_dcb(17,bytearray([int(value)])) elif(name == "set_room_temp"): self.set_dcb(18,bytearray([int(value)])) elif(name == "floor_max_limit"): self.set_dcb(19,bytearray([int(value)])) elif(name == "floor_max_limit_enable"): if((value == True) or (value == "True") or (value == "1") or (value == 1)): value = 1 elif((value == False) or (value == "False") or (value == "0") or (value == 0)): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: True, 1, False or 0") self.set_dcb(20,bytearray([value])) elif(name == "on_off"): if(value == "On"): value = 1 elif(value == "Off"): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: 'On' or 'Off'") self.set_dcb(21,bytearray([value])) elif(name == "key_lock"): if(value == "Lock"): value = 1 elif(value == "Unlock"): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: 'Lock' or 'Unlock'") self.set_dcb(22,bytearray([value])) elif(name == "run_mode"): if(value == "Frost protection mode"): value = 1 elif(value == "Heating mode (normal mode)"): value = 0 else: raise Exception("'"+name+"' invalid value '"+str(value)+"'\n" + "Valid values: 'Frost protection mode' or " + "'Heating mode (normal mode)'") self.set_dcb(23,bytearray([value])) else: raise Exception("'"+name+"' not supported to be set") ############################################################################### # Below is a command line tool for reading and setting parameters of a # Heatmiser Wifi thermostat. It can also be seen as an example on how to use # the library. def print_dict(dict, level=""): for i in dict.items(): if(isinstance(i[1],OrderedDict)): print(level+i[0]+":") print_dict(i[1],level + " ") else: print(level+str(i[0])+" = "+str(i[1])) def main(): # This function shows how to use the Heatmiser class. parser = OptionParser("Usage: %prog [options] <Heatmiser Thermostat address>") parser.add_option("-p", "--port", dest="port", type="int", help="Port of HeatMiser Thermostat (default 8068)", default=8068) parser.add_option("-c", "--pin", dest="pin", type="int", help="Pin code of HeatMiser Thermostat (default 0000)", default=0) parser.add_option("-l", "--list", action="store_true", dest="list_all", help="List all parameters in Thermostat", default=False) parser.add_option("-r", "--read", dest="parameter", help="Read one parameter in Thermostat (-r param)", default="") parser.add_option("-w", "--write", dest="param_value", nargs=2, help="Write value to parameter in Thermostat (-w param value)") (options, args) = parser.parse_args() if (len(args) != 1): parser.error("Wrong number of arguments") host = args[0] # Create a new Heatmiser object heatmiser = Heatmiser(host,options.port,options.pin) # Connect to Thermostat heatmiser.connect() # Read all parameters info = heatmiser.get_info() # Print all parameters in Thermostat if(options.list_all): print_dict(info) # Print one parameter in Thermostat if(options.parameter != ""):
print(options.parameter + " = " + str(info[options.parameter])) else: sys.stderr.write("Error!\n"+ "Parameter '"+options.parameter+"' does not exist\n") # Write value to one parameter in Thermostat if(options.param_value != None): param = options.param_value[0] value = options.param_value[1] if (param in info): try: heatmiser.set_value(param,value) info2 = heatmiser.get_info() print("Before change: " + param + " = " + str(info[param])) print("After change: " + param + " = " + str(info2[param])) except Exception as e: sys.stderr.write(e.args[0]+"\n") else: sys.stderr.write("Error!\n"+ "Parameter '"+param+"' does not exist\n") heatmiser.disconnect() if __name__ == '__main__': main()
if (options.parameter in info):
random_line_split
lib.rs
use cpython::{ py_class, py_exception, py_module_initializer, ObjectProtocol, PyClone, PyDrop, PyErr, PyObject, PyResult, PySequence, PythonObject, exc::{TypeError} }; use search::Graph; use std::cell::RefCell; use std::collections::{BTreeSet, HashMap}; use std::convert::TryInto; mod search; #[cfg(feature = "python2")] pub type Int = std::os::raw::c_long; #[cfg(feature = "python3")] pub type Int = isize; // Simple utility, make a hash set out of python sequence macro_rules! hash_seq { ($py:expr, $seq:expr) => { $seq.iter($py)? .filter_map(|v| match v { Ok(v) => v.hash($py).ok(), _ => None, }) .collect() }; } // Small utility to log using python logger. macro_rules! warn { ($py:expr, $message:expr) => { $py.import("logging")? .call($py, "getLogger", ("to",), None)? .call_method($py, "warning", (&$message,), None)?; }; } ////////////////////////////////////////////////// // MODULE SETUP // NOTE: "_internal" is the name of this module after build process moves it py_module_initializer!(_internal, |py, m| { m.add(py, "__doc__", "Simple plugin based A to B function chaining. You could be wanting to convert between a chain of types, or traverse a bunch of object oriented links. If you're often thinking \"I have this, how can I get that\", then this type of solution could help. >>> conv = Conversions() >>> conv.add_conversion(1, str, [\"url\"], WebPage, [], load_webpage) >>> conv.add_revealer(str, http_revealer) # optional convenience >>> conv.convert(\"http://somewhere.html\", WebPage) ")?; m.add(py, "ConversionError", py.get_type::<ConversionError>())?; m.add_class::<Conversions>(py)?; Ok(()) }); ////////////////////////////////////////////////// ////////////////////////////////////////////////// // Exceptions py_exception!(to, ConversionError); // Triggered when errors occurred during conversion process ////////////////////////////////////////////////// py_class!(class Conversions |py| { data graph: RefCell<Graph<Int, Int, Int>>; data functions: RefCell<HashMap<Int, PyObject>>; data revealers: RefCell<HashMap<Int, Vec<PyObject>>>; def __new__(_cls) -> PyResult<Conversions> { Conversions::create_instance( py, RefCell::new(Graph::new()), RefCell::new(HashMap::new()), RefCell::new(HashMap::new()), ) } /// Add a function so it may be used as a step in the composition process later. /// Eventually a composition chain will consist of a number of these functions placed back to back. /// So the simpler, smaller and more focused the function the better. /// /// Args: /// cost (int): /// A number representing how much work this function needs to do. /// Lower numbers are prioritized. This lets the composition prefer the cheapest option. /// eg: just getting an attribute would be a low number. Accessing an network service would be higher etc /// type_in (Type[A]): /// Type of input expected. /// eg str / MyClass or a composite type eg frozenset([Type1, Type2]) /// variations_in (Sequence[Hashable]): /// A sequence of hashable "tags" further describing the input type. /// For the node to be used, all these variations are required (dependencies). /// This is useful if the more simple type is not enough by itself. /// eg: str (can be path/url/email/name/etc) /// type_out (Type[B]): /// Same as "type_in", but representing the output of the transmutation. /// variations_out (Sequence[Hashable]): /// Same as "variations_in" except that variations are descriptive and not dependencies. /// They can satisfy dependencies for transmuters further down the chain. /// function (Callable[[A], B]): /// The converter itself. Take a single input, produce a single output. /// It is important that only an simple conversion is made, and that any deviation is raised as an Error. /// eg: maybe some attribute is not available and usually you'd return None. There is no strict type /// checking here, so raise an error and bail instead. def add_conversion( &self, cost: Int, type_in: &PyObject, variations_in: &PySequence, type_out: &PyObject, variations_out: &PySequence, function: PyObject ) -> PyResult<PyObject> { let hash_in = type_in.hash(py)?; let hash_out = type_out.hash(py)?; let hash_func = function.hash(py)?; let hash_var_in = hash_seq!(py, variations_in); let hash_var_out = hash_seq!(py, variations_out); // Store a reference to the python object in this outer layer // but refer to it via its hash. self.functions(py).borrow_mut().insert(hash_func, function); self.graph(py).borrow_mut().add_edge( cost.try_into().expect("Cost needs to be an int"), hash_in, hash_var_in, hash_out, hash_var_out, hash_func, ); Ok(py.None()) } /// Supply a function that will attempt to reveal insights into the provided data as variations. /// This is a convenience aid, to assist in detecting input variations automatically so they do not /// need to be expicitly specified. /// The activator function should run quickly so as to keep the entire process smooth. /// ie simple attribute checks, string regex etc /// /// Important note: These functions are not run on intermediate conversions, but only on the /// supplied data. /// /// Args: /// type_in (Type[A]): /// The type of input this function accepts. /// function (Callable[[A], Iterator[Hashable]]): /// Function that takes the value provided (of the type above) and yields any variations it finds. /// eg: str type could check for link type if the string is http://something.html and /// yield "protocol" "http" "url" def add_revealer(&self, type_in: &PyObject, function: PyObject) -> PyResult<PyObject> { self.revealers(py).borrow_mut().entry(type_in.hash(py)?).or_insert(Vec::new()).push(function); Ok(py.None()) } /// From a given type, attempt to produce a requested type. /// OR from some given data, attempt to traverse links to get the requested data. /// /// Args: /// value (Any): The input you have going into the process. This can be anything. /// type_want (Type[B]): /// The type you want to recieve. A chain of converters will be produced /// attempting to attain this type. /// variations_want (Sequence[Hashable]): /// A sequence of variations further describing the type you wish to attain. /// This is optional but can help guide the selection of converters through more complex transitions. /// type_have (Type[A]): /// An optional override for the starting type. /// If not provided the type of the value is taken instead. /// variations_have (Sequence[Hashable]): /// Optionally include any extra variations to the input. /// If context is known but hard to detect this can help direct a more complex /// transmutation. /// explicit (bool): /// If this is True, the "variations_have" argument will entirely override /// any detected tags. Enable this to use precisesly what you specify (no automatic detection). /// Returns: /// B: Whatever the result requested happens to be def convert( &self, value: PyObject, type_want: &PyObject, variations_want: Option<&PySequence> = None, type_have: Option<&PyObject> = None, variations_have: Option<&PySequence> = None, explicit: bool = false, debug: bool = false, ) -> PyResult<PyObject> { let hash_in = match type_have { Some(type_override) => type_override.hash(py)?, None => value.get_type(py).into_object().hash(py)? }; let hash_out = type_want.hash(py)?; let hash_var_out = match variations_want { Some(vars) => hash_seq!(py, vars), None => BTreeSet::new(), }; let mut hash_var_in = match variations_have { Some(vars) => hash_seq!(py, vars), None => BTreeSet::new(), }; if !explicit { // We don't want to be explicit, so // run the activator to detect initial variations if let Some(funcs) = self.revealers(py).borrow().get(&hash_in) { for func in funcs { for variation in func.call(py, (value.clone_ref(py),), None)?.iter(py)? { hash_var_in.insert(variation?.hash(py)?); } } }
// and there are still errors. Raise with info from all of them. let mut skip_edges = BTreeSet::new(); let mut errors = Vec::new(); 'outer: for _ in 0..10 { if let Some(edges) = self.graph(py).borrow().search(hash_in, &hash_var_in, hash_out, &hash_var_out, &skip_edges) { let functions = self.functions(py).borrow(); let mut result = value.clone_ref(py); for edge in edges { let func = functions.get(&edge.data).expect("Function is there"); if debug { warn!(py, format!("{}({}) -> ...", func.to_string(), result.to_string())); } match func.call(py, (result,), None) { Ok(res) => { if debug { warn!(py, format!("... -> {}", res.to_string())); } result = res; }, Err(mut err) => { let message = format!( "{}: {}", err.get_type(py).name(py), err.instance(py).str(py)?.to_string(py)?, ); warn!(py, message); errors.push(message); // Ignore these when trying again. // This allows some level of failure // and with enough edges perhaps we // can find another path. skip_edges.insert(edge); continue 'outer } }; } return Ok(result) } break } if errors.len() != 0 { Err(PyErr::new::<ConversionError, _>(py, format!( "Some problems occurred during the conversion process:\n{}", errors.join("\n") ))) } else { Err(PyErr::new::<TypeError, _>( py, format!( "Could not convert {} to {}. Perhaps some conversion steps are missing.", value, type_want ))) } } /////////////////////////////////////////////////////////////// // Satisfy python garbage collector // because we hold a reference to some functions provided def __traverse__(&self, visit) { for function in self.functions(py).borrow().values() { visit.call(function)?; } for functions in self.revealers(py).borrow().values() { for function in functions { visit.call(function)?; } } Ok(()) } def __clear__(&self) { for (_, func) in self.functions(py).borrow_mut().drain() { func.release_ref(py); } for (_, mut funcs) in self.revealers(py).borrow_mut().drain() { for func in funcs.drain(..) { func.release_ref(py); } } } /////////////////////////////////////////////////////////////// });
} // Retry a few times, if something breaks along the way. // Collect errors. // If we run out of paths to take or run out of reties,
random_line_split
lib.rs
//! This crate wraps [libkres](https://knot-resolver.cz) from //! [CZ.NIC Labs](https://labs.nic.cz). libkres is an implementation of a full DNS recursive resolver, //! including cache and DNSSEC validation. It doesn't require a specific I/O model and instead provides //! a generic interface for pushing/pulling DNS messages until the request is satisfied. //! //! The interface provided implements a minimal subset of operations from the engine: //! //! * `struct kr_context` is wrapped by [Context](struct.Context.html). Functions from libkres that //! operate on `struct kr_context` are accessed using methods on [Context](struct.Context.html). //! The context implements lock guards for all FFI calls on context, and all FFI calls on request //! that borrows given context. //! //! * `struct kr_request` is wrapped by [Request](struct.Request.html). Methods on //! [Request](struct.Request.html) are used to safely access the fields of `struct kr_request`. //! Methods that wrap FFI calls lock request and its context for thread-safe access. //! //! Example: //! //! ``` //! use std::net::{SocketAddr, UdpSocket}; //! use kres::{Context, Request, State}; //! //! // DNS message wire format //! let question = [2, 104, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1]; //! let from_addr = "127.0.0.1:1234".parse::<SocketAddr>().unwrap(); //! //! let context = Context::new(); //! let req = Request::new(context.clone()); //! let mut state = req.consume(&question, from_addr); //! while state == State::PRODUCE { //! state = match req.produce() { //! Some((msg, addr_set)) => { //! // This can be any I/O model the application uses //! let mut socket = UdpSocket::bind("0.0.0.0:0").unwrap(); //! socket.send_to(&msg, &addr_set[0]).unwrap(); //! let mut buf = [0; 512]; //! let (amt, src) = socket.recv_from(&mut buf).unwrap(); //! // Pass the response back to the request //! req.consume(&buf[..amt], src) //! }, //! None => { //! break; //! } //! } //! } //! //! // Convert request into final answer //! let answer = req.finish(state).unwrap(); //! ``` #[cfg(feature = "jemalloc")] use jemallocator; #[cfg(feature = "jemalloc")] #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; use bytes::Bytes; use parking_lot::{Mutex, MutexGuard}; use std::ffi::{CStr, CString}; use std::io::{Error, ErrorKind, Result}; use std::mem; use std::net::{IpAddr, SocketAddr}; use std::ptr; use std::sync::Arc; /// Number of tries to produce a next message const MAX_PRODUCE_TRIES : usize = 3; // Wrapped C library mod c { #![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); } /// Request state enumeration pub use self::c::lkr_state as State; /// Shared context for the request resolution. /// All requests create with a given context use its facilities: /// * Trust Anchor storage /// * Root Server bootstrap set /// * Cache /// * Default EDNS options /// * Default options pub struct Context { inner: Mutex<*mut c::lkr_context>, } /* Context itself is not thread-safe, but Mutex wrapping it is */ unsafe impl Send for Context {} unsafe impl Sync for Context {} impl Context { /// Create an empty context without internal cache pub fn new() -> Arc<Self> { unsafe { Arc::new(Self { inner: Mutex::new(c::lkr_context_new()), }) } } /// Create an empty context with local disk cache pub fn with_cache(path: &str, max_bytes: usize) -> Result<Arc<Self>> { unsafe { let inner = c::lkr_context_new(); let path_c = CString::new(path).unwrap(); let cache_c = CStr::from_bytes_with_nul(b"cache\0").unwrap(); match c::lkr_cache_open(inner, path_c.as_ptr(), max_bytes) { 0 => { c::lkr_module_load(inner, cache_c.as_ptr()); Ok(Arc::new(Self { inner: Mutex::new(inner), })) } _ => Err(Error::new(ErrorKind::Other, "failed to open cache")), } } } /// Add a resolver module, see [Knot Resolver modules](https://knot-resolver.readthedocs.io/en/stable/modules.html) for reference pub fn add_module(&self, name: &str) -> Result<()> { let inner = self.locked(); let name_c = CString::new(name)?; unsafe { let res = c::lkr_module_load(*inner, name_c.as_ptr()); if res != 0 { return Err(Error::new(ErrorKind::NotFound, "failed to load module")); } } Ok(()) } /// Remove a resolver module, see [Knot Resolver modules](https://knot-resolver.readthedocs.io/en/stable/modules.html) for reference pub fn remove_module(&self, name: &str) -> Result<()> { let inner = self.locked(); let name_c = CString::new(name)?; unsafe { let res = c::lkr_module_unload(*inner, name_c.as_ptr()); if res != 0 { return Err(Error::new(ErrorKind::NotFound, "failed to unload module")); } } Ok(()) } /// Add a root server hint to the context. The root server hints are used to bootstrap the resolver, there must be at least one. pub fn add_root_hint(&self, addr: IpAddr) -> Result<()> { let inner = self.locked(); let slice = match addr { IpAddr::V4(ip) => ip.octets().to_vec(), IpAddr::V6(ip) => ip.octets().to_vec(), }; unsafe { let res = c::lkr_root_hint(*inner, slice.as_ptr(), slice.len()); if res != 0 { return Err(Error::new( ErrorKind::InvalidInput, "failed to add a root hint", )); } } Ok(()) } /// Add a trust anchor to the resolver. If the context has at least 1 trust anchor, it will perform DNSSEC validation under it. pub fn add_trust_anchor(&self, rdata: &[u8]) -> Result<()> { let inner = self.locked(); unsafe { let res = c::lkr_trust_anchor(*inner, rdata.as_ptr(), rdata.len()); if res != 0 { return Err(Error::new( ErrorKind::InvalidInput, "failed to add trust anchor", )); } } Ok(()) } /// Set or reset verbose mode pub fn set_verbose(&self, val: bool) { let inner = self.locked(); unsafe { c::lkr_verbose(*inner, val); } } fn locked(&self) -> MutexGuard<*mut c::lkr_context> { self.inner.lock() } } impl Drop for Context { fn drop(&mut self) { let inner = self.locked(); if !inner.is_null() { unsafe { c::lkr_context_free(*inner); } } } } /// Request wraps `struct kr_request` and keeps a reference for the context. /// The request is not automatically executed, it must be driven the caller to completion. pub struct Request { context: Arc<Context>, inner: Mutex<*mut c::lkr_request>, } /* Neither request nor context are thread safe. * Both request and context pointers is guarded by a mutex, * and must be locked during any operation on the request. */ unsafe impl Send for Request {} unsafe impl Sync for Request {} impl Request { /// Create a new request under the context. The request is bound to the context for its lifetime. pub fn new(context: Arc<Context>) -> Self { let inner = unsafe { c::lkr_request_new(*context.locked()) }; Self { context, inner: Mutex::new(inner), } } /// Consume an input from the caller, this is typically either a client query or response to an outbound query. pub fn consume(&self, msg: &[u8], from: SocketAddr) -> State { let (_context, inner) = self.locked(); let from = socket2::SockAddr::from(from); let msg_ptr = if !msg.is_empty() { msg.as_ptr() } else { ptr::null() }; unsafe { c::lkr_consume(*inner, from.as_ptr() as *const _, msg_ptr, msg.len()) } } /// Generate an outbound query for the request. This should be called when `consume()` returns a `Produce` state. pub fn produce(&self) -> Option<(Bytes, Vec<SocketAddr>)> { let mut msg = vec![0; 512]; let mut addresses = Vec::new(); let mut sa_vec: Vec<*mut c::sockaddr> = vec![ptr::null_mut(); 4]; let (_context, inner) = self.locked(); let state = { let mut state = State::PRODUCE; let mut tries = MAX_PRODUCE_TRIES; while state == State::PRODUCE { if tries == 0 { break; } tries -= 1; // Prepare socket address vector let addr_ptr = sa_vec.as_mut_ptr(); let addr_capacity = sa_vec.capacity(); // Prepare message buffer let msg_capacity = msg.capacity(); let msg_ptr = msg.as_mut_ptr(); let mut msg_size = msg_capacity; // Generate next message unsafe { mem::forget(msg); mem::forget(sa_vec); state = c::lkr_produce( *inner, addr_ptr, addr_capacity, msg_ptr, &mut msg_size, false, ); // Rebuild vectors from modified pointers msg = Vec::from_raw_parts(msg_ptr, msg_size, msg_capacity); sa_vec = Vec::from_raw_parts(addr_ptr, addr_capacity, addr_capacity); } } state }; match state { State::DONE => None, State::CONSUME => { for ptr_addr in sa_vec { if ptr_addr.is_null() { break; } let addr = unsafe { socket2::SockAddr::from_raw_parts( ptr_addr as *const _, c::lkr_sockaddr_len(ptr_addr) as u32, ) }; if let Some(as_inet) = addr.as_inet() { addresses.push(as_inet.into()); } else { addresses.push(addr.as_inet6().unwrap().into()); } } Some((Bytes::from(msg), addresses)) } _ => None, } } /// Finish request processing and convert Request into the final answer. pub fn finish(self, state: State) -> Result<Bytes> { let (_context, inner) = self.locked(); let answer_len = unsafe { c::lkr_finish(*inner, state) }; if answer_len == 0 { return Err(ErrorKind::UnexpectedEof.into()) } let mut v: Vec<u8> = Vec::with_capacity(answer_len); let p = v.as_mut_ptr(); let v = unsafe { mem::forget(v); c::lkr_write_answer(*inner, p, answer_len); Vec::from_raw_parts(p, answer_len, answer_len) }; Ok(Bytes::from(v)) } fn locked( &self, ) -> ( MutexGuard<*mut c::lkr_context>, MutexGuard<*mut c::lkr_request>, ) { (self.context.locked(), self.inner.lock()) } } impl Drop for Request { fn drop(&mut self) { let (_context, mut inner) = self.locked(); if !inner.is_null() { unsafe { c::lkr_request_free(*inner); *inner = ptr::null_mut(); } } } } #[cfg(test)] mod tests { use super::{Context, Request, State}; use dnssector::constants::*; use dnssector::synth::gen; use dnssector::{DNSSector, Section}; use std::net::SocketAddr; #[test] fn context_create() { let context = Context::new(); let r1 = Request::new(context.clone()); let r2 = Request::new(context.clone()); let (_, p1) = r1.locked(); let (_, p2) = r2.locked(); assert!(*p1 != *p2); } #[test] fn context_create_cached() { assert!(Context::with_cache(".", 64 * 1024).is_ok()); } #[test] fn context_root_hints() { let context = Context::new(); assert!(context.add_root_hint("127.0.0.1".parse().unwrap()).is_ok()); assert!(context.add_root_hint("::1".parse().unwrap()).is_ok()); } #[test] fn
() { let context = Context::new(); assert!(context.add_module("iterate").is_ok()); assert!(context.remove_module("iterate").is_ok()); } #[test] fn context_trust_anchor() { let context = Context::new(); let ta = gen::RR::from_string( ". 0 IN DS 20326 8 2 E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D", ) .unwrap(); assert!(context.add_trust_anchor(ta.rdata()).is_ok()); } #[test] fn context_verbose() { let context = Context::new(); context.set_verbose(true); context.set_verbose(false); } #[test] fn request_processing() { let context = Context::new(); // Create a ". NS" query (priming) let request = Request::new(context.clone()); let buf = gen::query( b".", Type::from_string("NS").unwrap(), Class::from_string("IN").unwrap(), ) .unwrap(); // Push it as a question to request let addr = "1.1.1.1:53".parse::<SocketAddr>().unwrap(); request.consume(buf.packet(), addr); // Generate an outbound query let state = match request.produce() { Some((buf, addresses)) => { // Generate a mock answer to the outbound query let mut resp = DNSSector::new(buf.to_vec()).unwrap().parse().unwrap(); resp.set_response(true); resp.insert_rr( Section::Answer, gen::RR::from_string(". 86399 IN NS e.root-servers.net").unwrap(), ) .unwrap(); resp.insert_rr( Section::Additional, gen::RR::from_string("e.root-servers.net 86399 IN A 192.203.230.10").unwrap(), ) .unwrap(); // Consume the mock answer and expect resolution to be done request.consume(resp.packet(), addresses[0]) } None => State::DONE, }; // Get final answer assert_eq!(state, State::DONE); let buf = request.finish(state).unwrap(); let resp = DNSSector::new(buf.to_vec()).unwrap().parse(); assert!(resp.is_ok()); } }
context_with_module
identifier_name
lib.rs
//! This crate wraps [libkres](https://knot-resolver.cz) from //! [CZ.NIC Labs](https://labs.nic.cz). libkres is an implementation of a full DNS recursive resolver, //! including cache and DNSSEC validation. It doesn't require a specific I/O model and instead provides //! a generic interface for pushing/pulling DNS messages until the request is satisfied. //! //! The interface provided implements a minimal subset of operations from the engine: //! //! * `struct kr_context` is wrapped by [Context](struct.Context.html). Functions from libkres that //! operate on `struct kr_context` are accessed using methods on [Context](struct.Context.html). //! The context implements lock guards for all FFI calls on context, and all FFI calls on request //! that borrows given context. //! //! * `struct kr_request` is wrapped by [Request](struct.Request.html). Methods on //! [Request](struct.Request.html) are used to safely access the fields of `struct kr_request`. //! Methods that wrap FFI calls lock request and its context for thread-safe access. //! //! Example: //! //! ``` //! use std::net::{SocketAddr, UdpSocket}; //! use kres::{Context, Request, State}; //! //! // DNS message wire format //! let question = [2, 104, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1]; //! let from_addr = "127.0.0.1:1234".parse::<SocketAddr>().unwrap(); //! //! let context = Context::new(); //! let req = Request::new(context.clone()); //! let mut state = req.consume(&question, from_addr); //! while state == State::PRODUCE { //! state = match req.produce() { //! Some((msg, addr_set)) => { //! // This can be any I/O model the application uses //! let mut socket = UdpSocket::bind("0.0.0.0:0").unwrap(); //! socket.send_to(&msg, &addr_set[0]).unwrap(); //! let mut buf = [0; 512]; //! let (amt, src) = socket.recv_from(&mut buf).unwrap(); //! // Pass the response back to the request //! req.consume(&buf[..amt], src) //! }, //! None => { //! break; //! } //! } //! } //! //! // Convert request into final answer //! let answer = req.finish(state).unwrap(); //! ``` #[cfg(feature = "jemalloc")] use jemallocator; #[cfg(feature = "jemalloc")] #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; use bytes::Bytes; use parking_lot::{Mutex, MutexGuard}; use std::ffi::{CStr, CString}; use std::io::{Error, ErrorKind, Result}; use std::mem; use std::net::{IpAddr, SocketAddr}; use std::ptr; use std::sync::Arc; /// Number of tries to produce a next message const MAX_PRODUCE_TRIES : usize = 3; // Wrapped C library mod c { #![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); } /// Request state enumeration pub use self::c::lkr_state as State; /// Shared context for the request resolution. /// All requests create with a given context use its facilities: /// * Trust Anchor storage /// * Root Server bootstrap set /// * Cache /// * Default EDNS options /// * Default options pub struct Context { inner: Mutex<*mut c::lkr_context>, } /* Context itself is not thread-safe, but Mutex wrapping it is */ unsafe impl Send for Context {} unsafe impl Sync for Context {} impl Context { /// Create an empty context without internal cache pub fn new() -> Arc<Self> { unsafe { Arc::new(Self { inner: Mutex::new(c::lkr_context_new()), }) } } /// Create an empty context with local disk cache pub fn with_cache(path: &str, max_bytes: usize) -> Result<Arc<Self>> { unsafe { let inner = c::lkr_context_new(); let path_c = CString::new(path).unwrap(); let cache_c = CStr::from_bytes_with_nul(b"cache\0").unwrap(); match c::lkr_cache_open(inner, path_c.as_ptr(), max_bytes) { 0 => { c::lkr_module_load(inner, cache_c.as_ptr()); Ok(Arc::new(Self { inner: Mutex::new(inner), })) } _ => Err(Error::new(ErrorKind::Other, "failed to open cache")), } } } /// Add a resolver module, see [Knot Resolver modules](https://knot-resolver.readthedocs.io/en/stable/modules.html) for reference pub fn add_module(&self, name: &str) -> Result<()> { let inner = self.locked(); let name_c = CString::new(name)?; unsafe { let res = c::lkr_module_load(*inner, name_c.as_ptr()); if res != 0 { return Err(Error::new(ErrorKind::NotFound, "failed to load module")); } } Ok(()) } /// Remove a resolver module, see [Knot Resolver modules](https://knot-resolver.readthedocs.io/en/stable/modules.html) for reference pub fn remove_module(&self, name: &str) -> Result<()> { let inner = self.locked(); let name_c = CString::new(name)?; unsafe { let res = c::lkr_module_unload(*inner, name_c.as_ptr()); if res != 0 { return Err(Error::new(ErrorKind::NotFound, "failed to unload module")); } } Ok(()) } /// Add a root server hint to the context. The root server hints are used to bootstrap the resolver, there must be at least one. pub fn add_root_hint(&self, addr: IpAddr) -> Result<()> { let inner = self.locked(); let slice = match addr { IpAddr::V4(ip) => ip.octets().to_vec(), IpAddr::V6(ip) => ip.octets().to_vec(), }; unsafe { let res = c::lkr_root_hint(*inner, slice.as_ptr(), slice.len()); if res != 0 { return Err(Error::new( ErrorKind::InvalidInput, "failed to add a root hint", )); } } Ok(()) } /// Add a trust anchor to the resolver. If the context has at least 1 trust anchor, it will perform DNSSEC validation under it. pub fn add_trust_anchor(&self, rdata: &[u8]) -> Result<()> { let inner = self.locked(); unsafe { let res = c::lkr_trust_anchor(*inner, rdata.as_ptr(), rdata.len()); if res != 0 { return Err(Error::new( ErrorKind::InvalidInput, "failed to add trust anchor", )); } } Ok(()) } /// Set or reset verbose mode pub fn set_verbose(&self, val: bool) { let inner = self.locked(); unsafe { c::lkr_verbose(*inner, val); } } fn locked(&self) -> MutexGuard<*mut c::lkr_context> { self.inner.lock() } } impl Drop for Context { fn drop(&mut self) { let inner = self.locked(); if !inner.is_null() { unsafe { c::lkr_context_free(*inner); }
} } /// Request wraps `struct kr_request` and keeps a reference for the context. /// The request is not automatically executed, it must be driven the caller to completion. pub struct Request { context: Arc<Context>, inner: Mutex<*mut c::lkr_request>, } /* Neither request nor context are thread safe. * Both request and context pointers is guarded by a mutex, * and must be locked during any operation on the request. */ unsafe impl Send for Request {} unsafe impl Sync for Request {} impl Request { /// Create a new request under the context. The request is bound to the context for its lifetime. pub fn new(context: Arc<Context>) -> Self { let inner = unsafe { c::lkr_request_new(*context.locked()) }; Self { context, inner: Mutex::new(inner), } } /// Consume an input from the caller, this is typically either a client query or response to an outbound query. pub fn consume(&self, msg: &[u8], from: SocketAddr) -> State { let (_context, inner) = self.locked(); let from = socket2::SockAddr::from(from); let msg_ptr = if !msg.is_empty() { msg.as_ptr() } else { ptr::null() }; unsafe { c::lkr_consume(*inner, from.as_ptr() as *const _, msg_ptr, msg.len()) } } /// Generate an outbound query for the request. This should be called when `consume()` returns a `Produce` state. pub fn produce(&self) -> Option<(Bytes, Vec<SocketAddr>)> { let mut msg = vec![0; 512]; let mut addresses = Vec::new(); let mut sa_vec: Vec<*mut c::sockaddr> = vec![ptr::null_mut(); 4]; let (_context, inner) = self.locked(); let state = { let mut state = State::PRODUCE; let mut tries = MAX_PRODUCE_TRIES; while state == State::PRODUCE { if tries == 0 { break; } tries -= 1; // Prepare socket address vector let addr_ptr = sa_vec.as_mut_ptr(); let addr_capacity = sa_vec.capacity(); // Prepare message buffer let msg_capacity = msg.capacity(); let msg_ptr = msg.as_mut_ptr(); let mut msg_size = msg_capacity; // Generate next message unsafe { mem::forget(msg); mem::forget(sa_vec); state = c::lkr_produce( *inner, addr_ptr, addr_capacity, msg_ptr, &mut msg_size, false, ); // Rebuild vectors from modified pointers msg = Vec::from_raw_parts(msg_ptr, msg_size, msg_capacity); sa_vec = Vec::from_raw_parts(addr_ptr, addr_capacity, addr_capacity); } } state }; match state { State::DONE => None, State::CONSUME => { for ptr_addr in sa_vec { if ptr_addr.is_null() { break; } let addr = unsafe { socket2::SockAddr::from_raw_parts( ptr_addr as *const _, c::lkr_sockaddr_len(ptr_addr) as u32, ) }; if let Some(as_inet) = addr.as_inet() { addresses.push(as_inet.into()); } else { addresses.push(addr.as_inet6().unwrap().into()); } } Some((Bytes::from(msg), addresses)) } _ => None, } } /// Finish request processing and convert Request into the final answer. pub fn finish(self, state: State) -> Result<Bytes> { let (_context, inner) = self.locked(); let answer_len = unsafe { c::lkr_finish(*inner, state) }; if answer_len == 0 { return Err(ErrorKind::UnexpectedEof.into()) } let mut v: Vec<u8> = Vec::with_capacity(answer_len); let p = v.as_mut_ptr(); let v = unsafe { mem::forget(v); c::lkr_write_answer(*inner, p, answer_len); Vec::from_raw_parts(p, answer_len, answer_len) }; Ok(Bytes::from(v)) } fn locked( &self, ) -> ( MutexGuard<*mut c::lkr_context>, MutexGuard<*mut c::lkr_request>, ) { (self.context.locked(), self.inner.lock()) } } impl Drop for Request { fn drop(&mut self) { let (_context, mut inner) = self.locked(); if !inner.is_null() { unsafe { c::lkr_request_free(*inner); *inner = ptr::null_mut(); } } } } #[cfg(test)] mod tests { use super::{Context, Request, State}; use dnssector::constants::*; use dnssector::synth::gen; use dnssector::{DNSSector, Section}; use std::net::SocketAddr; #[test] fn context_create() { let context = Context::new(); let r1 = Request::new(context.clone()); let r2 = Request::new(context.clone()); let (_, p1) = r1.locked(); let (_, p2) = r2.locked(); assert!(*p1 != *p2); } #[test] fn context_create_cached() { assert!(Context::with_cache(".", 64 * 1024).is_ok()); } #[test] fn context_root_hints() { let context = Context::new(); assert!(context.add_root_hint("127.0.0.1".parse().unwrap()).is_ok()); assert!(context.add_root_hint("::1".parse().unwrap()).is_ok()); } #[test] fn context_with_module() { let context = Context::new(); assert!(context.add_module("iterate").is_ok()); assert!(context.remove_module("iterate").is_ok()); } #[test] fn context_trust_anchor() { let context = Context::new(); let ta = gen::RR::from_string( ". 0 IN DS 20326 8 2 E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D", ) .unwrap(); assert!(context.add_trust_anchor(ta.rdata()).is_ok()); } #[test] fn context_verbose() { let context = Context::new(); context.set_verbose(true); context.set_verbose(false); } #[test] fn request_processing() { let context = Context::new(); // Create a ". NS" query (priming) let request = Request::new(context.clone()); let buf = gen::query( b".", Type::from_string("NS").unwrap(), Class::from_string("IN").unwrap(), ) .unwrap(); // Push it as a question to request let addr = "1.1.1.1:53".parse::<SocketAddr>().unwrap(); request.consume(buf.packet(), addr); // Generate an outbound query let state = match request.produce() { Some((buf, addresses)) => { // Generate a mock answer to the outbound query let mut resp = DNSSector::new(buf.to_vec()).unwrap().parse().unwrap(); resp.set_response(true); resp.insert_rr( Section::Answer, gen::RR::from_string(". 86399 IN NS e.root-servers.net").unwrap(), ) .unwrap(); resp.insert_rr( Section::Additional, gen::RR::from_string("e.root-servers.net 86399 IN A 192.203.230.10").unwrap(), ) .unwrap(); // Consume the mock answer and expect resolution to be done request.consume(resp.packet(), addresses[0]) } None => State::DONE, }; // Get final answer assert_eq!(state, State::DONE); let buf = request.finish(state).unwrap(); let resp = DNSSector::new(buf.to_vec()).unwrap().parse(); assert!(resp.is_ok()); } }
}
random_line_split
lib.rs
//! This crate wraps [libkres](https://knot-resolver.cz) from //! [CZ.NIC Labs](https://labs.nic.cz). libkres is an implementation of a full DNS recursive resolver, //! including cache and DNSSEC validation. It doesn't require a specific I/O model and instead provides //! a generic interface for pushing/pulling DNS messages until the request is satisfied. //! //! The interface provided implements a minimal subset of operations from the engine: //! //! * `struct kr_context` is wrapped by [Context](struct.Context.html). Functions from libkres that //! operate on `struct kr_context` are accessed using methods on [Context](struct.Context.html). //! The context implements lock guards for all FFI calls on context, and all FFI calls on request //! that borrows given context. //! //! * `struct kr_request` is wrapped by [Request](struct.Request.html). Methods on //! [Request](struct.Request.html) are used to safely access the fields of `struct kr_request`. //! Methods that wrap FFI calls lock request and its context for thread-safe access. //! //! Example: //! //! ``` //! use std::net::{SocketAddr, UdpSocket}; //! use kres::{Context, Request, State}; //! //! // DNS message wire format //! let question = [2, 104, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1]; //! let from_addr = "127.0.0.1:1234".parse::<SocketAddr>().unwrap(); //! //! let context = Context::new(); //! let req = Request::new(context.clone()); //! let mut state = req.consume(&question, from_addr); //! while state == State::PRODUCE { //! state = match req.produce() { //! Some((msg, addr_set)) => { //! // This can be any I/O model the application uses //! let mut socket = UdpSocket::bind("0.0.0.0:0").unwrap(); //! socket.send_to(&msg, &addr_set[0]).unwrap(); //! let mut buf = [0; 512]; //! let (amt, src) = socket.recv_from(&mut buf).unwrap(); //! // Pass the response back to the request //! req.consume(&buf[..amt], src) //! }, //! None => { //! break; //! } //! } //! } //! //! // Convert request into final answer //! let answer = req.finish(state).unwrap(); //! ``` #[cfg(feature = "jemalloc")] use jemallocator; #[cfg(feature = "jemalloc")] #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; use bytes::Bytes; use parking_lot::{Mutex, MutexGuard}; use std::ffi::{CStr, CString}; use std::io::{Error, ErrorKind, Result}; use std::mem; use std::net::{IpAddr, SocketAddr}; use std::ptr; use std::sync::Arc; /// Number of tries to produce a next message const MAX_PRODUCE_TRIES : usize = 3; // Wrapped C library mod c { #![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); } /// Request state enumeration pub use self::c::lkr_state as State; /// Shared context for the request resolution. /// All requests create with a given context use its facilities: /// * Trust Anchor storage /// * Root Server bootstrap set /// * Cache /// * Default EDNS options /// * Default options pub struct Context { inner: Mutex<*mut c::lkr_context>, } /* Context itself is not thread-safe, but Mutex wrapping it is */ unsafe impl Send for Context {} unsafe impl Sync for Context {} impl Context { /// Create an empty context without internal cache pub fn new() -> Arc<Self> { unsafe { Arc::new(Self { inner: Mutex::new(c::lkr_context_new()), }) } } /// Create an empty context with local disk cache pub fn with_cache(path: &str, max_bytes: usize) -> Result<Arc<Self>> { unsafe { let inner = c::lkr_context_new(); let path_c = CString::new(path).unwrap(); let cache_c = CStr::from_bytes_with_nul(b"cache\0").unwrap(); match c::lkr_cache_open(inner, path_c.as_ptr(), max_bytes) { 0 => { c::lkr_module_load(inner, cache_c.as_ptr()); Ok(Arc::new(Self { inner: Mutex::new(inner), })) } _ => Err(Error::new(ErrorKind::Other, "failed to open cache")), } } } /// Add a resolver module, see [Knot Resolver modules](https://knot-resolver.readthedocs.io/en/stable/modules.html) for reference pub fn add_module(&self, name: &str) -> Result<()> { let inner = self.locked(); let name_c = CString::new(name)?; unsafe { let res = c::lkr_module_load(*inner, name_c.as_ptr()); if res != 0 { return Err(Error::new(ErrorKind::NotFound, "failed to load module")); } } Ok(()) } /// Remove a resolver module, see [Knot Resolver modules](https://knot-resolver.readthedocs.io/en/stable/modules.html) for reference pub fn remove_module(&self, name: &str) -> Result<()> { let inner = self.locked(); let name_c = CString::new(name)?; unsafe { let res = c::lkr_module_unload(*inner, name_c.as_ptr()); if res != 0 { return Err(Error::new(ErrorKind::NotFound, "failed to unload module")); } } Ok(()) } /// Add a root server hint to the context. The root server hints are used to bootstrap the resolver, there must be at least one. pub fn add_root_hint(&self, addr: IpAddr) -> Result<()> { let inner = self.locked(); let slice = match addr { IpAddr::V4(ip) => ip.octets().to_vec(), IpAddr::V6(ip) => ip.octets().to_vec(), }; unsafe { let res = c::lkr_root_hint(*inner, slice.as_ptr(), slice.len()); if res != 0 { return Err(Error::new( ErrorKind::InvalidInput, "failed to add a root hint", )); } } Ok(()) } /// Add a trust anchor to the resolver. If the context has at least 1 trust anchor, it will perform DNSSEC validation under it. pub fn add_trust_anchor(&self, rdata: &[u8]) -> Result<()> { let inner = self.locked(); unsafe { let res = c::lkr_trust_anchor(*inner, rdata.as_ptr(), rdata.len()); if res != 0 { return Err(Error::new( ErrorKind::InvalidInput, "failed to add trust anchor", )); } } Ok(()) } /// Set or reset verbose mode pub fn set_verbose(&self, val: bool) { let inner = self.locked(); unsafe { c::lkr_verbose(*inner, val); } } fn locked(&self) -> MutexGuard<*mut c::lkr_context> { self.inner.lock() } } impl Drop for Context { fn drop(&mut self) { let inner = self.locked(); if !inner.is_null() { unsafe { c::lkr_context_free(*inner); } } } } /// Request wraps `struct kr_request` and keeps a reference for the context. /// The request is not automatically executed, it must be driven the caller to completion. pub struct Request { context: Arc<Context>, inner: Mutex<*mut c::lkr_request>, } /* Neither request nor context are thread safe. * Both request and context pointers is guarded by a mutex, * and must be locked during any operation on the request. */ unsafe impl Send for Request {} unsafe impl Sync for Request {} impl Request { /// Create a new request under the context. The request is bound to the context for its lifetime. pub fn new(context: Arc<Context>) -> Self { let inner = unsafe { c::lkr_request_new(*context.locked()) }; Self { context, inner: Mutex::new(inner), } } /// Consume an input from the caller, this is typically either a client query or response to an outbound query. pub fn consume(&self, msg: &[u8], from: SocketAddr) -> State
/// Generate an outbound query for the request. This should be called when `consume()` returns a `Produce` state. pub fn produce(&self) -> Option<(Bytes, Vec<SocketAddr>)> { let mut msg = vec![0; 512]; let mut addresses = Vec::new(); let mut sa_vec: Vec<*mut c::sockaddr> = vec![ptr::null_mut(); 4]; let (_context, inner) = self.locked(); let state = { let mut state = State::PRODUCE; let mut tries = MAX_PRODUCE_TRIES; while state == State::PRODUCE { if tries == 0 { break; } tries -= 1; // Prepare socket address vector let addr_ptr = sa_vec.as_mut_ptr(); let addr_capacity = sa_vec.capacity(); // Prepare message buffer let msg_capacity = msg.capacity(); let msg_ptr = msg.as_mut_ptr(); let mut msg_size = msg_capacity; // Generate next message unsafe { mem::forget(msg); mem::forget(sa_vec); state = c::lkr_produce( *inner, addr_ptr, addr_capacity, msg_ptr, &mut msg_size, false, ); // Rebuild vectors from modified pointers msg = Vec::from_raw_parts(msg_ptr, msg_size, msg_capacity); sa_vec = Vec::from_raw_parts(addr_ptr, addr_capacity, addr_capacity); } } state }; match state { State::DONE => None, State::CONSUME => { for ptr_addr in sa_vec { if ptr_addr.is_null() { break; } let addr = unsafe { socket2::SockAddr::from_raw_parts( ptr_addr as *const _, c::lkr_sockaddr_len(ptr_addr) as u32, ) }; if let Some(as_inet) = addr.as_inet() { addresses.push(as_inet.into()); } else { addresses.push(addr.as_inet6().unwrap().into()); } } Some((Bytes::from(msg), addresses)) } _ => None, } } /// Finish request processing and convert Request into the final answer. pub fn finish(self, state: State) -> Result<Bytes> { let (_context, inner) = self.locked(); let answer_len = unsafe { c::lkr_finish(*inner, state) }; if answer_len == 0 { return Err(ErrorKind::UnexpectedEof.into()) } let mut v: Vec<u8> = Vec::with_capacity(answer_len); let p = v.as_mut_ptr(); let v = unsafe { mem::forget(v); c::lkr_write_answer(*inner, p, answer_len); Vec::from_raw_parts(p, answer_len, answer_len) }; Ok(Bytes::from(v)) } fn locked( &self, ) -> ( MutexGuard<*mut c::lkr_context>, MutexGuard<*mut c::lkr_request>, ) { (self.context.locked(), self.inner.lock()) } } impl Drop for Request { fn drop(&mut self) { let (_context, mut inner) = self.locked(); if !inner.is_null() { unsafe { c::lkr_request_free(*inner); *inner = ptr::null_mut(); } } } } #[cfg(test)] mod tests { use super::{Context, Request, State}; use dnssector::constants::*; use dnssector::synth::gen; use dnssector::{DNSSector, Section}; use std::net::SocketAddr; #[test] fn context_create() { let context = Context::new(); let r1 = Request::new(context.clone()); let r2 = Request::new(context.clone()); let (_, p1) = r1.locked(); let (_, p2) = r2.locked(); assert!(*p1 != *p2); } #[test] fn context_create_cached() { assert!(Context::with_cache(".", 64 * 1024).is_ok()); } #[test] fn context_root_hints() { let context = Context::new(); assert!(context.add_root_hint("127.0.0.1".parse().unwrap()).is_ok()); assert!(context.add_root_hint("::1".parse().unwrap()).is_ok()); } #[test] fn context_with_module() { let context = Context::new(); assert!(context.add_module("iterate").is_ok()); assert!(context.remove_module("iterate").is_ok()); } #[test] fn context_trust_anchor() { let context = Context::new(); let ta = gen::RR::from_string( ". 0 IN DS 20326 8 2 E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D", ) .unwrap(); assert!(context.add_trust_anchor(ta.rdata()).is_ok()); } #[test] fn context_verbose() { let context = Context::new(); context.set_verbose(true); context.set_verbose(false); } #[test] fn request_processing() { let context = Context::new(); // Create a ". NS" query (priming) let request = Request::new(context.clone()); let buf = gen::query( b".", Type::from_string("NS").unwrap(), Class::from_string("IN").unwrap(), ) .unwrap(); // Push it as a question to request let addr = "1.1.1.1:53".parse::<SocketAddr>().unwrap(); request.consume(buf.packet(), addr); // Generate an outbound query let state = match request.produce() { Some((buf, addresses)) => { // Generate a mock answer to the outbound query let mut resp = DNSSector::new(buf.to_vec()).unwrap().parse().unwrap(); resp.set_response(true); resp.insert_rr( Section::Answer, gen::RR::from_string(". 86399 IN NS e.root-servers.net").unwrap(), ) .unwrap(); resp.insert_rr( Section::Additional, gen::RR::from_string("e.root-servers.net 86399 IN A 192.203.230.10").unwrap(), ) .unwrap(); // Consume the mock answer and expect resolution to be done request.consume(resp.packet(), addresses[0]) } None => State::DONE, }; // Get final answer assert_eq!(state, State::DONE); let buf = request.finish(state).unwrap(); let resp = DNSSector::new(buf.to_vec()).unwrap().parse(); assert!(resp.is_ok()); } }
{ let (_context, inner) = self.locked(); let from = socket2::SockAddr::from(from); let msg_ptr = if !msg.is_empty() { msg.as_ptr() } else { ptr::null() }; unsafe { c::lkr_consume(*inner, from.as_ptr() as *const _, msg_ptr, msg.len()) } }
identifier_body
e.rs
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; #[allow(unused_macros)] macro_rules! debug { ($($a:expr),* $(,)*) => { #[cfg(debug_assertions)] eprintln!(concat!($("| ", stringify!($a), "={:?} "),*, "|"), $(&$a),*); }; } fn main() { input! { n: usize, k: usize, a: [[i64; n]; n], } let row = |i| i; let col = |j| n + j; let mut graph = MinCostFlowGraph::new(2 * n + 2); let source = 2 * n; let target = 2 * n + 1; for i in 0..n { for j in 0..n { graph.add_edge(col(j), row(i), 1, 10000000000 - a[i][j]); } } for i in 0..n { graph.add_edge(source, col(i), k as i64, 0); graph.add_edge(row(i), target, k as i64, 0); } graph.add_edge(source, target, 100000000, 10000000000); graph.flow(source, target, 100000000); let mut result = 0; let mut s = vec![vec!['.'; n]; n]; for e in graph.edges() { debug!(e.from, e.to, e.cap, e.flow, e.cost); if e.from != source && e.to != target && e.flow >= 1 { let i = e.to; let j = e.from - n; result += a[i][j]; s[i][j] = 'X'; } } println!("{}", result); for i in 0..n { println!("{}", s[i].iter().collect::<String>()); } } //https://github.com/rust-lang-ja/ac-library-rs pub mod internal_type_traits { use std::{ fmt, iter::{Product, Sum}, ops::{ Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, }, }; // Skipped: // // - `is_signed_int_t<T>` (probably won't be used directly in `modint.rs`) // - `is_unsigned_int_t<T>` (probably won't be used directly in `modint.rs`) // - `to_unsigned_t<T>` (not used in `fenwicktree.rs`) /// Corresponds to `std::is_integral` in C++. // We will remove unnecessary bounds later. // // Maybe we should rename this to `PrimitiveInteger` or something, as it probably won't be used in the // same way as the original ACL. pub trait Integral: 'static + Send + Sync + Copy + Ord + Not<Output = Self> + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Div<Output = Self> + Rem<Output = Self> + AddAssign + SubAssign + MulAssign + DivAssign + RemAssign + Sum + Product + BitOr<Output = Self> + BitAnd<Output = Self> + BitXor<Output = Self> + BitOrAssign + BitAndAssign + BitXorAssign + Shl<Output = Self> + Shr<Output = Self> + ShlAssign + ShrAssign + fmt::Display + fmt::Debug + fmt::Binary + fmt::Octal + Zero + One + BoundedBelow + BoundedAbove { } /// Class that has additive identity element pub trait Zero { /// The additive identity element fn zero() -> Self; } /// Class that has multiplicative identity element pub trait One { /// The multiplicative identity element fn one() -> Self; } pub trait BoundedBelow { fn min_value() -> Self; } pub trait BoundedAbove { fn max_value() -> Self; } macro_rules! impl_integral { ($($ty:ty),*) => { $( impl Zero for $ty { #[inline] fn zero() -> Self { 0 } } impl One for $ty { #[inline] fn one() -> Self { 1 } } impl BoundedBelow for $ty { #[inline] fn min_value() -> Self { Self::min_value() } } impl BoundedAbove for $ty { #[inline] fn max_value() -> Self { Self::max_value() } } impl Integral for $ty {} )* }; } impl_integral!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize); } pub mod mincostflow { use crate::internal_type_traits::Integral; pub struct MinCostFlowEdge<T> { pub from: usize, pub to: usize, pub cap: T, pub flow: T, pub cost: T, } pub struct MinCostFlowGraph<T> { pos: Vec<(usize, usize)>, g: Vec<Vec<_Edge<T>>>, cost_sum: T, } impl<T> MinCostFlowGraph<T> where T: Integral + std::ops::Neg<Output = T>, { pub fn new(n: usize) -> Self { Self { pos: vec![], g: (0..n).map(|_| vec![]).collect(), cost_sum: T::zero(), } } pub fn get_edge(&self, i: usize) -> MinCostFlowEdge<T> { assert!(i < self.pos.len()); let e = &self.g[self.pos[i].0][self.pos[i].1]; let re = &self.g[e.to][e.rev]; MinCostFlowEdge { from: self.pos[i].0, to: e.to, cap: e.cap + re.cap, flow: re.cap, cost: e.cost, } } pub fn edges(&self) -> Vec<MinCostFlowEdge<T>> { let m = self.pos.len(); let mut result = vec![]; for i in 0..m { result.push(self.get_edge(i)); } result } pub fn add_edge(&mut self, from: usize, to: usize, cap: T, cost: T) -> usize { assert!(from < self.g.len()); assert!(to < self.g.len()); assert_ne!(from, to); assert!(cap >= T::zero()); assert!(cost >= T::zero()); self.pos.push((from, self.g[from].len())); self.cost_sum += cost; let rev = self.g[to].len(); self.g[from].push(_Edge { to, rev, cap, cost }); let rev = self.g[from].len() - 1; self.g[to].push(_Edge { to: from, rev, cap: T::zero(), cost: -cost, }); self.pos.len() - 1 } /// Returns (maximum flow, cost) pub fn flow(&mut self, source: usize, sink: usize, flow_limit: T) -> (T, T) { self.slope(source, sink, flow_limit).pop().unwrap() } pub fn slope(&mut self, source: usize, sink: usize, flow_limit: T) -> Vec<(T, T)> { let n = self.g.len(); assert!(source < n); assert!(sink < n); assert_ne!(source, sink); let mut dual = vec![T::zero(); n]; let mut prev_v = vec![0; n]; let mut prev_e = vec![0; n]; let mut flow = T::zero(); let mut cost = T::zero(); let mut prev_cost: Option<T> = None; let mut result = vec![(flow, cost)]; while flow < flow_limit { if !self.refine_dual(source, sink, &mut dual, &mut prev_v, &mut prev_e) { break; } let mut c = flow_limit - flow; let mut v = sink; while v != source { c = std::cmp::min(c, self.g[prev_v[v]][prev_e[v]].cap); v = prev_v[v]; } let mut v = sink; while v != source { self.g[prev_v[v]][prev_e[v]].cap -= c; let rev = self.g[prev_v[v]][prev_e[v]].rev; self.g[v][rev].cap += c; v = prev_v[v]; } let d = -dual[source]; flow += c; cost += d * c; if prev_cost == Some(d) { assert!(result.pop().is_some()); } result.push((flow, cost)); prev_cost = Some(cost); } result } fn
( &self, source: usize, sink: usize, dual: &mut [T], pv: &mut [usize], pe: &mut [usize], ) -> bool { let n = self.g.len(); let mut dist = vec![self.cost_sum; n]; let mut vis = vec![false; n]; let mut que = std::collections::BinaryHeap::new(); dist[source] = T::zero(); que.push((std::cmp::Reverse(T::zero()), source)); while let Some((_, v)) = que.pop() { if vis[v] { continue; } vis[v] = true; if v == sink { break; } for (i, e) in self.g[v].iter().enumerate() { if vis[e.to] || e.cap == T::zero() { continue; } let cost = e.cost - dual[e.to] + dual[v]; if dist[e.to] - dist[v] > cost { dist[e.to] = dist[v] + cost; pv[e.to] = v; pe[e.to] = i; que.push((std::cmp::Reverse(dist[e.to]), e.to)); } } } if !vis[sink] { return false; } for v in 0..n { if !vis[v] { continue; } dual[v] -= dist[sink] - dist[v]; } true } } struct _Edge<T> { to: usize, rev: usize, cap: T, cost: T, } #[cfg(test)] mod tests { use super::*; #[test] fn test_min_cost_flow() { let mut graph = MinCostFlowGraph::new(4); graph.add_edge(0, 1, 2, 1); graph.add_edge(0, 2, 1, 2); graph.add_edge(1, 2, 1, 1); graph.add_edge(1, 3, 1, 3); graph.add_edge(2, 3, 2, 1); let (flow, cost) = graph.flow(0, 3, 2); assert_eq!(flow, 2); assert_eq!(cost, 6); } } } use mincostflow::*;
refine_dual
identifier_name
e.rs
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; #[allow(unused_macros)] macro_rules! debug { ($($a:expr),* $(,)*) => { #[cfg(debug_assertions)] eprintln!(concat!($("| ", stringify!($a), "={:?} "),*, "|"), $(&$a),*); }; } fn main() { input! { n: usize, k: usize, a: [[i64; n]; n], } let row = |i| i; let col = |j| n + j; let mut graph = MinCostFlowGraph::new(2 * n + 2); let source = 2 * n; let target = 2 * n + 1; for i in 0..n { for j in 0..n { graph.add_edge(col(j), row(i), 1, 10000000000 - a[i][j]); } } for i in 0..n { graph.add_edge(source, col(i), k as i64, 0); graph.add_edge(row(i), target, k as i64, 0); } graph.add_edge(source, target, 100000000, 10000000000); graph.flow(source, target, 100000000); let mut result = 0; let mut s = vec![vec!['.'; n]; n]; for e in graph.edges() { debug!(e.from, e.to, e.cap, e.flow, e.cost); if e.from != source && e.to != target && e.flow >= 1 { let i = e.to; let j = e.from - n; result += a[i][j]; s[i][j] = 'X'; } } println!("{}", result); for i in 0..n { println!("{}", s[i].iter().collect::<String>()); } } //https://github.com/rust-lang-ja/ac-library-rs pub mod internal_type_traits { use std::{ fmt, iter::{Product, Sum}, ops::{ Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, }, }; // Skipped: // // - `is_signed_int_t<T>` (probably won't be used directly in `modint.rs`) // - `is_unsigned_int_t<T>` (probably won't be used directly in `modint.rs`) // - `to_unsigned_t<T>` (not used in `fenwicktree.rs`) /// Corresponds to `std::is_integral` in C++. // We will remove unnecessary bounds later. // // Maybe we should rename this to `PrimitiveInteger` or something, as it probably won't be used in the // same way as the original ACL. pub trait Integral: 'static + Send + Sync + Copy + Ord + Not<Output = Self> + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Div<Output = Self> + Rem<Output = Self> + AddAssign + SubAssign + MulAssign + DivAssign + RemAssign + Sum + Product + BitOr<Output = Self> + BitAnd<Output = Self> + BitXor<Output = Self> + BitOrAssign + BitAndAssign + BitXorAssign + Shl<Output = Self> + Shr<Output = Self> + ShlAssign + ShrAssign + fmt::Display + fmt::Debug + fmt::Binary + fmt::Octal + Zero + One + BoundedBelow + BoundedAbove { } /// Class that has additive identity element pub trait Zero { /// The additive identity element fn zero() -> Self; } /// Class that has multiplicative identity element pub trait One { /// The multiplicative identity element fn one() -> Self; } pub trait BoundedBelow { fn min_value() -> Self; } pub trait BoundedAbove { fn max_value() -> Self; } macro_rules! impl_integral { ($($ty:ty),*) => { $( impl Zero for $ty { #[inline] fn zero() -> Self { 0 } } impl One for $ty { #[inline] fn one() -> Self { 1 } } impl BoundedBelow for $ty { #[inline] fn min_value() -> Self { Self::min_value() } } impl BoundedAbove for $ty { #[inline] fn max_value() -> Self { Self::max_value() } } impl Integral for $ty {} )* }; } impl_integral!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize); } pub mod mincostflow { use crate::internal_type_traits::Integral; pub struct MinCostFlowEdge<T> { pub from: usize, pub to: usize, pub cap: T, pub flow: T, pub cost: T, } pub struct MinCostFlowGraph<T> { pos: Vec<(usize, usize)>, g: Vec<Vec<_Edge<T>>>, cost_sum: T, } impl<T> MinCostFlowGraph<T> where T: Integral + std::ops::Neg<Output = T>, { pub fn new(n: usize) -> Self { Self { pos: vec![], g: (0..n).map(|_| vec![]).collect(), cost_sum: T::zero(), } } pub fn get_edge(&self, i: usize) -> MinCostFlowEdge<T> { assert!(i < self.pos.len()); let e = &self.g[self.pos[i].0][self.pos[i].1]; let re = &self.g[e.to][e.rev]; MinCostFlowEdge { from: self.pos[i].0, to: e.to, cap: e.cap + re.cap, flow: re.cap, cost: e.cost, } } pub fn edges(&self) -> Vec<MinCostFlowEdge<T>> { let m = self.pos.len(); let mut result = vec![]; for i in 0..m { result.push(self.get_edge(i)); } result } pub fn add_edge(&mut self, from: usize, to: usize, cap: T, cost: T) -> usize { assert!(from < self.g.len()); assert!(to < self.g.len()); assert_ne!(from, to); assert!(cap >= T::zero()); assert!(cost >= T::zero()); self.pos.push((from, self.g[from].len())); self.cost_sum += cost; let rev = self.g[to].len(); self.g[from].push(_Edge { to, rev, cap, cost }); let rev = self.g[from].len() - 1; self.g[to].push(_Edge { to: from, rev, cap: T::zero(), cost: -cost, }); self.pos.len() - 1 } /// Returns (maximum flow, cost) pub fn flow(&mut self, source: usize, sink: usize, flow_limit: T) -> (T, T) { self.slope(source, sink, flow_limit).pop().unwrap() } pub fn slope(&mut self, source: usize, sink: usize, flow_limit: T) -> Vec<(T, T)> { let n = self.g.len(); assert!(source < n); assert!(sink < n); assert_ne!(source, sink); let mut dual = vec![T::zero(); n]; let mut prev_v = vec![0; n]; let mut prev_e = vec![0; n]; let mut flow = T::zero(); let mut cost = T::zero(); let mut prev_cost: Option<T> = None; let mut result = vec![(flow, cost)]; while flow < flow_limit { if !self.refine_dual(source, sink, &mut dual, &mut prev_v, &mut prev_e) { break; } let mut c = flow_limit - flow; let mut v = sink; while v != source { c = std::cmp::min(c, self.g[prev_v[v]][prev_e[v]].cap); v = prev_v[v]; } let mut v = sink; while v != source { self.g[prev_v[v]][prev_e[v]].cap -= c; let rev = self.g[prev_v[v]][prev_e[v]].rev; self.g[v][rev].cap += c; v = prev_v[v]; } let d = -dual[source]; flow += c; cost += d * c; if prev_cost == Some(d) { assert!(result.pop().is_some()); } result.push((flow, cost)); prev_cost = Some(cost); } result } fn refine_dual( &self, source: usize, sink: usize, dual: &mut [T], pv: &mut [usize], pe: &mut [usize], ) -> bool { let n = self.g.len(); let mut dist = vec![self.cost_sum; n]; let mut vis = vec![false; n]; let mut que = std::collections::BinaryHeap::new(); dist[source] = T::zero(); que.push((std::cmp::Reverse(T::zero()), source)); while let Some((_, v)) = que.pop() { if vis[v] { continue; } vis[v] = true; if v == sink { break; } for (i, e) in self.g[v].iter().enumerate() { if vis[e.to] || e.cap == T::zero() { continue; } let cost = e.cost - dual[e.to] + dual[v]; if dist[e.to] - dist[v] > cost
} } if !vis[sink] { return false; } for v in 0..n { if !vis[v] { continue; } dual[v] -= dist[sink] - dist[v]; } true } } struct _Edge<T> { to: usize, rev: usize, cap: T, cost: T, } #[cfg(test)] mod tests { use super::*; #[test] fn test_min_cost_flow() { let mut graph = MinCostFlowGraph::new(4); graph.add_edge(0, 1, 2, 1); graph.add_edge(0, 2, 1, 2); graph.add_edge(1, 2, 1, 1); graph.add_edge(1, 3, 1, 3); graph.add_edge(2, 3, 2, 1); let (flow, cost) = graph.flow(0, 3, 2); assert_eq!(flow, 2); assert_eq!(cost, 6); } } } use mincostflow::*;
{ dist[e.to] = dist[v] + cost; pv[e.to] = v; pe[e.to] = i; que.push((std::cmp::Reverse(dist[e.to]), e.to)); }
conditional_block
e.rs
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; #[allow(unused_macros)] macro_rules! debug { ($($a:expr),* $(,)*) => { #[cfg(debug_assertions)] eprintln!(concat!($("| ", stringify!($a), "={:?} "),*, "|"), $(&$a),*); }; } fn main() { input! { n: usize, k: usize, a: [[i64; n]; n], } let row = |i| i; let col = |j| n + j; let mut graph = MinCostFlowGraph::new(2 * n + 2); let source = 2 * n; let target = 2 * n + 1; for i in 0..n { for j in 0..n { graph.add_edge(col(j), row(i), 1, 10000000000 - a[i][j]); } } for i in 0..n { graph.add_edge(source, col(i), k as i64, 0); graph.add_edge(row(i), target, k as i64, 0); } graph.add_edge(source, target, 100000000, 10000000000); graph.flow(source, target, 100000000); let mut result = 0; let mut s = vec![vec!['.'; n]; n]; for e in graph.edges() { debug!(e.from, e.to, e.cap, e.flow, e.cost); if e.from != source && e.to != target && e.flow >= 1 { let i = e.to; let j = e.from - n; result += a[i][j]; s[i][j] = 'X'; } } println!("{}", result); for i in 0..n { println!("{}", s[i].iter().collect::<String>()); } } //https://github.com/rust-lang-ja/ac-library-rs pub mod internal_type_traits { use std::{ fmt, iter::{Product, Sum}, ops::{ Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, }, }; // Skipped: // // - `is_signed_int_t<T>` (probably won't be used directly in `modint.rs`) // - `is_unsigned_int_t<T>` (probably won't be used directly in `modint.rs`) // - `to_unsigned_t<T>` (not used in `fenwicktree.rs`) /// Corresponds to `std::is_integral` in C++. // We will remove unnecessary bounds later. // // Maybe we should rename this to `PrimitiveInteger` or something, as it probably won't be used in the // same way as the original ACL. pub trait Integral: 'static + Send + Sync + Copy + Ord + Not<Output = Self> + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Div<Output = Self> + Rem<Output = Self> + AddAssign + SubAssign + MulAssign + DivAssign + RemAssign + Sum + Product + BitOr<Output = Self> + BitAnd<Output = Self> + BitXor<Output = Self> + BitOrAssign + BitAndAssign + BitXorAssign + Shl<Output = Self> + Shr<Output = Self> + ShlAssign + ShrAssign + fmt::Display + fmt::Debug + fmt::Binary + fmt::Octal + Zero + One + BoundedBelow + BoundedAbove { } /// Class that has additive identity element pub trait Zero { /// The additive identity element fn zero() -> Self; } /// Class that has multiplicative identity element pub trait One { /// The multiplicative identity element fn one() -> Self; } pub trait BoundedBelow { fn min_value() -> Self; } pub trait BoundedAbove { fn max_value() -> Self; } macro_rules! impl_integral { ($($ty:ty),*) => { $( impl Zero for $ty { #[inline] fn zero() -> Self { 0 } } impl One for $ty { #[inline] fn one() -> Self { 1 } } impl BoundedBelow for $ty { #[inline] fn min_value() -> Self {
} } impl BoundedAbove for $ty { #[inline] fn max_value() -> Self { Self::max_value() } } impl Integral for $ty {} )* }; } impl_integral!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize); } pub mod mincostflow { use crate::internal_type_traits::Integral; pub struct MinCostFlowEdge<T> { pub from: usize, pub to: usize, pub cap: T, pub flow: T, pub cost: T, } pub struct MinCostFlowGraph<T> { pos: Vec<(usize, usize)>, g: Vec<Vec<_Edge<T>>>, cost_sum: T, } impl<T> MinCostFlowGraph<T> where T: Integral + std::ops::Neg<Output = T>, { pub fn new(n: usize) -> Self { Self { pos: vec![], g: (0..n).map(|_| vec![]).collect(), cost_sum: T::zero(), } } pub fn get_edge(&self, i: usize) -> MinCostFlowEdge<T> { assert!(i < self.pos.len()); let e = &self.g[self.pos[i].0][self.pos[i].1]; let re = &self.g[e.to][e.rev]; MinCostFlowEdge { from: self.pos[i].0, to: e.to, cap: e.cap + re.cap, flow: re.cap, cost: e.cost, } } pub fn edges(&self) -> Vec<MinCostFlowEdge<T>> { let m = self.pos.len(); let mut result = vec![]; for i in 0..m { result.push(self.get_edge(i)); } result } pub fn add_edge(&mut self, from: usize, to: usize, cap: T, cost: T) -> usize { assert!(from < self.g.len()); assert!(to < self.g.len()); assert_ne!(from, to); assert!(cap >= T::zero()); assert!(cost >= T::zero()); self.pos.push((from, self.g[from].len())); self.cost_sum += cost; let rev = self.g[to].len(); self.g[from].push(_Edge { to, rev, cap, cost }); let rev = self.g[from].len() - 1; self.g[to].push(_Edge { to: from, rev, cap: T::zero(), cost: -cost, }); self.pos.len() - 1 } /// Returns (maximum flow, cost) pub fn flow(&mut self, source: usize, sink: usize, flow_limit: T) -> (T, T) { self.slope(source, sink, flow_limit).pop().unwrap() } pub fn slope(&mut self, source: usize, sink: usize, flow_limit: T) -> Vec<(T, T)> { let n = self.g.len(); assert!(source < n); assert!(sink < n); assert_ne!(source, sink); let mut dual = vec![T::zero(); n]; let mut prev_v = vec![0; n]; let mut prev_e = vec![0; n]; let mut flow = T::zero(); let mut cost = T::zero(); let mut prev_cost: Option<T> = None; let mut result = vec![(flow, cost)]; while flow < flow_limit { if !self.refine_dual(source, sink, &mut dual, &mut prev_v, &mut prev_e) { break; } let mut c = flow_limit - flow; let mut v = sink; while v != source { c = std::cmp::min(c, self.g[prev_v[v]][prev_e[v]].cap); v = prev_v[v]; } let mut v = sink; while v != source { self.g[prev_v[v]][prev_e[v]].cap -= c; let rev = self.g[prev_v[v]][prev_e[v]].rev; self.g[v][rev].cap += c; v = prev_v[v]; } let d = -dual[source]; flow += c; cost += d * c; if prev_cost == Some(d) { assert!(result.pop().is_some()); } result.push((flow, cost)); prev_cost = Some(cost); } result } fn refine_dual( &self, source: usize, sink: usize, dual: &mut [T], pv: &mut [usize], pe: &mut [usize], ) -> bool { let n = self.g.len(); let mut dist = vec![self.cost_sum; n]; let mut vis = vec![false; n]; let mut que = std::collections::BinaryHeap::new(); dist[source] = T::zero(); que.push((std::cmp::Reverse(T::zero()), source)); while let Some((_, v)) = que.pop() { if vis[v] { continue; } vis[v] = true; if v == sink { break; } for (i, e) in self.g[v].iter().enumerate() { if vis[e.to] || e.cap == T::zero() { continue; } let cost = e.cost - dual[e.to] + dual[v]; if dist[e.to] - dist[v] > cost { dist[e.to] = dist[v] + cost; pv[e.to] = v; pe[e.to] = i; que.push((std::cmp::Reverse(dist[e.to]), e.to)); } } } if !vis[sink] { return false; } for v in 0..n { if !vis[v] { continue; } dual[v] -= dist[sink] - dist[v]; } true } } struct _Edge<T> { to: usize, rev: usize, cap: T, cost: T, } #[cfg(test)] mod tests { use super::*; #[test] fn test_min_cost_flow() { let mut graph = MinCostFlowGraph::new(4); graph.add_edge(0, 1, 2, 1); graph.add_edge(0, 2, 1, 2); graph.add_edge(1, 2, 1, 1); graph.add_edge(1, 3, 1, 3); graph.add_edge(2, 3, 2, 1); let (flow, cost) = graph.flow(0, 3, 2); assert_eq!(flow, 2); assert_eq!(cost, 6); } } } use mincostflow::*;
Self::min_value()
random_line_split
e.rs
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; #[allow(unused_macros)] macro_rules! debug { ($($a:expr),* $(,)*) => { #[cfg(debug_assertions)] eprintln!(concat!($("| ", stringify!($a), "={:?} "),*, "|"), $(&$a),*); }; } fn main() { input! { n: usize, k: usize, a: [[i64; n]; n], } let row = |i| i; let col = |j| n + j; let mut graph = MinCostFlowGraph::new(2 * n + 2); let source = 2 * n; let target = 2 * n + 1; for i in 0..n { for j in 0..n { graph.add_edge(col(j), row(i), 1, 10000000000 - a[i][j]); } } for i in 0..n { graph.add_edge(source, col(i), k as i64, 0); graph.add_edge(row(i), target, k as i64, 0); } graph.add_edge(source, target, 100000000, 10000000000); graph.flow(source, target, 100000000); let mut result = 0; let mut s = vec![vec!['.'; n]; n]; for e in graph.edges() { debug!(e.from, e.to, e.cap, e.flow, e.cost); if e.from != source && e.to != target && e.flow >= 1 { let i = e.to; let j = e.from - n; result += a[i][j]; s[i][j] = 'X'; } } println!("{}", result); for i in 0..n { println!("{}", s[i].iter().collect::<String>()); } } //https://github.com/rust-lang-ja/ac-library-rs pub mod internal_type_traits { use std::{ fmt, iter::{Product, Sum}, ops::{ Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, }, }; // Skipped: // // - `is_signed_int_t<T>` (probably won't be used directly in `modint.rs`) // - `is_unsigned_int_t<T>` (probably won't be used directly in `modint.rs`) // - `to_unsigned_t<T>` (not used in `fenwicktree.rs`) /// Corresponds to `std::is_integral` in C++. // We will remove unnecessary bounds later. // // Maybe we should rename this to `PrimitiveInteger` or something, as it probably won't be used in the // same way as the original ACL. pub trait Integral: 'static + Send + Sync + Copy + Ord + Not<Output = Self> + Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Div<Output = Self> + Rem<Output = Self> + AddAssign + SubAssign + MulAssign + DivAssign + RemAssign + Sum + Product + BitOr<Output = Self> + BitAnd<Output = Self> + BitXor<Output = Self> + BitOrAssign + BitAndAssign + BitXorAssign + Shl<Output = Self> + Shr<Output = Self> + ShlAssign + ShrAssign + fmt::Display + fmt::Debug + fmt::Binary + fmt::Octal + Zero + One + BoundedBelow + BoundedAbove { } /// Class that has additive identity element pub trait Zero { /// The additive identity element fn zero() -> Self; } /// Class that has multiplicative identity element pub trait One { /// The multiplicative identity element fn one() -> Self; } pub trait BoundedBelow { fn min_value() -> Self; } pub trait BoundedAbove { fn max_value() -> Self; } macro_rules! impl_integral { ($($ty:ty),*) => { $( impl Zero for $ty { #[inline] fn zero() -> Self { 0 } } impl One for $ty { #[inline] fn one() -> Self { 1 } } impl BoundedBelow for $ty { #[inline] fn min_value() -> Self { Self::min_value() } } impl BoundedAbove for $ty { #[inline] fn max_value() -> Self { Self::max_value() } } impl Integral for $ty {} )* }; } impl_integral!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize); } pub mod mincostflow { use crate::internal_type_traits::Integral; pub struct MinCostFlowEdge<T> { pub from: usize, pub to: usize, pub cap: T, pub flow: T, pub cost: T, } pub struct MinCostFlowGraph<T> { pos: Vec<(usize, usize)>, g: Vec<Vec<_Edge<T>>>, cost_sum: T, } impl<T> MinCostFlowGraph<T> where T: Integral + std::ops::Neg<Output = T>, { pub fn new(n: usize) -> Self { Self { pos: vec![], g: (0..n).map(|_| vec![]).collect(), cost_sum: T::zero(), } } pub fn get_edge(&self, i: usize) -> MinCostFlowEdge<T> { assert!(i < self.pos.len()); let e = &self.g[self.pos[i].0][self.pos[i].1]; let re = &self.g[e.to][e.rev]; MinCostFlowEdge { from: self.pos[i].0, to: e.to, cap: e.cap + re.cap, flow: re.cap, cost: e.cost, } } pub fn edges(&self) -> Vec<MinCostFlowEdge<T>> { let m = self.pos.len(); let mut result = vec![]; for i in 0..m { result.push(self.get_edge(i)); } result } pub fn add_edge(&mut self, from: usize, to: usize, cap: T, cost: T) -> usize { assert!(from < self.g.len()); assert!(to < self.g.len()); assert_ne!(from, to); assert!(cap >= T::zero()); assert!(cost >= T::zero()); self.pos.push((from, self.g[from].len())); self.cost_sum += cost; let rev = self.g[to].len(); self.g[from].push(_Edge { to, rev, cap, cost }); let rev = self.g[from].len() - 1; self.g[to].push(_Edge { to: from, rev, cap: T::zero(), cost: -cost, }); self.pos.len() - 1 } /// Returns (maximum flow, cost) pub fn flow(&mut self, source: usize, sink: usize, flow_limit: T) -> (T, T) { self.slope(source, sink, flow_limit).pop().unwrap() } pub fn slope(&mut self, source: usize, sink: usize, flow_limit: T) -> Vec<(T, T)>
fn refine_dual( &self, source: usize, sink: usize, dual: &mut [T], pv: &mut [usize], pe: &mut [usize], ) -> bool { let n = self.g.len(); let mut dist = vec![self.cost_sum; n]; let mut vis = vec![false; n]; let mut que = std::collections::BinaryHeap::new(); dist[source] = T::zero(); que.push((std::cmp::Reverse(T::zero()), source)); while let Some((_, v)) = que.pop() { if vis[v] { continue; } vis[v] = true; if v == sink { break; } for (i, e) in self.g[v].iter().enumerate() { if vis[e.to] || e.cap == T::zero() { continue; } let cost = e.cost - dual[e.to] + dual[v]; if dist[e.to] - dist[v] > cost { dist[e.to] = dist[v] + cost; pv[e.to] = v; pe[e.to] = i; que.push((std::cmp::Reverse(dist[e.to]), e.to)); } } } if !vis[sink] { return false; } for v in 0..n { if !vis[v] { continue; } dual[v] -= dist[sink] - dist[v]; } true } } struct _Edge<T> { to: usize, rev: usize, cap: T, cost: T, } #[cfg(test)] mod tests { use super::*; #[test] fn test_min_cost_flow() { let mut graph = MinCostFlowGraph::new(4); graph.add_edge(0, 1, 2, 1); graph.add_edge(0, 2, 1, 2); graph.add_edge(1, 2, 1, 1); graph.add_edge(1, 3, 1, 3); graph.add_edge(2, 3, 2, 1); let (flow, cost) = graph.flow(0, 3, 2); assert_eq!(flow, 2); assert_eq!(cost, 6); } } } use mincostflow::*;
{ let n = self.g.len(); assert!(source < n); assert!(sink < n); assert_ne!(source, sink); let mut dual = vec![T::zero(); n]; let mut prev_v = vec![0; n]; let mut prev_e = vec![0; n]; let mut flow = T::zero(); let mut cost = T::zero(); let mut prev_cost: Option<T> = None; let mut result = vec![(flow, cost)]; while flow < flow_limit { if !self.refine_dual(source, sink, &mut dual, &mut prev_v, &mut prev_e) { break; } let mut c = flow_limit - flow; let mut v = sink; while v != source { c = std::cmp::min(c, self.g[prev_v[v]][prev_e[v]].cap); v = prev_v[v]; } let mut v = sink; while v != source { self.g[prev_v[v]][prev_e[v]].cap -= c; let rev = self.g[prev_v[v]][prev_e[v]].rev; self.g[v][rev].cap += c; v = prev_v[v]; } let d = -dual[source]; flow += c; cost += d * c; if prev_cost == Some(d) { assert!(result.pop().is_some()); } result.push((flow, cost)); prev_cost = Some(cost); } result }
identifier_body
state-object.ts
import * as http from 'http' import * as send from 'send' import * as url from 'url' import { Stream, Writable } from 'stream' import { format } from 'util' import { RequestEvent } from './request-event' import { colors } from './constants' import { Config, OptionsConfig, ServerConfig, ServerConfig_AccessOptions, ErrorResponse, isError, JsonError, padLeft, ServerEventEmitter, StandardResponseHeaders, StateObjectUrl, StatPathResult, tryParseJSON, } from './server' import { HttpResponse, Header } from './types' let DEBUGLEVEL = -1 /** * 4 - Errors that require the process to exit for restart * 3 - Major errors that are handled and do not require a server restart * 2 - Warnings or errors that do not alter the program flow but need to be marked (minimum for status 500) * 1 - Info - Most startup messages * 0 - Normal debug messages and all software and request-side error messages * -1 - Detailed debug messages from high level apis * -2 - Response status messages and error response data * -3 - Request and response data for all messages (verbose) * -4 - Protocol details and full data dump (such as encryption steps and keys) */ declare function DebugLog( this: { debugOutput: Writable; settings: ServerConfig }, level: number, str: string | NodeJS.ErrnoException, ...args: any[] ) export class StateObject<STATPATH = StatPathResult, T = any> { static parseURL(str: string): StateObjectUrl { let item = url.parse(str, true) let { path, pathname, query, search, href } = item return { path: path || '', pathname: pathname || '', query: query || '', search: search || '', href: href || '', } } get allow(): ServerConfig_AccessOptions { if (this.authAccountsKey) { return this.settings.authAccounts[this.authAccountsKey].permissions } else { return this.settings.bindInfo.localAddressPermissions[this.hostLevelPermissionsKey] } } get hostRoot() { return this.settings.tree[this.treeHostIndex].$mount } startTime: [number, number] timestamp: string body: string = '' json: any | undefined /** The StatPathResult if this request resolves to a path */ //@ts-ignore Property has no initializer and is not definitely assigned in the constructor. statPath: STATPATH /** The tree ancestors in descending order, including the final folder element. */ //@ts-ignore Property has no initializer and is not definitely assigned in the constructor. ancestry: Config.MountElement[] /** The tree ancestors options as they apply to this request */ //@ts-ignore Property has no initializer and is not definitely assigned in the constructor. treeOptions: OptionsConfig url: StateObjectUrl path: string[] // where: string; query: any restrict: any pathOptions: { noTrailingSlash: boolean noDataFolder: boolean } = { noTrailingSlash: false, noDataFolder: false, } req: http.IncomingMessage res: http.ServerResponse responseHeaders: StandardResponseHeaders = {} as any responseSent: boolean = false private _req: http.IncomingMessage private _res: http.ServerResponse public hostLevelPermissionsKey: string public authAccountsKey: string /** The HostElement array index in settings.tree */ public treeHostIndex: number public username: string public readonly settings: Readonly<ServerConfig> public debugOutput: Writable constructor(private eventer: ServerEventEmitter, ev2: RequestEvent)
loglevel: number = DEBUGLEVEL doneMessage: string[] = [] hasCriticalLogs: boolean = false /** * 4 - Errors that require the process to exit for restart * 3 - Major errors that are handled and do not require a server restart * 2 - Warnings or errors that do not alter the program flow but need to be marked (minimum for status 500) * 1 - Info - Most startup messages * 0 - Normal debug messages and all software and request-side error messages * -1 - Detailed debug messages from high level apis * -2 - Response status messages and error response data * -3 - Request and response data for all messages (verbose) * -4 - Protocol details and full data dump (such as encryption steps and keys) */ log(level: number, template: any, ...args: any[]) { if (level < this.loglevel) return this if (level > 1) { this.hasCriticalLogs = true debugger } this.doneMessage.push(format(template, ...args)) return this } /** * if the client is allowed to recieve error info, sends `message`, otherwise sends `reason`. * `reason` is always sent as the status header. */ throwError(statusCode: number, error: ErrorResponse, headers?: StandardResponseHeaders) { return this.throwReason(statusCode, this.allow.writeErrors ? error : error.reason, headers) } throwReason( statusCode: number, reason: string | ErrorResponse, headers?: StandardResponseHeaders ) { if (!this.responseSent) { if (typeof reason === 'string') { let res = this.respond(statusCode, reason, headers) if (statusCode !== HttpResponse.NoContent) res.string(reason) } else { let res = this.respond(statusCode, reason.reason, headers) if (statusCode !== HttpResponse.NoContent) res.string(reason.message) } } } throw(statusCode: number, headers?: StandardResponseHeaders) { if (!this.responseSent) { if (headers) this.setHeaders(headers) this.respond(statusCode).empty() } } setHeader(key: keyof StandardResponseHeaders, val: string) { this.setHeaders({ [key]: val } as any) } setHeaders(headers: StandardResponseHeaders) { Object.assign( this.responseHeaders, headers, headers[Header.SetCookie] ? { 'Set-Cookie': (this.responseHeaders[Header.SetCookie] || []).concat( headers[Header.SetCookie] || [] ), } : {} ) } respond(code: number, message?: string, headers?: StandardResponseHeaders) { if (headers) this.setHeaders(headers) if (!message) message = http.STATUS_CODES[code] if (this.settings._devmode) { let stack = new Error().stack setTimeout(() => { if (!this.responseSent) this.debugOutput.write('Response not sent syncly\n ' + stack) }, 0) } const subthis = { json: (data: any) => { this.setHeader(Header.ContentType, 'application/json') subthis.string(JSON.stringify(data)) }, string: (data: string) => { subthis.buffer(Buffer.from(data, 'utf8')) }, stream: (data: Stream) => { this._res.writeHead(code, message, this.responseHeaders as any) data.pipe(this._res) this.responseSent = true }, buffer: (data: Buffer) => { this.setHeader(Header.ContentLength, data.byteLength.toString()) this._res.writeHead(code, message, this.responseHeaders as any) this._res.write(data) this._res.end() this.responseSent = true }, empty: () => { this._res.writeHead(code, message, this.responseHeaders as any) this._res.end() this.responseSent = true }, } return subthis } redirect(redirect: string) { this.respond(302, '', { Location: redirect, }).empty() } send(options: { root: string | undefined filepath: string error?: (err: any) => void directory?: (filepath: string) => void headers?: (filepath: string) => http.OutgoingHttpHeaders }) { const { filepath, root, error, directory, headers } = options const sender = send(this._req, filepath, { root }) if (error) sender.on('error', error) if (directory) sender.on('directory', (res: http.ServerResponse, fp) => directory(fp)) if (headers) sender.on('headers', (res: http.ServerResponse, fp) => { const hdrs = headers(fp) Object.keys(hdrs).forEach(e => { let item = hdrs[e] if (item) res.setHeader(e, item.toString()) }) }) sender.pipe(this._res) } /** * Recieves the body of the request and stores it in body and json. If there is an * error parsing body as json, the error callback will be called or if the callback * is boolean true it will send an error response with the json error position. * * @param {(true | ((e: JsonError) => void))} errorCB sends an error response * showing the incorrect JSON syntax if true, or calls the function * @returns {Observable<StateObject>} * @memberof StateObject */ recieveBody(parseJSON: boolean, errorCB?: true | ((e: JsonError) => void)) { return new Promise<Buffer>(resolve => { let chunks: Buffer[] = [] this._req.on('data', chunk => { if (typeof chunk === 'string') { chunks.push(Buffer.from(chunk)) } else { chunks.push(chunk) } }) this._req.on('end', () => { this.body = Buffer.concat(chunks).toString('utf8') if (this.body.length === 0 || !parseJSON) return resolve() let catchHandler = errorCB === true ? (e: JsonError) => { this.respond(400, '', { 'Content-Type': 'text/plain', }).string(e.errorPosition) //return undefined; } : errorCB this.json = catchHandler ? tryParseJSON<any>(this.body, catchHandler) : tryParseJSON(this.body) resolve() }) }) } static DebugLogger(prefix: string, ignoreLevel?: boolean): typeof DebugLog { return function( this: { debugOutput: Writable; settings: ServerConfig }, msgLevel: number, tempString: any, ...args: any[] ) { if (!ignoreLevel && this.settings.logging.debugLevel > msgLevel) return if (isError(args[0])) { let err = args[0] args = [] if (err.stack) args.push(err.stack) else args.push('Error %s: %s', err.name, err.message) } let t = new Date() let date = format( '%s-%s-%s %s:%s:%s', t.getFullYear(), padLeft(t.getMonth() + 1, '00'), padLeft(t.getDate(), '00'), padLeft(t.getHours(), '00'), padLeft(t.getMinutes(), '00'), padLeft(t.getSeconds(), '00') ) this.debugOutput.write( ' ' + (msgLevel >= 3 ? colors.BgRed + colors.FgWhite : colors.FgRed) + prefix + ' ' + colors.FgCyan + date + colors.Reset + ' ' + format .apply(null, [tempString, ...args]) .split('\n') .map((e, i) => { if (i > 0) { return new Array(23 + prefix.length).join(' ') + e } else { return e } }) .join('\n'), 'utf8' ) } } }
{ this.req = this._req = ev2.request this.res = this._res = ev2.response this.hostLevelPermissionsKey = ev2.localAddressPermissionsKey this.authAccountsKey = ev2.authAccountKey this.treeHostIndex = ev2.treeHostIndex this.username = ev2.username this.settings = ev2.settings this.debugOutput = ev2.debugOutput || RequestEvent.MakeDebugOutput(ev2.settings) this.startTime = process.hrtime() //parse the url and store in state. this.url = StateObject.parseURL(this.req.url as string) //parse the path for future use this.path = (this.url.pathname as string).split('/') let t = new Date() this.timestamp = format( '%s-%s-%s %s:%s:%s', t.getFullYear(), padLeft(t.getMonth() + 1, '00'), padLeft(t.getDate(), '00'), padLeft(t.getHours(), '00'), padLeft(t.getMinutes(), '00'), padLeft(t.getSeconds(), '00') ) const interval = setInterval(() => { this.log(-2, 'LONG RUNNING RESPONSE') this.log(-2, '%s %s ', this.req.method, this.req.url) }, 60000) this._res.on('finish', () => { clearInterval(interval) if (this.hasCriticalLogs) this.eventer.emit('stateError', this) else this.eventer.emit('stateDebug', this) }) }
identifier_body
state-object.ts
import * as http from 'http' import * as send from 'send' import * as url from 'url' import { Stream, Writable } from 'stream' import { format } from 'util' import { RequestEvent } from './request-event' import { colors } from './constants' import { Config, OptionsConfig, ServerConfig, ServerConfig_AccessOptions, ErrorResponse, isError, JsonError, padLeft, ServerEventEmitter, StandardResponseHeaders, StateObjectUrl, StatPathResult, tryParseJSON, } from './server' import { HttpResponse, Header } from './types' let DEBUGLEVEL = -1 /** * 4 - Errors that require the process to exit for restart * 3 - Major errors that are handled and do not require a server restart * 2 - Warnings or errors that do not alter the program flow but need to be marked (minimum for status 500) * 1 - Info - Most startup messages * 0 - Normal debug messages and all software and request-side error messages * -1 - Detailed debug messages from high level apis * -2 - Response status messages and error response data * -3 - Request and response data for all messages (verbose) * -4 - Protocol details and full data dump (such as encryption steps and keys) */ declare function DebugLog( this: { debugOutput: Writable; settings: ServerConfig }, level: number, str: string | NodeJS.ErrnoException, ...args: any[] ) export class StateObject<STATPATH = StatPathResult, T = any> { static parseURL(str: string): StateObjectUrl { let item = url.parse(str, true) let { path, pathname, query, search, href } = item return { path: path || '', pathname: pathname || '', query: query || '', search: search || '', href: href || '', } } get allow(): ServerConfig_AccessOptions { if (this.authAccountsKey) { return this.settings.authAccounts[this.authAccountsKey].permissions } else { return this.settings.bindInfo.localAddressPermissions[this.hostLevelPermissionsKey] } } get hostRoot() { return this.settings.tree[this.treeHostIndex].$mount } startTime: [number, number] timestamp: string body: string = '' json: any | undefined /** The StatPathResult if this request resolves to a path */ //@ts-ignore Property has no initializer and is not definitely assigned in the constructor. statPath: STATPATH /** The tree ancestors in descending order, including the final folder element. */ //@ts-ignore Property has no initializer and is not definitely assigned in the constructor. ancestry: Config.MountElement[] /** The tree ancestors options as they apply to this request */ //@ts-ignore Property has no initializer and is not definitely assigned in the constructor. treeOptions: OptionsConfig url: StateObjectUrl path: string[] // where: string; query: any restrict: any pathOptions: { noTrailingSlash: boolean noDataFolder: boolean } = { noTrailingSlash: false, noDataFolder: false, } req: http.IncomingMessage res: http.ServerResponse responseHeaders: StandardResponseHeaders = {} as any responseSent: boolean = false private _req: http.IncomingMessage private _res: http.ServerResponse public hostLevelPermissionsKey: string public authAccountsKey: string /** The HostElement array index in settings.tree */ public treeHostIndex: number public username: string public readonly settings: Readonly<ServerConfig> public debugOutput: Writable constructor(private eventer: ServerEventEmitter, ev2: RequestEvent) { this.req = this._req = ev2.request this.res = this._res = ev2.response this.hostLevelPermissionsKey = ev2.localAddressPermissionsKey this.authAccountsKey = ev2.authAccountKey this.treeHostIndex = ev2.treeHostIndex this.username = ev2.username this.settings = ev2.settings this.debugOutput = ev2.debugOutput || RequestEvent.MakeDebugOutput(ev2.settings) this.startTime = process.hrtime() //parse the url and store in state. this.url = StateObject.parseURL(this.req.url as string) //parse the path for future use this.path = (this.url.pathname as string).split('/') let t = new Date() this.timestamp = format( '%s-%s-%s %s:%s:%s', t.getFullYear(), padLeft(t.getMonth() + 1, '00'), padLeft(t.getDate(), '00'), padLeft(t.getHours(), '00'), padLeft(t.getMinutes(), '00'), padLeft(t.getSeconds(), '00') )
this._res.on('finish', () => { clearInterval(interval) if (this.hasCriticalLogs) this.eventer.emit('stateError', this) else this.eventer.emit('stateDebug', this) }) } loglevel: number = DEBUGLEVEL doneMessage: string[] = [] hasCriticalLogs: boolean = false /** * 4 - Errors that require the process to exit for restart * 3 - Major errors that are handled and do not require a server restart * 2 - Warnings or errors that do not alter the program flow but need to be marked (minimum for status 500) * 1 - Info - Most startup messages * 0 - Normal debug messages and all software and request-side error messages * -1 - Detailed debug messages from high level apis * -2 - Response status messages and error response data * -3 - Request and response data for all messages (verbose) * -4 - Protocol details and full data dump (such as encryption steps and keys) */ log(level: number, template: any, ...args: any[]) { if (level < this.loglevel) return this if (level > 1) { this.hasCriticalLogs = true debugger } this.doneMessage.push(format(template, ...args)) return this } /** * if the client is allowed to recieve error info, sends `message`, otherwise sends `reason`. * `reason` is always sent as the status header. */ throwError(statusCode: number, error: ErrorResponse, headers?: StandardResponseHeaders) { return this.throwReason(statusCode, this.allow.writeErrors ? error : error.reason, headers) } throwReason( statusCode: number, reason: string | ErrorResponse, headers?: StandardResponseHeaders ) { if (!this.responseSent) { if (typeof reason === 'string') { let res = this.respond(statusCode, reason, headers) if (statusCode !== HttpResponse.NoContent) res.string(reason) } else { let res = this.respond(statusCode, reason.reason, headers) if (statusCode !== HttpResponse.NoContent) res.string(reason.message) } } } throw(statusCode: number, headers?: StandardResponseHeaders) { if (!this.responseSent) { if (headers) this.setHeaders(headers) this.respond(statusCode).empty() } } setHeader(key: keyof StandardResponseHeaders, val: string) { this.setHeaders({ [key]: val } as any) } setHeaders(headers: StandardResponseHeaders) { Object.assign( this.responseHeaders, headers, headers[Header.SetCookie] ? { 'Set-Cookie': (this.responseHeaders[Header.SetCookie] || []).concat( headers[Header.SetCookie] || [] ), } : {} ) } respond(code: number, message?: string, headers?: StandardResponseHeaders) { if (headers) this.setHeaders(headers) if (!message) message = http.STATUS_CODES[code] if (this.settings._devmode) { let stack = new Error().stack setTimeout(() => { if (!this.responseSent) this.debugOutput.write('Response not sent syncly\n ' + stack) }, 0) } const subthis = { json: (data: any) => { this.setHeader(Header.ContentType, 'application/json') subthis.string(JSON.stringify(data)) }, string: (data: string) => { subthis.buffer(Buffer.from(data, 'utf8')) }, stream: (data: Stream) => { this._res.writeHead(code, message, this.responseHeaders as any) data.pipe(this._res) this.responseSent = true }, buffer: (data: Buffer) => { this.setHeader(Header.ContentLength, data.byteLength.toString()) this._res.writeHead(code, message, this.responseHeaders as any) this._res.write(data) this._res.end() this.responseSent = true }, empty: () => { this._res.writeHead(code, message, this.responseHeaders as any) this._res.end() this.responseSent = true }, } return subthis } redirect(redirect: string) { this.respond(302, '', { Location: redirect, }).empty() } send(options: { root: string | undefined filepath: string error?: (err: any) => void directory?: (filepath: string) => void headers?: (filepath: string) => http.OutgoingHttpHeaders }) { const { filepath, root, error, directory, headers } = options const sender = send(this._req, filepath, { root }) if (error) sender.on('error', error) if (directory) sender.on('directory', (res: http.ServerResponse, fp) => directory(fp)) if (headers) sender.on('headers', (res: http.ServerResponse, fp) => { const hdrs = headers(fp) Object.keys(hdrs).forEach(e => { let item = hdrs[e] if (item) res.setHeader(e, item.toString()) }) }) sender.pipe(this._res) } /** * Recieves the body of the request and stores it in body and json. If there is an * error parsing body as json, the error callback will be called or if the callback * is boolean true it will send an error response with the json error position. * * @param {(true | ((e: JsonError) => void))} errorCB sends an error response * showing the incorrect JSON syntax if true, or calls the function * @returns {Observable<StateObject>} * @memberof StateObject */ recieveBody(parseJSON: boolean, errorCB?: true | ((e: JsonError) => void)) { return new Promise<Buffer>(resolve => { let chunks: Buffer[] = [] this._req.on('data', chunk => { if (typeof chunk === 'string') { chunks.push(Buffer.from(chunk)) } else { chunks.push(chunk) } }) this._req.on('end', () => { this.body = Buffer.concat(chunks).toString('utf8') if (this.body.length === 0 || !parseJSON) return resolve() let catchHandler = errorCB === true ? (e: JsonError) => { this.respond(400, '', { 'Content-Type': 'text/plain', }).string(e.errorPosition) //return undefined; } : errorCB this.json = catchHandler ? tryParseJSON<any>(this.body, catchHandler) : tryParseJSON(this.body) resolve() }) }) } static DebugLogger(prefix: string, ignoreLevel?: boolean): typeof DebugLog { return function( this: { debugOutput: Writable; settings: ServerConfig }, msgLevel: number, tempString: any, ...args: any[] ) { if (!ignoreLevel && this.settings.logging.debugLevel > msgLevel) return if (isError(args[0])) { let err = args[0] args = [] if (err.stack) args.push(err.stack) else args.push('Error %s: %s', err.name, err.message) } let t = new Date() let date = format( '%s-%s-%s %s:%s:%s', t.getFullYear(), padLeft(t.getMonth() + 1, '00'), padLeft(t.getDate(), '00'), padLeft(t.getHours(), '00'), padLeft(t.getMinutes(), '00'), padLeft(t.getSeconds(), '00') ) this.debugOutput.write( ' ' + (msgLevel >= 3 ? colors.BgRed + colors.FgWhite : colors.FgRed) + prefix + ' ' + colors.FgCyan + date + colors.Reset + ' ' + format .apply(null, [tempString, ...args]) .split('\n') .map((e, i) => { if (i > 0) { return new Array(23 + prefix.length).join(' ') + e } else { return e } }) .join('\n'), 'utf8' ) } } }
const interval = setInterval(() => { this.log(-2, 'LONG RUNNING RESPONSE') this.log(-2, '%s %s ', this.req.method, this.req.url) }, 60000)
random_line_split
state-object.ts
import * as http from 'http' import * as send from 'send' import * as url from 'url' import { Stream, Writable } from 'stream' import { format } from 'util' import { RequestEvent } from './request-event' import { colors } from './constants' import { Config, OptionsConfig, ServerConfig, ServerConfig_AccessOptions, ErrorResponse, isError, JsonError, padLeft, ServerEventEmitter, StandardResponseHeaders, StateObjectUrl, StatPathResult, tryParseJSON, } from './server' import { HttpResponse, Header } from './types' let DEBUGLEVEL = -1 /** * 4 - Errors that require the process to exit for restart * 3 - Major errors that are handled and do not require a server restart * 2 - Warnings or errors that do not alter the program flow but need to be marked (minimum for status 500) * 1 - Info - Most startup messages * 0 - Normal debug messages and all software and request-side error messages * -1 - Detailed debug messages from high level apis * -2 - Response status messages and error response data * -3 - Request and response data for all messages (verbose) * -4 - Protocol details and full data dump (such as encryption steps and keys) */ declare function DebugLog( this: { debugOutput: Writable; settings: ServerConfig }, level: number, str: string | NodeJS.ErrnoException, ...args: any[] ) export class StateObject<STATPATH = StatPathResult, T = any> { static parseURL(str: string): StateObjectUrl { let item = url.parse(str, true) let { path, pathname, query, search, href } = item return { path: path || '', pathname: pathname || '', query: query || '', search: search || '', href: href || '', } } get allow(): ServerConfig_AccessOptions { if (this.authAccountsKey) { return this.settings.authAccounts[this.authAccountsKey].permissions } else { return this.settings.bindInfo.localAddressPermissions[this.hostLevelPermissionsKey] } } get
() { return this.settings.tree[this.treeHostIndex].$mount } startTime: [number, number] timestamp: string body: string = '' json: any | undefined /** The StatPathResult if this request resolves to a path */ //@ts-ignore Property has no initializer and is not definitely assigned in the constructor. statPath: STATPATH /** The tree ancestors in descending order, including the final folder element. */ //@ts-ignore Property has no initializer and is not definitely assigned in the constructor. ancestry: Config.MountElement[] /** The tree ancestors options as they apply to this request */ //@ts-ignore Property has no initializer and is not definitely assigned in the constructor. treeOptions: OptionsConfig url: StateObjectUrl path: string[] // where: string; query: any restrict: any pathOptions: { noTrailingSlash: boolean noDataFolder: boolean } = { noTrailingSlash: false, noDataFolder: false, } req: http.IncomingMessage res: http.ServerResponse responseHeaders: StandardResponseHeaders = {} as any responseSent: boolean = false private _req: http.IncomingMessage private _res: http.ServerResponse public hostLevelPermissionsKey: string public authAccountsKey: string /** The HostElement array index in settings.tree */ public treeHostIndex: number public username: string public readonly settings: Readonly<ServerConfig> public debugOutput: Writable constructor(private eventer: ServerEventEmitter, ev2: RequestEvent) { this.req = this._req = ev2.request this.res = this._res = ev2.response this.hostLevelPermissionsKey = ev2.localAddressPermissionsKey this.authAccountsKey = ev2.authAccountKey this.treeHostIndex = ev2.treeHostIndex this.username = ev2.username this.settings = ev2.settings this.debugOutput = ev2.debugOutput || RequestEvent.MakeDebugOutput(ev2.settings) this.startTime = process.hrtime() //parse the url and store in state. this.url = StateObject.parseURL(this.req.url as string) //parse the path for future use this.path = (this.url.pathname as string).split('/') let t = new Date() this.timestamp = format( '%s-%s-%s %s:%s:%s', t.getFullYear(), padLeft(t.getMonth() + 1, '00'), padLeft(t.getDate(), '00'), padLeft(t.getHours(), '00'), padLeft(t.getMinutes(), '00'), padLeft(t.getSeconds(), '00') ) const interval = setInterval(() => { this.log(-2, 'LONG RUNNING RESPONSE') this.log(-2, '%s %s ', this.req.method, this.req.url) }, 60000) this._res.on('finish', () => { clearInterval(interval) if (this.hasCriticalLogs) this.eventer.emit('stateError', this) else this.eventer.emit('stateDebug', this) }) } loglevel: number = DEBUGLEVEL doneMessage: string[] = [] hasCriticalLogs: boolean = false /** * 4 - Errors that require the process to exit for restart * 3 - Major errors that are handled and do not require a server restart * 2 - Warnings or errors that do not alter the program flow but need to be marked (minimum for status 500) * 1 - Info - Most startup messages * 0 - Normal debug messages and all software and request-side error messages * -1 - Detailed debug messages from high level apis * -2 - Response status messages and error response data * -3 - Request and response data for all messages (verbose) * -4 - Protocol details and full data dump (such as encryption steps and keys) */ log(level: number, template: any, ...args: any[]) { if (level < this.loglevel) return this if (level > 1) { this.hasCriticalLogs = true debugger } this.doneMessage.push(format(template, ...args)) return this } /** * if the client is allowed to recieve error info, sends `message`, otherwise sends `reason`. * `reason` is always sent as the status header. */ throwError(statusCode: number, error: ErrorResponse, headers?: StandardResponseHeaders) { return this.throwReason(statusCode, this.allow.writeErrors ? error : error.reason, headers) } throwReason( statusCode: number, reason: string | ErrorResponse, headers?: StandardResponseHeaders ) { if (!this.responseSent) { if (typeof reason === 'string') { let res = this.respond(statusCode, reason, headers) if (statusCode !== HttpResponse.NoContent) res.string(reason) } else { let res = this.respond(statusCode, reason.reason, headers) if (statusCode !== HttpResponse.NoContent) res.string(reason.message) } } } throw(statusCode: number, headers?: StandardResponseHeaders) { if (!this.responseSent) { if (headers) this.setHeaders(headers) this.respond(statusCode).empty() } } setHeader(key: keyof StandardResponseHeaders, val: string) { this.setHeaders({ [key]: val } as any) } setHeaders(headers: StandardResponseHeaders) { Object.assign( this.responseHeaders, headers, headers[Header.SetCookie] ? { 'Set-Cookie': (this.responseHeaders[Header.SetCookie] || []).concat( headers[Header.SetCookie] || [] ), } : {} ) } respond(code: number, message?: string, headers?: StandardResponseHeaders) { if (headers) this.setHeaders(headers) if (!message) message = http.STATUS_CODES[code] if (this.settings._devmode) { let stack = new Error().stack setTimeout(() => { if (!this.responseSent) this.debugOutput.write('Response not sent syncly\n ' + stack) }, 0) } const subthis = { json: (data: any) => { this.setHeader(Header.ContentType, 'application/json') subthis.string(JSON.stringify(data)) }, string: (data: string) => { subthis.buffer(Buffer.from(data, 'utf8')) }, stream: (data: Stream) => { this._res.writeHead(code, message, this.responseHeaders as any) data.pipe(this._res) this.responseSent = true }, buffer: (data: Buffer) => { this.setHeader(Header.ContentLength, data.byteLength.toString()) this._res.writeHead(code, message, this.responseHeaders as any) this._res.write(data) this._res.end() this.responseSent = true }, empty: () => { this._res.writeHead(code, message, this.responseHeaders as any) this._res.end() this.responseSent = true }, } return subthis } redirect(redirect: string) { this.respond(302, '', { Location: redirect, }).empty() } send(options: { root: string | undefined filepath: string error?: (err: any) => void directory?: (filepath: string) => void headers?: (filepath: string) => http.OutgoingHttpHeaders }) { const { filepath, root, error, directory, headers } = options const sender = send(this._req, filepath, { root }) if (error) sender.on('error', error) if (directory) sender.on('directory', (res: http.ServerResponse, fp) => directory(fp)) if (headers) sender.on('headers', (res: http.ServerResponse, fp) => { const hdrs = headers(fp) Object.keys(hdrs).forEach(e => { let item = hdrs[e] if (item) res.setHeader(e, item.toString()) }) }) sender.pipe(this._res) } /** * Recieves the body of the request and stores it in body and json. If there is an * error parsing body as json, the error callback will be called or if the callback * is boolean true it will send an error response with the json error position. * * @param {(true | ((e: JsonError) => void))} errorCB sends an error response * showing the incorrect JSON syntax if true, or calls the function * @returns {Observable<StateObject>} * @memberof StateObject */ recieveBody(parseJSON: boolean, errorCB?: true | ((e: JsonError) => void)) { return new Promise<Buffer>(resolve => { let chunks: Buffer[] = [] this._req.on('data', chunk => { if (typeof chunk === 'string') { chunks.push(Buffer.from(chunk)) } else { chunks.push(chunk) } }) this._req.on('end', () => { this.body = Buffer.concat(chunks).toString('utf8') if (this.body.length === 0 || !parseJSON) return resolve() let catchHandler = errorCB === true ? (e: JsonError) => { this.respond(400, '', { 'Content-Type': 'text/plain', }).string(e.errorPosition) //return undefined; } : errorCB this.json = catchHandler ? tryParseJSON<any>(this.body, catchHandler) : tryParseJSON(this.body) resolve() }) }) } static DebugLogger(prefix: string, ignoreLevel?: boolean): typeof DebugLog { return function( this: { debugOutput: Writable; settings: ServerConfig }, msgLevel: number, tempString: any, ...args: any[] ) { if (!ignoreLevel && this.settings.logging.debugLevel > msgLevel) return if (isError(args[0])) { let err = args[0] args = [] if (err.stack) args.push(err.stack) else args.push('Error %s: %s', err.name, err.message) } let t = new Date() let date = format( '%s-%s-%s %s:%s:%s', t.getFullYear(), padLeft(t.getMonth() + 1, '00'), padLeft(t.getDate(), '00'), padLeft(t.getHours(), '00'), padLeft(t.getMinutes(), '00'), padLeft(t.getSeconds(), '00') ) this.debugOutput.write( ' ' + (msgLevel >= 3 ? colors.BgRed + colors.FgWhite : colors.FgRed) + prefix + ' ' + colors.FgCyan + date + colors.Reset + ' ' + format .apply(null, [tempString, ...args]) .split('\n') .map((e, i) => { if (i > 0) { return new Array(23 + prefix.length).join(' ') + e } else { return e } }) .join('\n'), 'utf8' ) } } }
hostRoot
identifier_name
docker-compose-dot.go
package main import ( "fmt" "io/ioutil" "os" "path/filepath" "strings" "flag" "log" "github.com/awalterschulze/gographviz" yaml "gopkg.in/yaml.v2" ) //Graphvix formatting //TODO: move to some sort of template.CSS const ( fontname string = "Helvetica" colorVolumes = "orange" colorPorts = "lightgrey" colorContainerName = "lightblue" colorEnvironment = "pink" colorNetworks = "palegreen" ) type config struct { Version string Networks map[string]network Volumes map[string]volume Services map[string]service } type network struct { Driver string DriverOpts map[string]string `yaml:"driver_opts,omitempty"` External map[string]string `yaml:"external,omitempty"` name map[string]string `yaml:"name,omitempty"` } type volume struct { Driver, External string DriverOpts map[string]string `yaml:"driver_opts,omitempty"` } type service struct { ContainerName string `yaml:"container_name,omitempty"` Image string Networks, Ports, Volumes []string Command CommandWrapper VolumesFrom []string `yaml:"volumes_from,omitempty"` DependsOn []string `yaml:"depends_on,omitempty"` CapAdd []string `yaml:"cap_add,omitempty"` Build BuildWrapper Environment map[string]string } // https://docs.docker.com/compose/compose-file/#service-configuration-reference // command // Override the default command. // command: bundle exec thin -p 3000 // The command can also be a list, in a manner similar to dockerfile: // command: ["bundle", "exec", "thin", "-p", "3000"] //CommandWrapper handles YAML "command" which has 2 formats type CommandWrapper struct { Command string Commands []string } //UnmarshalYAML handles the dynamic parsing of the YAML options func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error { var err error var str string if err = unmarshal(&str); err == nil { w.Command = str return nil } var commandArray []string if err = unmarshal(&commandArray); err == nil { w.Commands = commandArray return nil } return nil //TODO: should be an error , something like UNhhandledError } // https://docs.docker.com/compose/compose-file/#service-configuration-reference // build // Configuration options that are applied at build time. // // build can be specified either as a string containing a path to the build context: // version: '3' // services: // webapp: // build: ./dir // //Or, as an object with the path specified under context and optionally Dockerfile and args: // version: '3' // services: // webapp: // build: // context: ./dir // dockerfile: Dockerfile-alternate // args: // buildno: 1 // If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image: // // build: ./dir // image: webapp:tag // This results in an image named webapp and tagged tag, built from ./dir. //BuildWrapper handls YAML build which has 2 formats type BuildWrapper struct { BuildString string BuildObject map[string]string } //UnmarshalYAML handles the dynamic parsing of the YAML options func (w *BuildWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error { var err error var buildString string if err = unmarshal(&buildString); err == nil { //str := command //*w = CommandWrapper(str) w.BuildString = buildString return nil } // if err != nil { // return err // } // return json.Unmarshal([]byte(str), w) var buildObject map[string]string if err = unmarshal(&buildObject); err == nil { //str := command //*w = CommandWrapper(commandArray[0]) w.BuildObject = buildObject return nil } return nil //should be an error , something like UNhhandledError } func nodify(s string) string { return strings.Replace(s, "-", "_", -1) } func check(e error) { if e != nil { panic(e) } } //CLI flag configuration var flagFileOut bool func init() { flag.BoolVar(&flagFileOut, "fileOut", false, "Send Output to a file.") } var flagOutputMarkDown bool func init() { flag.BoolVar(&flagOutputMarkDown, "outputMarkDown", false, "Produce MarkDown formatted output.") } var flagQuiet bool func init() { flag.BoolVar(&flagQuiet, "quiet", false, "Suppress console output.") } var flagHelp bool func init() { flag.BoolVar(&flagHelp, "help", false, "Displays usage Help.") } var flagNoLegend bool func init() { flag.BoolVar(&flagNoLegend, "noLegend", false, "Suppress output of legend.") } var flagOnlyLegend bool func init() { flag.BoolVar(&flagOnlyLegend, "onlyLegend", false, "Output only the legend.") } func main() { var ( bytes []byte err error graph *gographviz.Graph project string cmdlineArguments []string ) if len(os.Args) < 2 { log.Fatal("Need at least an input file! USAGE --help") } if len(os.Args) >= 2 { flag.Parse() log.Println("Flag --fileOut :", flagFileOut) log.Println("Flag --outputMarkDown :", flagOutputMarkDown) log.Println("Flag --quiet :", flagQuiet) log.Println("Flag --noLegend :", flagNoLegend) log.Println("Flag --onlyLegend :", flagOnlyLegend) log.Println("Flag --help :", flagHelp) log.Println("Remaining Arguments (tail):", flag.Args()) cmdlineArguments = flag.Args() if flagHelp { consoleHelp() return } //log.Fatal("Need at leaset input file!") } else { cmdlineArguments = os.Args[1:] } composerFileFullPath, _ := filepath.Abs(cmdlineArguments[0]) composerFileExtension := filepath.Ext(composerFileFullPath) outputFileFullPathBase := strings.Split(composerFileFullPath, composerFileExtension)[0] bytes, err = ioutil.ReadFile(cmdlineArguments[0]) if err != nil { log.Fatal(err) } // Parse it as YML data := &config{} err = yaml.Unmarshal(bytes, &data) if err != nil { log.Fatal(err) } // Create directed graph graph = gographviz.NewGraph() graph.SetName(project) graph.SetDir(true) if !flagNoLegend || flagOnlyLegend { // Add legend graph.AddSubGraph(project, "cluster_legend", map[string]string{"label": "Legend"}) graph.AddNode("cluster_legend", "legend_service", map[string]string{"shape": "plaintext", "fontname": fontname, "label": "<<TABLE BORDER='0'>" + "<TR><TD BGCOLOR='" + colorContainerName + "'>container_name</TD></TR>" + "<TR><TD BGCOLOR='" + colorPorts + "'><FONT POINT-SIZE='9'>ports ext:int</FONT></TD></TR>" + "<TR><TD BGCOLOR='" + colorVolumes + "'><FONT POINT-SIZE='9'>volumes host:container</FONT></TD></TR>" + "<TR><TD BGCOLOR='" + colorEnvironment + "'><FONT POINT-SIZE='9'>environment</FONT></TD></TR>" + "</TABLE>>", }) } if !flagOnlyLegend { /** NETWORK NODES **/ for name := range data.Networks { /** if external**/ var ename = name if data.Networks[name].External != nil { ename = data.Networks[name].External["name"] } else { ename = name } graph.AddNode(project, nodify(name), map[string]string{ "label": fmt.Sprintf("\"Network: %s\"", ename), "fontname": fontname, "style": "filled", "shape": "box", "fillcolor": colorNetworks, }) } /** SERVICE NODES **/ for name, service := range data.Services { var attrs = map[string]string{"shape": "plaintext", "fontname": fontname, "label": "<<TABLE BORDER='0'>"} attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR='"+ colorContainerName+ "'>%s</TD></TR>", name) if service.Ports != nil { for _, port := range service.Ports { attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR='"+ colorPorts+ "'><FONT POINT-SIZE='9'>%s</FONT></TD></TR>", port) } } if service.Volumes != nil { for _, vol := range service.Volumes { attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR='"+ colorVolumes+ "'><FONT POINT-SIZE='9'>%s</FONT></TD></TR>", vol) } } /* if service.Environment != nil { for k, v := range service.Environment { attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR="+ colorEnvironment+ "><FONT POINT-SIZE='9'>%s: %s</FONT></TD></TR>",k,v) } }*/ attrs["label"] += "</TABLE>>" graph.AddNode(project, nodify(name), attrs) } /** EDGES **/ for name, service := range data.Services { // Links to networks if service.Networks != nil { for _, linkTo := range service.Networks { if strings.Contains(linkTo, ":") { linkTo = strings.Split(linkTo, ":")[0] } graph.AddEdge(nodify(name), nodify(linkTo), true, map[string]string{"dir": "none"}) // ,"fontname": fontname } } // volumes_from if service.VolumesFrom != nil { for _, linkTo := range service.VolumesFrom { graph.AddEdge(nodify(name), nodify(linkTo), true, map[string]string{"style": "dashed", "fontname": fontname, "label": "volumes_from"}) } } // depends_on if service.DependsOn != nil { for _, linkTo := range service.DependsOn { graph.AddEdge(nodify(name), nodify(linkTo), true, map[string]string{"style": "dashed", "fontname": fontname, "label": "depends_on"}) } } } } if flagFileOut && flagOutputMarkDown { fileOutputMarkdown(outputFileFullPathBase, graph.String()) } if !flagQuiet && flagOutputMarkDown { consoleOutputMarkdown(graph.String()) } else if !flagQuiet { consoleOutputStandardGraph(graph.String()) } } //consoleHelp responds to cli --help flag func consoleHelp() { const helpmsg = `docker-compose-dot: Generates graph representation of the docker-compose instance Command Line <flags> <yaml/yml file> Where <flags> are -- fileOut : Send Output to a file. --outputMarkDown : Produce MarkDown formatted output. --quiet : Suppress console output. --noLegend : Suppress display of legend. --onlyLegend : Display only the legend. --help : Display this help information. and <yaml/yml file> is the docker-composer.yaml file. ` log.Print(helpmsg) } func consoleOutputStandardGraph(graphString string)
func consoleOutputMarkdown(graphString string) { // Produce Markdown output with embedded graph // graph.String() fmt.Print("\n\n```viz\n\n") fmt.Print(graphString) fmt.Print("```\n\n") } func fileOutputMarkdown(outputFileFullPathBase string, graphString string) { // Produce Markdown output with embedded graph // outputFileFullPathBase // graph.String() outputMDfileFullPath := outputFileFullPathBase + ".md" //pngFile := absName + ".png"; fout, err := os.Create(outputMDfileFullPath) check(err) // It's idiomatic to defer a `Close` immediately // after opening a file. defer fout.Close() fmt.Fprintf(fout, "\n```viz\n") fmt.Fprintf(fout, graphString) fmt.Fprintf(fout, "```\n") // Issue a `Sync` to flush writes to stable storage. fout.Sync() }
{ // Produce Markdown output with embedded graph // graph.String() fmt.Print(graphString) }
identifier_body
docker-compose-dot.go
package main import ( "fmt" "io/ioutil" "os" "path/filepath" "strings" "flag" "log" "github.com/awalterschulze/gographviz" yaml "gopkg.in/yaml.v2" ) //Graphvix formatting //TODO: move to some sort of template.CSS const ( fontname string = "Helvetica" colorVolumes = "orange" colorPorts = "lightgrey" colorContainerName = "lightblue" colorEnvironment = "pink" colorNetworks = "palegreen" ) type config struct { Version string Networks map[string]network Volumes map[string]volume Services map[string]service } type network struct { Driver string DriverOpts map[string]string `yaml:"driver_opts,omitempty"` External map[string]string `yaml:"external,omitempty"` name map[string]string `yaml:"name,omitempty"` } type volume struct { Driver, External string DriverOpts map[string]string `yaml:"driver_opts,omitempty"` } type service struct { ContainerName string `yaml:"container_name,omitempty"` Image string Networks, Ports, Volumes []string Command CommandWrapper VolumesFrom []string `yaml:"volumes_from,omitempty"` DependsOn []string `yaml:"depends_on,omitempty"` CapAdd []string `yaml:"cap_add,omitempty"` Build BuildWrapper Environment map[string]string } // https://docs.docker.com/compose/compose-file/#service-configuration-reference // command // Override the default command. // command: bundle exec thin -p 3000 // The command can also be a list, in a manner similar to dockerfile: // command: ["bundle", "exec", "thin", "-p", "3000"] //CommandWrapper handles YAML "command" which has 2 formats type CommandWrapper struct { Command string Commands []string } //UnmarshalYAML handles the dynamic parsing of the YAML options func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error { var err error var str string if err = unmarshal(&str); err == nil { w.Command = str return nil } var commandArray []string if err = unmarshal(&commandArray); err == nil { w.Commands = commandArray return nil } return nil //TODO: should be an error , something like UNhhandledError } // https://docs.docker.com/compose/compose-file/#service-configuration-reference // build // Configuration options that are applied at build time. // // build can be specified either as a string containing a path to the build context: // version: '3' // services: // webapp: // build: ./dir // //Or, as an object with the path specified under context and optionally Dockerfile and args: // version: '3' // services: // webapp: // build: // context: ./dir // dockerfile: Dockerfile-alternate // args: // buildno: 1 // If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image: // // build: ./dir // image: webapp:tag // This results in an image named webapp and tagged tag, built from ./dir. //BuildWrapper handls YAML build which has 2 formats type BuildWrapper struct { BuildString string BuildObject map[string]string } //UnmarshalYAML handles the dynamic parsing of the YAML options func (w *BuildWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error { var err error var buildString string if err = unmarshal(&buildString); err == nil { //str := command //*w = CommandWrapper(str) w.BuildString = buildString return nil } // if err != nil { // return err // } // return json.Unmarshal([]byte(str), w) var buildObject map[string]string if err = unmarshal(&buildObject); err == nil { //str := command //*w = CommandWrapper(commandArray[0]) w.BuildObject = buildObject return nil } return nil //should be an error , something like UNhhandledError } func nodify(s string) string { return strings.Replace(s, "-", "_", -1) } func check(e error) { if e != nil { panic(e) } } //CLI flag configuration var flagFileOut bool func init() { flag.BoolVar(&flagFileOut, "fileOut", false, "Send Output to a file.") } var flagOutputMarkDown bool func init() { flag.BoolVar(&flagOutputMarkDown, "outputMarkDown", false, "Produce MarkDown formatted output.") } var flagQuiet bool func init() { flag.BoolVar(&flagQuiet, "quiet", false, "Suppress console output.") }
func init() { flag.BoolVar(&flagHelp, "help", false, "Displays usage Help.") } var flagNoLegend bool func init() { flag.BoolVar(&flagNoLegend, "noLegend", false, "Suppress output of legend.") } var flagOnlyLegend bool func init() { flag.BoolVar(&flagOnlyLegend, "onlyLegend", false, "Output only the legend.") } func main() { var ( bytes []byte err error graph *gographviz.Graph project string cmdlineArguments []string ) if len(os.Args) < 2 { log.Fatal("Need at least an input file! USAGE --help") } if len(os.Args) >= 2 { flag.Parse() log.Println("Flag --fileOut :", flagFileOut) log.Println("Flag --outputMarkDown :", flagOutputMarkDown) log.Println("Flag --quiet :", flagQuiet) log.Println("Flag --noLegend :", flagNoLegend) log.Println("Flag --onlyLegend :", flagOnlyLegend) log.Println("Flag --help :", flagHelp) log.Println("Remaining Arguments (tail):", flag.Args()) cmdlineArguments = flag.Args() if flagHelp { consoleHelp() return } //log.Fatal("Need at leaset input file!") } else { cmdlineArguments = os.Args[1:] } composerFileFullPath, _ := filepath.Abs(cmdlineArguments[0]) composerFileExtension := filepath.Ext(composerFileFullPath) outputFileFullPathBase := strings.Split(composerFileFullPath, composerFileExtension)[0] bytes, err = ioutil.ReadFile(cmdlineArguments[0]) if err != nil { log.Fatal(err) } // Parse it as YML data := &config{} err = yaml.Unmarshal(bytes, &data) if err != nil { log.Fatal(err) } // Create directed graph graph = gographviz.NewGraph() graph.SetName(project) graph.SetDir(true) if !flagNoLegend || flagOnlyLegend { // Add legend graph.AddSubGraph(project, "cluster_legend", map[string]string{"label": "Legend"}) graph.AddNode("cluster_legend", "legend_service", map[string]string{"shape": "plaintext", "fontname": fontname, "label": "<<TABLE BORDER='0'>" + "<TR><TD BGCOLOR='" + colorContainerName + "'>container_name</TD></TR>" + "<TR><TD BGCOLOR='" + colorPorts + "'><FONT POINT-SIZE='9'>ports ext:int</FONT></TD></TR>" + "<TR><TD BGCOLOR='" + colorVolumes + "'><FONT POINT-SIZE='9'>volumes host:container</FONT></TD></TR>" + "<TR><TD BGCOLOR='" + colorEnvironment + "'><FONT POINT-SIZE='9'>environment</FONT></TD></TR>" + "</TABLE>>", }) } if !flagOnlyLegend { /** NETWORK NODES **/ for name := range data.Networks { /** if external**/ var ename = name if data.Networks[name].External != nil { ename = data.Networks[name].External["name"] } else { ename = name } graph.AddNode(project, nodify(name), map[string]string{ "label": fmt.Sprintf("\"Network: %s\"", ename), "fontname": fontname, "style": "filled", "shape": "box", "fillcolor": colorNetworks, }) } /** SERVICE NODES **/ for name, service := range data.Services { var attrs = map[string]string{"shape": "plaintext", "fontname": fontname, "label": "<<TABLE BORDER='0'>"} attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR='"+ colorContainerName+ "'>%s</TD></TR>", name) if service.Ports != nil { for _, port := range service.Ports { attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR='"+ colorPorts+ "'><FONT POINT-SIZE='9'>%s</FONT></TD></TR>", port) } } if service.Volumes != nil { for _, vol := range service.Volumes { attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR='"+ colorVolumes+ "'><FONT POINT-SIZE='9'>%s</FONT></TD></TR>", vol) } } /* if service.Environment != nil { for k, v := range service.Environment { attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR="+ colorEnvironment+ "><FONT POINT-SIZE='9'>%s: %s</FONT></TD></TR>",k,v) } }*/ attrs["label"] += "</TABLE>>" graph.AddNode(project, nodify(name), attrs) } /** EDGES **/ for name, service := range data.Services { // Links to networks if service.Networks != nil { for _, linkTo := range service.Networks { if strings.Contains(linkTo, ":") { linkTo = strings.Split(linkTo, ":")[0] } graph.AddEdge(nodify(name), nodify(linkTo), true, map[string]string{"dir": "none"}) // ,"fontname": fontname } } // volumes_from if service.VolumesFrom != nil { for _, linkTo := range service.VolumesFrom { graph.AddEdge(nodify(name), nodify(linkTo), true, map[string]string{"style": "dashed", "fontname": fontname, "label": "volumes_from"}) } } // depends_on if service.DependsOn != nil { for _, linkTo := range service.DependsOn { graph.AddEdge(nodify(name), nodify(linkTo), true, map[string]string{"style": "dashed", "fontname": fontname, "label": "depends_on"}) } } } } if flagFileOut && flagOutputMarkDown { fileOutputMarkdown(outputFileFullPathBase, graph.String()) } if !flagQuiet && flagOutputMarkDown { consoleOutputMarkdown(graph.String()) } else if !flagQuiet { consoleOutputStandardGraph(graph.String()) } } //consoleHelp responds to cli --help flag func consoleHelp() { const helpmsg = `docker-compose-dot: Generates graph representation of the docker-compose instance Command Line <flags> <yaml/yml file> Where <flags> are -- fileOut : Send Output to a file. --outputMarkDown : Produce MarkDown formatted output. --quiet : Suppress console output. --noLegend : Suppress display of legend. --onlyLegend : Display only the legend. --help : Display this help information. and <yaml/yml file> is the docker-composer.yaml file. ` log.Print(helpmsg) } func consoleOutputStandardGraph(graphString string) { // Produce Markdown output with embedded graph // graph.String() fmt.Print(graphString) } func consoleOutputMarkdown(graphString string) { // Produce Markdown output with embedded graph // graph.String() fmt.Print("\n\n```viz\n\n") fmt.Print(graphString) fmt.Print("```\n\n") } func fileOutputMarkdown(outputFileFullPathBase string, graphString string) { // Produce Markdown output with embedded graph // outputFileFullPathBase // graph.String() outputMDfileFullPath := outputFileFullPathBase + ".md" //pngFile := absName + ".png"; fout, err := os.Create(outputMDfileFullPath) check(err) // It's idiomatic to defer a `Close` immediately // after opening a file. defer fout.Close() fmt.Fprintf(fout, "\n```viz\n") fmt.Fprintf(fout, graphString) fmt.Fprintf(fout, "```\n") // Issue a `Sync` to flush writes to stable storage. fout.Sync() }
var flagHelp bool
random_line_split
docker-compose-dot.go
package main import ( "fmt" "io/ioutil" "os" "path/filepath" "strings" "flag" "log" "github.com/awalterschulze/gographviz" yaml "gopkg.in/yaml.v2" ) //Graphvix formatting //TODO: move to some sort of template.CSS const ( fontname string = "Helvetica" colorVolumes = "orange" colorPorts = "lightgrey" colorContainerName = "lightblue" colorEnvironment = "pink" colorNetworks = "palegreen" ) type config struct { Version string Networks map[string]network Volumes map[string]volume Services map[string]service } type network struct { Driver string DriverOpts map[string]string `yaml:"driver_opts,omitempty"` External map[string]string `yaml:"external,omitempty"` name map[string]string `yaml:"name,omitempty"` } type volume struct { Driver, External string DriverOpts map[string]string `yaml:"driver_opts,omitempty"` } type service struct { ContainerName string `yaml:"container_name,omitempty"` Image string Networks, Ports, Volumes []string Command CommandWrapper VolumesFrom []string `yaml:"volumes_from,omitempty"` DependsOn []string `yaml:"depends_on,omitempty"` CapAdd []string `yaml:"cap_add,omitempty"` Build BuildWrapper Environment map[string]string } // https://docs.docker.com/compose/compose-file/#service-configuration-reference // command // Override the default command. // command: bundle exec thin -p 3000 // The command can also be a list, in a manner similar to dockerfile: // command: ["bundle", "exec", "thin", "-p", "3000"] //CommandWrapper handles YAML "command" which has 2 formats type CommandWrapper struct { Command string Commands []string } //UnmarshalYAML handles the dynamic parsing of the YAML options func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error { var err error var str string if err = unmarshal(&str); err == nil { w.Command = str return nil } var commandArray []string if err = unmarshal(&commandArray); err == nil { w.Commands = commandArray return nil } return nil //TODO: should be an error , something like UNhhandledError } // https://docs.docker.com/compose/compose-file/#service-configuration-reference // build // Configuration options that are applied at build time. // // build can be specified either as a string containing a path to the build context: // version: '3' // services: // webapp: // build: ./dir // //Or, as an object with the path specified under context and optionally Dockerfile and args: // version: '3' // services: // webapp: // build: // context: ./dir // dockerfile: Dockerfile-alternate // args: // buildno: 1 // If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image: // // build: ./dir // image: webapp:tag // This results in an image named webapp and tagged tag, built from ./dir. //BuildWrapper handls YAML build which has 2 formats type BuildWrapper struct { BuildString string BuildObject map[string]string } //UnmarshalYAML handles the dynamic parsing of the YAML options func (w *BuildWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error { var err error var buildString string if err = unmarshal(&buildString); err == nil { //str := command //*w = CommandWrapper(str) w.BuildString = buildString return nil } // if err != nil { // return err // } // return json.Unmarshal([]byte(str), w) var buildObject map[string]string if err = unmarshal(&buildObject); err == nil { //str := command //*w = CommandWrapper(commandArray[0]) w.BuildObject = buildObject return nil } return nil //should be an error , something like UNhhandledError } func nodify(s string) string { return strings.Replace(s, "-", "_", -1) } func check(e error) { if e != nil { panic(e) } } //CLI flag configuration var flagFileOut bool func init() { flag.BoolVar(&flagFileOut, "fileOut", false, "Send Output to a file.") } var flagOutputMarkDown bool func init() { flag.BoolVar(&flagOutputMarkDown, "outputMarkDown", false, "Produce MarkDown formatted output.") } var flagQuiet bool func init() { flag.BoolVar(&flagQuiet, "quiet", false, "Suppress console output.") } var flagHelp bool func init() { flag.BoolVar(&flagHelp, "help", false, "Displays usage Help.") } var flagNoLegend bool func init() { flag.BoolVar(&flagNoLegend, "noLegend", false, "Suppress output of legend.") } var flagOnlyLegend bool func init() { flag.BoolVar(&flagOnlyLegend, "onlyLegend", false, "Output only the legend.") } func main() { var ( bytes []byte err error graph *gographviz.Graph project string cmdlineArguments []string ) if len(os.Args) < 2 { log.Fatal("Need at least an input file! USAGE --help") } if len(os.Args) >= 2 { flag.Parse() log.Println("Flag --fileOut :", flagFileOut) log.Println("Flag --outputMarkDown :", flagOutputMarkDown) log.Println("Flag --quiet :", flagQuiet) log.Println("Flag --noLegend :", flagNoLegend) log.Println("Flag --onlyLegend :", flagOnlyLegend) log.Println("Flag --help :", flagHelp) log.Println("Remaining Arguments (tail):", flag.Args()) cmdlineArguments = flag.Args() if flagHelp { consoleHelp() return } //log.Fatal("Need at leaset input file!") } else { cmdlineArguments = os.Args[1:] } composerFileFullPath, _ := filepath.Abs(cmdlineArguments[0]) composerFileExtension := filepath.Ext(composerFileFullPath) outputFileFullPathBase := strings.Split(composerFileFullPath, composerFileExtension)[0] bytes, err = ioutil.ReadFile(cmdlineArguments[0]) if err != nil { log.Fatal(err) } // Parse it as YML data := &config{} err = yaml.Unmarshal(bytes, &data) if err != nil { log.Fatal(err) } // Create directed graph graph = gographviz.NewGraph() graph.SetName(project) graph.SetDir(true) if !flagNoLegend || flagOnlyLegend
if !flagOnlyLegend { /** NETWORK NODES **/ for name := range data.Networks { /** if external**/ var ename = name if data.Networks[name].External != nil { ename = data.Networks[name].External["name"] } else { ename = name } graph.AddNode(project, nodify(name), map[string]string{ "label": fmt.Sprintf("\"Network: %s\"", ename), "fontname": fontname, "style": "filled", "shape": "box", "fillcolor": colorNetworks, }) } /** SERVICE NODES **/ for name, service := range data.Services { var attrs = map[string]string{"shape": "plaintext", "fontname": fontname, "label": "<<TABLE BORDER='0'>"} attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR='"+ colorContainerName+ "'>%s</TD></TR>", name) if service.Ports != nil { for _, port := range service.Ports { attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR='"+ colorPorts+ "'><FONT POINT-SIZE='9'>%s</FONT></TD></TR>", port) } } if service.Volumes != nil { for _, vol := range service.Volumes { attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR='"+ colorVolumes+ "'><FONT POINT-SIZE='9'>%s</FONT></TD></TR>", vol) } } /* if service.Environment != nil { for k, v := range service.Environment { attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR="+ colorEnvironment+ "><FONT POINT-SIZE='9'>%s: %s</FONT></TD></TR>",k,v) } }*/ attrs["label"] += "</TABLE>>" graph.AddNode(project, nodify(name), attrs) } /** EDGES **/ for name, service := range data.Services { // Links to networks if service.Networks != nil { for _, linkTo := range service.Networks { if strings.Contains(linkTo, ":") { linkTo = strings.Split(linkTo, ":")[0] } graph.AddEdge(nodify(name), nodify(linkTo), true, map[string]string{"dir": "none"}) // ,"fontname": fontname } } // volumes_from if service.VolumesFrom != nil { for _, linkTo := range service.VolumesFrom { graph.AddEdge(nodify(name), nodify(linkTo), true, map[string]string{"style": "dashed", "fontname": fontname, "label": "volumes_from"}) } } // depends_on if service.DependsOn != nil { for _, linkTo := range service.DependsOn { graph.AddEdge(nodify(name), nodify(linkTo), true, map[string]string{"style": "dashed", "fontname": fontname, "label": "depends_on"}) } } } } if flagFileOut && flagOutputMarkDown { fileOutputMarkdown(outputFileFullPathBase, graph.String()) } if !flagQuiet && flagOutputMarkDown { consoleOutputMarkdown(graph.String()) } else if !flagQuiet { consoleOutputStandardGraph(graph.String()) } } //consoleHelp responds to cli --help flag func consoleHelp() { const helpmsg = `docker-compose-dot: Generates graph representation of the docker-compose instance Command Line <flags> <yaml/yml file> Where <flags> are -- fileOut : Send Output to a file. --outputMarkDown : Produce MarkDown formatted output. --quiet : Suppress console output. --noLegend : Suppress display of legend. --onlyLegend : Display only the legend. --help : Display this help information. and <yaml/yml file> is the docker-composer.yaml file. ` log.Print(helpmsg) } func consoleOutputStandardGraph(graphString string) { // Produce Markdown output with embedded graph // graph.String() fmt.Print(graphString) } func consoleOutputMarkdown(graphString string) { // Produce Markdown output with embedded graph // graph.String() fmt.Print("\n\n```viz\n\n") fmt.Print(graphString) fmt.Print("```\n\n") } func fileOutputMarkdown(outputFileFullPathBase string, graphString string) { // Produce Markdown output with embedded graph // outputFileFullPathBase // graph.String() outputMDfileFullPath := outputFileFullPathBase + ".md" //pngFile := absName + ".png"; fout, err := os.Create(outputMDfileFullPath) check(err) // It's idiomatic to defer a `Close` immediately // after opening a file. defer fout.Close() fmt.Fprintf(fout, "\n```viz\n") fmt.Fprintf(fout, graphString) fmt.Fprintf(fout, "```\n") // Issue a `Sync` to flush writes to stable storage. fout.Sync() }
{ // Add legend graph.AddSubGraph(project, "cluster_legend", map[string]string{"label": "Legend"}) graph.AddNode("cluster_legend", "legend_service", map[string]string{"shape": "plaintext", "fontname": fontname, "label": "<<TABLE BORDER='0'>" + "<TR><TD BGCOLOR='" + colorContainerName + "'>container_name</TD></TR>" + "<TR><TD BGCOLOR='" + colorPorts + "'><FONT POINT-SIZE='9'>ports ext:int</FONT></TD></TR>" + "<TR><TD BGCOLOR='" + colorVolumes + "'><FONT POINT-SIZE='9'>volumes host:container</FONT></TD></TR>" + "<TR><TD BGCOLOR='" + colorEnvironment + "'><FONT POINT-SIZE='9'>environment</FONT></TD></TR>" + "</TABLE>>", }) }
conditional_block
docker-compose-dot.go
package main import ( "fmt" "io/ioutil" "os" "path/filepath" "strings" "flag" "log" "github.com/awalterschulze/gographviz" yaml "gopkg.in/yaml.v2" ) //Graphvix formatting //TODO: move to some sort of template.CSS const ( fontname string = "Helvetica" colorVolumes = "orange" colorPorts = "lightgrey" colorContainerName = "lightblue" colorEnvironment = "pink" colorNetworks = "palegreen" ) type config struct { Version string Networks map[string]network Volumes map[string]volume Services map[string]service } type network struct { Driver string DriverOpts map[string]string `yaml:"driver_opts,omitempty"` External map[string]string `yaml:"external,omitempty"` name map[string]string `yaml:"name,omitempty"` } type volume struct { Driver, External string DriverOpts map[string]string `yaml:"driver_opts,omitempty"` } type service struct { ContainerName string `yaml:"container_name,omitempty"` Image string Networks, Ports, Volumes []string Command CommandWrapper VolumesFrom []string `yaml:"volumes_from,omitempty"` DependsOn []string `yaml:"depends_on,omitempty"` CapAdd []string `yaml:"cap_add,omitempty"` Build BuildWrapper Environment map[string]string } // https://docs.docker.com/compose/compose-file/#service-configuration-reference // command // Override the default command. // command: bundle exec thin -p 3000 // The command can also be a list, in a manner similar to dockerfile: // command: ["bundle", "exec", "thin", "-p", "3000"] //CommandWrapper handles YAML "command" which has 2 formats type CommandWrapper struct { Command string Commands []string } //UnmarshalYAML handles the dynamic parsing of the YAML options func (w *CommandWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error { var err error var str string if err = unmarshal(&str); err == nil { w.Command = str return nil } var commandArray []string if err = unmarshal(&commandArray); err == nil { w.Commands = commandArray return nil } return nil //TODO: should be an error , something like UNhhandledError } // https://docs.docker.com/compose/compose-file/#service-configuration-reference // build // Configuration options that are applied at build time. // // build can be specified either as a string containing a path to the build context: // version: '3' // services: // webapp: // build: ./dir // //Or, as an object with the path specified under context and optionally Dockerfile and args: // version: '3' // services: // webapp: // build: // context: ./dir // dockerfile: Dockerfile-alternate // args: // buildno: 1 // If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image: // // build: ./dir // image: webapp:tag // This results in an image named webapp and tagged tag, built from ./dir. //BuildWrapper handls YAML build which has 2 formats type BuildWrapper struct { BuildString string BuildObject map[string]string } //UnmarshalYAML handles the dynamic parsing of the YAML options func (w *BuildWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error { var err error var buildString string if err = unmarshal(&buildString); err == nil { //str := command //*w = CommandWrapper(str) w.BuildString = buildString return nil } // if err != nil { // return err // } // return json.Unmarshal([]byte(str), w) var buildObject map[string]string if err = unmarshal(&buildObject); err == nil { //str := command //*w = CommandWrapper(commandArray[0]) w.BuildObject = buildObject return nil } return nil //should be an error , something like UNhhandledError } func nodify(s string) string { return strings.Replace(s, "-", "_", -1) } func check(e error) { if e != nil { panic(e) } } //CLI flag configuration var flagFileOut bool func init() { flag.BoolVar(&flagFileOut, "fileOut", false, "Send Output to a file.") } var flagOutputMarkDown bool func init() { flag.BoolVar(&flagOutputMarkDown, "outputMarkDown", false, "Produce MarkDown formatted output.") } var flagQuiet bool func init() { flag.BoolVar(&flagQuiet, "quiet", false, "Suppress console output.") } var flagHelp bool func init() { flag.BoolVar(&flagHelp, "help", false, "Displays usage Help.") } var flagNoLegend bool func init() { flag.BoolVar(&flagNoLegend, "noLegend", false, "Suppress output of legend.") } var flagOnlyLegend bool func init() { flag.BoolVar(&flagOnlyLegend, "onlyLegend", false, "Output only the legend.") } func main() { var ( bytes []byte err error graph *gographviz.Graph project string cmdlineArguments []string ) if len(os.Args) < 2 { log.Fatal("Need at least an input file! USAGE --help") } if len(os.Args) >= 2 { flag.Parse() log.Println("Flag --fileOut :", flagFileOut) log.Println("Flag --outputMarkDown :", flagOutputMarkDown) log.Println("Flag --quiet :", flagQuiet) log.Println("Flag --noLegend :", flagNoLegend) log.Println("Flag --onlyLegend :", flagOnlyLegend) log.Println("Flag --help :", flagHelp) log.Println("Remaining Arguments (tail):", flag.Args()) cmdlineArguments = flag.Args() if flagHelp { consoleHelp() return } //log.Fatal("Need at leaset input file!") } else { cmdlineArguments = os.Args[1:] } composerFileFullPath, _ := filepath.Abs(cmdlineArguments[0]) composerFileExtension := filepath.Ext(composerFileFullPath) outputFileFullPathBase := strings.Split(composerFileFullPath, composerFileExtension)[0] bytes, err = ioutil.ReadFile(cmdlineArguments[0]) if err != nil { log.Fatal(err) } // Parse it as YML data := &config{} err = yaml.Unmarshal(bytes, &data) if err != nil { log.Fatal(err) } // Create directed graph graph = gographviz.NewGraph() graph.SetName(project) graph.SetDir(true) if !flagNoLegend || flagOnlyLegend { // Add legend graph.AddSubGraph(project, "cluster_legend", map[string]string{"label": "Legend"}) graph.AddNode("cluster_legend", "legend_service", map[string]string{"shape": "plaintext", "fontname": fontname, "label": "<<TABLE BORDER='0'>" + "<TR><TD BGCOLOR='" + colorContainerName + "'>container_name</TD></TR>" + "<TR><TD BGCOLOR='" + colorPorts + "'><FONT POINT-SIZE='9'>ports ext:int</FONT></TD></TR>" + "<TR><TD BGCOLOR='" + colorVolumes + "'><FONT POINT-SIZE='9'>volumes host:container</FONT></TD></TR>" + "<TR><TD BGCOLOR='" + colorEnvironment + "'><FONT POINT-SIZE='9'>environment</FONT></TD></TR>" + "</TABLE>>", }) } if !flagOnlyLegend { /** NETWORK NODES **/ for name := range data.Networks { /** if external**/ var ename = name if data.Networks[name].External != nil { ename = data.Networks[name].External["name"] } else { ename = name } graph.AddNode(project, nodify(name), map[string]string{ "label": fmt.Sprintf("\"Network: %s\"", ename), "fontname": fontname, "style": "filled", "shape": "box", "fillcolor": colorNetworks, }) } /** SERVICE NODES **/ for name, service := range data.Services { var attrs = map[string]string{"shape": "plaintext", "fontname": fontname, "label": "<<TABLE BORDER='0'>"} attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR='"+ colorContainerName+ "'>%s</TD></TR>", name) if service.Ports != nil { for _, port := range service.Ports { attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR='"+ colorPorts+ "'><FONT POINT-SIZE='9'>%s</FONT></TD></TR>", port) } } if service.Volumes != nil { for _, vol := range service.Volumes { attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR='"+ colorVolumes+ "'><FONT POINT-SIZE='9'>%s</FONT></TD></TR>", vol) } } /* if service.Environment != nil { for k, v := range service.Environment { attrs["label"] += fmt.Sprintf("<TR><TD BGCOLOR="+ colorEnvironment+ "><FONT POINT-SIZE='9'>%s: %s</FONT></TD></TR>",k,v) } }*/ attrs["label"] += "</TABLE>>" graph.AddNode(project, nodify(name), attrs) } /** EDGES **/ for name, service := range data.Services { // Links to networks if service.Networks != nil { for _, linkTo := range service.Networks { if strings.Contains(linkTo, ":") { linkTo = strings.Split(linkTo, ":")[0] } graph.AddEdge(nodify(name), nodify(linkTo), true, map[string]string{"dir": "none"}) // ,"fontname": fontname } } // volumes_from if service.VolumesFrom != nil { for _, linkTo := range service.VolumesFrom { graph.AddEdge(nodify(name), nodify(linkTo), true, map[string]string{"style": "dashed", "fontname": fontname, "label": "volumes_from"}) } } // depends_on if service.DependsOn != nil { for _, linkTo := range service.DependsOn { graph.AddEdge(nodify(name), nodify(linkTo), true, map[string]string{"style": "dashed", "fontname": fontname, "label": "depends_on"}) } } } } if flagFileOut && flagOutputMarkDown { fileOutputMarkdown(outputFileFullPathBase, graph.String()) } if !flagQuiet && flagOutputMarkDown { consoleOutputMarkdown(graph.String()) } else if !flagQuiet { consoleOutputStandardGraph(graph.String()) } } //consoleHelp responds to cli --help flag func consoleHelp() { const helpmsg = `docker-compose-dot: Generates graph representation of the docker-compose instance Command Line <flags> <yaml/yml file> Where <flags> are -- fileOut : Send Output to a file. --outputMarkDown : Produce MarkDown formatted output. --quiet : Suppress console output. --noLegend : Suppress display of legend. --onlyLegend : Display only the legend. --help : Display this help information. and <yaml/yml file> is the docker-composer.yaml file. ` log.Print(helpmsg) } func
(graphString string) { // Produce Markdown output with embedded graph // graph.String() fmt.Print(graphString) } func consoleOutputMarkdown(graphString string) { // Produce Markdown output with embedded graph // graph.String() fmt.Print("\n\n```viz\n\n") fmt.Print(graphString) fmt.Print("```\n\n") } func fileOutputMarkdown(outputFileFullPathBase string, graphString string) { // Produce Markdown output with embedded graph // outputFileFullPathBase // graph.String() outputMDfileFullPath := outputFileFullPathBase + ".md" //pngFile := absName + ".png"; fout, err := os.Create(outputMDfileFullPath) check(err) // It's idiomatic to defer a `Close` immediately // after opening a file. defer fout.Close() fmt.Fprintf(fout, "\n```viz\n") fmt.Fprintf(fout, graphString) fmt.Fprintf(fout, "```\n") // Issue a `Sync` to flush writes to stable storage. fout.Sync() }
consoleOutputStandardGraph
identifier_name
api.rs
// Copyright (c) 2019 Cloudflare, Inc. All rights reserved. // SPDX-License-Identifier: BSD-3-Clause use super::dev_lock::LockReadGuard; use super::drop_privileges::get_saved_ids; use super::{AllowedIP, Device, Error, SocketAddr}; use crate::device::Action; use crate::serialization::KeyBytes; use crate::x25519; use hex::encode as encode_hex; use libc::*; use std::fs::{create_dir, remove_file}; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net::{UnixListener, UnixStream}; use std::sync::atomic::Ordering; const SOCK_DIR: &str = "/var/run/wireguard/"; fn create_sock_dir() { let _ = create_dir(SOCK_DIR); // Create the directory if it does not exist if let Ok((saved_uid, saved_gid)) = get_saved_ids() { unsafe { let c_path = std::ffi::CString::new(SOCK_DIR).unwrap(); // The directory is under the root user, but we want to be able to // delete the files there when we exit, so we need to change the owner chown( c_path.as_bytes_with_nul().as_ptr() as _, saved_uid, saved_gid, ); } } } impl Device { /// Register the api handler for this Device. The api handler receives stream connections on a Unix socket /// with a known path: /var/run/wireguard/{tun_name}.sock. pub fn register_api_handler(&mut self) -> Result<(), Error> { let path = format!("{}/{}.sock", SOCK_DIR, self.iface.name()?); create_sock_dir(); let _ = remove_file(&path); // Attempt to remove the socket if already exists let api_listener = UnixListener::bind(&path).map_err(Error::ApiSocket)?; // Bind a new socket to the path self.cleanup_paths.push(path.clone()); self.queue.new_event( api_listener.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api unix socket let (api_conn, _) = match api_listener.accept() { Ok(conn) => conn, _ => return Action::Continue, }; let mut reader = BufReader::new(&api_conn); let mut writer = BufWriter::new(&api_conn); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } Action::Continue // Indicates the worker thread should continue as normal }), )?; self.register_monitor(path)?; self.register_api_signal_handlers() } pub fn register_api_fd(&mut self, fd: i32) -> Result<(), Error> { let io_file = unsafe { UnixStream::from_raw_fd(fd) }; self.queue.new_event( io_file.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api file descriptor let mut reader = BufReader::new(&io_file); let mut writer = BufWriter::new(&io_file); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } else { // The remote side is likely closed; we should trigger an exit. d.trigger_exit(); return Action::Exit; } Action::Continue // Indicates the worker thread should continue as normal }), )?; Ok(()) } fn register_monitor(&self, path: String) -> Result<(), Error> { self.queue.new_periodic_event( Box::new(move |d, _| { // This is not a very nice hack to detect if the control socket was removed // and exiting nicely as a result. We check every 3 seconds in a loop if the // file was deleted by stating it. // The problem is that on linux inotify can be used quite beautifully to detect // deletion, and kqueue EVFILT_VNODE can be used for the same purpose, but that // will require introducing new events, for no measurable benefit. // TODO: Could this be an issue if we restart the service too quickly? let path = std::path::Path::new(&path); if !path.exists() { d.trigger_exit(); return Action::Exit; } // Periodically read the mtu of the interface in case it changes if let Ok(mtu) = d.iface.mtu() { d.mtu.store(mtu, Ordering::Relaxed); } Action::Continue }), std::time::Duration::from_millis(1000), )?; Ok(()) } fn register_api_signal_handlers(&self) -> Result<(), Error> { self.queue .new_signal_event(SIGINT, Box::new(move |_, _| Action::Exit))?; self.queue .new_signal_event(SIGTERM, Box::new(move |_, _| Action::Exit))?; Ok(()) } } #[allow(unused_must_use)] fn api_get(writer: &mut BufWriter<&UnixStream>, d: &Device) -> i32 { // get command requires an empty line, but there is no reason to be religious about it if let Some(ref k) = d.key_pair { writeln!(writer, "own_public_key={}", encode_hex(k.1.as_bytes())); } if d.listen_port != 0 { writeln!(writer, "listen_port={}", d.listen_port); } if let Some(fwmark) = d.fwmark { writeln!(writer, "fwmark={}", fwmark); } for (k, p) in d.peers.iter() { let p = p.lock(); writeln!(writer, "public_key={}", encode_hex(k.as_bytes())); if let Some(ref key) = p.preshared_key() { writeln!(writer, "preshared_key={}", encode_hex(key)); } if let Some(keepalive) = p.persistent_keepalive() { writeln!(writer, "persistent_keepalive_interval={}", keepalive); } if let Some(ref addr) = p.endpoint().addr { writeln!(writer, "endpoint={}", addr); } for (ip, cidr) in p.allowed_ips() { writeln!(writer, "allowed_ip={}/{}", ip, cidr); } if let Some(time) = p.time_since_last_handshake() { writeln!(writer, "last_handshake_time_sec={}", time.as_secs()); writeln!(writer, "last_handshake_time_nsec={}", time.subsec_nanos()); } let (_, tx_bytes, rx_bytes, ..) = p.tunnel.stats(); writeln!(writer, "rx_bytes={}", rx_bytes); writeln!(writer, "tx_bytes={}", tx_bytes); } 0 } fn api_set(reader: &mut BufReader<&UnixStream>, d: &mut LockReadGuard<Device>) -> i32
fn api_set_peer( reader: &mut BufReader<&UnixStream>, d: &mut Device, pub_key: x25519::PublicKey, ) -> i32 { let mut cmd = String::new(); let mut remove = false; let mut replace_ips = false; let mut endpoint = None; let mut keepalive = None; let mut public_key = pub_key; let mut preshared_key = None; let mut allowed_ips: Vec<AllowedIP> = vec![]; while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.splitn(2, '=').collect(); if parsed_cmd.len() != 2 { return EPROTO; } let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "remove" => match val.parse::<bool>() { Ok(true) => remove = true, Ok(false) => remove = false, Err(_) => return EINVAL, }, "preshared_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => preshared_key = Some(key_bytes.0), Err(_) => return EINVAL, }, "endpoint" => match val.parse::<SocketAddr>() { Ok(addr) => endpoint = Some(addr), Err(_) => return EINVAL, }, "persistent_keepalive_interval" => match val.parse::<u16>() { Ok(interval) => keepalive = Some(interval), Err(_) => return EINVAL, }, "replace_allowed_ips" => match val.parse::<bool>() { Ok(true) => replace_ips = true, Ok(false) => replace_ips = false, Err(_) => return EINVAL, }, "allowed_ip" => match val.parse::<AllowedIP>() { Ok(ip) => allowed_ips.push(ip), Err(_) => return EINVAL, }, "public_key" => { // Indicates a new peer section. Commit changes for current peer, and continue to next peer d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update match val.parse::<KeyBytes>() { Ok(key_bytes) => public_key = key_bytes.0.into(), Err(_) => return EINVAL, } } "protocol_version" => match val.parse::<u32>() { Ok(1) => {} // Only version 1 is legal _ => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }
{ d.try_writeable( |device| device.trigger_yield(), |device| { device.cancel_yield(); let mut cmd = String::new(); while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.split('=').collect(); if parsed_cmd.len() != 2 { return EPROTO; } let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "private_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => { device.set_key(x25519::StaticSecret::from(key_bytes.0)) } Err(_) => return EINVAL, }, "listen_port" => match val.parse::<u16>() { Ok(port) => match device.open_listen_socket(port) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, #[cfg(any( target_os = "android", target_os = "fuchsia", target_os = "linux" ))] "fwmark" => match val.parse::<u32>() { Ok(mark) => match device.set_fwmark(mark) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, "replace_peers" => match val.parse::<bool>() { Ok(true) => device.clear_peers(), Ok(false) => {} Err(_) => return EINVAL, }, "public_key" => match val.parse::<KeyBytes>() { // Indicates a new peer section Ok(key_bytes) => { return api_set_peer( reader, device, x25519::PublicKey::from(key_bytes.0), ) } Err(_) => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }, ) .unwrap_or(EIO) }
identifier_body
api.rs
// Copyright (c) 2019 Cloudflare, Inc. All rights reserved. // SPDX-License-Identifier: BSD-3-Clause use super::dev_lock::LockReadGuard; use super::drop_privileges::get_saved_ids; use super::{AllowedIP, Device, Error, SocketAddr}; use crate::device::Action; use crate::serialization::KeyBytes; use crate::x25519; use hex::encode as encode_hex; use libc::*; use std::fs::{create_dir, remove_file}; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net::{UnixListener, UnixStream}; use std::sync::atomic::Ordering; const SOCK_DIR: &str = "/var/run/wireguard/"; fn create_sock_dir() { let _ = create_dir(SOCK_DIR); // Create the directory if it does not exist if let Ok((saved_uid, saved_gid)) = get_saved_ids() { unsafe { let c_path = std::ffi::CString::new(SOCK_DIR).unwrap(); // The directory is under the root user, but we want to be able to // delete the files there when we exit, so we need to change the owner chown( c_path.as_bytes_with_nul().as_ptr() as _, saved_uid, saved_gid, ); } } } impl Device { /// Register the api handler for this Device. The api handler receives stream connections on a Unix socket /// with a known path: /var/run/wireguard/{tun_name}.sock. pub fn register_api_handler(&mut self) -> Result<(), Error> { let path = format!("{}/{}.sock", SOCK_DIR, self.iface.name()?); create_sock_dir(); let _ = remove_file(&path); // Attempt to remove the socket if already exists let api_listener = UnixListener::bind(&path).map_err(Error::ApiSocket)?; // Bind a new socket to the path self.cleanup_paths.push(path.clone()); self.queue.new_event( api_listener.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api unix socket let (api_conn, _) = match api_listener.accept() { Ok(conn) => conn, _ => return Action::Continue, }; let mut reader = BufReader::new(&api_conn); let mut writer = BufWriter::new(&api_conn); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } Action::Continue // Indicates the worker thread should continue as normal }), )?; self.register_monitor(path)?; self.register_api_signal_handlers() } pub fn register_api_fd(&mut self, fd: i32) -> Result<(), Error> { let io_file = unsafe { UnixStream::from_raw_fd(fd) }; self.queue.new_event( io_file.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api file descriptor let mut reader = BufReader::new(&io_file); let mut writer = BufWriter::new(&io_file); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } else { // The remote side is likely closed; we should trigger an exit. d.trigger_exit(); return Action::Exit; } Action::Continue // Indicates the worker thread should continue as normal }), )?; Ok(()) } fn register_monitor(&self, path: String) -> Result<(), Error> { self.queue.new_periodic_event( Box::new(move |d, _| { // This is not a very nice hack to detect if the control socket was removed // and exiting nicely as a result. We check every 3 seconds in a loop if the // file was deleted by stating it. // The problem is that on linux inotify can be used quite beautifully to detect // deletion, and kqueue EVFILT_VNODE can be used for the same purpose, but that // will require introducing new events, for no measurable benefit. // TODO: Could this be an issue if we restart the service too quickly? let path = std::path::Path::new(&path); if !path.exists() { d.trigger_exit(); return Action::Exit; } // Periodically read the mtu of the interface in case it changes if let Ok(mtu) = d.iface.mtu() { d.mtu.store(mtu, Ordering::Relaxed); } Action::Continue }), std::time::Duration::from_millis(1000), )?; Ok(()) } fn register_api_signal_handlers(&self) -> Result<(), Error> { self.queue .new_signal_event(SIGINT, Box::new(move |_, _| Action::Exit))?; self.queue .new_signal_event(SIGTERM, Box::new(move |_, _| Action::Exit))?; Ok(()) } } #[allow(unused_must_use)] fn api_get(writer: &mut BufWriter<&UnixStream>, d: &Device) -> i32 { // get command requires an empty line, but there is no reason to be religious about it if let Some(ref k) = d.key_pair { writeln!(writer, "own_public_key={}", encode_hex(k.1.as_bytes())); } if d.listen_port != 0 { writeln!(writer, "listen_port={}", d.listen_port); } if let Some(fwmark) = d.fwmark { writeln!(writer, "fwmark={}", fwmark); } for (k, p) in d.peers.iter() { let p = p.lock(); writeln!(writer, "public_key={}", encode_hex(k.as_bytes())); if let Some(ref key) = p.preshared_key() { writeln!(writer, "preshared_key={}", encode_hex(key)); } if let Some(keepalive) = p.persistent_keepalive() { writeln!(writer, "persistent_keepalive_interval={}", keepalive); } if let Some(ref addr) = p.endpoint().addr { writeln!(writer, "endpoint={}", addr); } for (ip, cidr) in p.allowed_ips() { writeln!(writer, "allowed_ip={}/{}", ip, cidr); } if let Some(time) = p.time_since_last_handshake() { writeln!(writer, "last_handshake_time_sec={}", time.as_secs()); writeln!(writer, "last_handshake_time_nsec={}", time.subsec_nanos()); } let (_, tx_bytes, rx_bytes, ..) = p.tunnel.stats(); writeln!(writer, "rx_bytes={}", rx_bytes); writeln!(writer, "tx_bytes={}", tx_bytes); } 0 } fn api_set(reader: &mut BufReader<&UnixStream>, d: &mut LockReadGuard<Device>) -> i32 { d.try_writeable( |device| device.trigger_yield(), |device| { device.cancel_yield(); let mut cmd = String::new(); while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.split('=').collect(); if parsed_cmd.len() != 2 { return EPROTO; } let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "private_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => { device.set_key(x25519::StaticSecret::from(key_bytes.0)) } Err(_) => return EINVAL, }, "listen_port" => match val.parse::<u16>() { Ok(port) => match device.open_listen_socket(port) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, #[cfg(any( target_os = "android",
Ok(mark) => match device.set_fwmark(mark) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, "replace_peers" => match val.parse::<bool>() { Ok(true) => device.clear_peers(), Ok(false) => {} Err(_) => return EINVAL, }, "public_key" => match val.parse::<KeyBytes>() { // Indicates a new peer section Ok(key_bytes) => { return api_set_peer( reader, device, x25519::PublicKey::from(key_bytes.0), ) } Err(_) => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }, ) .unwrap_or(EIO) } fn api_set_peer( reader: &mut BufReader<&UnixStream>, d: &mut Device, pub_key: x25519::PublicKey, ) -> i32 { let mut cmd = String::new(); let mut remove = false; let mut replace_ips = false; let mut endpoint = None; let mut keepalive = None; let mut public_key = pub_key; let mut preshared_key = None; let mut allowed_ips: Vec<AllowedIP> = vec![]; while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.splitn(2, '=').collect(); if parsed_cmd.len() != 2 { return EPROTO; } let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "remove" => match val.parse::<bool>() { Ok(true) => remove = true, Ok(false) => remove = false, Err(_) => return EINVAL, }, "preshared_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => preshared_key = Some(key_bytes.0), Err(_) => return EINVAL, }, "endpoint" => match val.parse::<SocketAddr>() { Ok(addr) => endpoint = Some(addr), Err(_) => return EINVAL, }, "persistent_keepalive_interval" => match val.parse::<u16>() { Ok(interval) => keepalive = Some(interval), Err(_) => return EINVAL, }, "replace_allowed_ips" => match val.parse::<bool>() { Ok(true) => replace_ips = true, Ok(false) => replace_ips = false, Err(_) => return EINVAL, }, "allowed_ip" => match val.parse::<AllowedIP>() { Ok(ip) => allowed_ips.push(ip), Err(_) => return EINVAL, }, "public_key" => { // Indicates a new peer section. Commit changes for current peer, and continue to next peer d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update match val.parse::<KeyBytes>() { Ok(key_bytes) => public_key = key_bytes.0.into(), Err(_) => return EINVAL, } } "protocol_version" => match val.parse::<u32>() { Ok(1) => {} // Only version 1 is legal _ => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }
target_os = "fuchsia", target_os = "linux" ))] "fwmark" => match val.parse::<u32>() {
random_line_split
api.rs
// Copyright (c) 2019 Cloudflare, Inc. All rights reserved. // SPDX-License-Identifier: BSD-3-Clause use super::dev_lock::LockReadGuard; use super::drop_privileges::get_saved_ids; use super::{AllowedIP, Device, Error, SocketAddr}; use crate::device::Action; use crate::serialization::KeyBytes; use crate::x25519; use hex::encode as encode_hex; use libc::*; use std::fs::{create_dir, remove_file}; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net::{UnixListener, UnixStream}; use std::sync::atomic::Ordering; const SOCK_DIR: &str = "/var/run/wireguard/"; fn create_sock_dir() { let _ = create_dir(SOCK_DIR); // Create the directory if it does not exist if let Ok((saved_uid, saved_gid)) = get_saved_ids() { unsafe { let c_path = std::ffi::CString::new(SOCK_DIR).unwrap(); // The directory is under the root user, but we want to be able to // delete the files there when we exit, so we need to change the owner chown( c_path.as_bytes_with_nul().as_ptr() as _, saved_uid, saved_gid, ); } } } impl Device { /// Register the api handler for this Device. The api handler receives stream connections on a Unix socket /// with a known path: /var/run/wireguard/{tun_name}.sock. pub fn register_api_handler(&mut self) -> Result<(), Error> { let path = format!("{}/{}.sock", SOCK_DIR, self.iface.name()?); create_sock_dir(); let _ = remove_file(&path); // Attempt to remove the socket if already exists let api_listener = UnixListener::bind(&path).map_err(Error::ApiSocket)?; // Bind a new socket to the path self.cleanup_paths.push(path.clone()); self.queue.new_event( api_listener.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api unix socket let (api_conn, _) = match api_listener.accept() { Ok(conn) => conn, _ => return Action::Continue, }; let mut reader = BufReader::new(&api_conn); let mut writer = BufWriter::new(&api_conn); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } Action::Continue // Indicates the worker thread should continue as normal }), )?; self.register_monitor(path)?; self.register_api_signal_handlers() } pub fn
(&mut self, fd: i32) -> Result<(), Error> { let io_file = unsafe { UnixStream::from_raw_fd(fd) }; self.queue.new_event( io_file.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api file descriptor let mut reader = BufReader::new(&io_file); let mut writer = BufWriter::new(&io_file); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } else { // The remote side is likely closed; we should trigger an exit. d.trigger_exit(); return Action::Exit; } Action::Continue // Indicates the worker thread should continue as normal }), )?; Ok(()) } fn register_monitor(&self, path: String) -> Result<(), Error> { self.queue.new_periodic_event( Box::new(move |d, _| { // This is not a very nice hack to detect if the control socket was removed // and exiting nicely as a result. We check every 3 seconds in a loop if the // file was deleted by stating it. // The problem is that on linux inotify can be used quite beautifully to detect // deletion, and kqueue EVFILT_VNODE can be used for the same purpose, but that // will require introducing new events, for no measurable benefit. // TODO: Could this be an issue if we restart the service too quickly? let path = std::path::Path::new(&path); if !path.exists() { d.trigger_exit(); return Action::Exit; } // Periodically read the mtu of the interface in case it changes if let Ok(mtu) = d.iface.mtu() { d.mtu.store(mtu, Ordering::Relaxed); } Action::Continue }), std::time::Duration::from_millis(1000), )?; Ok(()) } fn register_api_signal_handlers(&self) -> Result<(), Error> { self.queue .new_signal_event(SIGINT, Box::new(move |_, _| Action::Exit))?; self.queue .new_signal_event(SIGTERM, Box::new(move |_, _| Action::Exit))?; Ok(()) } } #[allow(unused_must_use)] fn api_get(writer: &mut BufWriter<&UnixStream>, d: &Device) -> i32 { // get command requires an empty line, but there is no reason to be religious about it if let Some(ref k) = d.key_pair { writeln!(writer, "own_public_key={}", encode_hex(k.1.as_bytes())); } if d.listen_port != 0 { writeln!(writer, "listen_port={}", d.listen_port); } if let Some(fwmark) = d.fwmark { writeln!(writer, "fwmark={}", fwmark); } for (k, p) in d.peers.iter() { let p = p.lock(); writeln!(writer, "public_key={}", encode_hex(k.as_bytes())); if let Some(ref key) = p.preshared_key() { writeln!(writer, "preshared_key={}", encode_hex(key)); } if let Some(keepalive) = p.persistent_keepalive() { writeln!(writer, "persistent_keepalive_interval={}", keepalive); } if let Some(ref addr) = p.endpoint().addr { writeln!(writer, "endpoint={}", addr); } for (ip, cidr) in p.allowed_ips() { writeln!(writer, "allowed_ip={}/{}", ip, cidr); } if let Some(time) = p.time_since_last_handshake() { writeln!(writer, "last_handshake_time_sec={}", time.as_secs()); writeln!(writer, "last_handshake_time_nsec={}", time.subsec_nanos()); } let (_, tx_bytes, rx_bytes, ..) = p.tunnel.stats(); writeln!(writer, "rx_bytes={}", rx_bytes); writeln!(writer, "tx_bytes={}", tx_bytes); } 0 } fn api_set(reader: &mut BufReader<&UnixStream>, d: &mut LockReadGuard<Device>) -> i32 { d.try_writeable( |device| device.trigger_yield(), |device| { device.cancel_yield(); let mut cmd = String::new(); while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.split('=').collect(); if parsed_cmd.len() != 2 { return EPROTO; } let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "private_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => { device.set_key(x25519::StaticSecret::from(key_bytes.0)) } Err(_) => return EINVAL, }, "listen_port" => match val.parse::<u16>() { Ok(port) => match device.open_listen_socket(port) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, #[cfg(any( target_os = "android", target_os = "fuchsia", target_os = "linux" ))] "fwmark" => match val.parse::<u32>() { Ok(mark) => match device.set_fwmark(mark) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, "replace_peers" => match val.parse::<bool>() { Ok(true) => device.clear_peers(), Ok(false) => {} Err(_) => return EINVAL, }, "public_key" => match val.parse::<KeyBytes>() { // Indicates a new peer section Ok(key_bytes) => { return api_set_peer( reader, device, x25519::PublicKey::from(key_bytes.0), ) } Err(_) => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }, ) .unwrap_or(EIO) } fn api_set_peer( reader: &mut BufReader<&UnixStream>, d: &mut Device, pub_key: x25519::PublicKey, ) -> i32 { let mut cmd = String::new(); let mut remove = false; let mut replace_ips = false; let mut endpoint = None; let mut keepalive = None; let mut public_key = pub_key; let mut preshared_key = None; let mut allowed_ips: Vec<AllowedIP> = vec![]; while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.splitn(2, '=').collect(); if parsed_cmd.len() != 2 { return EPROTO; } let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "remove" => match val.parse::<bool>() { Ok(true) => remove = true, Ok(false) => remove = false, Err(_) => return EINVAL, }, "preshared_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => preshared_key = Some(key_bytes.0), Err(_) => return EINVAL, }, "endpoint" => match val.parse::<SocketAddr>() { Ok(addr) => endpoint = Some(addr), Err(_) => return EINVAL, }, "persistent_keepalive_interval" => match val.parse::<u16>() { Ok(interval) => keepalive = Some(interval), Err(_) => return EINVAL, }, "replace_allowed_ips" => match val.parse::<bool>() { Ok(true) => replace_ips = true, Ok(false) => replace_ips = false, Err(_) => return EINVAL, }, "allowed_ip" => match val.parse::<AllowedIP>() { Ok(ip) => allowed_ips.push(ip), Err(_) => return EINVAL, }, "public_key" => { // Indicates a new peer section. Commit changes for current peer, and continue to next peer d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update match val.parse::<KeyBytes>() { Ok(key_bytes) => public_key = key_bytes.0.into(), Err(_) => return EINVAL, } } "protocol_version" => match val.parse::<u32>() { Ok(1) => {} // Only version 1 is legal _ => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }
register_api_fd
identifier_name
api.rs
// Copyright (c) 2019 Cloudflare, Inc. All rights reserved. // SPDX-License-Identifier: BSD-3-Clause use super::dev_lock::LockReadGuard; use super::drop_privileges::get_saved_ids; use super::{AllowedIP, Device, Error, SocketAddr}; use crate::device::Action; use crate::serialization::KeyBytes; use crate::x25519; use hex::encode as encode_hex; use libc::*; use std::fs::{create_dir, remove_file}; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net::{UnixListener, UnixStream}; use std::sync::atomic::Ordering; const SOCK_DIR: &str = "/var/run/wireguard/"; fn create_sock_dir() { let _ = create_dir(SOCK_DIR); // Create the directory if it does not exist if let Ok((saved_uid, saved_gid)) = get_saved_ids() { unsafe { let c_path = std::ffi::CString::new(SOCK_DIR).unwrap(); // The directory is under the root user, but we want to be able to // delete the files there when we exit, so we need to change the owner chown( c_path.as_bytes_with_nul().as_ptr() as _, saved_uid, saved_gid, ); } } } impl Device { /// Register the api handler for this Device. The api handler receives stream connections on a Unix socket /// with a known path: /var/run/wireguard/{tun_name}.sock. pub fn register_api_handler(&mut self) -> Result<(), Error> { let path = format!("{}/{}.sock", SOCK_DIR, self.iface.name()?); create_sock_dir(); let _ = remove_file(&path); // Attempt to remove the socket if already exists let api_listener = UnixListener::bind(&path).map_err(Error::ApiSocket)?; // Bind a new socket to the path self.cleanup_paths.push(path.clone()); self.queue.new_event( api_listener.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api unix socket let (api_conn, _) = match api_listener.accept() { Ok(conn) => conn, _ => return Action::Continue, }; let mut reader = BufReader::new(&api_conn); let mut writer = BufWriter::new(&api_conn); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } Action::Continue // Indicates the worker thread should continue as normal }), )?; self.register_monitor(path)?; self.register_api_signal_handlers() } pub fn register_api_fd(&mut self, fd: i32) -> Result<(), Error> { let io_file = unsafe { UnixStream::from_raw_fd(fd) }; self.queue.new_event( io_file.as_raw_fd(), Box::new(move |d, _| { // This is the closure that listens on the api file descriptor let mut reader = BufReader::new(&io_file); let mut writer = BufWriter::new(&io_file); let mut cmd = String::new(); if reader.read_line(&mut cmd).is_ok() { cmd.pop(); // pop the new line character let status = match cmd.as_ref() { // Only two commands are legal according to the protocol, get=1 and set=1. "get=1" => api_get(&mut writer, d), "set=1" => api_set(&mut reader, d), _ => EIO, }; // The protocol requires to return an error code as the response, or zero on success writeln!(writer, "errno={}\n", status).ok(); } else { // The remote side is likely closed; we should trigger an exit. d.trigger_exit(); return Action::Exit; } Action::Continue // Indicates the worker thread should continue as normal }), )?; Ok(()) } fn register_monitor(&self, path: String) -> Result<(), Error> { self.queue.new_periodic_event( Box::new(move |d, _| { // This is not a very nice hack to detect if the control socket was removed // and exiting nicely as a result. We check every 3 seconds in a loop if the // file was deleted by stating it. // The problem is that on linux inotify can be used quite beautifully to detect // deletion, and kqueue EVFILT_VNODE can be used for the same purpose, but that // will require introducing new events, for no measurable benefit. // TODO: Could this be an issue if we restart the service too quickly? let path = std::path::Path::new(&path); if !path.exists() { d.trigger_exit(); return Action::Exit; } // Periodically read the mtu of the interface in case it changes if let Ok(mtu) = d.iface.mtu() { d.mtu.store(mtu, Ordering::Relaxed); } Action::Continue }), std::time::Duration::from_millis(1000), )?; Ok(()) } fn register_api_signal_handlers(&self) -> Result<(), Error> { self.queue .new_signal_event(SIGINT, Box::new(move |_, _| Action::Exit))?; self.queue .new_signal_event(SIGTERM, Box::new(move |_, _| Action::Exit))?; Ok(()) } } #[allow(unused_must_use)] fn api_get(writer: &mut BufWriter<&UnixStream>, d: &Device) -> i32 { // get command requires an empty line, but there is no reason to be religious about it if let Some(ref k) = d.key_pair { writeln!(writer, "own_public_key={}", encode_hex(k.1.as_bytes())); } if d.listen_port != 0 { writeln!(writer, "listen_port={}", d.listen_port); } if let Some(fwmark) = d.fwmark { writeln!(writer, "fwmark={}", fwmark); } for (k, p) in d.peers.iter() { let p = p.lock(); writeln!(writer, "public_key={}", encode_hex(k.as_bytes())); if let Some(ref key) = p.preshared_key() { writeln!(writer, "preshared_key={}", encode_hex(key)); } if let Some(keepalive) = p.persistent_keepalive() { writeln!(writer, "persistent_keepalive_interval={}", keepalive); } if let Some(ref addr) = p.endpoint().addr { writeln!(writer, "endpoint={}", addr); } for (ip, cidr) in p.allowed_ips() { writeln!(writer, "allowed_ip={}/{}", ip, cidr); } if let Some(time) = p.time_since_last_handshake() { writeln!(writer, "last_handshake_time_sec={}", time.as_secs()); writeln!(writer, "last_handshake_time_nsec={}", time.subsec_nanos()); } let (_, tx_bytes, rx_bytes, ..) = p.tunnel.stats(); writeln!(writer, "rx_bytes={}", rx_bytes); writeln!(writer, "tx_bytes={}", tx_bytes); } 0 } fn api_set(reader: &mut BufReader<&UnixStream>, d: &mut LockReadGuard<Device>) -> i32 { d.try_writeable( |device| device.trigger_yield(), |device| { device.cancel_yield(); let mut cmd = String::new(); while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.split('=').collect(); if parsed_cmd.len() != 2 { return EPROTO; } let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "private_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => { device.set_key(x25519::StaticSecret::from(key_bytes.0)) } Err(_) => return EINVAL, }, "listen_port" => match val.parse::<u16>() { Ok(port) => match device.open_listen_socket(port) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, #[cfg(any( target_os = "android", target_os = "fuchsia", target_os = "linux" ))] "fwmark" => match val.parse::<u32>() { Ok(mark) => match device.set_fwmark(mark) { Ok(()) => {} Err(_) => return EADDRINUSE, }, Err(_) => return EINVAL, }, "replace_peers" => match val.parse::<bool>() { Ok(true) => device.clear_peers(), Ok(false) => {} Err(_) => return EINVAL, }, "public_key" => match val.parse::<KeyBytes>() { // Indicates a new peer section Ok(key_bytes) => { return api_set_peer( reader, device, x25519::PublicKey::from(key_bytes.0), ) } Err(_) => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }, ) .unwrap_or(EIO) } fn api_set_peer( reader: &mut BufReader<&UnixStream>, d: &mut Device, pub_key: x25519::PublicKey, ) -> i32 { let mut cmd = String::new(); let mut remove = false; let mut replace_ips = false; let mut endpoint = None; let mut keepalive = None; let mut public_key = pub_key; let mut preshared_key = None; let mut allowed_ips: Vec<AllowedIP> = vec![]; while reader.read_line(&mut cmd).is_ok() { cmd.pop(); // remove newline if any if cmd.is_empty() { d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update return 0; // Done } { let parsed_cmd: Vec<&str> = cmd.splitn(2, '=').collect(); if parsed_cmd.len() != 2
let (key, val) = (parsed_cmd[0], parsed_cmd[1]); match key { "remove" => match val.parse::<bool>() { Ok(true) => remove = true, Ok(false) => remove = false, Err(_) => return EINVAL, }, "preshared_key" => match val.parse::<KeyBytes>() { Ok(key_bytes) => preshared_key = Some(key_bytes.0), Err(_) => return EINVAL, }, "endpoint" => match val.parse::<SocketAddr>() { Ok(addr) => endpoint = Some(addr), Err(_) => return EINVAL, }, "persistent_keepalive_interval" => match val.parse::<u16>() { Ok(interval) => keepalive = Some(interval), Err(_) => return EINVAL, }, "replace_allowed_ips" => match val.parse::<bool>() { Ok(true) => replace_ips = true, Ok(false) => replace_ips = false, Err(_) => return EINVAL, }, "allowed_ip" => match val.parse::<AllowedIP>() { Ok(ip) => allowed_ips.push(ip), Err(_) => return EINVAL, }, "public_key" => { // Indicates a new peer section. Commit changes for current peer, and continue to next peer d.update_peer( public_key, remove, replace_ips, endpoint, allowed_ips.as_slice(), keepalive, preshared_key, ); allowed_ips.clear(); //clear the vector content after update match val.parse::<KeyBytes>() { Ok(key_bytes) => public_key = key_bytes.0.into(), Err(_) => return EINVAL, } } "protocol_version" => match val.parse::<u32>() { Ok(1) => {} // Only version 1 is legal _ => return EINVAL, }, _ => return EINVAL, } } cmd.clear(); } 0 }
{ return EPROTO; }
conditional_block
switch.go
package output import ( "context" "errors" "fmt" "sync" "time" "github.com/Jeffail/benthos/v3/internal/batch" "github.com/Jeffail/benthos/v3/internal/bloblang/mapping" "github.com/Jeffail/benthos/v3/internal/component/output" "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/internal/interop" imessage "github.com/Jeffail/benthos/v3/internal/message" "github.com/Jeffail/benthos/v3/internal/shutdown" "github.com/Jeffail/benthos/v3/lib/condition" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/message" "github.com/Jeffail/benthos/v3/lib/metrics" "github.com/Jeffail/benthos/v3/lib/response" "github.com/Jeffail/benthos/v3/lib/types" "github.com/Jeffail/benthos/v3/lib/util/throttle" "github.com/Jeffail/gabs/v2" "golang.org/x/sync/errgroup" ) //------------------------------------------------------------------------------ var ( // ErrSwitchNoConditionMet is returned when a message does not match any // output conditions. ErrSwitchNoConditionMet = errors.New("no switch output conditions were met by message") // ErrSwitchNoCasesMatched is returned when a message does not match any // output cases. ErrSwitchNoCasesMatched = errors.New("no switch cases were matched by message") // ErrSwitchNoOutputs is returned when creating a Switch type with less than // 2 outputs. ErrSwitchNoOutputs = errors.New("attempting to create switch with fewer than 2 cases") ) //------------------------------------------------------------------------------ func
() { Constructors[TypeSwitch] = TypeSpec{ constructor: fromSimpleConstructor(NewSwitch), Summary: ` The switch output type allows you to route messages to different outputs based on their contents.`, Description: ` Messages must successfully route to one or more outputs, otherwise this is considered an error and the message is reprocessed. In order to explicitly drop messages that do not match your cases add one final case with a [drop output](/docs/components/outputs/drop).`, config: docs.FieldComponent().WithChildren( docs.FieldCommon( "retry_until_success", ` If a selected output fails to send a message this field determines whether it is reattempted indefinitely. If set to false the error is instead propagated back to the input level. If a message can be routed to >1 outputs it is usually best to set this to true in order to avoid duplicate messages being routed to an output.`, ), docs.FieldAdvanced( "strict_mode", ` This field determines whether an error should be reported if no condition is met. If set to true, an error is propagated back to the input level. The default behavior is false, which will drop the message.`, ), docs.FieldAdvanced( "max_in_flight", "The maximum number of parallel message batches to have in flight at any given time. Note that if a child output has a higher `max_in_flight` then the switch output will automatically match it, therefore this value is the minimum `max_in_flight` to set in cases where the child values can't be inferred (such as when using resource outputs as children).", ), docs.FieldCommon( "cases", "A list of switch cases, outlining outputs that can be routed to.", []interface{}{ map[string]interface{}{ "check": `this.urls.contains("http://benthos.dev")`, "output": map[string]interface{}{ "cache": map[string]interface{}{ "target": "foo", "key": "${!json(\"id\")}", }, }, "continue": true, }, map[string]interface{}{ "output": map[string]interface{}{ "s3": map[string]interface{}{ "bucket": "bar", "path": "${!json(\"id\")}", }, }, }, }, ).Array().WithChildren( docs.FieldBloblang( "check", "A [Bloblang query](/docs/guides/bloblang/about/) that should return a boolean value indicating whether a message should be routed to the case output. If left empty the case always passes.", `this.type == "foo"`, `this.contents.urls.contains("https://benthos.dev/")`, ).HasDefault(""), docs.FieldCommon( "output", "An [output](/docs/components/outputs/about/) for messages that pass the check to be routed to.", ).HasDefault(map[string]interface{}{}).HasType(docs.FieldTypeOutput), docs.FieldAdvanced( "continue", "Indicates whether, if this case passes for a message, the next case should also be tested.", ).HasDefault(false).HasType(docs.FieldTypeBool), ), docs.FieldDeprecated("outputs").Array().WithChildren( docs.FieldDeprecated("condition").HasType(docs.FieldTypeCondition), docs.FieldDeprecated("fallthrough"), docs.FieldDeprecated("output").HasType(docs.FieldTypeOutput), ).OmitWhen(func(v, _ interface{}) (string, bool) { arr, ok := v.([]interface{}) return "field outputs is deprecated in favour of cases", ok && len(arr) == 0 }), ).Linter(func(ctx docs.LintContext, line, col int, value interface{}) []docs.Lint { if _, ok := value.(map[string]interface{}); !ok { return nil } gObj := gabs.Wrap(value) retry, exists := gObj.S("retry_until_success").Data().(bool) // TODO: V4 Is retry_until_success going to be false by default now? if exists && !retry { return nil } for _, cObj := range gObj.S("cases").Children() { typeStr, _ := cObj.S("output", "type").Data().(string) isReject := cObj.Exists("output", "reject") if typeStr == "reject" || isReject { return []docs.Lint{ docs.NewLintError(line, "a `switch` output with a `reject` case output must have the field `switch.retry_until_success` set to `false` (defaults to `true`), otherwise the `reject` child output will result in infinite retries"), } } } return nil }), Categories: []Category{ CategoryUtility, }, Examples: []docs.AnnotatedExample{ { Title: "Basic Multiplexing", Summary: ` The most common use for a switch output is to multiplex messages across a range of output destinations. The following config checks the contents of the field ` + "`type` of messages and sends `foo` type messages to an `amqp_1` output, `bar` type messages to a `gcp_pubsub` output, and everything else to a `redis_streams` output" + `. Outputs can have their own processors associated with them, and in this example the ` + "`redis_streams`" + ` output has a processor that enforces the presence of a type field before sending it.`, Config: ` output: switch: cases: - check: this.type == "foo" output: amqp_1: url: amqps://guest:guest@localhost:5672/ target_address: queue:/the_foos - check: this.type == "bar" output: gcp_pubsub: project: dealing_with_mike topic: mikes_bars - output: redis_streams: url: tcp://localhost:6379 stream: everything_else processors: - bloblang: | root = this root.type = this.type | "unknown" `, }, { Title: "Control Flow", Summary: ` The ` + "`continue`" + ` field allows messages that have passed a case to be tested against the next one also. This can be useful when combining non-mutually-exclusive case checks. In the following example a message that passes both the check of the first case as well as the second will be routed to both.`, Config: ` output: switch: cases: - check: 'this.user.interests.contains("walks").catch(false)' output: amqp_1: url: amqps://guest:guest@localhost:5672/ target_address: queue:/people_what_think_good continue: true - check: 'this.user.dislikes.contains("videogames").catch(false)' output: gcp_pubsub: project: people topic: that_i_dont_want_to_hang_with `, }, }, } } //------------------------------------------------------------------------------ // SwitchConfig contains configuration fields for the Switch output type. type SwitchConfig struct { RetryUntilSuccess bool `json:"retry_until_success" yaml:"retry_until_success"` StrictMode bool `json:"strict_mode" yaml:"strict_mode"` MaxInFlight int `json:"max_in_flight" yaml:"max_in_flight"` Cases []SwitchConfigCase `json:"cases" yaml:"cases"` Outputs []SwitchConfigOutput `json:"outputs" yaml:"outputs"` } // NewSwitchConfig creates a new SwitchConfig with default values. func NewSwitchConfig() SwitchConfig { return SwitchConfig{ RetryUntilSuccess: true, // TODO: V4 consider making this true by default. StrictMode: false, MaxInFlight: 1, Cases: []SwitchConfigCase{}, Outputs: []SwitchConfigOutput{}, } } // SwitchConfigCase contains configuration fields per output of a switch type. type SwitchConfigCase struct { Check string `json:"check" yaml:"check"` Continue bool `json:"continue" yaml:"continue"` Output Config `json:"output" yaml:"output"` } // NewSwitchConfigCase creates a new switch output config with default values. func NewSwitchConfigCase() SwitchConfigCase { return SwitchConfigCase{ Check: "", Continue: false, Output: NewConfig(), } } //------------------------------------------------------------------------------ // Switch is a broker that implements types.Consumer and broadcasts each message // out to an array of outputs. type Switch struct { logger log.Modular stats metrics.Type mMsgRcvd metrics.StatCounter mMsgSnt metrics.StatCounter mOutputErr metrics.StatCounter maxInFlight int transactions <-chan types.Transaction retryUntilSuccess bool strictMode bool outputTSChans []chan types.Transaction outputs []types.Output checks []*mapping.Executor conditions []types.Condition continues []bool fallthroughs []bool ctx context.Context close func() closedChan chan struct{} } // NewSwitch creates a new Switch type by providing outputs. Messages will be // sent to a subset of outputs according to condition and fallthrough settings. func NewSwitch( conf Config, mgr types.Manager, logger log.Modular, stats metrics.Type, ) (Type, error) { ctx, done := context.WithCancel(context.Background()) o := &Switch{ stats: stats, logger: logger, maxInFlight: conf.Switch.MaxInFlight, transactions: nil, retryUntilSuccess: conf.Switch.RetryUntilSuccess, strictMode: conf.Switch.StrictMode, closedChan: make(chan struct{}), ctx: ctx, close: done, mMsgRcvd: stats.GetCounter("switch.messages.received"), mMsgSnt: stats.GetCounter("switch.messages.sent"), mOutputErr: stats.GetCounter("switch.output.error"), } lCases := len(conf.Switch.Cases) lOutputs := len(conf.Switch.Outputs) if lCases < 2 && lOutputs < 2 { return nil, ErrSwitchNoOutputs } if lCases > 0 { if lOutputs > 0 { return nil, errors.New("combining switch cases with deprecated outputs is not supported") } o.outputs = make([]types.Output, lCases) o.checks = make([]*mapping.Executor, lCases) o.continues = make([]bool, lCases) o.fallthroughs = make([]bool, lCases) } else { o.outputs = make([]types.Output, lOutputs) o.conditions = make([]types.Condition, lOutputs) o.fallthroughs = make([]bool, lOutputs) } var err error for i, oConf := range conf.Switch.Outputs { ns := fmt.Sprintf("switch.%v", i) oMgr, oLog, oStats := interop.LabelChild(ns+".output", mgr, logger, stats) oStats = metrics.Combine(stats, oStats) if o.outputs[i], err = New(oConf.Output, oMgr, oLog, oStats); err != nil { return nil, fmt.Errorf("failed to create output '%v' type '%v': %v", i, oConf.Output.Type, err) } cMgr, cLog, cStats := interop.LabelChild(ns+".condition", mgr, logger, stats) if o.conditions[i], err = condition.New(oConf.Condition, cMgr, cLog, cStats); err != nil { return nil, fmt.Errorf("failed to create output '%v' condition '%v': %v", i, oConf.Condition.Type, err) } o.fallthroughs[i] = oConf.Fallthrough } for i, cConf := range conf.Switch.Cases { oMgr, oLog, oStats := interop.LabelChild(fmt.Sprintf("switch.%v.output", i), mgr, logger, stats) oStats = metrics.Combine(stats, oStats) if o.outputs[i], err = New(cConf.Output, oMgr, oLog, oStats); err != nil { return nil, fmt.Errorf("failed to create case '%v' output type '%v': %v", i, cConf.Output.Type, err) } if len(cConf.Check) > 0 { if o.checks[i], err = interop.NewBloblangMapping(mgr, cConf.Check); err != nil { return nil, fmt.Errorf("failed to parse case '%v' check mapping: %v", i, err) } } o.continues[i] = cConf.Continue } o.outputTSChans = make([]chan types.Transaction, len(o.outputs)) for i := range o.outputTSChans { if mif, ok := output.GetMaxInFlight(o.outputs[i]); ok && mif > o.maxInFlight { o.maxInFlight = mif } o.outputTSChans[i] = make(chan types.Transaction) if err := o.outputs[i].Consume(o.outputTSChans[i]); err != nil { return nil, err } } return o, nil } //------------------------------------------------------------------------------ // Consume assigns a new transactions channel for the broker to read. func (o *Switch) Consume(transactions <-chan types.Transaction) error { if o.transactions != nil { return types.ErrAlreadyStarted } o.transactions = transactions if len(o.conditions) > 0 { o.logger.Warnf("Using deprecated field `outputs` which will be removed in the next major release of Benthos. For more information check out the docs at https://www.benthos.dev/docs/components/outputs/switch.") go o.loopDeprecated() } else { go o.loop() } return nil } // MaxInFlight returns the maximum number of in flight messages permitted by the // output. This value can be used to determine a sensible value for parent // outputs, but should not be relied upon as part of dispatcher logic. func (o *Switch) MaxInFlight() (int, bool) { return o.maxInFlight, true } // Connected returns a boolean indicating whether this output is currently // connected to its target. func (o *Switch) Connected() bool { for _, out := range o.outputs { if !out.Connected() { return false } } return true } //------------------------------------------------------------------------------ func (o *Switch) dispatchRetryOnErr(outputTargets [][]types.Part) error { var owg errgroup.Group for target, parts := range outputTargets { if len(parts) == 0 { continue } msgCopy, i := message.New(nil), target msgCopy.SetAll(parts) owg.Go(func() error { throt := throttle.New(throttle.OptCloseChan(o.ctx.Done())) resChan := make(chan types.Response) // Try until success or shutdown. for { select { case o.outputTSChans[i] <- types.NewTransaction(msgCopy, resChan): case <-o.ctx.Done(): return types.ErrTypeClosed } select { case res := <-resChan: if res.Error() != nil { o.logger.Errorf("Failed to dispatch switch message: %v\n", res.Error()) o.mOutputErr.Incr(1) if !throt.Retry() { return types.ErrTypeClosed } } else { o.mMsgSnt.Incr(1) return nil } case <-o.ctx.Done(): return types.ErrTypeClosed } } }) } return owg.Wait() } func (o *Switch) dispatchNoRetries(group *imessage.SortGroup, sourceMessage types.Message, outputTargets [][]types.Part) error { var wg sync.WaitGroup var setErr func(error) var setErrForPart func(types.Part, error) var getErr func() error { var generalErr error var batchErr *batch.Error var errLock sync.Mutex setErr = func(err error) { if err == nil { return } errLock.Lock() generalErr = err errLock.Unlock() } setErrForPart = func(part types.Part, err error) { if err == nil { return } errLock.Lock() defer errLock.Unlock() index := group.GetIndex(part) if index == -1 { generalErr = err return } if batchErr == nil { batchErr = batch.NewError(sourceMessage, err) } batchErr.Failed(index, err) } getErr = func() error { if batchErr != nil { return batchErr } return generalErr } } for target, parts := range outputTargets { if len(parts) == 0 { continue } wg.Add(1) msgCopy, i := message.New(nil), target msgCopy.SetAll(parts) go func() { defer wg.Done() resChan := make(chan types.Response) select { case o.outputTSChans[i] <- types.NewTransaction(msgCopy, resChan): case <-o.ctx.Done(): setErr(types.ErrTypeClosed) return } select { case res := <-resChan: if res.Error() != nil { o.mOutputErr.Incr(1) if bErr, ok := res.Error().(*batch.Error); ok { bErr.WalkParts(func(i int, p types.Part, e error) bool { if e != nil { setErrForPart(p, e) } return true }) } else { msgCopy.Iter(func(i int, p types.Part) error { setErrForPart(p, res.Error()) return nil }) } } else { o.mMsgSnt.Incr(1) } case <-o.ctx.Done(): setErr(types.ErrTypeClosed) } }() } wg.Wait() return getErr() } // loop is an internal loop that brokers incoming messages to many outputs. func (o *Switch) loop() { var wg sync.WaitGroup defer func() { wg.Wait() for i, output := range o.outputs { output.CloseAsync() close(o.outputTSChans[i]) } for _, output := range o.outputs { _ = output.WaitForClose(shutdown.MaximumShutdownWait()) } close(o.closedChan) }() sendLoop := func() { defer wg.Done() for { var ts types.Transaction var open bool select { case ts, open = <-o.transactions: if !open { return } case <-o.ctx.Done(): return } o.mMsgRcvd.Incr(1) group, trackedMsg := imessage.NewSortGroup(ts.Payload) outputTargets := make([][]types.Part, len(o.checks)) if checksErr := trackedMsg.Iter(func(i int, p types.Part) error { routedAtLeastOnce := false for j, exe := range o.checks { test := true if exe != nil { var err error if test, err = exe.QueryPart(i, trackedMsg); err != nil { test = false o.logger.Errorf("Failed to test case %v: %v\n", j, err) } } if test { routedAtLeastOnce = true outputTargets[j] = append(outputTargets[j], p.Copy()) if !o.continues[j] { return nil } } } if !routedAtLeastOnce && o.strictMode { return ErrSwitchNoConditionMet } return nil }); checksErr != nil { select { case ts.ResponseChan <- response.NewError(checksErr): case <-o.ctx.Done(): return } continue } var resErr error if o.retryUntilSuccess { resErr = o.dispatchRetryOnErr(outputTargets) } else { resErr = o.dispatchNoRetries(group, trackedMsg, outputTargets) } var oResponse types.Response = response.NewAck() if resErr != nil { oResponse = response.NewError(resErr) } select { case ts.ResponseChan <- oResponse: case <-o.ctx.Done(): return } } } // Max in flight for i := 0; i < o.maxInFlight; i++ { wg.Add(1) go sendLoop() } } // CloseAsync shuts down the Switch broker and stops processing requests. func (o *Switch) CloseAsync() { o.close() } // WaitForClose blocks until the Switch broker has closed down. func (o *Switch) WaitForClose(timeout time.Duration) error { select { case <-o.closedChan: case <-time.After(timeout): return types.ErrTimeout } return nil } //------------------------------------------------------------------------------
init
identifier_name
switch.go
package output import ( "context" "errors" "fmt" "sync" "time" "github.com/Jeffail/benthos/v3/internal/batch" "github.com/Jeffail/benthos/v3/internal/bloblang/mapping" "github.com/Jeffail/benthos/v3/internal/component/output" "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/internal/interop" imessage "github.com/Jeffail/benthos/v3/internal/message" "github.com/Jeffail/benthos/v3/internal/shutdown" "github.com/Jeffail/benthos/v3/lib/condition" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/message" "github.com/Jeffail/benthos/v3/lib/metrics" "github.com/Jeffail/benthos/v3/lib/response" "github.com/Jeffail/benthos/v3/lib/types" "github.com/Jeffail/benthos/v3/lib/util/throttle" "github.com/Jeffail/gabs/v2" "golang.org/x/sync/errgroup" ) //------------------------------------------------------------------------------ var ( // ErrSwitchNoConditionMet is returned when a message does not match any // output conditions. ErrSwitchNoConditionMet = errors.New("no switch output conditions were met by message") // ErrSwitchNoCasesMatched is returned when a message does not match any // output cases. ErrSwitchNoCasesMatched = errors.New("no switch cases were matched by message") // ErrSwitchNoOutputs is returned when creating a Switch type with less than // 2 outputs. ErrSwitchNoOutputs = errors.New("attempting to create switch with fewer than 2 cases") ) //------------------------------------------------------------------------------ func init()
//------------------------------------------------------------------------------ // SwitchConfig contains configuration fields for the Switch output type. type SwitchConfig struct { RetryUntilSuccess bool `json:"retry_until_success" yaml:"retry_until_success"` StrictMode bool `json:"strict_mode" yaml:"strict_mode"` MaxInFlight int `json:"max_in_flight" yaml:"max_in_flight"` Cases []SwitchConfigCase `json:"cases" yaml:"cases"` Outputs []SwitchConfigOutput `json:"outputs" yaml:"outputs"` } // NewSwitchConfig creates a new SwitchConfig with default values. func NewSwitchConfig() SwitchConfig { return SwitchConfig{ RetryUntilSuccess: true, // TODO: V4 consider making this true by default. StrictMode: false, MaxInFlight: 1, Cases: []SwitchConfigCase{}, Outputs: []SwitchConfigOutput{}, } } // SwitchConfigCase contains configuration fields per output of a switch type. type SwitchConfigCase struct { Check string `json:"check" yaml:"check"` Continue bool `json:"continue" yaml:"continue"` Output Config `json:"output" yaml:"output"` } // NewSwitchConfigCase creates a new switch output config with default values. func NewSwitchConfigCase() SwitchConfigCase { return SwitchConfigCase{ Check: "", Continue: false, Output: NewConfig(), } } //------------------------------------------------------------------------------ // Switch is a broker that implements types.Consumer and broadcasts each message // out to an array of outputs. type Switch struct { logger log.Modular stats metrics.Type mMsgRcvd metrics.StatCounter mMsgSnt metrics.StatCounter mOutputErr metrics.StatCounter maxInFlight int transactions <-chan types.Transaction retryUntilSuccess bool strictMode bool outputTSChans []chan types.Transaction outputs []types.Output checks []*mapping.Executor conditions []types.Condition continues []bool fallthroughs []bool ctx context.Context close func() closedChan chan struct{} } // NewSwitch creates a new Switch type by providing outputs. Messages will be // sent to a subset of outputs according to condition and fallthrough settings. func NewSwitch( conf Config, mgr types.Manager, logger log.Modular, stats metrics.Type, ) (Type, error) { ctx, done := context.WithCancel(context.Background()) o := &Switch{ stats: stats, logger: logger, maxInFlight: conf.Switch.MaxInFlight, transactions: nil, retryUntilSuccess: conf.Switch.RetryUntilSuccess, strictMode: conf.Switch.StrictMode, closedChan: make(chan struct{}), ctx: ctx, close: done, mMsgRcvd: stats.GetCounter("switch.messages.received"), mMsgSnt: stats.GetCounter("switch.messages.sent"), mOutputErr: stats.GetCounter("switch.output.error"), } lCases := len(conf.Switch.Cases) lOutputs := len(conf.Switch.Outputs) if lCases < 2 && lOutputs < 2 { return nil, ErrSwitchNoOutputs } if lCases > 0 { if lOutputs > 0 { return nil, errors.New("combining switch cases with deprecated outputs is not supported") } o.outputs = make([]types.Output, lCases) o.checks = make([]*mapping.Executor, lCases) o.continues = make([]bool, lCases) o.fallthroughs = make([]bool, lCases) } else { o.outputs = make([]types.Output, lOutputs) o.conditions = make([]types.Condition, lOutputs) o.fallthroughs = make([]bool, lOutputs) } var err error for i, oConf := range conf.Switch.Outputs { ns := fmt.Sprintf("switch.%v", i) oMgr, oLog, oStats := interop.LabelChild(ns+".output", mgr, logger, stats) oStats = metrics.Combine(stats, oStats) if o.outputs[i], err = New(oConf.Output, oMgr, oLog, oStats); err != nil { return nil, fmt.Errorf("failed to create output '%v' type '%v': %v", i, oConf.Output.Type, err) } cMgr, cLog, cStats := interop.LabelChild(ns+".condition", mgr, logger, stats) if o.conditions[i], err = condition.New(oConf.Condition, cMgr, cLog, cStats); err != nil { return nil, fmt.Errorf("failed to create output '%v' condition '%v': %v", i, oConf.Condition.Type, err) } o.fallthroughs[i] = oConf.Fallthrough } for i, cConf := range conf.Switch.Cases { oMgr, oLog, oStats := interop.LabelChild(fmt.Sprintf("switch.%v.output", i), mgr, logger, stats) oStats = metrics.Combine(stats, oStats) if o.outputs[i], err = New(cConf.Output, oMgr, oLog, oStats); err != nil { return nil, fmt.Errorf("failed to create case '%v' output type '%v': %v", i, cConf.Output.Type, err) } if len(cConf.Check) > 0 { if o.checks[i], err = interop.NewBloblangMapping(mgr, cConf.Check); err != nil { return nil, fmt.Errorf("failed to parse case '%v' check mapping: %v", i, err) } } o.continues[i] = cConf.Continue } o.outputTSChans = make([]chan types.Transaction, len(o.outputs)) for i := range o.outputTSChans { if mif, ok := output.GetMaxInFlight(o.outputs[i]); ok && mif > o.maxInFlight { o.maxInFlight = mif } o.outputTSChans[i] = make(chan types.Transaction) if err := o.outputs[i].Consume(o.outputTSChans[i]); err != nil { return nil, err } } return o, nil } //------------------------------------------------------------------------------ // Consume assigns a new transactions channel for the broker to read. func (o *Switch) Consume(transactions <-chan types.Transaction) error { if o.transactions != nil { return types.ErrAlreadyStarted } o.transactions = transactions if len(o.conditions) > 0 { o.logger.Warnf("Using deprecated field `outputs` which will be removed in the next major release of Benthos. For more information check out the docs at https://www.benthos.dev/docs/components/outputs/switch.") go o.loopDeprecated() } else { go o.loop() } return nil } // MaxInFlight returns the maximum number of in flight messages permitted by the // output. This value can be used to determine a sensible value for parent // outputs, but should not be relied upon as part of dispatcher logic. func (o *Switch) MaxInFlight() (int, bool) { return o.maxInFlight, true } // Connected returns a boolean indicating whether this output is currently // connected to its target. func (o *Switch) Connected() bool { for _, out := range o.outputs { if !out.Connected() { return false } } return true } //------------------------------------------------------------------------------ func (o *Switch) dispatchRetryOnErr(outputTargets [][]types.Part) error { var owg errgroup.Group for target, parts := range outputTargets { if len(parts) == 0 { continue } msgCopy, i := message.New(nil), target msgCopy.SetAll(parts) owg.Go(func() error { throt := throttle.New(throttle.OptCloseChan(o.ctx.Done())) resChan := make(chan types.Response) // Try until success or shutdown. for { select { case o.outputTSChans[i] <- types.NewTransaction(msgCopy, resChan): case <-o.ctx.Done(): return types.ErrTypeClosed } select { case res := <-resChan: if res.Error() != nil { o.logger.Errorf("Failed to dispatch switch message: %v\n", res.Error()) o.mOutputErr.Incr(1) if !throt.Retry() { return types.ErrTypeClosed } } else { o.mMsgSnt.Incr(1) return nil } case <-o.ctx.Done(): return types.ErrTypeClosed } } }) } return owg.Wait() } func (o *Switch) dispatchNoRetries(group *imessage.SortGroup, sourceMessage types.Message, outputTargets [][]types.Part) error { var wg sync.WaitGroup var setErr func(error) var setErrForPart func(types.Part, error) var getErr func() error { var generalErr error var batchErr *batch.Error var errLock sync.Mutex setErr = func(err error) { if err == nil { return } errLock.Lock() generalErr = err errLock.Unlock() } setErrForPart = func(part types.Part, err error) { if err == nil { return } errLock.Lock() defer errLock.Unlock() index := group.GetIndex(part) if index == -1 { generalErr = err return } if batchErr == nil { batchErr = batch.NewError(sourceMessage, err) } batchErr.Failed(index, err) } getErr = func() error { if batchErr != nil { return batchErr } return generalErr } } for target, parts := range outputTargets { if len(parts) == 0 { continue } wg.Add(1) msgCopy, i := message.New(nil), target msgCopy.SetAll(parts) go func() { defer wg.Done() resChan := make(chan types.Response) select { case o.outputTSChans[i] <- types.NewTransaction(msgCopy, resChan): case <-o.ctx.Done(): setErr(types.ErrTypeClosed) return } select { case res := <-resChan: if res.Error() != nil { o.mOutputErr.Incr(1) if bErr, ok := res.Error().(*batch.Error); ok { bErr.WalkParts(func(i int, p types.Part, e error) bool { if e != nil { setErrForPart(p, e) } return true }) } else { msgCopy.Iter(func(i int, p types.Part) error { setErrForPart(p, res.Error()) return nil }) } } else { o.mMsgSnt.Incr(1) } case <-o.ctx.Done(): setErr(types.ErrTypeClosed) } }() } wg.Wait() return getErr() } // loop is an internal loop that brokers incoming messages to many outputs. func (o *Switch) loop() { var wg sync.WaitGroup defer func() { wg.Wait() for i, output := range o.outputs { output.CloseAsync() close(o.outputTSChans[i]) } for _, output := range o.outputs { _ = output.WaitForClose(shutdown.MaximumShutdownWait()) } close(o.closedChan) }() sendLoop := func() { defer wg.Done() for { var ts types.Transaction var open bool select { case ts, open = <-o.transactions: if !open { return } case <-o.ctx.Done(): return } o.mMsgRcvd.Incr(1) group, trackedMsg := imessage.NewSortGroup(ts.Payload) outputTargets := make([][]types.Part, len(o.checks)) if checksErr := trackedMsg.Iter(func(i int, p types.Part) error { routedAtLeastOnce := false for j, exe := range o.checks { test := true if exe != nil { var err error if test, err = exe.QueryPart(i, trackedMsg); err != nil { test = false o.logger.Errorf("Failed to test case %v: %v\n", j, err) } } if test { routedAtLeastOnce = true outputTargets[j] = append(outputTargets[j], p.Copy()) if !o.continues[j] { return nil } } } if !routedAtLeastOnce && o.strictMode { return ErrSwitchNoConditionMet } return nil }); checksErr != nil { select { case ts.ResponseChan <- response.NewError(checksErr): case <-o.ctx.Done(): return } continue } var resErr error if o.retryUntilSuccess { resErr = o.dispatchRetryOnErr(outputTargets) } else { resErr = o.dispatchNoRetries(group, trackedMsg, outputTargets) } var oResponse types.Response = response.NewAck() if resErr != nil { oResponse = response.NewError(resErr) } select { case ts.ResponseChan <- oResponse: case <-o.ctx.Done(): return } } } // Max in flight for i := 0; i < o.maxInFlight; i++ { wg.Add(1) go sendLoop() } } // CloseAsync shuts down the Switch broker and stops processing requests. func (o *Switch) CloseAsync() { o.close() } // WaitForClose blocks until the Switch broker has closed down. func (o *Switch) WaitForClose(timeout time.Duration) error { select { case <-o.closedChan: case <-time.After(timeout): return types.ErrTimeout } return nil } //------------------------------------------------------------------------------
{ Constructors[TypeSwitch] = TypeSpec{ constructor: fromSimpleConstructor(NewSwitch), Summary: ` The switch output type allows you to route messages to different outputs based on their contents.`, Description: ` Messages must successfully route to one or more outputs, otherwise this is considered an error and the message is reprocessed. In order to explicitly drop messages that do not match your cases add one final case with a [drop output](/docs/components/outputs/drop).`, config: docs.FieldComponent().WithChildren( docs.FieldCommon( "retry_until_success", ` If a selected output fails to send a message this field determines whether it is reattempted indefinitely. If set to false the error is instead propagated back to the input level. If a message can be routed to >1 outputs it is usually best to set this to true in order to avoid duplicate messages being routed to an output.`, ), docs.FieldAdvanced( "strict_mode", ` This field determines whether an error should be reported if no condition is met. If set to true, an error is propagated back to the input level. The default behavior is false, which will drop the message.`, ), docs.FieldAdvanced( "max_in_flight", "The maximum number of parallel message batches to have in flight at any given time. Note that if a child output has a higher `max_in_flight` then the switch output will automatically match it, therefore this value is the minimum `max_in_flight` to set in cases where the child values can't be inferred (such as when using resource outputs as children).", ), docs.FieldCommon( "cases", "A list of switch cases, outlining outputs that can be routed to.", []interface{}{ map[string]interface{}{ "check": `this.urls.contains("http://benthos.dev")`, "output": map[string]interface{}{ "cache": map[string]interface{}{ "target": "foo", "key": "${!json(\"id\")}", }, }, "continue": true, }, map[string]interface{}{ "output": map[string]interface{}{ "s3": map[string]interface{}{ "bucket": "bar", "path": "${!json(\"id\")}", }, }, }, }, ).Array().WithChildren( docs.FieldBloblang( "check", "A [Bloblang query](/docs/guides/bloblang/about/) that should return a boolean value indicating whether a message should be routed to the case output. If left empty the case always passes.", `this.type == "foo"`, `this.contents.urls.contains("https://benthos.dev/")`, ).HasDefault(""), docs.FieldCommon( "output", "An [output](/docs/components/outputs/about/) for messages that pass the check to be routed to.", ).HasDefault(map[string]interface{}{}).HasType(docs.FieldTypeOutput), docs.FieldAdvanced( "continue", "Indicates whether, if this case passes for a message, the next case should also be tested.", ).HasDefault(false).HasType(docs.FieldTypeBool), ), docs.FieldDeprecated("outputs").Array().WithChildren( docs.FieldDeprecated("condition").HasType(docs.FieldTypeCondition), docs.FieldDeprecated("fallthrough"), docs.FieldDeprecated("output").HasType(docs.FieldTypeOutput), ).OmitWhen(func(v, _ interface{}) (string, bool) { arr, ok := v.([]interface{}) return "field outputs is deprecated in favour of cases", ok && len(arr) == 0 }), ).Linter(func(ctx docs.LintContext, line, col int, value interface{}) []docs.Lint { if _, ok := value.(map[string]interface{}); !ok { return nil } gObj := gabs.Wrap(value) retry, exists := gObj.S("retry_until_success").Data().(bool) // TODO: V4 Is retry_until_success going to be false by default now? if exists && !retry { return nil } for _, cObj := range gObj.S("cases").Children() { typeStr, _ := cObj.S("output", "type").Data().(string) isReject := cObj.Exists("output", "reject") if typeStr == "reject" || isReject { return []docs.Lint{ docs.NewLintError(line, "a `switch` output with a `reject` case output must have the field `switch.retry_until_success` set to `false` (defaults to `true`), otherwise the `reject` child output will result in infinite retries"), } } } return nil }), Categories: []Category{ CategoryUtility, }, Examples: []docs.AnnotatedExample{ { Title: "Basic Multiplexing", Summary: ` The most common use for a switch output is to multiplex messages across a range of output destinations. The following config checks the contents of the field ` + "`type` of messages and sends `foo` type messages to an `amqp_1` output, `bar` type messages to a `gcp_pubsub` output, and everything else to a `redis_streams` output" + `. Outputs can have their own processors associated with them, and in this example the ` + "`redis_streams`" + ` output has a processor that enforces the presence of a type field before sending it.`, Config: ` output: switch: cases: - check: this.type == "foo" output: amqp_1: url: amqps://guest:guest@localhost:5672/ target_address: queue:/the_foos - check: this.type == "bar" output: gcp_pubsub: project: dealing_with_mike topic: mikes_bars - output: redis_streams: url: tcp://localhost:6379 stream: everything_else processors: - bloblang: | root = this root.type = this.type | "unknown" `, }, { Title: "Control Flow", Summary: ` The ` + "`continue`" + ` field allows messages that have passed a case to be tested against the next one also. This can be useful when combining non-mutually-exclusive case checks. In the following example a message that passes both the check of the first case as well as the second will be routed to both.`, Config: ` output: switch: cases: - check: 'this.user.interests.contains("walks").catch(false)' output: amqp_1: url: amqps://guest:guest@localhost:5672/ target_address: queue:/people_what_think_good continue: true - check: 'this.user.dislikes.contains("videogames").catch(false)' output: gcp_pubsub: project: people topic: that_i_dont_want_to_hang_with `, }, }, } }
identifier_body
switch.go
package output import ( "context" "errors" "fmt" "sync" "time" "github.com/Jeffail/benthos/v3/internal/batch" "github.com/Jeffail/benthos/v3/internal/bloblang/mapping" "github.com/Jeffail/benthos/v3/internal/component/output" "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/internal/interop" imessage "github.com/Jeffail/benthos/v3/internal/message" "github.com/Jeffail/benthos/v3/internal/shutdown" "github.com/Jeffail/benthos/v3/lib/condition" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/message" "github.com/Jeffail/benthos/v3/lib/metrics" "github.com/Jeffail/benthos/v3/lib/response" "github.com/Jeffail/benthos/v3/lib/types" "github.com/Jeffail/benthos/v3/lib/util/throttle" "github.com/Jeffail/gabs/v2" "golang.org/x/sync/errgroup" ) //------------------------------------------------------------------------------ var ( // ErrSwitchNoConditionMet is returned when a message does not match any // output conditions. ErrSwitchNoConditionMet = errors.New("no switch output conditions were met by message") // ErrSwitchNoCasesMatched is returned when a message does not match any // output cases. ErrSwitchNoCasesMatched = errors.New("no switch cases were matched by message") // ErrSwitchNoOutputs is returned when creating a Switch type with less than // 2 outputs. ErrSwitchNoOutputs = errors.New("attempting to create switch with fewer than 2 cases") ) //------------------------------------------------------------------------------ func init() { Constructors[TypeSwitch] = TypeSpec{ constructor: fromSimpleConstructor(NewSwitch), Summary: ` The switch output type allows you to route messages to different outputs based on their contents.`, Description: ` Messages must successfully route to one or more outputs, otherwise this is considered an error and the message is reprocessed. In order to explicitly drop messages that do not match your cases add one final case with a [drop output](/docs/components/outputs/drop).`, config: docs.FieldComponent().WithChildren( docs.FieldCommon( "retry_until_success", ` If a selected output fails to send a message this field determines whether it is reattempted indefinitely. If set to false the error is instead propagated back to the input level. If a message can be routed to >1 outputs it is usually best to set this to true in order to avoid duplicate messages being routed to an output.`, ), docs.FieldAdvanced( "strict_mode", ` This field determines whether an error should be reported if no condition is met. If set to true, an error is propagated back to the input level. The default behavior is false, which will drop the message.`, ), docs.FieldAdvanced( "max_in_flight", "The maximum number of parallel message batches to have in flight at any given time. Note that if a child output has a higher `max_in_flight` then the switch output will automatically match it, therefore this value is the minimum `max_in_flight` to set in cases where the child values can't be inferred (such as when using resource outputs as children).", ), docs.FieldCommon( "cases", "A list of switch cases, outlining outputs that can be routed to.", []interface{}{ map[string]interface{}{ "check": `this.urls.contains("http://benthos.dev")`, "output": map[string]interface{}{ "cache": map[string]interface{}{ "target": "foo", "key": "${!json(\"id\")}", }, }, "continue": true, }, map[string]interface{}{ "output": map[string]interface{}{ "s3": map[string]interface{}{ "bucket": "bar", "path": "${!json(\"id\")}", }, }, }, }, ).Array().WithChildren( docs.FieldBloblang( "check", "A [Bloblang query](/docs/guides/bloblang/about/) that should return a boolean value indicating whether a message should be routed to the case output. If left empty the case always passes.", `this.type == "foo"`, `this.contents.urls.contains("https://benthos.dev/")`, ).HasDefault(""), docs.FieldCommon( "output", "An [output](/docs/components/outputs/about/) for messages that pass the check to be routed to.", ).HasDefault(map[string]interface{}{}).HasType(docs.FieldTypeOutput), docs.FieldAdvanced( "continue", "Indicates whether, if this case passes for a message, the next case should also be tested.", ).HasDefault(false).HasType(docs.FieldTypeBool), ), docs.FieldDeprecated("outputs").Array().WithChildren( docs.FieldDeprecated("condition").HasType(docs.FieldTypeCondition), docs.FieldDeprecated("fallthrough"), docs.FieldDeprecated("output").HasType(docs.FieldTypeOutput), ).OmitWhen(func(v, _ interface{}) (string, bool) { arr, ok := v.([]interface{}) return "field outputs is deprecated in favour of cases", ok && len(arr) == 0 }), ).Linter(func(ctx docs.LintContext, line, col int, value interface{}) []docs.Lint { if _, ok := value.(map[string]interface{}); !ok { return nil } gObj := gabs.Wrap(value) retry, exists := gObj.S("retry_until_success").Data().(bool) // TODO: V4 Is retry_until_success going to be false by default now? if exists && !retry { return nil } for _, cObj := range gObj.S("cases").Children() { typeStr, _ := cObj.S("output", "type").Data().(string) isReject := cObj.Exists("output", "reject") if typeStr == "reject" || isReject { return []docs.Lint{ docs.NewLintError(line, "a `switch` output with a `reject` case output must have the field `switch.retry_until_success` set to `false` (defaults to `true`), otherwise the `reject` child output will result in infinite retries"), } } } return nil }), Categories: []Category{ CategoryUtility, }, Examples: []docs.AnnotatedExample{ { Title: "Basic Multiplexing", Summary: ` The most common use for a switch output is to multiplex messages across a range of output destinations. The following config checks the contents of the field ` + "`type` of messages and sends `foo` type messages to an `amqp_1` output, `bar` type messages to a `gcp_pubsub` output, and everything else to a `redis_streams` output" + `. Outputs can have their own processors associated with them, and in this example the ` + "`redis_streams`" + ` output has a processor that enforces the presence of a type field before sending it.`, Config: ` output: switch: cases: - check: this.type == "foo" output: amqp_1: url: amqps://guest:guest@localhost:5672/ target_address: queue:/the_foos - check: this.type == "bar" output: gcp_pubsub: project: dealing_with_mike topic: mikes_bars - output: redis_streams: url: tcp://localhost:6379 stream: everything_else processors: - bloblang: | root = this root.type = this.type | "unknown" `, }, { Title: "Control Flow", Summary: ` The ` + "`continue`" + ` field allows messages that have passed a case to be tested against the next one also. This can be useful when combining non-mutually-exclusive case checks. In the following example a message that passes both the check of the first case as well as the second will be routed to both.`, Config: ` output: switch: cases: - check: 'this.user.interests.contains("walks").catch(false)' output: amqp_1: url: amqps://guest:guest@localhost:5672/ target_address: queue:/people_what_think_good continue: true - check: 'this.user.dislikes.contains("videogames").catch(false)' output: gcp_pubsub: project: people topic: that_i_dont_want_to_hang_with `, }, }, } } //------------------------------------------------------------------------------ // SwitchConfig contains configuration fields for the Switch output type. type SwitchConfig struct { RetryUntilSuccess bool `json:"retry_until_success" yaml:"retry_until_success"` StrictMode bool `json:"strict_mode" yaml:"strict_mode"` MaxInFlight int `json:"max_in_flight" yaml:"max_in_flight"` Cases []SwitchConfigCase `json:"cases" yaml:"cases"` Outputs []SwitchConfigOutput `json:"outputs" yaml:"outputs"` } // NewSwitchConfig creates a new SwitchConfig with default values. func NewSwitchConfig() SwitchConfig { return SwitchConfig{ RetryUntilSuccess: true, // TODO: V4 consider making this true by default. StrictMode: false, MaxInFlight: 1, Cases: []SwitchConfigCase{}, Outputs: []SwitchConfigOutput{}, } } // SwitchConfigCase contains configuration fields per output of a switch type. type SwitchConfigCase struct { Check string `json:"check" yaml:"check"` Continue bool `json:"continue" yaml:"continue"` Output Config `json:"output" yaml:"output"` } // NewSwitchConfigCase creates a new switch output config with default values. func NewSwitchConfigCase() SwitchConfigCase { return SwitchConfigCase{ Check: "", Continue: false, Output: NewConfig(), } } //------------------------------------------------------------------------------ // Switch is a broker that implements types.Consumer and broadcasts each message // out to an array of outputs. type Switch struct { logger log.Modular stats metrics.Type mMsgRcvd metrics.StatCounter mMsgSnt metrics.StatCounter mOutputErr metrics.StatCounter maxInFlight int transactions <-chan types.Transaction retryUntilSuccess bool strictMode bool outputTSChans []chan types.Transaction outputs []types.Output checks []*mapping.Executor conditions []types.Condition continues []bool fallthroughs []bool ctx context.Context close func() closedChan chan struct{} } // NewSwitch creates a new Switch type by providing outputs. Messages will be // sent to a subset of outputs according to condition and fallthrough settings. func NewSwitch( conf Config, mgr types.Manager, logger log.Modular, stats metrics.Type, ) (Type, error) { ctx, done := context.WithCancel(context.Background()) o := &Switch{ stats: stats, logger: logger, maxInFlight: conf.Switch.MaxInFlight, transactions: nil, retryUntilSuccess: conf.Switch.RetryUntilSuccess, strictMode: conf.Switch.StrictMode, closedChan: make(chan struct{}), ctx: ctx, close: done, mMsgRcvd: stats.GetCounter("switch.messages.received"), mMsgSnt: stats.GetCounter("switch.messages.sent"), mOutputErr: stats.GetCounter("switch.output.error"), } lCases := len(conf.Switch.Cases) lOutputs := len(conf.Switch.Outputs) if lCases < 2 && lOutputs < 2 { return nil, ErrSwitchNoOutputs } if lCases > 0 { if lOutputs > 0 { return nil, errors.New("combining switch cases with deprecated outputs is not supported") } o.outputs = make([]types.Output, lCases) o.checks = make([]*mapping.Executor, lCases) o.continues = make([]bool, lCases) o.fallthroughs = make([]bool, lCases) } else { o.outputs = make([]types.Output, lOutputs) o.conditions = make([]types.Condition, lOutputs) o.fallthroughs = make([]bool, lOutputs) } var err error for i, oConf := range conf.Switch.Outputs { ns := fmt.Sprintf("switch.%v", i) oMgr, oLog, oStats := interop.LabelChild(ns+".output", mgr, logger, stats) oStats = metrics.Combine(stats, oStats) if o.outputs[i], err = New(oConf.Output, oMgr, oLog, oStats); err != nil { return nil, fmt.Errorf("failed to create output '%v' type '%v': %v", i, oConf.Output.Type, err) } cMgr, cLog, cStats := interop.LabelChild(ns+".condition", mgr, logger, stats) if o.conditions[i], err = condition.New(oConf.Condition, cMgr, cLog, cStats); err != nil { return nil, fmt.Errorf("failed to create output '%v' condition '%v': %v", i, oConf.Condition.Type, err) } o.fallthroughs[i] = oConf.Fallthrough } for i, cConf := range conf.Switch.Cases { oMgr, oLog, oStats := interop.LabelChild(fmt.Sprintf("switch.%v.output", i), mgr, logger, stats) oStats = metrics.Combine(stats, oStats) if o.outputs[i], err = New(cConf.Output, oMgr, oLog, oStats); err != nil { return nil, fmt.Errorf("failed to create case '%v' output type '%v': %v", i, cConf.Output.Type, err) } if len(cConf.Check) > 0 { if o.checks[i], err = interop.NewBloblangMapping(mgr, cConf.Check); err != nil { return nil, fmt.Errorf("failed to parse case '%v' check mapping: %v", i, err) } } o.continues[i] = cConf.Continue } o.outputTSChans = make([]chan types.Transaction, len(o.outputs)) for i := range o.outputTSChans { if mif, ok := output.GetMaxInFlight(o.outputs[i]); ok && mif > o.maxInFlight { o.maxInFlight = mif } o.outputTSChans[i] = make(chan types.Transaction) if err := o.outputs[i].Consume(o.outputTSChans[i]); err != nil { return nil, err } } return o, nil } //------------------------------------------------------------------------------ // Consume assigns a new transactions channel for the broker to read. func (o *Switch) Consume(transactions <-chan types.Transaction) error { if o.transactions != nil { return types.ErrAlreadyStarted } o.transactions = transactions if len(o.conditions) > 0 { o.logger.Warnf("Using deprecated field `outputs` which will be removed in the next major release of Benthos. For more information check out the docs at https://www.benthos.dev/docs/components/outputs/switch.") go o.loopDeprecated() } else { go o.loop() } return nil } // MaxInFlight returns the maximum number of in flight messages permitted by the // output. This value can be used to determine a sensible value for parent // outputs, but should not be relied upon as part of dispatcher logic. func (o *Switch) MaxInFlight() (int, bool) { return o.maxInFlight, true } // Connected returns a boolean indicating whether this output is currently // connected to its target. func (o *Switch) Connected() bool { for _, out := range o.outputs { if !out.Connected() { return false } } return true } //------------------------------------------------------------------------------ func (o *Switch) dispatchRetryOnErr(outputTargets [][]types.Part) error { var owg errgroup.Group for target, parts := range outputTargets { if len(parts) == 0 { continue } msgCopy, i := message.New(nil), target msgCopy.SetAll(parts) owg.Go(func() error { throt := throttle.New(throttle.OptCloseChan(o.ctx.Done())) resChan := make(chan types.Response) // Try until success or shutdown. for { select { case o.outputTSChans[i] <- types.NewTransaction(msgCopy, resChan): case <-o.ctx.Done(): return types.ErrTypeClosed } select { case res := <-resChan: if res.Error() != nil { o.logger.Errorf("Failed to dispatch switch message: %v\n", res.Error()) o.mOutputErr.Incr(1) if !throt.Retry() { return types.ErrTypeClosed } } else { o.mMsgSnt.Incr(1) return nil } case <-o.ctx.Done(): return types.ErrTypeClosed } } }) } return owg.Wait() } func (o *Switch) dispatchNoRetries(group *imessage.SortGroup, sourceMessage types.Message, outputTargets [][]types.Part) error { var wg sync.WaitGroup var setErr func(error) var setErrForPart func(types.Part, error) var getErr func() error { var generalErr error var batchErr *batch.Error var errLock sync.Mutex setErr = func(err error) { if err == nil { return } errLock.Lock() generalErr = err errLock.Unlock() } setErrForPart = func(part types.Part, err error) { if err == nil { return } errLock.Lock() defer errLock.Unlock() index := group.GetIndex(part) if index == -1 { generalErr = err return } if batchErr == nil { batchErr = batch.NewError(sourceMessage, err) } batchErr.Failed(index, err) } getErr = func() error { if batchErr != nil { return batchErr } return generalErr } } for target, parts := range outputTargets { if len(parts) == 0 { continue } wg.Add(1) msgCopy, i := message.New(nil), target msgCopy.SetAll(parts) go func() { defer wg.Done() resChan := make(chan types.Response) select { case o.outputTSChans[i] <- types.NewTransaction(msgCopy, resChan): case <-o.ctx.Done(): setErr(types.ErrTypeClosed) return } select { case res := <-resChan: if res.Error() != nil { o.mOutputErr.Incr(1) if bErr, ok := res.Error().(*batch.Error); ok { bErr.WalkParts(func(i int, p types.Part, e error) bool { if e != nil { setErrForPart(p, e) } return true }) } else { msgCopy.Iter(func(i int, p types.Part) error { setErrForPart(p, res.Error()) return nil }) } } else { o.mMsgSnt.Incr(1) } case <-o.ctx.Done(): setErr(types.ErrTypeClosed) } }() } wg.Wait() return getErr() } // loop is an internal loop that brokers incoming messages to many outputs. func (o *Switch) loop() { var wg sync.WaitGroup defer func() { wg.Wait() for i, output := range o.outputs { output.CloseAsync() close(o.outputTSChans[i]) } for _, output := range o.outputs { _ = output.WaitForClose(shutdown.MaximumShutdownWait()) } close(o.closedChan) }() sendLoop := func() { defer wg.Done() for { var ts types.Transaction var open bool select { case ts, open = <-o.transactions: if !open { return } case <-o.ctx.Done(): return } o.mMsgRcvd.Incr(1) group, trackedMsg := imessage.NewSortGroup(ts.Payload) outputTargets := make([][]types.Part, len(o.checks)) if checksErr := trackedMsg.Iter(func(i int, p types.Part) error { routedAtLeastOnce := false for j, exe := range o.checks { test := true if exe != nil
if test { routedAtLeastOnce = true outputTargets[j] = append(outputTargets[j], p.Copy()) if !o.continues[j] { return nil } } } if !routedAtLeastOnce && o.strictMode { return ErrSwitchNoConditionMet } return nil }); checksErr != nil { select { case ts.ResponseChan <- response.NewError(checksErr): case <-o.ctx.Done(): return } continue } var resErr error if o.retryUntilSuccess { resErr = o.dispatchRetryOnErr(outputTargets) } else { resErr = o.dispatchNoRetries(group, trackedMsg, outputTargets) } var oResponse types.Response = response.NewAck() if resErr != nil { oResponse = response.NewError(resErr) } select { case ts.ResponseChan <- oResponse: case <-o.ctx.Done(): return } } } // Max in flight for i := 0; i < o.maxInFlight; i++ { wg.Add(1) go sendLoop() } } // CloseAsync shuts down the Switch broker and stops processing requests. func (o *Switch) CloseAsync() { o.close() } // WaitForClose blocks until the Switch broker has closed down. func (o *Switch) WaitForClose(timeout time.Duration) error { select { case <-o.closedChan: case <-time.After(timeout): return types.ErrTimeout } return nil } //------------------------------------------------------------------------------
{ var err error if test, err = exe.QueryPart(i, trackedMsg); err != nil { test = false o.logger.Errorf("Failed to test case %v: %v\n", j, err) } }
conditional_block