INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Build a list of all options for a given command.
def _bash_comp_command(self, cmd, add_help=True): """Build a list of all options for a given command. Args: cmd (str): command name, set to None or '' for bare command. add_help (bool): add an help option. Returns: list of str: list of CLI options strings. ...
Write bash complete script.
def bash_complete(self, path, cmd, *cmds): """Write bash complete script. Args: path (path-like): desired path of the complete script. cmd (str): command name that should be completed. cmds (str): extra command names that should be completed. """ path...
Try to guess zsh version return ( 0 0 ) on failure.
def zsh_version(): """Try to guess zsh version, return (0, 0) on failure.""" try: out = subprocess.check_output(shlex.split('zsh --version')) except (FileNotFoundError, subprocess.CalledProcessError): return (0, 0) match = re.search(br'[0-9]+\.[0-9]+', out) return tuple(map(int, matc...
Starts a new HighFive master at the given host and port and returns it.
async def start_master(host="", port=48484, *, loop=None): """ Starts a new HighFive master at the given host and port, and returns it. """ loop = loop if loop is not None else asyncio.get_event_loop() manager = jobs.JobManager(loop=loop) workers = set() server = await loop.create_server( ...
Called when a remote worker connection has been found. Finishes setting up the protocol object.
def connection_made(self, transport): """ Called when a remote worker connection has been found. Finishes setting up the protocol object. """ if self._manager.is_closed(): logger.debug("worker tried to connect while manager was closed") return lo...
Called when a chunk of data is received from the remote worker. These chunks are stored in a buffer. When a complete line is found in the buffer it removed and sent to line_received ().
def data_received(self, data): """ Called when a chunk of data is received from the remote worker. These chunks are stored in a buffer. When a complete line is found in the buffer, it removed and sent to line_received(). """ self._buffer.extend(data) while True: ...
Called when a complete line is found from the remote worker. Decodes a response object from the line then passes it to the worker object.
def line_received(self, line): """ Called when a complete line is found from the remote worker. Decodes a response object from the line, then passes it to the worker object. """ response = json.loads(line.decode("utf-8")) self._worker.response_received(response)
Called when the connection to the remote worker is broken. Closes the worker.
def connection_lost(self, exc): """ Called when the connection to the remote worker is broken. Closes the worker. """ logger.debug("worker connection lost") self._worker.close() self._workers.remove(self._worker)
Called when a job has been found for the worker to run. Sends the job s RPC to the remote worker.
def _job_loaded(self, job): """ Called when a job has been found for the worker to run. Sends the job's RPC to the remote worker. """ logger.debug("worker {} found a job".format(id(self))) if self._closed: self._manager.return_job(job) return ...
Called when a response to a job RPC has been received. Decodes the response and finalizes the result then reports the result to the job manager.
def response_received(self, response): """ Called when a response to a job RPC has been received. Decodes the response and finalizes the result, then reports the result to the job manager. """ if self._closed: return assert self._job is not None ...
Closes the worker. No more jobs will be handled by the worker and any running job is immediately returned to the job manager.
def close(self): """ Closes the worker. No more jobs will be handled by the worker, and any running job is immediately returned to the job manager. """ if self._closed: return self._closed = True if self._job is not None: self._manager.r...
Runs a job set which consists of the jobs in an iterable job list.
def run(self, job_list): """ Runs a job set which consists of the jobs in an iterable job list. """ if self._closed: raise RuntimeError("master is closed") return self._manager.add_job_set(job_list)
Starts closing the HighFive master. The server will be closed and all queued job sets will be cancelled.
def close(self): """ Starts closing the HighFive master. The server will be closed and all queued job sets will be cancelled. """ if self._closed: return self._closed = True self._server.close() self._manager.close() for worker in se...
Called when a state change has occurred. Waiters are notified that a change has occurred.
def _change(self): """ Called when a state change has occurred. Waiters are notified that a change has occurred. """ for waiter in self._waiters: if not waiter.done(): waiter.set_result(None) self._waiters = []
Adds a new result.
def add(self, result): """ Adds a new result. """ assert not self._complete self._results.append(result) self._change()
Waits until the result set changes. Possible changes can be a result being added or the result set becoming complete. If the result set is already completed this method returns immediately.
async def wait_changed(self): """ Waits until the result set changes. Possible changes can be a result being added or the result set becoming complete. If the result set is already completed, this method returns immediately. """ if not self.is_complete(): wai...
If there is still a job in the job iterator loads it and increments the active job count.
def _load_job(self): """ If there is still a job in the job iterator, loads it and increments the active job count. """ try: next_job = next(self._jobs) except StopIteration: self._on_deck = None else: if not isinstance(next_jo...
Marks the job set as completed and notifies all waiting tasks.
def _done(self): """ Marks the job set as completed, and notifies all waiting tasks. """ self._results.complete() waiters = self._waiters for waiter in waiters: waiter.set_result(None) self._manager.job_set_done(self)
Gets a job from the job set if one is queued. The jobs_available () method should be consulted first to determine if a job can be obtained from a call to this method. If no jobs are available an IndexError is raised.
def get_job(self): """ Gets a job from the job set if one is queued. The jobs_available() method should be consulted first to determine if a job can be obtained from a call to this method. If no jobs are available, an IndexError is raised. """ if len(self._return...
Adds the result of a completed job to the result list then decrements the active job count. If the job set is already complete the result is simply discarded instead.
def add_result(self, result): """ Adds the result of a completed job to the result list, then decrements the active job count. If the job set is already complete, the result is simply discarded instead. """ if self._active_jobs == 0: return self._res...
Cancels the job set. The job set is immediately finished and all queued jobs are discarded.
def cancel(self): """ Cancels the job set. The job set is immediately finished, and all queued jobs are discarded. """ if self._active_jobs == 0: return self._jobs = iter(()) self._on_deck = None self._return_queue.clear() self._activ...
Waits until the job set is finished. Returns immediately if the job set is already finished.
async def wait_done(self): """ Waits until the job set is finished. Returns immediately if the job set is already finished. """ if self._active_jobs > 0: future = self._loop.create_future() self._waiters.append(future) await future
Distributes jobs from the active job set to any waiting get_job callbacks.
def _distribute_jobs(self): """ Distributes jobs from the active job set to any waiting get_job callbacks. """ while (self._active_js.job_available() and len(self._ready_callbacks) > 0): job = self._active_js.get_job() self._job_sources[jo...
Adds a job set to the manager s queue. If there is no job set running it is activated immediately. A new job set handle is returned.
def add_job_set(self, job_list): """ Adds a job set to the manager's queue. If there is no job set running, it is activated immediately. A new job set handle is returned. """ assert not self._closed results = Results(loop=self._loop) js = JobSet(job_list, result...
Calls the given callback function when a job becomes available.
def get_job(self, callback): """ Calls the given callback function when a job becomes available. """ assert not self._closed if self._active_js is None or not self._active_js.job_available(): self._ready_callbacks.append(callback) else: job = sel...
Returns a job to its source job set to be run again later.
def return_job(self, job): """ Returns a job to its source job set to be run again later. """ if self._closed: return js = self._job_sources[job] if len(self._ready_callbacks) > 0: callback = self._ready_callbacks.popleft() callback(j...
Adds the result of a job to the results list of the job s source job set.
def add_result(self, job, result): """ Adds the result of a job to the results list of the job's source job set. """ if self._closed: return js = self._job_sources[job] del self._job_sources[job] js.add_result(result)
Called when a job set has been completed or cancelled. If the job set was active the next incomplete job set is loaded from the job set queue and is activated.
def job_set_done(self, js): """ Called when a job set has been completed or cancelled. If the job set was active, the next incomplete job set is loaded from the job set queue and is activated. """ if self._closed: return if self._active_js != js: ...
Closes the job manager. No more jobs will be assigned no more job sets will be added and any queued or active job sets will be cancelled.
def close(self): """ Closes the job manager. No more jobs will be assigned, no more job sets will be added, and any queued or active job sets will be cancelled. """ if self._closed: return self._closed = True if self._active_js is not None: ...
External entry point which calls main () and if Stop is raised calls sys. exit ()
def entry_point(items=tuple()): """ External entry point which calls main() and if Stop is raised, calls sys.exit() """ try: if not items: from .example import ExampleCommand from .version import Version items = [(ExampleCommand.NAME, ExampleCommand), ...
Remove duplicates in a list.
def _uniquify(_list): """Remove duplicates in a list.""" seen = set() result = [] for x in _list: if x not in seen: result.append(x) seen.add(x) return result
Returns true if the regex matches the object or a string in the object if it is some sort of container.
def _match_regex(regex, obj): """ Returns true if the regex matches the object, or a string in the object if it is some sort of container. :param regex: A regex. :type regex: ``regex`` :param obj: An arbitrary object. :type object: ``object`` :rtype: ``bool`` """ if isinstance(...
Lists all available instances.
def get_entries(latest, filters, exclude, limit=None): """ Lists all available instances. :param latest: If true, ignores the cache and grabs the latest list. :type latest: ``bool`` :param filters: Filters to apply to results. A result will only be shown if it includes all text ...
Use the environment to get the current region
def get_region(): """Use the environment to get the current region""" global _REGION if _REGION is None: region_name = os.getenv("AWS_DEFAULT_REGION") or "us-east-1" region_dict = {r.name: r for r in boto.regioninfo.get_regions("ec2")} if region_name not in region_dict: r...
Returns if the cache is valid ( exists and modified within the interval ).: return: Whether the cache is valid.: rtype: bool
def _is_valid_cache(): """ Returns if the cache is valid (exists and modified within the interval). :return: Whether the cache is valid. :rtype: ``bool`` """ if not os.path.exists(get_cache_location()): return False modified = os.path.getmtime(get_cache_location()) modified = tim...
Reads the description cache returning each instance s information.: return: A list of host entries.: rtype: [: py: class: HostEntry ]
def _list_all_cached(): """ Reads the description cache, returning each instance's information. :return: A list of host entries. :rtype: [:py:class:`HostEntry`] """ with open(get_cache_location()) as f: contents = f.read() objects = json.loads(contents) return [HostEntry....
Filters a list of host entries according to the given filters.
def filter_entries(entries, filters, exclude): """ Filters a list of host entries according to the given filters. :param entries: A list of host entries. :type entries: [:py:class:`HostEntry`] :param filters: Regexes that must match a `HostEntry`. :type filters: [``str``] :param exclude: Re...
Prints the public dns name of name if it exists.
def get_host(name): """ Prints the public dns name of `name`, if it exists. :param name: The instance name. :type name: ``str`` """ f = {'instance-state-name': 'running', 'tag:Name': name} ec2 = boto.connect_ec2(region=get_region()) rs = ec2.get_all_instances(filters=f) if len(rs) =...
Deserialize a HostEntry from a dictionary.
def from_dict(cls, entry_dict): """Deserialize a HostEntry from a dictionary. This is more or less the same as calling HostEntry(**entry_dict), but is clearer if something is missing. :param entry_dict: A dictionary in the format outputted by to_dict(). :type entry_dict...
Given an attribute name looks it up on the entry. Names that start with tags. are looked up in the tags dictionary.
def _get_attrib(self, attr, convert_to_str=False): """ Given an attribute name, looks it up on the entry. Names that start with ``tags.`` are looked up in the ``tags`` dictionary. :param attr: Name of attribute to look up. :type attr: ``str`` :param convert_to_str: Conve...
Lists all of the attributes to be found on an instance of this class. It creates a fake instance by passing in None to all of the __init__ arguments then returns all of the attributes of that instance.
def list_attributes(cls): """ Lists all of the attributes to be found on an instance of this class. It creates a "fake instance" by passing in `None` to all of the ``__init__`` arguments, then returns all of the attributes of that instance. :return: A list of instance at...
Sorts a list of entries by the given attribute.
def sort_by(cls, entries, attribute): """ Sorts a list of entries by the given attribute. """ def key(entry): return entry._get_attrib(attribute, convert_to_str=True) return sorted(entries, key=key)
Returns a representation of the host as a single line with columns joined by sep.
def repr_as_line(self, additional_columns=None, only_show=None, sep=','): """ Returns a representation of the host as a single line, with columns joined by ``sep``. :param additional_columns: Columns to show in addition to defaults. :type additional_columns: ``list`` of ``str`` ...
Loads a HostEntry from a boto instance.
def from_boto_instance(cls, instance): """ Loads a ``HostEntry`` from a boto instance. :param instance: A boto instance object. :type instance: :py:class:`boto.ec2.instanceInstance` :rtype: :py:class:`HostEntry` """ return cls( name=instance.tags.get...
Returns whether the instance matches the given filter text.
def matches(self, _filter): """ Returns whether the instance matches the given filter text. :param _filter: A regex filter. If it starts with `<identifier>:`, then the part before the colon will be used as an attribute and the part after will be a...
Returns the best name to display for this host. Uses the instance name if available ; else just the public IP.
def display(self): """ Returns the best name to display for this host. Uses the instance name if available; else just the public IP. :rtype: ``str`` """ if isinstance(self.name, six.string_types) and len(self.name) > 0: return '{0} ({1})'.format(self.name, se...
Returns the pretty name ( capitalized etc ) of an attribute by looking it up in cls. COLUMN_NAMES if it exists there.
def prettyname(cls, attrib_name): """ Returns the "pretty name" (capitalized, etc) of an attribute, by looking it up in ``cls.COLUMN_NAMES`` if it exists there. :param attrib_name: An attribute name. :type attrib_name: ``str`` :rtype: ``str`` """ if attr...
Takes a string containing 0 or more { variables } and formats it according to this instance s attributes.
def format_string(self, fmat_string): """ Takes a string containing 0 or more {variables} and formats it according to this instance's attributes. :param fmat_string: A string, e.g. '{name}-foo.txt' :type fmat_string: ``str`` :return: The string formatted according to th...
Pretty - prints a list of entries. If the window is wide enough to support printing as a table runs the print_table. render_table function on the table. Otherwise constructs a line - by - line representation..
def render_entries(cls, entries, additional_columns=None, only_show=None, numbers=False): """ Pretty-prints a list of entries. If the window is wide enough to support printing as a table, runs the `print_table.render_table` function on the table. Otherwise, constru...
Attach the event time as unix epoch
def add_timestamp(logger_class, log_method, event_dict): ''' Attach the event time, as unix epoch ''' event_dict['timestamp'] = calendar.timegm(time.gmtime()) return event_dict
Hivy formated logger
def setup(level='debug', output=None): ''' Hivy formated logger ''' output = output or settings.LOG['file'] level = level.upper() handlers = [ logbook.NullHandler() ] if output == 'stdout': handlers.append( logbook.StreamHandler(sys.stdout, ...
Configure and return a new logger for hivy modules
def logger(name=__name__, output=None, uuid=False, timestamp=False): ''' Configure and return a new logger for hivy modules ''' processors = [] if output == 'json': processors.append(structlog.processors.JSONRenderer()) if uuid: processors.append(add_unique_id) if uuid: proc...
Implement celery workers using json and redis
def setup(title, output='json', timezone=None): ''' Implement celery workers using json and redis ''' timezone = timezone or dna.time_utils._detect_timezone() broker_url = 'redis://{}:{}/{}'.format( os.environ.get('BROKER_HOST', 'localhost'), os.environ.get('BROKER_PORT', 6379), 0 ...
Return status report
def get(self, worker_id): ''' Return status report ''' code = 200 if worker_id == 'all': report = {'workers': [{ 'id': job, 'report': self._inspect_worker(job)} for job in self.jobs] } elif worker_id in self.jobs: ...
Stop and remove a worker
def delete(self, worker_id): ''' Stop and remove a worker ''' code = 200 if worker_id in self.jobs: # NOTE pop it if done ? self.jobs[worker_id]['worker'].revoke(terminate=True) report = { 'id': worker_id, 'revoked': True ...
Reusable entry point. Arguments are parsed via the argparse - subcommands configured via each Command class found in globals (). Stop exceptions are propagated to callers.
def main(fw_name, args=None, items=None): """ Reusable entry point. Arguments are parsed via the argparse-subcommands configured via each Command class found in globals(). Stop exceptions are propagated to callers. The name of the framework will be used in logging and similar. """ ...
Define a switchable ConfOpt.
def switch_opt(default, shortname, help_msg): """Define a switchable ConfOpt. This creates a boolean option. If you use it in your CLI, it can be switched on and off by prepending + or - to its name: +opt / -opt. Args: default (bool): the default value of the swith option. shortname (s...
Define a configuration section handling config file.
def config_conf_section(): """Define a configuration section handling config file. Returns: dict of ConfOpt: it defines the 'create', 'update', 'edit' and 'editor' configuration options. """ config_dict = OrderedDict(( ('create', ConfOpt(None, True, None, {'action': ...
Set options from a list of section. option = value string.
def set_conf_str(conf, optstrs): """Set options from a list of section.option=value string. Args: conf (:class:`~loam.manager.ConfigurationManager`): the conf to update. optstrs (list of str): the list of 'section.option=value' formatted string. """ falsy = ['0', 'no', 'n', ...
Implement the behavior of a subcmd using config_conf_section
def config_cmd_handler(conf, config='config'): """Implement the behavior of a subcmd using config_conf_section Args: conf (:class:`~loam.manager.ConfigurationManager`): it should contain a section created with :func:`config_conf_section` function. config (str): name of the configura...
Create completion files for bash and zsh.
def create_complete_files(climan, path, cmd, *cmds, zsh_sourceable=False): """Create completion files for bash and zsh. Args: climan (:class:`~loam.cli.CLIManager`): CLI manager. path (path-like): directory in which the config files should be created. It is created if it doesn't exi...
Renders a list of columns.
def render_columns(columns, write_borders=True, column_colors=None): """ Renders a list of columns. :param columns: A list of columns, where each column is a list of strings. :type columns: [[``str``]] :param write_borders: Whether to write the top and bottom borders. :type write_borders: ``boo...
Render the num th row of each column in columns.
def render_row(num, columns, widths, column_colors=None): """ Render the `num`th row of each column in `columns`. :param num: Which row to render. :type num: ``int`` :param columns: The list of columns. :type columns: [[``str``]] :param widths: The widths of each column. :type widths: [...
Renders a table. A table is a list of rows each of which is a list of arbitrary objects. The. str method will be called on each element of the row. Jagged tables are ok ; in this case each row will be expanded to the maximum row length.
def render_table(table, write_borders=True, column_colors=None): """ Renders a table. A table is a list of rows, each of which is a list of arbitrary objects. The `.str` method will be called on each element of the row. Jagged tables are ok; in this case, each row will be expanded to the maximum row...
Transposes a table turning rows into columns.: param table: A 2D string grid.: type table: [[ str ]]
def transpose_table(table): """ Transposes a table, turning rows into columns. :param table: A 2D string grid. :type table: [[``str``]] :return: The same table, with rows and columns flipped. :rtype: [[``str``]] """ if len(table) == 0: return table else: num_columns ...
Prepare the rows so they re all strings and all the same length.
def prepare_rows(table): """ Prepare the rows so they're all strings, and all the same length. :param table: A 2D grid of anything. :type table: [[``object``]] :return: A table of strings, where every row is the same length. :rtype: [[``str``]] """ num_columns = max(len(row) for row in...
Gets the width of the table that would be printed.: rtype: int
def get_table_width(table): """ Gets the width of the table that would be printed. :rtype: ``int`` """ columns = transpose_table(prepare_rows(table)) widths = [max(len(cell) for cell in column) for column in columns] return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')
Returns a function that colors a string with a number from 0 to 255.
def color(number): """ Returns a function that colors a string with a number from 0 to 255. """ if supports_256(): template = "\033[38;5;{number}m{text}\033[0m" else: template = "\033[{number}m{text}\033[0m" def _color(text): if not all([sys.stdout.isatty(), sys.stderr.is...
Hashes a string and returns a number between min and max.
def get_color_hash(string, _min=MIN_COLOR_BRIGHT, _max=MAX_COLOR_BRIGHT): """ Hashes a string and returns a number between ``min`` and ``max``. """ hash_num = int(hashlib.sha1(string.encode('utf-8')).hexdigest()[:6], 16) _range = _max - _min num_in_range = hash_num % _range return color(_min...
Returns a random color between min and max.
def random_color(_min=MIN_COLOR, _max=MAX_COLOR): """Returns a random color between min and max.""" return color(random.randint(_min, _max))
Reads stdin exits with a message if interrupted EOF or a quit message.
def get_input(prompt, default=None, exit_msg='bye!'): """ Reads stdin, exits with a message if interrupted, EOF, or a quit message. :return: The entered input. Converts to an integer if possible. :rtype: ``str`` or ``int`` """ try: response = six.moves.input(prompt) except (Keyboard...
Verify basic http authentification
def check_credentials(username, password): ''' Verify basic http authentification ''' user = models.User.objects( username=username, password=password ).first() return user or None
Verify http header token authentification
def check_token(token): ''' Verify http header token authentification ''' user = models.User.objects(api_key=token).first() return user or None
Flask decorator protecting ressources using username/ password scheme
def requires_basic_auth(resource): ''' Flask decorator protecting ressources using username/password scheme ''' @functools.wraps(resource) def decorated(*args, **kwargs): ''' Check provided username/password ''' auth = flask.request.authorization user = check_credentials(auth...
Flask decorator protecting ressources using token scheme
def requires_token_auth(resource): ''' Flask decorator protecting ressources using token scheme ''' @functools.wraps(resource) def decorated(*args, **kwargs): ''' Check provided token ''' token = flask.request.headers.get('Authorization') user = check_token(token) if...
pgrep returns an error code if no process was found
def is_running(process): ''' `pgrep` returns an error code if no process was found ''' try: pgrep = sh.Command('/usr/bin/pgrep') pgrep(process) flag = True except sh.ErrorReturnCode_1: flag = False return flag
Take a string and return the corresponding module
def dynamic_import(mod_path, obj_name=None): ''' Take a string and return the corresponding module ''' try: module = __import__(mod_path, fromlist=['whatever']) except ImportError, error: raise errors.DynamicImportFailed( module='.'.join([mod_path, obj_name]), reason=error) #...
Utility for logbook information injection
def self_ip(public=False): ''' Utility for logbook information injection ''' try: if public: data = str(urlopen('http://checkip.dyndns.com/').read()) ip_addr = re.compile( r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1) else: sock = soc...
Makes the HTTP request using RESTClient.
def request(self, method, url, query_params=None, headers=None, post_params=None, body=None): """ Makes the HTTP request using RESTClient. """ if method == "GET": return self.rest_client.GET(url, query_params=query_param...
Builds form parameters.
def prepare_post_parameters(self, post_params=None, files=None): """ Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. :return: Form parameters with files. """ params = {} if post_params: param...
Configure from cli and run the server
def serve(self, app_docopt=DEFAULT_DOC, description=''): ''' Configure from cli and run the server ''' exit_status = 0 if isinstance(app_docopt, str): args = docopt(app_docopt, version=description) elif isinstance(app_docopt, dict): args = app_docopt else...
Include a hidden input to stored the serialized upload value.
def render(self, name, value, attrs=None): """Include a hidden input to stored the serialized upload value.""" context = attrs or {} context.update({'name': name, 'value': value, }) return render_to_string(self.template_name, context)
Starts command in a subprocess. Prints every line the command prints prefaced with description.
def stream_command(command, formatter=None, write_stdin=None, ignore_empty=False): """ Starts `command` in a subprocess. Prints every line the command prints, prefaced with `description`. :param command: The bash command to run. Must use fully-qualified paths. :type command: ``str`` :param form...
Takes a list of dictionaries with keys corresponding to stream_command arguments and runs all concurrently.
def stream_command_dicts(commands, parallel=False): """ Takes a list of dictionaries with keys corresponding to ``stream_command`` arguments, and runs all concurrently. :param commands: A list of dictionaries, the keys of which should line up with the arguments to ``stream_command`...
Runs multiple commands optionally in parallel. Each command should be a dictionary with a command key and optionally description and write_stdin keys.
def stream_commands(commands, hash_colors=True, parallel=False): """ Runs multiple commands, optionally in parallel. Each command should be a dictionary with a 'command' key and optionally 'description' and 'write_stdin' keys. """ def _get_color(string): if hash_colors is True: ...
Return the net work days according to RH s calendar.
def networkdays(from_date, to_date, locale='en-US'): """ Return the net work days according to RH's calendar. """ holidays = locales[locale] return workdays.networkdays(from_date, to_date, holidays)
Recursive dict merge. Inspired by: meth: dict. update () instead of updating only top - level keys dict_merge recurses down into dicts nested to an arbitrary depth updating keys. The other is merged into dicto.: param dicto: dict onto which the merge is executed: param other: dict that is going to merged into dicto: re...
def merge(dicto, other): """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``other`` is merged into ``dicto``. :param dicto: dict onto which the merge is execute...
Lets the user choose which instance to SSH into.
def _run_ssh(entries, username, idfile, no_prompt=False, command=None, show=None, only=None, sort_by=None, limit=None, tunnel=None, num=None, random=False): """ Lets the user choose which instance to SSH into. :param entries: The list of host entries. :type entries: [:py:class...
Queries bash to find the path to a commmand on the system.
def _get_path(cmd): """Queries bash to find the path to a commmand on the system.""" if cmd in _PATHS: return _PATHS[cmd] out = subprocess.check_output('which {}'.format(cmd), shell=True) _PATHS[cmd] = out.decode("utf-8").strip() return _PATHS[cmd]
Uses hostname and other info to construct an SSH command.
def _build_ssh_command(hostname, username, idfile, ssh_command, tunnel): """Uses hostname and other info to construct an SSH command.""" command = [_get_path('ssh'), '-o', 'StrictHostKeyChecking=no', '-o', 'ConnectTimeout=5'] if idfile is not None: command.extend(['-i',...
Uses hostname and other info to construct an SCP command.
def _build_scp_command(hostname, username, idfile, is_get, local_path, remote_path): """ Uses hostname and other info to construct an SCP command. :param hostname: The hostname of the remote machine. :type hostname: ``str`` :param username: The username to use on the remote m...
Performs an SCP command where the remote_path is the target and the local_path is the source.
def _copy_to(entries, remote_path, local_path, profile): """ Performs an SCP command where the remote_path is the target and the local_path is the source. :param entries: A list of entries. :type entries: ``list`` of :py:class:`HostEntry` :param remote_path: The target path on the remote machin...
Performs an SCP command where the remote_path is the source and the local_path is a format string formatted individually for each host being copied from so as to create one or more distinct paths on the local system.
def _copy_from(entries, remote_path, local_path, profile): """ Performs an SCP command where the remote_path is the source and the local_path is a format string, formatted individually for each host being copied from so as to create one or more distinct paths on the local system. :param entries...
Runs the given command over SSH in parallel on all hosts in entries.
def _run_ssh_command(entries, username, idfile, command, tunnel, parallel=False): """ Runs the given command over SSH in parallel on all hosts in `entries`. :param entries: The host entries the hostnames from. :type entries: ``list`` of :py:class:`HostEntry` :param username: To...
SSH into to a host.
def _connect_ssh(entry, username, idfile, tunnel=None): """ SSH into to a host. :param entry: The host entry to pull the hostname from. :type entry: :py:class:`HostEntry` :param username: To use a specific username. :type username: ``str`` or ``NoneType`` :param idfile: The SSH identity fil...
Parse command - line arguments.
def _get_args(): """Parse command-line arguments.""" parser = argparse.ArgumentParser(description='List EC2 instances') parser.add_argument('-l', '--latest', action='store_true', default=False, help='Query AWS for latest instances') parser.add_argument('--version', action='store_...
Loads the user s LSI profile or provides a default.
def load(cls, profile_name=None): """Loads the user's LSI profile, or provides a default.""" lsi_location = os.path.expanduser('~/.lsi') if not os.path.exists(lsi_location): return LsiProfile() cfg_parser = ConfigParser() cfg_parser.read(lsi_location) if profi...
Takes arguments parsed from argparse and returns a profile.
def from_args(args): """Takes arguments parsed from argparse and returns a profile.""" # If the args specify a username explicitly, don't load from file. if args.username is not None or args.identity_file is not None: profile = LsiProfile() else: profile = LsiProf...
Recursive dict merge. Inspired by: meth: dict. update () instead of updating only top - level keys dict_merge recurses down into dicts nested to an arbitrary depth updating keys. The merge_dct is merged into self.: param self: dict onto which the merge is executed: param merge_dct: self merged into self: return: None
def merge_(self, merge_dct): """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``merge_dct`` is merged into ``self``. :param self: dict onto ...
Relate this package component to the supplied part.
def relate(self, part, id=None): """Relate this package component to the supplied part.""" assert part.name.startswith(self.base) name = part.name[len(self.base):].lstrip('/') rel = Relationship(self, name, part.rel_type, id=id) self.relationships.add(rel) return rel