INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Pulls an environment variable out of the environment, splitting it on a
separator, and returning it as a list. Extra whitespace on the list values
is stripped. List values that evaluate as falsy are removed. If not present
and no default specified, an empty list is returned.
:param name: The name of th... | def env_list(name: str,
separator: str =',',
required: bool=False,
default: Union[Type[empty], List[Any]]=empty) -> List[Any]:
"""Pulls an environment variable out of the environment, splitting it on a
separator, and returning it as a list. Extra whitespace on the list val... |
Generic getter for environment variables. Handles defaults,
required-ness, and what type to expect.
:param name: The name of the environment variable be pulled
:type name: str
:param required: Whether the environment variable is required. If ``True``
and the variable is not present, a ``KeyError``... | def get(name: str,
required: bool=False,
default: Union[Type[empty], T]=empty,
type: Type[T]=None) -> T:
"""Generic getter for environment variables. Handles defaults,
required-ness, and what type to expect.
:param name: The name of the environment variable be pulled
:type name:... |
Generate the receipt resulting from applying the transaction.
:param base_header: the header of the block before the transaction was applied.
:param transaction: the transaction used to generate the receipt
:param computation: the result of running the transaction computation
:param sta... | def make_receipt(self,
base_header: BlockHeader,
transaction: BaseTransaction,
computation: BaseComputation,
state: BaseState) -> Receipt:
"""
Generate the receipt resulting from applying the transaction.
:param... |
You probably want `VM().state` instead of this.
Occasionally, you want to build custom state against a particular header and DB,
even if you don't have the VM initialized. This is a convenience method to do that. | def build_state(
cls,
db: BaseAtomicDB,
header: BlockHeader,
previous_hashes: Iterable[Hash32] = ()) -> BaseState:
"""
You probably want `VM().state` instead of this.
Occasionally, you want to build custom state against a particular header and DB,... |
Apply the transaction to the current block. This is a wrapper around
:func:`~eth.vm.state.State.apply_transaction` with some extra orchestration logic.
:param header: header of the block before application
:param transaction: to apply | def apply_transaction(self,
header: BlockHeader,
transaction: BaseTransaction
) -> Tuple[Receipt, BaseComputation]:
"""
Apply the transaction to the current block. This is a wrapper around
:func:`~eth.vm.state.State.ap... |
Execute raw bytecode in the context of the current state of
the virtual machine. | def execute_bytecode(self,
origin: Address,
gas_price: int,
gas: int,
to: Address,
sender: Address,
value: int,
data: bytes,
... |
Determine the results of applying all transactions to the base header.
This does *not* update the current block or header of the VM.
:param transactions: an iterable of all transactions to apply
:param base_header: the starting header to apply transactions to
:return: the final header, ... | def apply_all_transactions(
self,
transactions: Tuple[BaseTransaction, ...],
base_header: BlockHeader
) -> Tuple[BlockHeader, Tuple[Receipt, ...], Tuple[BaseComputation, ...]]:
"""
Determine the results of applying all transactions to the base header.
This... |
Import the given block to the chain. | def import_block(self, block: BaseBlock) -> BaseBlock:
"""
Import the given block to the chain.
"""
if self.block.number != block.number:
raise ValidationError(
"This VM can only import blocks at number #{}, the attempted block was #{}".format(
... |
Mine the current block. Proxies to self.pack_block method. | def mine_block(self, *args: Any, **kwargs: Any) -> BaseBlock:
"""
Mine the current block. Proxies to self.pack_block method.
"""
packed_block = self.pack_block(self.block, *args, **kwargs)
final_block = self.finalize_block(packed_block)
# Perform validation
self... |
Perform any finalization steps like awarding the block mining reward,
and persisting the final state root. | def finalize_block(self, block: BaseBlock) -> BaseBlock:
"""
Perform any finalization steps like awarding the block mining reward,
and persisting the final state root.
"""
if block.number > 0:
self._assign_block_rewards(block)
# We need to call `persist` here... |
Pack block for mining.
:param bytes coinbase: 20-byte public address to receive block reward
:param bytes uncles_hash: 32 bytes
:param bytes state_root: 32 bytes
:param bytes transaction_root: 32 bytes
:param bytes receipt_root: 32 bytes
:param int bloom:
:param ... | def pack_block(self, block: BaseBlock, *args: Any, **kwargs: Any) -> BaseBlock:
"""
Pack block for mining.
:param bytes coinbase: 20-byte public address to receive block reward
:param bytes uncles_hash: 32 bytes
:param bytes state_root: 32 bytes
:param bytes transaction_... |
Generate block from parent header and coinbase. | def generate_block_from_parent_header_and_coinbase(cls,
parent_header: BlockHeader,
coinbase: Address) -> BaseBlock:
"""
Generate block from parent header and coinbase.
"""
block... |
Convenience API for accessing the previous 255 block hashes. | def previous_hashes(self) -> Optional[Iterable[Hash32]]:
"""
Convenience API for accessing the previous 255 block hashes.
"""
return self.get_prev_hashes(self.header.parent_hash, self.chaindb) |
Proxy for instantiating a signed transaction for this VM. | def create_transaction(self, *args: Any, **kwargs: Any) -> BaseTransaction:
"""
Proxy for instantiating a signed transaction for this VM.
"""
return self.get_transaction_class()(*args, **kwargs) |
Proxy for instantiating an unsigned transaction for this VM. | def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
... |
Validate the the given block. | def validate_block(self, block: BaseBlock) -> None:
"""
Validate the the given block.
"""
if not isinstance(block, self.get_block_class()):
raise ValidationError(
"This vm ({0!r}) is not equipped to validate a block of type {1!r}".format(
s... |
:raise eth.exceptions.ValidationError: if the header is not valid | def validate_header(cls,
header: BlockHeader,
parent_header: BlockHeader,
check_seal: bool = True) -> None:
"""
:raise eth.exceptions.ValidationError: if the header is not valid
"""
if parent_header is None:
... |
Validate the seal on the given header. | def validate_seal(cls, header: BlockHeader) -> None:
"""
Validate the seal on the given header.
"""
check_pow(
header.block_number, header.mining_hash,
header.mix_hash, header.nonce, header.difficulty) |
Validate the given uncle in the context of the given block. | def validate_uncle(cls, block: BaseBlock, uncle: BaseBlock, uncle_parent: BaseBlock) -> None:
"""
Validate the given uncle in the context of the given block.
"""
if uncle.block_number >= block.number:
raise ValidationError(
"Uncle number ({0}) is higher than b... |
https://github.com/ethereum/EIPs/pull/198 | def modexp(computation: BaseComputation) -> BaseComputation:
"""
https://github.com/ethereum/EIPs/pull/198
"""
data = computation.msg.data_as_bytes
gas_fee = _compute_modexp_gas_fee(data)
computation.consume_gas(gas_fee, reason='MODEXP Precompile')
result = _modexp(data)
_, _, modulus... |
Check that nothing will be overwritten when dictionaries are merged using `deep_merge`.
Examples:
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"c": 3})
True
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"a": 0, c": 3})
False
>>> is_cleanly_mergable({"a": 1, "b": {"ba": 2}}, ... | def is_cleanly_mergable(*dicts: Dict[Any, Any]) -> bool:
"""Check that nothing will be overwritten when dictionaries are merged using `deep_merge`.
Examples:
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"c": 3})
True
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"a": 0, c": 3})
... |
List all the keys that have been deleted. | def deleted_keys(self) -> Iterable[bytes]:
"""
List all the keys that have been deleted.
"""
for key, value in self._changes.items():
if value is DELETED:
yield key |
A tuple of (key, value) pairs for every key that has been updated.
Like :meth:`pending_keys()`, this does not return any deleted keys. | def pending_items(self) -> Iterable[Tuple[bytes, bytes]]:
"""
A tuple of (key, value) pairs for every key that has been updated.
Like :meth:`pending_keys()`, this does not return any deleted keys.
"""
for key, value in self._changes.items():
if value is not DELETED:
... |
Apply the changes in this diff to the given database.
You may choose to opt out of deleting any underlying keys.
:param apply_deletes: whether the pending deletes should be
applied to the database | def apply_to(self,
db: Union[BaseDB, ABC_Mutable_Mapping],
apply_deletes: bool = True) -> None:
"""
Apply the changes in this diff to the given database.
You may choose to opt out of deleting any underlying keys.
:param apply_deletes: whether the pendin... |
Join several DBDiff objects into a single DBDiff object.
In case of a conflict, changes in diffs that come later
in ``diffs`` will overwrite changes from earlier changes. | def join(cls, diffs: Iterable['DBDiff']) -> 'DBDiff':
"""
Join several DBDiff objects into a single DBDiff object.
In case of a conflict, changes in diffs that come later
in ``diffs`` will overwrite changes from earlier changes.
"""
tracker = DBDiffTracker()
for ... |
Helper function for computing the RLP hash of the logs from transaction
execution. | def hash_log_entries(log_entries: Iterable[Tuple[bytes, List[int], bytes]]) -> Hash32:
"""
Helper function for computing the RLP hash of the logs from transaction
execution.
"""
logs = [Log(*entry) for entry in log_entries]
encoded_logs = rlp.encode(logs)
logs_hash = keccak(encoded_logs)
... |
Returns the VM class for the given block number. | def get_vm_class_for_block_number(cls, block_number: BlockNumber) -> Type['BaseVM']:
"""
Returns the VM class for the given block number.
"""
if cls.vm_configuration is None:
raise AttributeError("Chain classes must define the VMs in vm_configuration")
validate_block... |
Validate that all of the descendents are valid, given that the root header is valid.
By default, check the seal validity (Proof-of-Work on Ethereum 1.x mainnet) of all headers.
This can be expensive. Instead, check a random sample of seals using
seal_check_random_sample_rate. | def validate_chain(
cls,
root: BlockHeader,
descendants: Tuple[BlockHeader, ...],
seal_check_random_sample_rate: int = 1) -> None:
"""
Validate that all of the descendents are valid, given that the root header is valid.
By default, check the seal ... |
Initializes the Chain from a genesis state. | def from_genesis(cls,
base_db: BaseAtomicDB,
genesis_params: Dict[str, HeaderParams],
genesis_state: AccountState=None) -> 'BaseChain':
"""
Initializes the Chain from a genesis state.
"""
genesis_vm_class = cls.get_vm_class_f... |
Initializes the chain from the genesis header. | def from_genesis_header(cls,
base_db: BaseAtomicDB,
genesis_header: BlockHeader) -> 'BaseChain':
"""
Initializes the chain from the genesis header.
"""
chaindb = cls.get_chaindb_class()(base_db)
chaindb.persist_header(genesi... |
Returns the VM instance for the given block number. | def get_vm(self, at_header: BlockHeader=None) -> 'BaseVM':
"""
Returns the VM instance for the given block number.
"""
header = self.ensure_header(at_header)
vm_class = self.get_vm_class_for_block_number(header.block_number)
return vm_class(header=header, chaindb=self.cha... |
Passthrough helper to the VM class of the block descending from the
given header. | def create_header_from_parent(self,
parent_header: BlockHeader,
**header_params: HeaderParams) -> BlockHeader:
"""
Passthrough helper to the VM class of the block descending from the
given header.
"""
return self... |
Returns the requested block header as specified by block hash.
Raises BlockNotFound if there's no block header with the given hash in the db. | def get_block_header_by_hash(self, block_hash: Hash32) -> BlockHeader:
"""
Returns the requested block header as specified by block hash.
Raises BlockNotFound if there's no block header with the given hash in the db.
"""
validate_word(block_hash, title="Block Hash")
retu... |
Return ``header`` if it is not ``None``, otherwise return the header
of the canonical head. | def ensure_header(self, header: BlockHeader=None) -> BlockHeader:
"""
Return ``header`` if it is not ``None``, otherwise return the header
of the canonical head.
"""
if header is None:
head = self.get_canonical_head()
return self.create_header_from_parent(... |
Return `limit` number of ancestor blocks from the current canonical head. | def get_ancestors(self, limit: int, header: BlockHeader) -> Tuple[BaseBlock, ...]:
"""
Return `limit` number of ancestor blocks from the current canonical head.
"""
ancestor_count = min(header.block_number, limit)
# We construct a temporary block object
vm_class = self.g... |
Returns the requested block as specified by block hash. | def get_block_by_hash(self, block_hash: Hash32) -> BaseBlock:
"""
Returns the requested block as specified by block hash.
"""
validate_word(block_hash, title="Block Hash")
block_header = self.get_block_header_by_hash(block_hash)
return self.get_block_by_header(block_heade... |
Returns the requested block as specified by the block header. | def get_block_by_header(self, block_header: BlockHeader) -> BaseBlock:
"""
Returns the requested block as specified by the block header.
"""
vm = self.get_vm(block_header)
return vm.block |
Returns the block with the given number in the canonical chain.
Raises BlockNotFound if there's no block with the given number in the
canonical chain. | def get_canonical_block_by_number(self, block_number: BlockNumber) -> BaseBlock:
"""
Returns the block with the given number in the canonical chain.
Raises BlockNotFound if there's no block with the given number in the
canonical chain.
"""
validate_uint256(block_number, ... |
Generate a block with the provided transactions. This does *not* import
that block into your chain. If you want this new block in your chain,
run :meth:`~import_block` with the result block from this method.
:param transactions: an iterable of transactions to insert to the block
:param ... | def build_block_with_transactions(
self,
transactions: Tuple[BaseTransaction, ...],
parent_header: BlockHeader=None
) -> Tuple[BaseBlock, Tuple[Receipt, ...], Tuple[BaseComputation, ...]]:
"""
Generate a block with the provided transactions. This does *not* import... |
Returns the requested transaction as specified by the transaction hash
from the canonical chain.
Raises TransactionNotFound if no transaction with the specified hash is
found in the main chain. | def get_canonical_transaction(self, transaction_hash: Hash32) -> BaseTransaction:
"""
Returns the requested transaction as specified by the transaction hash
from the canonical chain.
Raises TransactionNotFound if no transaction with the specified hash is
found in the main chain.... |
Passthrough helper to the current VM class. | def create_transaction(self, *args: Any, **kwargs: Any) -> BaseTransaction:
"""
Passthrough helper to the current VM class.
"""
return self.get_vm().create_transaction(*args, **kwargs) |
Passthrough helper to the current VM class. | def create_unsigned_transaction(self,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
... |
Return the result of running the given transaction.
This is referred to as a `call()` in web3. | def get_transaction_result(
self,
transaction: BaseOrSpoofTransaction,
at_header: BlockHeader) -> bytes:
"""
Return the result of running the given transaction.
This is referred to as a `call()` in web3.
"""
with self.get_vm(at_header).state_in... |
Returns an estimation of the amount of gas the given transaction will
use if executed on top of the block specified by the given header. | def estimate_gas(
self,
transaction: BaseOrSpoofTransaction,
at_header: BlockHeader=None) -> int:
"""
Returns an estimation of the amount of gas the given transaction will
use if executed on top of the block specified by the given header.
"""
i... |
Imports a complete block and returns a 3-tuple
- the imported block
- a tuple of blocks which are now part of the canonical chain.
- a tuple of blocks which were canonical and now are no longer canonical. | def import_block(self,
block: BaseBlock,
perform_validation: bool=True
) -> Tuple[BaseBlock, Tuple[BaseBlock, ...], Tuple[BaseBlock, ...]]:
"""
Imports a complete block and returns a 3-tuple
- the imported block
- a tuple of... |
Performs validation on a block that is either being mined or imported.
Since block validation (specifically the uncle validation) must have
access to the ancestor blocks, this validation must occur at the Chain
level.
Cannot be used to validate genesis block. | def validate_block(self, block: BaseBlock) -> None:
"""
Performs validation on a block that is either being mined or imported.
Since block validation (specifically the uncle validation) must have
access to the ancestor blocks, this validation must occur at the Chain
level.
... |
Validate the seal on the given header. | def validate_seal(self, header: BlockHeader) -> None:
"""
Validate the seal on the given header.
"""
VM_class = self.get_vm_class_for_block_number(BlockNumber(header.block_number))
VM_class.validate_seal(header) |
Validate the gas limit on the given header. | def validate_gaslimit(self, header: BlockHeader) -> None:
"""
Validate the gas limit on the given header.
"""
parent_header = self.get_block_header_by_hash(header.parent_hash)
low_bound, high_bound = compute_gas_limit_bounds(parent_header)
if header.gas_limit < low_bound:... |
Validate the uncles for the given block. | def validate_uncles(self, block: BaseBlock) -> None:
"""
Validate the uncles for the given block.
"""
has_uncles = len(block.uncles) > 0
should_have_uncles = block.header.uncles_hash != EMPTY_UNCLE_HASH
if not has_uncles and not should_have_uncles:
# optimiza... |
Applies the transaction to the current tip block.
WARNING: Receipt and Transaction trie generation is computationally
heavy and incurs significant performance overhead. | def apply_transaction(self,
transaction: BaseTransaction
) -> Tuple[BaseBlock, Receipt, BaseComputation]:
"""
Applies the transaction to the current tip block.
WARNING: Receipt and Transaction trie generation is computationally
heavy a... |
Mines the current block. Proxies to the current Virtual Machine.
See VM. :meth:`~eth.vm.base.VM.mine_block` | def mine_block(self, *args: Any, **kwargs: Any) -> BaseBlock:
"""
Mines the current block. Proxies to the current Virtual Machine.
See VM. :meth:`~eth.vm.base.VM.mine_block`
"""
mined_block = self.get_vm(self.header).mine_block(*args, **kwargs)
self.validate_block(mined_... |
Ping server and wait for response.
Ping a mongod or mongos every `interval` seconds until it responds, or
`timeout` seconds have passed. If `to_start` is set to False, will wait for
the node to shut down instead. This function can be called as a separate
thread.
If queue is provided, it will place... | def wait_for_host(port, interval=1, timeout=30, to_start=True, queue=None,
ssl_pymongo_options=None):
"""
Ping server and wait for response.
Ping a mongod or mongos every `interval` seconds until it responds, or
`timeout` seconds have passed. If `to_start` is set to False, will wait f... |
Send the shutdown command to a mongod or mongos on given port.
This function can be called as a separate thread. | def shutdown_host(port, username=None, password=None, authdb=None):
"""
Send the shutdown command to a mongod or mongos on given port.
This function can be called as a separate thread.
"""
host = 'localhost:%i' % port
try:
mc = MongoConnection(host)
try:
if username ... |
Main run method.
Called for all sub-commands and parameters. It sets up argument
parsing, then calls the sub-command method with the same name. | def run(self, arguments=None):
"""
Main run method.
Called for all sub-commands and parameters. It sets up argument
parsing, then calls the sub-command method with the same name.
"""
# set up argument parsing in run, so that subsequent calls
# to run can call dif... |
Sub-command init.
Branches out to sharded, replicaset or single node methods. | def init(self):
"""
Sub-command init.
Branches out to sharded, replicaset or single node methods.
"""
# check for existing environment. Only allow subsequent
# 'mlaunch init' if they are identical.
if self._load_parameters():
if self.loaded_args != se... |
Sub-command start. | def start(self):
"""Sub-command start."""
self.discover()
# startup_info only gets loaded from protocol version 2 on,
# check if it's loaded
if not self.startup_info:
# hack to make environment startable with older protocol
# versions < 2: try to start no... |
Sub-command list.
Takes no further parameters. Will discover the current configuration
and print a table of all the nodes with status and port. | def list(self):
"""
Sub-command list.
Takes no further parameters. Will discover the current configuration
and print a table of all the nodes with status and port.
"""
self.discover()
print_docs = []
# mongos
for node in sorted(self.get_tagged(['... |
Fetch state for each processes.
Build the self.cluster_tree, self.cluster_tags, self.cluster_running
data structures, needed for sub-commands start, stop, list. | def discover(self):
"""
Fetch state for each processes.
Build the self.cluster_tree, self.cluster_tags, self.cluster_running
data structures, needed for sub-commands start, stop, list.
"""
# need self.args['command'] so fail if it's not available
if (not self.arg... |
Return True if a host on a specific port is running. | def is_running(self, port):
"""Return True if a host on a specific port is running."""
try:
con = self.client('localhost:%s' % port)
con.admin.command('ping')
return True
except (AutoReconnect, ConnectionFailure, OperationFailure):
# Catch Operatio... |
Tag format.
The format for the tags list is tuples for tags: mongos, config, shard,
secondary tags of the form (tag, number), e.g. ('mongos', 2) which
references the second mongos in the list. For all other tags, it is
simply the string, e.g. 'primary'. | def get_tagged(self, tags):
"""
Tag format.
The format for the tags list is tuples for tags: mongos, config, shard,
secondary tags of the form (tag, number), e.g. ('mongos', 2) which
references the second mongos in the list. For all other tags, it is
simply the string, e... |
Get all tags related to a given port.
This is the inverse of what is stored in self.cluster_tags). | def get_tags_of_port(self, port):
"""
Get all tags related to a given port.
This is the inverse of what is stored in self.cluster_tags).
"""
return(sorted([tag for tag in self.cluster_tags
if port in self.cluster_tags[tag]])) |
Spawn threads to ping host using a list of ports.
Returns when all hosts are running (if to_start=True) / shut down (if
to_start=False). | def wait_for(self, ports, interval=1.0, timeout=30, to_start=True):
"""
Spawn threads to ping host using a list of ports.
Returns when all hosts are running (if to_start=True) / shut down (if
to_start=False).
"""
threads = []
queue = Queue.Queue()
for po... |
Load the .mlaunch_startup file that exists in each datadir.
Handles different protocol versions. | def _load_parameters(self):
"""
Load the .mlaunch_startup file that exists in each datadir.
Handles different protocol versions.
"""
datapath = self.dir
startup_file = os.path.join(datapath, '.mlaunch_startup')
if not os.path.exists(startup_file):
re... |
Store startup params and config in datadir/.mlaunch_startup. | def _store_parameters(self):
"""Store startup params and config in datadir/.mlaunch_startup."""
datapath = self.dir
out_dict = {
'protocol_version': 2,
'mtools_version': __version__,
'parsed_args': self.args,
'unknown_args': self.unknown_args,
... |
Create datadir and subdir paths. | def _create_paths(self, basedir, name=None):
"""Create datadir and subdir paths."""
if name:
datapath = os.path.join(basedir, name)
else:
datapath = basedir
dbpath = os.path.join(datapath, 'db')
if not os.path.exists(dbpath):
os.makedirs(dbpat... |
Return a list of accepted arguments.
Check which arguments in list are accepted by the specified binary
(mongod, mongos). If an argument does not start with '-' but its
preceding argument was accepted, then it is accepted as well. Example
['--slowms', '1000'] both arguments would be acc... | def _filter_valid_arguments(self, arguments, binary="mongod",
config=False):
"""
Return a list of accepted arguments.
Check which arguments in list are accepted by the specified binary
(mongod, mongos). If an argument does not start with '-' but its
... |
Get the shard names based on the self.args['sharded'] parameter.
If it's a number, create shard names of type shard##, where ## is a
2-digit number. Returns a list [None] if no shards are present. | def _get_shard_names(self, args):
"""
Get the shard names based on the self.args['sharded'] parameter.
If it's a number, create shard names of type shard##, where ## is a
2-digit number. Returns a list [None] if no shards are present.
"""
if 'sharded' in args and args['s... |
Initiate replica set. | def _initiate_replset(self, port, name, maxwait=30):
"""Initiate replica set."""
if not self.args['replicaset'] and name != 'configRepl':
if self.args['verbose']:
print('Skipping replica set initialization for %s' % name)
return
con = self.client('localho... |
Top-level _construct_* method.
From here, it will branch out to the different cases:
_construct_sharded, _construct_replicaset, _construct_single. These can
themselves call each other (for example sharded needs to create the
shards with either replicaset or single node). At the lowest l... | def _construct_cmdlines(self):
"""
Top-level _construct_* method.
From here, it will branch out to the different cases:
_construct_sharded, _construct_replicaset, _construct_single. These can
themselves call each other (for example sharded needs to create the
shards with... |
Construct command line strings for a sharded cluster. | def _construct_sharded(self):
"""Construct command line strings for a sharded cluster."""
current_version = self.getMongoDVersion()
num_mongos = self.args['mongos'] if self.args['mongos'] > 0 else 1
shard_names = self._get_shard_names(self.args)
# create shards as stand-alones... |
Construct command line strings for a replicaset.
Handles single set or sharded cluster. | def _construct_replset(self, basedir, portstart, name, num_nodes,
arbiter, extra=''):
"""
Construct command line strings for a replicaset.
Handles single set or sharded cluster.
"""
self.config_docs[name] = {'_id': name, 'members': []}
# Const... |
Construct command line strings for a config server. | def _construct_config(self, basedir, port, name=None, isreplset=False):
"""Construct command line strings for a config server."""
if isreplset:
return self._construct_replset(basedir=basedir, portstart=port,
name=name,
... |
Construct command line strings for a single node.
Handles shards and stand-alones. | def _construct_single(self, basedir, port, name=None, extra=''):
"""
Construct command line strings for a single node.
Handles shards and stand-alones.
"""
datapath = self._create_paths(basedir, name)
self._construct_mongod(os.path.join(datapath, 'db'),
... |
Construct command line strings for mongod process. | def _construct_mongod(self, dbpath, logpath, port, replset=None, extra=''):
"""Construct command line strings for mongod process."""
rs_param = ''
if replset:
rs_param = '--replSet %s' % replset
auth_param = ''
if self.args['auth']:
key_path = os.path.abs... |
Construct command line strings for a mongos process. | def _construct_mongos(self, logpath, port, configdb):
"""Construct command line strings for a mongos process."""
extra = ''
auth_param = ''
if self.args['auth']:
key_path = os.path.abspath(os.path.join(self.dir, 'keyfile'))
auth_param = '--keyFile %s' % key_path
... |
Run this section and print out information. | def run(self):
"""Run this section and print out information."""
if self.mloginfo.logfile.repl_set:
print(" rs name: %s" % self.mloginfo.logfile.repl_set)
print(" rs members: %s"
% (self.mloginfo.logfile.repl_set_members
if self.mloginfo.... |
Add a match to the LogCodeLine.
Include the version, filename of the source file, the line number, and
the loglevel. | def addMatch(self, version, filename, lineno, loglevel, trigger):
"""
Add a match to the LogCodeLine.
Include the version, filename of the source file, the line number, and
the loglevel.
"""
self.versions.add(version)
self.matches[version].append((filename, linen... |
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not. | def accept(self, logevent):
"""
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not.
"""
if logevent.duration is not None:
return logevent.duration >= self.slowms
re... |
Return True on match.
Only match log lines containing 'is now in state' (reflects other
node's state changes) or of type "[rsMgr] replSet PRIMARY" (reflects
own state changes). | def accept_line(self, logevent):
"""
Return True on match.
Only match log lines containing 'is now in state' (reflects other
node's state changes) or of type "[rsMgr] replSet PRIMARY" (reflects
own state changes).
"""
if ("is now in state" in logevent.line_str an... |
Change default color behavior.
Map certain states always to the same colors (similar to MMS). | def color_map(cls, group):
print("Group %s" % group)
"""
Change default color behavior.
Map certain states always to the same colors (similar to MMS).
"""
try:
state_idx = cls.states.index(group)
except ValueError:
# on any unexpected stat... |
Called per artist (group), with possibly a list of indices. | def onpick(self, event):
"""Called per artist (group), with possibly a list of indices."""
if hasattr(event.artist, '_mt_legend_item'):
# legend item, instead of data point
idx = event.artist._mt_legend_item
try:
self.toggle_artist(self.artists[idx])
... |
Append log line to this plot type. | def add_line(self, logevent):
"""Append log line to this plot type."""
key = None
self.empty = False
self.groups.setdefault(key, list()).append(logevent) |
Iterator yielding all logevents from groups dictionary. | def logevents(self):
"""Iterator yielding all logevents from groups dictionary."""
for key in self.groups:
for logevent in self.groups[key]:
yield logevent |
(re-)group all logevents by the given group. | def group(self):
"""(re-)group all logevents by the given group."""
if hasattr(self, 'group_by'):
group_by = self.group_by
else:
group_by = self.default_group_by
if self.args['group'] is not None:
group_by = self.args['group']
self.gro... |
Plot the histogram as a whole over all groups.
Do not plot as individual groups like other plot types. | def plot(self, axis, ith_plot, total_plots, limits):
"""
Plot the histogram as a whole over all groups.
Do not plot as individual groups like other plot types.
"""
print(self.plot_type_str.upper() + " plot")
print("%5s %9s %s" % ("id", " #points", "group"))
for... |
Print group name and number of items in bin. | def clicked(self, event):
"""Print group name and number of items in bin."""
group = event.artist._mt_group
n = event.artist._mt_n
dt = num2date(event.artist._mt_bin)
print("%4i %s events in %s sec beginning at %s"
% (n, group, self.bucketsize, dt.strftime("%b %d %H... |
General purpose class to group items by certain criteria. | def add(self, item, group_by=None):
"""General purpose class to group items by certain criteria."""
key = None
if not group_by:
group_by = self.group_by
if group_by:
# if group_by is a function, use it with item as argument
if hasattr(group_by, '__ca... |
Regroup items. | def regroup(self, group_by=None):
"""Regroup items."""
if not group_by:
group_by = self.group_by
groups = self.groups
self.groups = {}
for g in groups:
for item in groups[g]:
self.add(item, group_by) |
Take all elements from the from_group and add it to the to_group. | def move_items(self, from_group, to_group):
"""Take all elements from the from_group and add it to the to_group."""
if from_group not in self.keys() or len(self.groups[from_group]) == 0:
return
self.groups.setdefault(to_group, list()).extend(self.groups.get
... |
Sort the groups by the number of elements they contain, descending.
Also has option to limit the number of groups. If this option is
chosen, the remaining elements are placed into another group with the
name specified with others_label. if discard_others is True, the others
group is rem... | def sort_by_size(self, group_limit=None, discard_others=False,
others_label='others'):
"""
Sort the groups by the number of elements they contain, descending.
Also has option to limit the number of groups. If this option is
chosen, the remaining elements are placed ... |
Static import helper function.
Checks if the log2code.pickle exists first, otherwise raises ImportError. | def import_l2c_db():
"""
Static import helper function.
Checks if the log2code.pickle exists first, otherwise raises ImportError.
"""
data_path = os.path.join(os.path.dirname(mtools.__file__), 'data')
if os.path.exists(os.path.join(data_path, 'log2code.pickle')):
av, lv, lbw, lcl = cPic... |
Find the codeline end by taking out the counters and durations. | def _strip_counters(self, sub_line):
"""Find the codeline end by taking out the counters and durations."""
try:
end = sub_line.rindex('}')
except ValueError:
return sub_line
else:
return sub_line[:(end + 1)] |
Strip datetime and other parts so that there is no redundancy. | def _strip_datetime(self, sub_line):
"""Strip datetime and other parts so that there is no redundancy."""
try:
begin = sub_line.index(']')
except ValueError:
return sub_line
else:
# create a "" in place character for the beginnings..
# need... |
Return the variable parts of the code given a tuple of strings pattern.
Example: (this, is, a, pattern) -> 'this is a good pattern' -> [good] | def _find_variable(self, pattern, logline):
"""
Return the variable parts of the code given a tuple of strings pattern.
Example: (this, is, a, pattern) -> 'this is a good pattern' -> [good]
"""
var_subs = []
# find the beginning of the pattern
first_index = logli... |
Return variable parts of the codeline, given the static parts. | def _variable_parts(self, line, codeline):
"""Return variable parts of the codeline, given the static parts."""
var_subs = []
# codeline has pattern and then has the outputs in different versions
if codeline:
var_subs = self._find_variable(codeline.pattern, line)
else... |
Combine a pattern and variable parts to be a line string again. | def combine(self, pattern, variable):
"""Combine a pattern and variable parts to be a line string again."""
inter_zip = izip_longest(variable, pattern, fillvalue='')
interleaved = [elt for pair in inter_zip for elt in pair]
return ''.join(interleaved) |
Init point to execute the script.
If `arguments` string is given, will evaluate the arguments, else
evaluates sys.argv. Any inheriting class should extend the run method
(but first calling BaseCmdLineTool.run(self)). | def run(self, arguments=None, get_unknowns=False):
"""
Init point to execute the script.
If `arguments` string is given, will evaluate the arguments, else
evaluates sys.argv. Any inheriting class should extend the run method
(but first calling BaseCmdLineTool.run(self)).
... |
Convert the datetime to unix epoch (properly). | def _datetime_to_epoch(self, dt):
"""Convert the datetime to unix epoch (properly)."""
if dt:
td = (dt - datetime.datetime.fromtimestamp(0, tzutc()))
# don't use total_seconds(), that's only available in 2.7
total_secs = int((td.microseconds +
... |
Print a progress bar for longer-running scripts.
The progress value is a value between 0.0 and 1.0. If a prefix is
present, it will be printed before the progress bar. | def update_progress(self, progress, prefix=''):
"""
Print a progress bar for longer-running scripts.
The progress value is a value between 0.0 and 1.0. If a prefix is
present, it will be printed before the progress bar.
"""
total_length = 40
if progress == 1.:
... |
Return True if the log line has the nominated yaxis field. | def accept_line(self, logevent):
"""Return True if the log line has the nominated yaxis field."""
if self.regex_mode:
return bool(re.search(self.field, logevent.line_str))
else:
return getattr(logevent, self.field) is not None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.