idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
40,100
def main ( ) : save_settings = None stdin_fd = - 1 try : import termios stdin_fd = sys . stdin . fileno ( ) save_settings = termios . tcgetattr ( stdin_fd ) except : pass try : real_main ( ) finally : if save_settings : termios . tcsetattr ( stdin_fd , termios . TCSANOW , save_settings )
This main function saves the stdin termios settings calls real_main and restores stdin termios settings when it returns .
40,101
def close ( self ) : if self . pyb and self . pyb . serial : self . pyb . serial . close ( ) self . pyb = None
Closes the serial port .
40,102
def is_root_path ( self , filename ) : test_filename = filename + '/' for root_dir in self . root_dirs : if test_filename . startswith ( root_dir ) : return True return False
Determines if filename corresponds to a directory on this device .
40,103
def read ( self , num_bytes ) : self . check_pyb ( ) try : return self . pyb . serial . read ( num_bytes ) except ( serial . serialutil . SerialException , TypeError ) : self . close ( ) raise DeviceError ( 'serial port %s closed' % self . dev_name_short )
Reads data from the pyboard over the serial port .
40,104
def remote ( self , func , * args , xfer_func = None , ** kwargs ) : global HAS_BUFFER HAS_BUFFER = self . has_buffer if hasattr ( func , 'extra_funcs' ) : func_name = func . name func_lines = [ ] for extra_func in func . extra_funcs : func_lines += inspect . getsource ( extra_func ) . split ( '\n' ) func_lines += [ ''...
Calls func with the indicated args on the micropython board .
40,105
def sync_time ( self ) : now = time . localtime ( time . time ( ) ) self . remote ( set_time , ( now . tm_year , now . tm_mon , now . tm_mday , now . tm_wday + 1 , now . tm_hour , now . tm_min , now . tm_sec , 0 ) ) return now
Sets the time on the pyboard to match the time on the host .
40,106
def write ( self , buf ) : self . check_pyb ( ) try : return self . pyb . serial . write ( buf ) except ( serial . serialutil . SerialException , BrokenPipeError , TypeError ) : self . close ( ) raise DeviceError ( '{} closed' . format ( self . dev_name_short ) )
Writes data to the pyboard over the serial port .
40,107
def timeout ( self , value ) : self . check_pyb ( ) try : self . pyb . serial . timeout = value except : pass
Sets the timeout associated with the serial port .
40,108
def onecmd ( self , line ) : if DEBUG : print ( 'Executing "%s"' % line ) self . line_num += 1 if line == "EOF" or line == 'exit' : if cmd . Cmd . use_rawinput : self . print ( '' ) return True comment_idx = line . find ( "#" ) if comment_idx >= 0 : line = line [ 0 : comment_idx ] line = line . strip ( ) lexer = shlex ...
Override onecmd .
40,109
def print ( self , * args , end = '\n' , file = None ) : if file is None : file = self . stdout s = ' ' . join ( str ( arg ) for arg in args ) + end file . write ( s )
Convenience function so you don t need to remember to put the \ n at the end of the line .
40,110
def filename_complete ( self , text , line , begidx , endidx ) : try : return self . real_filename_complete ( text , line , begidx , endidx ) except : traceback . print_exc ( )
Wrapper for catching exceptions since cmd seems to silently absorb them .
40,111
def real_filename_complete ( self , text , line , begidx , endidx ) : if begidx >= len ( line ) : before_match = begidx else : for before_match in range ( begidx , 0 , - 1 ) : if line [ before_match ] in DELIMS and before_match >= 1 and line [ before_match - 1 ] != '\\' : break fixed = unescape ( line [ before_match + ...
Figure out what filenames match the completion .
40,112
def directory_complete ( self , text , line , begidx , endidx ) : return [ filename for filename in self . filename_complete ( text , line , begidx , endidx ) if filename [ - 1 ] == '/' ]
Figure out what directories match the completion .
40,113
def line_to_args ( self , line ) : args = shlex . split ( line ) self . redirect_filename = '' self . redirect_dev = None redirect_index = - 1 if '>' in args : redirect_index = args . index ( '>' ) elif '>>' in args : redirect_index = args . index ( '>>' ) if redirect_index >= 0 : if redirect_index + 1 >= len ( args ) ...
This will convert the line passed into the do_xxx functions into an array of arguments and handle the Output Redirection Operator .
40,114
def do_cat ( self , line ) : args = self . line_to_args ( line ) for filename in args : filename = resolve_path ( filename ) mode = auto ( get_mode , filename ) if not mode_exists ( mode ) : print_err ( "Cannot access '%s': No such file" % filename ) continue if not mode_isfile ( mode ) : print_err ( "'%s': is not a fi...
cat FILENAME ...
40,115
def do_echo ( self , line ) : args = self . line_to_args ( line ) self . print ( * args )
echo TEXT ...
40,116
def do_mkdir ( self , line ) : args = self . line_to_args ( line ) for filename in args : filename = resolve_path ( filename ) if not mkdir ( filename ) : print_err ( 'Unable to create %s' % filename )
mkdir DIRECTORY ...
40,117
def repl_serial_to_stdout ( self , dev ) : with self . serial_reader_running : try : save_timeout = dev . timeout dev . timeout = 1 while not self . quit_serial_reader : try : char = dev . read ( 1 ) except serial . serialutil . SerialException : return except TypeError : return except ConnectionResetError : return if ...
Runs as a thread which has a sole purpose of readding bytes from the serial port and writing them to stdout . Used by do_repl .
40,118
def set_status ( self , value ) : if not self . _status == value : old = self . _status self . _status = value logger . info ( "{} changing status from {} to {}" . format ( self , old . name , value . name ) ) self . _statusChanged ( old , value )
Set the status of the motor to the specified value if not already set .
40,119
def stop ( self , * args , ** kwargs ) : if self . status in ( Status . stopping , Status . stopped ) : logger . debug ( "{} is already {}" . format ( self , self . status . name ) ) else : self . status = Status . stopping self . onStopping ( * args , ** kwargs ) self . status = Status . stopped
Set the status to Status . stopping and also call onStopping with the provided args and kwargs .
40,120
def next_primary_replica_name_for_master ( self , node_reg , node_ids ) : name = self . _next_primary_node_name_for_master ( node_reg , node_ids ) return name , Replica . generateName ( nodeName = name , instId = 0 )
Returns name and corresponding instance name of the next node which is supposed to be a new Primary . In fact it is not round - robin on this abstraction layer as currently the primary of master instance is pointed directly depending on view number instance id and total number of nodes . But since the view number is in...
40,121
def next_primary_replica_name_for_backup ( self , instance_id , master_primary_rank , primaries , node_reg , node_ids ) : if node_reg is None : node_reg = self . node . nodeReg total_nodes = len ( node_reg ) rank = ( master_primary_rank + 1 ) % total_nodes name = self . node . get_name_by_rank ( rank , node_reg , node_...
Returns name and corresponding instance name of the next node which is supposed to be a new Primary for backup instance in round - robin fashion starting from primary of master instance .
40,122
def process_selection ( self , instance_count , node_reg , node_ids ) : if instance_count == 0 : return [ ] primaries = [ ] primary_rank = None for i in range ( instance_count ) : if i == 0 : primary_name = self . _next_primary_node_name_for_master ( node_reg , node_ids ) primary_rank = self . node . get_rank_by_name (...
Build a set of names of primaries it is needed to avoid duplicates of primary nodes for different replicas .
40,123
def take_ordereds_out_of_turn ( self ) -> tuple : for replica in self . _replicas . values ( ) : yield replica . instId , replica . _remove_ordered_from_queue ( )
Takes all Ordered messages from outbox out of turn
40,124
def _new_replica ( self , instance_id : int , is_master : bool , bls_bft : BlsBft ) -> Replica : return self . _replica_class ( self . _node , instance_id , self . _config , is_master , bls_bft , self . _metrics )
Create a new replica with the specified parameters .
40,125
def acquire ( self ) : now = self . get_current_time ( ) logger . debug ( "now: {}, len(actionsLog): {}" . format ( now , len ( self . actionsLog ) ) ) self . _trimActionsLog ( now ) logger . debug ( "after trim, len(actionsLog): {}" . format ( len ( self . actionsLog ) ) ) if len ( self . actionsLog ) == 0 : self . ac...
Acquires lock for action .
40,126
def lazy_field ( prop ) : @ property def wrapper ( self ) : if self not in _lazy_value_cache : _lazy_value_cache [ self ] = { } self_cache = _lazy_value_cache [ self ] if prop in self_cache : return self_cache [ prop ] prop_value = prop ( self ) self_cache [ prop ] = prop_value return prop_value return wrapper
Decorator which helps in creating lazy properties
40,127
def getRemote ( self , name : str = None , ha : HA = None ) : return self . findInRemotesByName ( name ) if name else self . findInRemotesByHA ( ha )
Find the remote by name or ha .
40,128
def findInRemotesByName ( self , name : str ) : remotes = [ r for r in self . remotes . values ( ) if r . name == name ] if len ( remotes ) > 1 : raise DuplicateRemotes ( remotes ) if not remotes : raise RemoteNotFound ( name ) return remotes [ 0 ]
Find the remote by name .
40,129
def removeRemoteByName ( self , name : str ) -> int : remote = self . getRemote ( name ) rid = remote . uid self . removeRemote ( remote ) return rid
Remove the remote by name .
40,130
def sameAddr ( self , ha , ha2 ) -> bool : if ha == ha2 : return True if ha [ 1 ] != ha2 [ 1 ] : return False return ha [ 0 ] in self . localips and ha2 [ 0 ] in self . localips
Check whether the two arguments correspond to the same address
40,131
def remotesByConnected ( self ) : conns , disconns = [ ] , [ ] for r in self . remotes . values ( ) : array = conns if self . isRemoteConnected ( r ) else disconns array . append ( r ) return conns , disconns
Partitions the remotes into connected and disconnected
40,132
def addIdentifier ( self , identifier = None , seed = None , signer = None , alias = None , didMethodName = None ) : dm = self . didMethods . get ( didMethodName ) signer = signer or dm . newSigner ( identifier = identifier , seed = seed ) self . idsToSigners [ signer . identifier ] = signer if self . defaultId is None...
Adds signer to the wallet . Requires complete signer identifier or seed .
40,133
def requiredIdr ( self , idr : Identifier = None , alias : str = None ) : if idr : if ':' in idr : idr = idr . split ( ':' ) [ 1 ] else : idr = self . aliasesToIds [ alias ] if alias else self . defaultId if not idr : raise EmptyIdentifier return idr
Checks whether signer identifier specified or can it be inferred from alias or can be default used instead
40,134
def signMsg ( self , msg : Dict , identifier : Identifier = None , otherIdentifier : Identifier = None ) : idr = self . requiredIdr ( idr = identifier or otherIdentifier ) signer = self . _signerById ( idr ) signature = signer . sign ( msg ) return signature
Creates signature for message using specified signer
40,135
def signRequest ( self , req : Request , identifier : Identifier = None ) -> Request : idr = self . requiredIdr ( idr = identifier or req . _identifier ) req . _identifier = idr req . reqId = req . gen_req_id ( ) req . signature = self . signMsg ( msg = req . signingPayloadState ( identifier = idr ) , identifier = idr ...
Signs request . Modifies reqId and signature . May modify identifier .
40,136
def signOp ( self , op : Dict , identifier : Identifier = None ) -> Request : request = Request ( operation = op , protocolVersion = CURRENT_PROTOCOL_VERSION ) return self . signRequest ( request , identifier )
Signs the message if a signer is configured
40,137
def listIds ( self , exclude = list ( ) ) : lst = list ( self . aliasesToIds . keys ( ) ) others = set ( self . idsToSigners . keys ( ) ) - set ( self . aliasesToIds . values ( ) ) lst . extend ( list ( others ) ) for x in exclude : lst . remove ( x ) return lst
For each signer in this wallet return its alias if present else return its identifier .
40,138
def saveWallet ( self , wallet , fpath ) : if not fpath : raise ValueError ( "empty path" ) _fpath = self . _normalize ( fpath ) _dpath = _fpath . parent try : _dpath . relative_to ( self . _baseDir ) except ValueError : raise ValueError ( "path {} is not is not relative to the keyrings {}" . format ( fpath , self . _b...
Save wallet into specified localtion .
40,139
def loadWallet ( self , fpath ) : if not fpath : raise ValueError ( "empty path" ) _fpath = self . _normalize ( fpath ) _dpath = _fpath . parent try : _dpath . relative_to ( self . _baseDir ) except ValueError : raise ValueError ( "path {} is not is not relative to the wallets {}" . format ( fpath , self . _baseDir ) )...
Load wallet from specified localtion .
40,140
def addVote ( self , prepare : Prepare , voter : str ) -> None : self . _add_msg ( prepare , voter )
Add the specified PREPARE to this replica s list of received PREPAREs .
40,141
def addVote ( self , commit : Commit , voter : str ) -> None : super ( ) . _add_msg ( commit , voter )
Add the specified COMMIT to this replica s list of received COMMITs .
40,142
def discard ( self , msg , reason , logMethod = logging . error , cliOutput = False ) : reason = "" if not reason else " because {}" . format ( reason ) logMethod ( "{} discarding message {}{}" . format ( self , msg , reason ) , extra = { "cli" : cliOutput } )
Discard a message and log a reason using the specified logMethod .
40,143
def toDict ( self , msg : Dict ) -> Dict : if isinstance ( msg , Request ) : tmsg = msg . as_dict elif hasattr ( msg , "_asdict" ) : tmsg = dict ( msg . _asdict ( ) ) elif hasattr ( msg , "__dict__" ) : tmsg = dict ( msg . __dict__ ) elif self . allowDictOnly : raise ValueError ( "Message cannot be converted to an appr...
Return a dictionary form of the message
40,144
def update_freshness ( self , ledger_id , ts ) : if ledger_id in self . _ledger_freshness : self . _ledger_freshness [ ledger_id ] . last_updated = ts
Updates the time at which the ledger was updated . Should be called whenever a txn for the ledger is ordered .
40,145
def get_last_update_time ( self ) : last_updated = { ledger_id : freshness_state . last_updated for ledger_id , freshness_state in self . _ledger_freshness . items ( ) } return OrderedDict ( sorted ( last_updated . items ( ) , key = lambda item : ( item [ 1 ] , item [ 0 ] ) ) )
Gets the time at which each ledger was updated . Can be called at any time to get this information .
40,146
def serialize ( self , obj , level = 0 , objname = None , topLevelKeysToIgnore = None , toBytes = True ) : res = None if not isinstance ( obj , acceptableTypes ) : error ( "invalid type found {}: {}" . format ( objname , obj ) ) elif isinstance ( obj , str ) : res = obj elif isinstance ( obj , dict ) : if level > 0 : k...
Create a string representation of the given object .
40,147
def reset ( self ) : self . getsCounter = 0 self . processedRequests = { } self . responses = { } self . transactions = { }
Clear the values of all attributes of the transaction store .
40,148
def stop ( self , timeout : int = 5 ) -> None : self . running = False start = time . perf_counter ( ) while True : if self . getsCounter == 0 : return True elif time . perf_counter ( ) <= start + timeout : time . sleep ( .1 ) else : raise StopTimeout ( "Stop timed out waiting for {} gets to " "complete." . format ( se...
Try to stop the transaction store in the given timeout or raise an exception .
40,149
def addToProcessedTxns ( self , identifier : str , txnId : str , reply : Reply ) -> None : self . transactions [ txnId ] = reply if identifier not in self . processedRequests : self . processedRequests [ identifier ] = { } self . processedRequests [ identifier ] [ reply . reqId ] = txnId
Add a client request to the transaction store s list of processed requests .
40,150
async def append ( self , reply : Reply ) -> None : result = reply . result identifier = result . get ( f . IDENTIFIER . nm ) txnId = result . get ( TXN_ID ) logger . debug ( "Reply being sent {}" . format ( reply ) ) if self . _isNewTxn ( identifier , reply , txnId ) : self . addToProcessedTxns ( identifier , txnId , ...
Add the given Reply to this transaction store s list of responses . Also add to processedRequests if not added previously .
40,151
def _isNewTxn ( self , identifier , reply , txnId ) -> bool : return ( identifier not in self . processedRequests or reply . reqId not in self . processedRequests [ identifier ] ) and txnId is not None
If client is not in processedRequests or requestId is not there in processed requests and txnId is present then its a new reply
40,152
def add ( self , req : Request ) : key = req . key if key not in self : self [ key ] = ReqState ( req ) return self [ key ]
Add the specified request to this request store .
40,153
def ordered_by_replica ( self , request_key ) : state = self . get ( request_key ) if not state : return state . unordered_by_replicas_num -= 1
Should be called by each replica when request is ordered or replica is removed .
40,154
def mark_as_forwarded ( self , req : Request , to : int ) : self [ req . key ] . forwarded = True self [ req . key ] . forwardedTo = to self [ req . key ] . unordered_by_replicas_num = to
Works together with mark_as_executed and free methods .
40,155
def add_propagate ( self , req : Request , sender : str ) : data = self . add ( req ) data . propagates [ sender ] = req
Add the specified request to the list of received PROPAGATEs .
40,156
def votes ( self , req ) -> int : try : votes = len ( self [ req . key ] . propagates ) except KeyError : votes = 0 return votes
Get the number of propagates for a given reqId and identifier .
40,157
def mark_as_executed ( self , req : Request ) : state = self [ req . key ] state . executed = True self . _clean ( state )
Works together with mark_as_forwarded and free methods .
40,158
def free ( self , request_key ) : state = self . get ( request_key ) if not state : return state . forwardedTo -= 1 self . _clean ( state )
Works together with mark_as_forwarded and mark_as_executed methods .
40,159
def has_propagated ( self , req : Request , sender : str ) -> bool : return req . key in self and sender in self [ req . key ] . propagates
Check whether the request specified has already been propagated .
40,160
def propagate ( self , request : Request , clientName ) : if self . requests . has_propagated ( request , self . name ) : logger . trace ( "{} already propagated {}" . format ( self , request ) ) else : with self . metrics . measure_time ( MetricsName . SEND_PROPAGATE_TIME ) : self . requests . add_propagate ( request ...
Broadcast a PROPAGATE to all other nodes
40,161
def createPropagate ( request : Union [ Request , dict ] , client_name ) -> Propagate : if not isinstance ( request , ( Request , dict ) ) : logger . error ( "{}Request not formatted properly to create propagate" . format ( THREE_PC_PREFIX ) ) return logger . trace ( "Creating PROPAGATE for REQUEST {}" . format ( reque...
Create a new PROPAGATE for the given REQUEST .
40,162
def forward ( self , request : Request ) : key = request . key num_replicas = self . replicas . num_replicas logger . debug ( '{} forwarding request {} to {} replicas' . format ( self , key , num_replicas ) ) self . replicas . pass_message ( ReqKey ( key ) ) self . monitor . requestUnOrdered ( key ) self . requests . m...
Forward the specified client REQUEST to the other replicas on this node
40,163
def recordAndPropagate ( self , request : Request , clientName ) : self . requests . add ( request ) self . propagate ( request , clientName ) self . tryForwarding ( request )
Record the request in the list of requests and propagate .
40,164
def tryForwarding ( self , request : Request ) : cannot_reason_msg = self . canForward ( request ) if cannot_reason_msg is None : self . forward ( request ) else : logger . trace ( "{} not forwarding request {} to its replicas " "since {}" . format ( self , request , cannot_reason_msg ) )
Try to forward the request if the required conditions are met . See the method canForward for the conditions to check before forwarding a request .
40,165
def removeRemote ( self , remote : Remote , clear = True ) : name = remote . name pkey = remote . publicKey vkey = remote . verKey if name in self . remotes : self . remotes . pop ( name ) self . remotesByKeys . pop ( pkey , None ) self . verifiers . pop ( vkey , None ) else : logger . info ( 'No remote named {} presen...
Currently not using clear
40,166
async def service ( self , limit = None , quota : Optional [ Quota ] = None ) -> int : if self . listener : await self . _serviceStack ( self . age , quota ) else : logger . info ( "{} is stopped" . format ( self ) ) r = len ( self . rxMsgs ) if r > 0 : pracLimit = limit if limit else sys . maxsize return self . proces...
Service limit number of received messages in this stack .
40,167
def connect ( self , name = None , remoteId = None , ha = None , verKeyRaw = None , publicKeyRaw = None ) : if not name : raise ValueError ( 'Remote name should be specified' ) publicKey = None if name in self . remotes : remote = self . remotes [ name ] else : publicKey = z85 . encode ( publicKeyRaw ) if publicKeyRaw ...
Connect to the node specified by name .
40,168
def reconnectRemote ( self , remote ) : if not isinstance ( remote , Remote ) : raise PlenumTypeError ( 'remote' , remote , Remote ) logger . info ( '{} reconnecting to {}' . format ( self , remote ) ) public , secret = self . selfEncKeys remote . disconnect ( ) remote . connect ( self . ctx , public , secret ) self . ...
Disconnect remote and connect to it again
40,169
def _readMultiple ( self , start , end , db ) : self . _validatePos ( start , end ) return [ bytes ( db . get ( str ( pos ) ) ) for pos in range ( start , end + 1 ) ]
Returns a list of hashes with serial numbers between start and end both inclusive .
40,170
def pack_nibbles ( nibbles ) : if nibbles [ - 1 ] == NIBBLE_TERMINATOR : flags = 2 nibbles = nibbles [ : - 1 ] else : flags = 0 oddlen = len ( nibbles ) % 2 flags |= oddlen if oddlen : nibbles = [ flags ] + nibbles else : nibbles = [ flags , 0 ] + nibbles o = b'' for i in range ( 0 , len ( nibbles ) , 2 ) : o += ascii_...
pack nibbles to binary
40,171
def _get_last_node_for_prfx ( self , node , key_prfx , seen_prfx ) : node_type = self . _get_node_type ( node ) if node_type == NODE_TYPE_BLANK : return BLANK_NODE if node_type == NODE_TYPE_BRANCH : if not key_prfx : return node sub_node = self . _decode_to_node ( node [ key_prfx [ 0 ] ] ) seen_prfx . append ( key_prfx...
get last node for the given prefix also update seen_prfx to track the path already traversed
40,172
def metrics ( self ) : masterThrp , backupThrp = self . getThroughputs ( self . instances . masterId ) r = self . instance_throughput_ratio ( self . instances . masterId ) m = [ ( "{} Monitor metrics:" . format ( self ) , None ) , ( "Delta" , self . Delta ) , ( "Lambda" , self . Lambda ) , ( "Omega" , self . Omega ) , ...
Calculate and return the metrics .
40,173
def prettymetrics ( self ) -> str : rendered = [ "{}: {}" . format ( * m ) for m in self . metrics ( ) ] return "\n " . join ( rendered )
Pretty printing for metrics
40,174
def reset ( self ) : logger . debug ( "{}'s Monitor being reset" . format ( self ) ) instances_ids = self . instances . started . keys ( ) self . numOrderedRequests = { inst_id : ( 0 , 0 ) for inst_id in instances_ids } self . requestTracker . reset ( ) self . masterReqLatencies = { } self . masterReqLatencyTooHigh = F...
Reset the monitor . Sets all monitored values to defaults .
40,175
def addInstance ( self , inst_id ) : self . instances . add ( inst_id ) self . requestTracker . add_instance ( inst_id ) self . numOrderedRequests [ inst_id ] = ( 0 , 0 ) rm = self . create_throughput_measurement ( self . config ) self . throughputs [ inst_id ] = rm lm = self . latency_measurement_cls ( self . config )...
Add one protocol instance for monitoring .
40,176
def requestOrdered ( self , reqIdrs : List [ str ] , instId : int , requests , byMaster : bool = False ) -> Dict : now = time . perf_counter ( ) if self . acc_monitor : self . acc_monitor . update_time ( now ) durations = { } for key in reqIdrs : if key not in self . requestTracker : logger . debug ( "Got untracked ord...
Measure the time taken for ordering of a request and return it . Monitor might have been reset due to view change due to which this method returns None
40,177
def requestUnOrdered ( self , key : str ) : now = time . perf_counter ( ) if self . acc_monitor : self . acc_monitor . update_time ( now ) self . acc_monitor . request_received ( key ) self . requestTracker . start ( key , now )
Record the time at which request ordering started .
40,178
def isMasterDegraded ( self ) : if self . acc_monitor : self . acc_monitor . update_time ( time . perf_counter ( ) ) return self . acc_monitor . is_master_degraded ( ) else : return ( self . instances . masterId is not None and ( self . isMasterThroughputTooLow ( ) or self . isMasterAvgReqLatencyTooHigh ( ) ) )
Return whether the master instance is slow .
40,179
def areBackupsDegraded ( self ) : slow_instances = [ ] if self . acc_monitor : for instance in self . instances . backupIds : if self . acc_monitor . is_instance_degraded ( instance ) : slow_instances . append ( instance ) else : for instance in self . instances . backupIds : if self . is_instance_throughput_too_low ( ...
Return slow instance .
40,180
def instance_throughput_ratio ( self , inst_id ) : inst_thrp , otherThrp = self . getThroughputs ( inst_id ) r = inst_thrp / otherThrp if otherThrp and inst_thrp is not None else None return r
The relative throughput of an instance compared to the backup instances .
40,181
def is_instance_throughput_too_low ( self , inst_id ) : r = self . instance_throughput_ratio ( inst_id ) if r is None : logger . debug ( "{} instance {} throughput is not " "measurable." . format ( self , inst_id ) ) return None too_low = r < self . Delta if too_low : logger . display ( "{}{} instance {} throughput rat...
Return whether the throughput of the master instance is greater than the acceptable threshold
40,182
def isMasterReqLatencyTooHigh ( self ) : r = self . masterReqLatencyTooHigh or next ( ( ( key , lat ) for key , lat in self . masterReqLatencies . items ( ) if lat > self . Lambda ) , None ) if r : logger . display ( "{}{} found master's latency {} to be higher than the threshold for request {}." . format ( MONITORING_...
Return whether the request latency of the master instance is greater than the acceptable threshold
40,183
def is_instance_avg_req_latency_too_high ( self , inst_id ) : avg_lat , avg_lat_others = self . getLatencies ( ) if not avg_lat or not avg_lat_others : return False d = avg_lat - avg_lat_others if d < self . Omega : return False if inst_id == self . instances . masterId : logger . info ( "{}{} found difference between ...
Return whether the average request latency of an instance is greater than the acceptable threshold
40,184
def getThroughputs ( self , desired_inst_id : int ) : instance_thrp = self . getThroughput ( desired_inst_id ) totalReqs , totalTm = self . getInstanceMetrics ( forAllExcept = desired_inst_id ) if len ( self . throughputs ) > 1 : thrs = [ ] for inst_id , thr_obj in self . throughputs . items ( ) : if inst_id == desired...
Return a tuple of the throughput of the given instance and the average throughput of the remaining instances .
40,185
def getThroughput ( self , instId : int ) -> float : if instId not in self . instances . ids : return None perf_time = time . perf_counter ( ) throughput = self . throughputs [ instId ] . get_throughput ( perf_time ) return throughput
Return the throughput of the specified instance .
40,186
def getInstanceMetrics ( self , forAllExcept : int ) -> Tuple [ Optional [ int ] , Optional [ float ] ] : m = [ ( reqs , tm ) for i , ( reqs , tm ) in self . numOrderedRequests . items ( ) if i != forAllExcept ] if m : reqs , tm = zip ( * m ) return sum ( reqs ) , sum ( tm ) else : return None , None
Calculate and return the average throughput of all the instances except the one specified as forAllExcept .
40,187
def getLatency ( self , instId : int ) -> float : if len ( self . clientAvgReqLatencies ) == 0 : return 0.0 return self . clientAvgReqLatencies [ instId ] . get_avg_latency ( )
Return a dict with client identifier as a key and calculated latency as a value
40,188
def _enqueue ( self , msg : Any , rid : int , signer : Signer ) -> None : if rid not in self . outBoxes : self . outBoxes [ rid ] = deque ( ) self . outBoxes [ rid ] . append ( msg )
Enqueue the message into the remote s queue .
40,189
def _enqueueIntoAllRemotes ( self , msg : Any , signer : Signer ) -> None : for rid in self . remotes . keys ( ) : self . _enqueue ( msg , rid , signer )
Enqueue the specified message into all the remotes in the nodestack .
40,190
def send ( self , msg : Any , * rids : Iterable [ int ] , signer : Signer = None , message_splitter = None ) -> None : message_parts , err_msg = self . prepare_for_sending ( msg , signer , message_splitter ) if err_msg is not None : return False , err_msg if rids : for r in rids : for part in message_parts : self . _en...
Enqueue the given message into the outBoxes of the specified remotes or into the outBoxes of all the remotes if rids is None
40,191
def flushOutBoxes ( self ) -> None : removedRemotes = [ ] for rid , msgs in self . outBoxes . items ( ) : try : dest = self . remotes [ rid ] . name except KeyError : removedRemotes . append ( rid ) continue if msgs : if self . _should_batch ( msgs ) : logger . trace ( "{} batching {} msgs to {} into fewer transmission...
Clear the outBoxes and transmit batched messages to remotes .
40,192
async def prodAllOnce ( self ) : limit = None s = 0 for n in self . prodables : s += await n . prod ( limit ) return s
Call prod once for each Prodable in this Looper
40,193
def add ( self , prodable : Prodable ) -> None : if prodable . name in [ p . name for p in self . prodables ] : raise ProdableAlreadyAdded ( "Prodable {} already added." . format ( prodable . name ) ) self . prodables . append ( prodable ) if self . autoStart : prodable . start ( self . loop )
Add one Prodable object to this Looper s list of Prodables
40,194
def removeProdable ( self , prodable : Prodable = None , name : str = None ) -> Optional [ Prodable ] : if prodable : self . prodables . remove ( prodable ) return prodable elif name : for p in self . prodables : if hasattr ( p , "name" ) and getattr ( p , "name" ) == name : prodable = p break if prodable : self . prod...
Remove the specified Prodable object from this Looper s list of Prodables
40,195
async def runOnceNicely ( self ) : start = time . perf_counter ( ) msgsProcessed = await self . prodAllOnce ( ) if msgsProcessed == 0 : await asyncio . sleep ( 0.01 , loop = self . loop ) dur = time . perf_counter ( ) - start if dur >= 15 : logger . info ( "it took {:.3f} seconds to run once nicely" . format ( dur ) , ...
Execute runOnce with a small tolerance of 0 . 01 seconds so that the Prodables can complete their other asynchronous tasks not running on the event - loop .
40,196
def run ( self , * coros : CoroWrapper ) : if not self . running : raise RuntimeError ( "not running!" ) async def wrapper ( ) : results = [ ] for coro in coros : try : if inspect . isawaitable ( coro ) : results . append ( await coro ) elif inspect . isfunction ( coro ) : res = coro ( ) if inspect . isawaitable ( res ...
Runs an arbitrary list of coroutines in order and then quits the loop if not running as a context manager .
40,197
async def shutdown ( self ) : logger . display ( "Looper shutting down now..." , extra = { "cli" : False } ) self . running = False start = time . perf_counter ( ) if not self . runFut . done ( ) : await self . runFut self . stopall ( ) logger . display ( "Looper shut down in {:.3f} seconds." . format ( time . perf_cou...
Shut down this Looper .
40,198
def create_default_bls_bft_factory ( node ) : bls_keys_dir = os . path . join ( node . keys_dir , node . name ) bls_crypto_factory = create_default_bls_crypto_factory ( bls_keys_dir ) return BlsFactoryBftPlenum ( bls_crypto_factory , node )
Creates a default BLS factory to instantiate BLS BFT classes .
40,199
def sign ( self , message , encoder = encoding . RawEncoder ) : raw_signed = libnacl . crypto_sign ( message , self . _signing_key ) signature = encoder . encode ( raw_signed [ : libnacl . crypto_sign_BYTES ] ) message = encoder . encode ( raw_signed [ libnacl . crypto_sign_BYTES : ] ) signed = encoder . encode ( raw_s...
Sign a message using this key .