desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Connect to hosts in hosts list. Returns status of connect as a dict. :param raise_on_any_error: Optional Raise an exception even if connecting to one of the hosts fails. :type raise_on_any_error: ``boolean`` :rtype: ``dict`` of ``str`` to ``dict``'
def connect(self, raise_on_any_error=False):
results = {} for host in self._hosts: while (not self._pool.free()): eventlet.sleep(self._scan_interval) self._pool.spawn(self._connect, host=host, results=results, raise_on_any_error=raise_on_any_error) self._pool.waitall() if (self._successful_connects < 1): LOG.err...
'Run a command on remote hosts. Returns a dict containing results of execution from all hosts. :param cmd: Command to run. Must be shlex quoted. :type cmd: ``str`` :param timeout: Optional Timeout for the command. :type timeout: ``int`` :param cwd: Optional Current working directory. Must be shlex quoted. :type cwd: ``...
def run(self, cmd, timeout=None):
options = {'cmd': cmd, 'timeout': timeout} results = self._execute_in_pool(self._run_command, **options) return results
'Copy a file or folder to remote host. :param local_path: Path to local file or dir. Must be shlex quoted. :type local_path: ``str`` :param remote_path: Path to remote file or dir. Must be shlex quoted. :type remote_path: ``str`` :param mode: Optional mode to use for the file or dir. :type mode: ``int`` :param mirror_l...
def put(self, local_path, remote_path, mode=None, mirror_local_mode=False):
if (not os.path.exists(local_path)): raise Exception(('Local path %s does not exist.' % local_path)) options = {'local_path': local_path, 'remote_path': remote_path, 'mode': mode, 'mirror_local_mode': mirror_local_mode} return self._execute_in_pool(self._put_files, **options)
'Create a directory on remote hosts. :param path: Path to remote dir that must be created. Must be shlex quoted. :type path: ``str`` :rtype path: ``dict`` of ``str`` to ``dict``'
def mkdir(self, path):
options = {'path': path} return self._execute_in_pool(self._mkdir, **options)
'Delete a file on remote hosts. :param path: Path to remote file that must be deleted. Must be shlex quoted. :type path: ``str`` :rtype path: ``dict`` of ``str`` to ``dict``'
def delete_file(self, path):
options = {'path': path} return self._execute_in_pool(self._delete_file, **options)
'Delete a dir on remote hosts. :param path: Path to remote dir that must be deleted. Must be shlex quoted. :type path: ``str`` :rtype path: ``dict`` of ``str`` to ``dict``'
def delete_dir(self, path, force=False, timeout=None):
options = {'path': path, 'force': force} return self._execute_in_pool(self._delete_dir, **options)
'Close all open SSH connections to hosts.'
def close(self):
for host in self._hosts_client.keys(): try: self._hosts_client[host].close() except: LOG.exception('Failed shutting down SSH connection to host: %s', host)
'Remove any potentially sensitive information from the command string. For now we only mask the values of the sensitive environment variables.'
@staticmethod def _sanitize_command_string(cmd):
if (not cmd): return cmd result = re.sub('ST2_ACTION_AUTH_TOKEN=(.+?)\\s+?', ('ST2_ACTION_AUTH_TOKEN=%s ' % MASKED_ATTRIBUTE_VALUE), cmd) return result
':param exc: Raised exception. :type exc: Exception. :param message: Error message which will be prefixed to the exception exception message. :type message: ``str``'
@staticmethod def _generate_error_result(exc, message):
exc_message = getattr(exc, 'message', str(exc)) error_message = ('%s %s' % (message, exc_message)) traceback_message = traceback.format_exc() if isinstance(exc, SSHCommandTimeoutError): return_code = (-9) timeout = True else: timeout = False return_code = 255 s...
'Apply the policy before the target do work. :param target: The instance of the resource being affected by this policy. :type target: ``object`` :rtype: ``object``'
def apply_before(self, target):
if (not coordination.configured()): LOG.warn('Coordination service is not configured. Policy enforcement is best effort.') return target
'Apply the policy after the target does work. :param target: The instance of the resource being affected by this policy. :type target: ``object`` :rtype: ``object``'
def apply_after(self, target):
if (not coordination.configured()): LOG.warn('Coordination service is not configured. Policy enforcement is best effort.') return target
'Return a safe string which can be used as a lock name. :param values: Dictionary with values to use in the lock name. :type values: ``dict`` :rtype: ``st``'
def _get_lock_name(self, values):
lock_uid = [] for (key, value) in six.iteritems(values): lock_uid.append(('%s=%s' % (key, value))) lock_uid = ','.join(lock_uid) return lock_uid
'Assign dynamic config value for a particular config item if the ite utilizes a Jinja expression for dynamic config values. Note: This method mutates config argument in place. :rtype: ``dict``'
def _assign_dynamic_config_values(self, schema, config, parent_keys=None):
parent_keys = (parent_keys or []) for (config_item_key, config_item_value) in six.iteritems(config): schema_item = schema.get(config_item_key, {}) is_dictionary = isinstance(config_item_value, dict) if is_dictionary: parent_keys += [config_item_key] self._assign_d...
'Assign default values for particular config if default values are provided in the config schema and a value is not specified in the config. Note: This method mutates config argument in place. :rtype: ``dict``'
def _assign_default_values(self, schema, config):
for (schema_item_key, schema_item) in six.iteritems(schema): has_default_value = ('default' in schema_item) has_config_value = (schema_item_key in config) default_value = schema_item.get('default', None) is_object = (schema_item.get('type', None) == 'object') has_properties =...
'Retrieve datastore value by first resolving the datastore expression and then retrieving the value from the datastore. :param key: Full path to the config item key (e.g. "token" / "auth.settings.token", etc.)'
def _get_datastore_value_for_expression(self, key, value, config_schema_item=None):
from st2common.services.config import deserialize_key_value config_schema_item = (config_schema_item or {}) secret = config_schema_item.get('secret', False) try: value = render_template_with_system_and_user_context(value=value, user=self.user) except Exception as e: exc_class = type(...
'Retrieve config for a particular pack. :return: Config object if config is found, ``None`` otherwise. :rtype: :class:`.ContentPackConfig` or ``None``'
def get_config(self):
global_config_path = self.get_global_config_path() config = self.get_and_parse_config(config_path=global_config_path) return config
'Retrieve config for a particular action inside the content pack. :param action_file_path: Full absolute path to the action file. :type action_file_path: ``str`` :return: Config object if config is found, ``None`` otherwise. :rtype: :class:`.ContentPackConfig` or ``None``'
def get_action_config(self, action_file_path):
global_config_path = self.get_global_config_path() config = self.get_and_parse_config(config_path=global_config_path) return config
'Retrieve config for a particular sensor inside the content pack. :param sensor_file_path: Full absolute path to the sensor file. :type sensor_file_path: ``str`` :return: Config object if config is found, ``None`` otherwise. :rtype: :class:`.ContentPackConfig` or ``None``'
def get_sensor_config(self, sensor_file_path):
global_config_path = self.get_global_config_path() config = self.get_and_parse_config(config_path=global_config_path) return config
'Called before acknowleding a message. Good place to track the message via a DB entry or some other applicable mechnism. The reponse of this method is passed into the ``process`` method. This was whatever is the processed version of the message can be moved forward. It is always possible to simply return ``message`` an...
@abc.abstractmethod def pre_ack_process(self, message):
pass
'Run the wrapped_callback in a protective covering of retries and error handling. :param connection: Connection to messaging service :type connection: kombu.connection.Connection :param wrapped_callback: Callback that will be wrapped by all the fine handling in this method. Expected signature of callback - ``def func(c...
def run(self, connection, wrapped_callback):
should_stop = False channel = None while (not should_stop): try: channel = connection.channel() wrapped_callback(connection=connection, channel=channel) should_stop = True except (connection.connection_errors + connection.channel_errors) as e: ...
'Ensure that recoverable errors are retried a set number of times before giving up. :param connection: Connection to messaging service :type connection: kombu.connection.Connection :param obj: Object whose method is to be ensured. Typically, channel, producer etc. from the kombu library. :type obj: Must support mixin k...
def ensured(self, connection, obj, to_ensure_func, **kwargs):
ensuring_func = connection.ensure(obj, to_ensure_func, errback=self.errback, max_retries=3) ensuring_func(**kwargs)
'Method which dispatches the trigger. :param trigger: Full name / reference of the trigger. :type trigger: ``str`` or ``object`` :param payload: Trigger payload. :type payload: ``dict`` :param trace_context: Trace context to associate with Trigger. :type trace_context: ``TraceContext``'
def dispatch(self, trigger, payload=None, trace_context=None):
assert isinstance(payload, (type(None), dict)) assert isinstance(trace_context, (type(None), TraceContext)) payload = {'trigger': trigger, 'payload': payload, TRACE_CONTEXT: trace_context} routing_key = 'trigger_instance' self._logger.debug('Dispatching trigger (trigger=%s,payload=%s)', trigge...
'Method which dispatches the announcement. :param routing_key: Routing key of the announcement. :type routing_key: ``str`` :param payload: Announcement payload. :type payload: ``dict`` :param trace_context: Trace context to associate with Announcement. :type trace_context: ``TraceContext``'
def dispatch(self, routing_key, payload, trace_context=None):
assert isinstance(payload, (type(None), dict)) assert isinstance(trace_context, (type(None), dict, TraceContext)) payload = {'payload': payload, TRACE_CONTEXT: trace_context} self._logger.debug('Dispatching announcement (routing_key=%s,payload=%s)', routing_key, payload) self._publisher.publis...
':param create_handler: Function which is called on SensorDB create event. :type create_handler: ``callable`` :param update_handler: Function which is called on SensorDB update event. :type update_handler: ``callable`` :param delete_handler: Function which is called on SensorDB delete event. :type delete_handler: ``cal...
def __init__(self, create_handler, update_handler, delete_handler, queue_suffix=None):
self._create_handler = create_handler self._update_handler = update_handler self._delete_handler = delete_handler self._sensor_watcher_q = self._get_queue(queue_suffix) self.connection = None self._updates_thread = None self._handlers = {publishers.CREATE_RK: create_handler, publishers.UPDAT...
':param create_handler: Function which is called on TriggerDB create event. :type create_handler: ``callable`` :param update_handler: Function which is called on TriggerDB update event. :type update_handler: ``callable`` :param delete_handler: Function which is called on TriggerDB delete event. :type delete_handler: ``...
def __init__(self, create_handler, update_handler, delete_handler, trigger_types=None, queue_suffix=None, exclusive=False):
self._create_handler = create_handler self._update_handler = update_handler self._delete_handler = delete_handler self._trigger_types = trigger_types self._trigger_watch_q = self._get_queue(queue_suffix, exclusive=exclusive) self.connection = None self._load_thread = None self._updates_t...
'Retrieve all the datastores items. :param local: List values from a namespace local to this pack/class. Defaults to True. :type: local: ``bool`` :param prefix: Optional key name prefix / startswith filter. :type prefix: ``str`` :rtype: ``list`` of :class:`KeyValuePair`'
def list_values(self, local=True, prefix=None):
client = self._get_api_client() self._logger.audit('Retrieving all the value from the datastore') key_prefix = self._get_full_key_prefix(local=local, prefix=prefix) kvps = client.keys.get_all(prefix=key_prefix) return kvps
'Retrieve a value from the datastore for the provided key. By default, value is retrieved from the namespace local to the pack/class. If you want to retrieve a global value from a datastore, pass local=False to this method. :param name: Key name. :type name: ``str`` :param local: Retrieve value from a namespace local t...
def get_value(self, name, local=True, scope=SYSTEM_SCOPE, decrypt=False):
if (scope != SYSTEM_SCOPE): raise ValueError(('Scope %s is unsupported.' % scope)) name = self._get_full_key_name(name=name, local=local) client = self._get_api_client() self._logger.audit('Retrieving value from the datastore (name=%s)', name) try: params = {'...
'Set a value for the provided key. By default, value is set in a namespace local to the pack/class. If you want to set a global value, pass local=False to this method. :param name: Key name. :type name: ``str`` :param value: Key value. :type value: ``str`` :param ttl: Optional TTL (in seconds). :type ttl: ``int`` :para...
def set_value(self, name, value, ttl=None, local=True, scope=SYSTEM_SCOPE, encrypt=False):
if (scope != SYSTEM_SCOPE): raise ValueError('Scope %s is unsupported.', scope) name = self._get_full_key_name(name=name, local=local) value = str(value) client = self._get_api_client() self._logger.audit('Setting value in the datastore (name=%s)', name) instance ...
'Delete the provided key. By default, value is deleted from a namespace local to the pack/class. If you want to delete a global value, pass local=False to this method. :param name: Name of the key to delete. :type name: ``str`` :param local: Delete a value in a namespace local to the pack/class. Defaults to True. :type...
def delete_value(self, name, local=True, scope=SYSTEM_SCOPE):
if (scope != SYSTEM_SCOPE): raise ValueError('Scope %s is unsupported.', scope) name = self._get_full_key_name(name=name, local=local) client = self._get_api_client() instance = KeyValuePair() instance.id = name instance.name = name self._logger.audit('Deleting value f...
'Retrieve API client instance.'
def _get_api_client(self):
token_expire = (self._token_expire <= get_datetime_utc_now()) if ((not self._client) or token_expire): self._logger.audit('Creating new Client object.') ttl = cfg.CONF.auth.service_token_ttl self._token_expire = (get_datetime_utc_now() + timedelta(seconds=ttl)) temporary...
'Retrieve a full key name. :rtype: ``str``'
def _get_full_key_name(self, name, local):
if local: name = self._get_key_name_with_prefix(name=name) return name
'Retrieve key prefix which is local to this pack/class.'
def _get_local_key_name_prefix(self):
key_prefix = (self._get_datastore_key_prefix() + self.DATASTORE_NAME_SEPARATOR) return key_prefix
'Retrieve a full key name which is local to the current pack/class. :param name: Base datastore key name. :type name: ``str`` :rtype: ``str``'
def _get_key_name_with_prefix(self, name):
prefix = self._get_datastore_key_prefix() full_name = ((prefix + self.DATASTORE_NAME_SEPARATOR) + name) return full_name
'This is the method individual queriers must implement. This method should return a tuple of (status, results). status should be one of LIVEACTION_STATUS_SUCCEEDED, LIVEACTION_STATUS_RUNNING, LIVEACTION_STATUS_FAILED defined in st2common.constants.action.'
def query(self, execution_id, query_context, last_query_time=None):
pass
'Returns the path to the hg executable :return: The string path to the executable or False on error'
def retrieve_binary(self):
name = 'hg' if (os.name == 'nt'): name += '.exe' binary = self.find_binary(name) if (not binary): show_error(u'\n Unable to find %s.\n\n Please set ...
'Updates the repository with remote changes :return: False or error, or True on success'
def run(self):
binary = self.retrieve_binary() if (not binary): return False args = [binary] args.extend(self.update_command) args.append('default') self.execute(args, self.working_copy, meaningful_output=True) return True
':return: bool if remote revisions are available'
def incoming(self):
cache_key = (self.working_copy + '.incoming') incoming = get_cache(cache_key) if (incoming is not None): return incoming binary = self.retrieve_binary() if (not binary): return False args = [binary, 'in', '-q', 'default'] output = self.execute(args, self.working_copy, meaning...
':return: The latest commit hash'
def latest_commit(self):
binary = self.retrieve_binary() if (not binary): return False args = [binary, 'id', '-i'] output = self.execute(args, self.working_copy) if (output is False): return False return output.strip()
'Returns the path to the git executable :return: The string path to the executable or False on error'
def retrieve_binary(self):
name = 'git' if (os.name == 'nt'): name += '.exe' binary = self.find_binary(name) if (not binary): show_error(u'\n Unable to find %s.\n\n Please set ...
'Updates the repository with remote changes :return: False or error, or True on success'
def run(self):
binary = self.retrieve_binary() if (not binary): return False info = self.get_working_copy_info() if (info is False): return False args = [binary] args.extend(self.update_command) args.extend([info['remote'], info['remote_branch']]) self.execute(args, self.working_copy, m...
':return: bool if remote revisions are available'
def incoming(self):
cache_key = (self.working_copy + '.incoming') incoming = get_cache(cache_key) if (incoming is not None): return incoming binary = self.retrieve_binary() if (not binary): return False info = self.get_working_copy_info() if (info is False): return False res = self.e...
':return: The latest commit hash'
def latest_commit(self):
binary = self.retrieve_binary() if (not binary): return False args = [binary, 'rev-parse', '--short', 'HEAD'] output = self.execute(args, self.working_copy) if (output is False): return False return output.strip()
'Quick panel user selection handler - enables the selected package :param picked: An integer of the 0-based package name index from the presented list. -1 means the user cancelled.'
def on_done(self, picked):
if (picked == (-1)): return package = self.disabled_packages[picked] self.reenable_package(package, 'enable') sublime.status_message(text.format('\n Package %s successfully removed from list of disabled packages -\n ...
'Input panel handler - adds the provided URL as a channel :param input: A string of the URL to the new channel'
def on_done(self, input):
input = input.strip() if (re.match('https?://', input, re.I) is None): show_error(u'\n Unable to add the channel "%s" since it does not appear to be\n ...
'Quick panel user selection handler - disables the selected package :param picked: An integer of the 0-based package name index from the presented list. -1 means the user cancelled.'
def on_done(self, picked):
if (picked == (-1)): return package = self.package_list[picked] self.disable_packages(package, 'disable') sublime.status_message(text.format('\n Package %s successfully added to list of disabled packages -\n ...
':param window: An instance of :class:`sublime.Window` that represents the Sublime Text window to show the list of installed packages in. :param filter_function: A callable to filter packages for display. This function gets called for each package in the list with a three-element list as returned by :meth:`ExistingPack...
def __init__(self, window, filter_function=None):
self.window = window self.filter_function = filter_function self.manager = PackageManager() threading.Thread.__init__(self)
'Quick panel user selection handler - opens the homepage for any selected package in the user\'s browser :param picked: An integer of the 0-based package name index from the presented list. -1 means the user cancelled.'
def on_done(self, picked):
if (picked == (-1)): return package_name = self.package_list[picked][0] def open_dir(): package_dir = self.manager.get_package_dir(package_name) package_file = None if (not os.path.exists(package_dir)): package_dir = self.manager.settings['installed_packages_path'...
'Input panel handler - adds the provided URL as a repository :param input: A string of the URL to the new repository'
def on_done(self, input):
input = input.strip() if (re.match('https?://', input, re.I) is None): show_error(u'\n Unable to add the repository "%s" since it does not appear to\n ...
':param window: An instance of :class:`sublime.Window` that represents the Sublime Text window to show the list of installed packages in.'
def __init__(self, window):
self.window = window self.manager = PackageManager()
'Quick panel user selection handler - deletes the selected package :param picked: An integer of the 0-based package name index from the presented list. -1 means the user cancelled.'
def on_done(self, picked):
if (picked == (-1)): return package = self.package_list[picked][0] self.disable_packages(package, 'remove') thread = RemovePackageThread(self.manager, package) thread.start() ThreadProgress(thread, ('Removing package %s' % package), ('Package %s successfully removed' % pac...
':param window: An instance of :class:`sublime.Window` that represents the Sublime Text window to show the list of upgradable packages in. :param package_renamer: An instance of :class:`PackageRenamer`'
def __init__(self, window, package_renamer):
self.window = window self.package_renamer = package_renamer self.completion_type = 'upgraded' threading.Thread.__init__(self) PackageInstaller.__init__(self)
'Quick panel user selection handler - disables a package, upgrades it, then re-enables the package :param picked: An integer of the 0-based package name index from the presented list. -1 means the user cancelled.'
def on_done(self, picked):
if (picked == (-1)): return name = self.package_list[picked][0] if (name in self.disable_packages(name, 'upgrade')): def on_complete(): self.reenable_package(name) else: on_complete = None thread = PackageInstallerThread(self.manager, name, on_complete, pause=True...
'Returns a list of installed packages suitable for displaying in the quick panel. :param action: An action to display at the beginning of the third element of the list returned for each package :return: A list of lists, each containing three strings: 0 - package name 1 - package description 2 - [action] installed versi...
def make_package_list(self, action=''):
packages = self.manager.list_packages() if action: action += ' ' package_list = [] for package in sorted(packages, key=(lambda s: s.lower())): package_entry = [package] metadata = self.manager.get_metadata(package) package_dir = os.path.join(sublime.packages_path(), pa...
'Input panel handler - adds the provided URL as a repository :param input: A string of the URL to the new repository'
def on_done(self, input):
input = input.strip() if (not input): show_error(u'\n No package names were entered\n ') return self.start(self.split(input))
':param window: An instance of :class:`sublime.Window` that represents the Sublime Text window to show the available package list in.'
def __init__(self, packages):
self.manager = PackageManager() self.packages = packages self.installed = self.manager.list_packages() self.disabled = [] for package_name in packages: operation_type = ('install' if (package_name not in self.installed) else 'upgrade') self.disabled.extend(self.disable_packages(packa...
'Quick panel handler - removes the repository from settings :param index: The numeric index of the repository in the list of repositories'
def on_done(self, index):
if (index == (-1)): return repository = self.repositories[index] try: self.repositories.remove(repository) self.settings.set('repositories', self.repositories) sublime.save_settings(pc_settings_filename()) sublime.status_message(('Repository %s successfully r...
':param window: An instance of :class:`sublime.Window` that represents the Sublime Text window to show the available package list in.'
def __init__(self, window):
self.window = window self.completion_type = 'installed' threading.Thread.__init__(self) PackageInstaller.__init__(self)
'Quick panel handler - removes the channel from settings :param index: The numeric index of the channel in the list of channels'
def on_done(self, index):
if (index == (-1)): return channel = self.channels[index] try: self.channels.remove(channel) self.settings.set('channels', self.channels) sublime.save_settings(pc_settings_filename()) sublime.status_message(('Channel %s successfully removed' % channel)) e...
'Quick panel user selection handler - addds a loader for the selected dependency :param picked: An integer of the 0-based package name index from the presented list. -1 means the user cancelled.'
def on_done(self, picked):
if (picked == (-1)): return dependency = self.dependency_list[picked] (priority, code) = self.manager.get_dependency_priority_code(dependency) loader.add(priority, dependency, code) sublime.status_message(text.format('\n Dependency %s succ...
'Determines the supported encodings we can decode :return: A comma-separated string of valid encodings'
def supported_encodings(self):
encodings = 'gzip,deflate' if bz2: encodings = ('bzip2,' + encodings) return encodings
'Decodes the raw response from the web server based on the Content-Encoding HTTP header :param encoding: The value of the Content-Encoding HTTP header :param response: The raw response from the server :return: The decoded response'
def decode_response(self, encoding, response):
if (encoding == 'bzip2'): if bz2: return bz2.decompress(response) else: raise DownloaderException(u'Received bzip2 file contents, but was unable to import the bz2 module') elif (encoding == 'gzip'): return gzip.GzipFile(fileobj=Str...
'Closes any persistent/open connections'
def close(self):
if (not self.opener): return handler = self.get_handler() if handler: handler.close() self.opener = None
'Downloads a URL and returns the contents Uses the proxy settings from the Package Control.sublime-settings file, however there seem to be a decent number of proxies that this code does not work with. Patches welcome! :param url: The URL to download :param error_message: A string to include in the console error that is...
def download(self, url, error_message, timeout, tries, prefer_cached=False):
if prefer_cached: cached = self.retrieve_cached(url) if cached: return cached self.setup_opener(url, timeout) debug = self.settings.get('debug') tried = tries error_string = None while (tries > 0): tries -= 1 try: request_headers = {'Accept...
'Get the HTTPHandler object for the current connection'
def get_handler(self):
if (not self.opener): return None for handler in self.opener.handlers: if (isinstance(handler, ValidatingHTTPSHandler) or isinstance(handler, DebuggableHTTPHandler)): return handler
'Sets up a urllib OpenerDirector to be used for requests. There is a fair amount of custom urllib code in Package Control, and part of it is to handle proxies and keep-alives. Creating an opener the way below is because the handlers have been customized to send the "Connection: Keep-Alive" header and hold onto connecti...
def setup_opener(self, url, timeout):
if (not self.opener): http_proxy = self.settings.get('http_proxy') https_proxy = self.settings.get('https_proxy') if (http_proxy or https_proxy): proxies = {} if http_proxy: proxies['http'] = http_proxy if https_proxy: proxi...
'Indicates if the object can handle HTTPS requests :return: If the object supports HTTPS requests'
def supports_ssl(self):
return (('ssl' in sys.modules) and hasattr(urllib_compat, 'HTTPSHandler'))
'Finds the given executable name in the system PATH :param name: The exact name of the executable to find :return: The absolute path to the executable :raises: BinaryNotFoundError when the executable can not be found'
def find_binary(self, name):
dirs = os.environ['PATH'].split(os.pathsep) if (os.name != 'nt'): dirs.append('/usr/local/bin') for dir_ in dirs: path = os.path.join(dir_, name) if os.path.exists(path): return path raise BinaryNotFoundError(('The binary %s could not be located' % n...
'Runs the executable and args and returns the result :param args: A list of the executable path and all arguments to be passed to it :return: The text output of the executable :raises: NonCleanExitError when the executable exits with an error'
def execute(self, args):
if self.settings.get('debug'): console_write(u'\n Trying to execute command %s\n ', create_cmd(args)) proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subp...
'No-op for compatibility with UrllibDownloader and WinINetDownloader'
def close(self):
pass
'Downloads a URL and returns the contents :param url: The URL to download :param error_message: A string to include in the console error that is printed when an error occurs :param timeout: The int number of seconds to set the timeout to :param tries: The int number of times to try and download the URL in the case of a...
def download(self, url, error_message, timeout, tries, prefer_cached=False):
if prefer_cached: cached = self.retrieve_cached(url) if cached: return cached self.tmp_file = tempfile.NamedTemporaryFile().name command = [self.wget, ('--connect-timeout=' + str_cls(int(timeout))), '-o', self.tmp_file, '-O', '-', '--secure-protocol=TLSv1'] user_agent = self....
'Indicates if the object can handle HTTPS requests :return: If the object supports HTTPS requests'
def supports_ssl(self):
return True
'Parses the wget output file, prints debug information and returns headers :param clean_run: If wget executed with a successful exit code :raises: NonHttpError - when clean_run is false and an error is detected :return: A tuple of (general, headers) where general is a dict with the keys: `version` - HTTP version number...
def parse_output(self, clean_run):
with open_compat(self.tmp_file, 'r') as f: output = read_compat(f).splitlines() self.clean_tmp_file() error = None header_lines = [] if self.debug: section = 'General' last_section = None for line in output: if (section == 'General'): if se...
'Determines if a debug line is skippable - usually because of extraneous or duplicate information. :param line: The debug line to check :return: True if the line is skippable, otherwise None'
def skippable_line(self, line):
if re.match('--\\d{4}-\\d{2}-\\d{2}', line): return True if re.match('\\d{4}-\\d{2}-\\d{2}', line): return True if re.match('\\d{3} ', line): return True if re.match('(Saving to:|\\s*\\d+K)', line): return True if re.match('Skipping \\d+ byte', line): ...
'Parses HTTP headers into two dict objects :param output: An array of header lines, if None, loads from temp output file :return: A tuple of (general, headers) where general is a dict with the keys: `version` - HTTP version number (string) `status` - HTTP status code (integer) `message` - HTTP status message (string) A...
def parse_headers(self, output=None):
if (not output): with open_compat(self.tmp_file, 'r') as f: output = read_compat(f).splitlines() self.clean_tmp_file() general = {'version': '0.9', 'status': 200, 'message': 'OK'} headers = {} for line in output: line = line.lstrip() if (line.find('HTTP/') == ...
'Add `If-Modified-Since` and `If-None-Match` headers to a request if a cached copy exists :param headers: A dict with the request headers :return: The request headers dict, possibly with new headers added'
def add_conditional_headers(self, url, headers):
if (not self.settings.get('cache')): return headers info_key = self.generate_key(url, '.info') info_json = self.settings['cache'].get(info_key) if (not info_json): return headers key = self.generate_key(url) if (not self.settings['cache'].has(key)): return headers try...
'Processes a request result, either caching the result, or returning the cached version of the url. :param method: The HTTP method used for the request :param url: The url of the request :param status: The numeric response status of the request :param headers: A dict of reponse headers, with keys being lowercase :param...
def cache_result(self, method, url, status, headers, content):
debug = self.settings.get('debug', False) cache = self.settings.get('cache') if (not cache): if debug: console_write(u'\n Skipping cache since there is no cache object\n ...
'Generates a key to store the cache under :param url: The URL being cached :param suffix: A string to append to the key :return: A string key for the URL'
def generate_key(self, url, suffix=''):
if isinstance(url, str_cls): url = url.encode('utf-8') key = hashlib.md5(url).hexdigest() return (key + suffix)
'Tries to return the cached content for a URL :param url: The URL to get the cached content for :return: The cached content'
def retrieve_cached(self, url):
key = self.generate_key(url) cache = self.settings['cache'] if (not cache.has(key)): return False if self.settings.get('debug'): console_write(u'\n Using cached content for %s from %s\n ...
'Checks the headers of a response object to make sure we are obeying the rate limit :param headers: The dict-like object that contains lower-cased headers :param url: The URL that was requested :raises: RateLimitException when the rate limit has been hit'
def handle_rate_limit(self, headers, url):
limit_remaining = headers.get('x-ratelimit-remaining', '1') limit = headers.get('x-ratelimit-limit', '1') if (str_cls(limit_remaining) == '0'): hostname = urlparse(url).hostname raise RateLimitException(hostname, limit)
'Adds a URL to the list to download :param url: The URL to download info about'
def add_url(self, url):
self.urls.append(url)
'Returns the provider for the URL specified :param url: The URL to return the provider for :return: The provider object for the URL'
def get_provider(self, url):
return self.used_providers.get(url)
'No-op for compatibility with UrllibDownloader and WinINetDownloader'
def close(self):
pass
'Downloads a URL and returns the contents :param url: The URL to download :param error_message: A string to include in the console error that is printed when an error occurs :param timeout: The int number of seconds to set the timeout to :param tries: The int number of times to try and download the URL in the case of a...
def download(self, url, error_message, timeout, tries, prefer_cached=False):
if prefer_cached: cached = self.retrieve_cached(url) if cached: return cached self.tmp_file = tempfile.NamedTemporaryFile().name command = [self.curl, '--connect-timeout', str_cls(int(timeout)), '-sSL', '--tlsv1', '--dump-header', self.tmp_file] user_agent = self.settings.get...
'Prints out the debug output from split_debug() :param sections: The second element in the tuple that is returned from split_debug()'
def print_debug(self, sections):
for section in sections: type = section['type'] indented_contents = section['contents'].replace(u'\n', u'\n ') console_write(u'\n Curl HTTP Debug %s\n ...
'Indicates if the object can handle HTTPS requests :return: If the object supports HTTPS requests'
def supports_ssl(self):
return True
'Takes debug output from curl and splits it into stderr and structured debug info :param string: The complete debug output from curl :return: A tuple with [0] stderr output and [1] a list of dict objects containing the keys "type" and "contents"'
def split_debug(self, string):
section = 'General' last_section = None stderr = u'' debug_sections = [] debug_section = u'' for line in string.splitlines(): if (line and (line[0:2] == u'{ ')): continue if (line and (line[0:18] == u'} [data not shown]')): continue if ...
'Closes any persistent/open connections'
def close(self):
changed_state_back = False if self.tcp_connection: wininet.InternetCloseHandle(self.tcp_connection) self.tcp_connection = None if self.network_connection: wininet.InternetCloseHandle(self.network_connection) self.network_connection = None if self.was_offline: dw_c...
'Downloads a URL and returns the contents :param url: The URL to download :param error_message: A string to include in the console error that is printed when an error occurs :param timeout: The int number of seconds to set the timeout to :param tries: The int number of times to try and download the URL in the case of a...
def download(self, url, error_message, timeout, tries, prefer_cached=False):
if prefer_cached: cached = self.retrieve_cached(url) if cached: return cached url_info = urlparse(url) if (not url_info.port): port = (443 if (url_info.scheme == 'https') else 80) hostname = url_info.netloc else: port = url_info.port hostname =...
'Windows returns times as 64-bit unsigned longs that are the number of hundreds of nanoseconds since Jan 1 1601. This converts it to a datetime object. :param filetime: A FileTime struct object :return: A (UTC) datetime object'
def convert_filetime_to_datetime(self, filetime):
hundreds_nano_seconds = struct.unpack('>Q', struct.pack('>LL', filetime.dwHighDateTime, filetime.dwLowDateTime))[0] seconds_since_1601 = (hundreds_nano_seconds / 10000000) epoch_seconds = (seconds_since_1601 - 11644473600) return datetime.datetime.fromtimestamp(epoch_seconds)
'Retrieves and formats an error from WinINet :return: A string with a nice description of the error'
def extract_error(self):
error_num = ctypes.GetLastError() raw_error_string = ctypes.FormatError(error_num) error_string = unicode_from_os(raw_error_string) if (error_string == u'<no description>'): error_lookup = {12007: u'host not found', 12029: u'connection refused', 12057: u'error checking for s...
'Indicates if the object can handle HTTPS requests :return: If the object supports HTTPS requests'
def supports_ssl(self):
return True
'Reads information about the internet connection, which may be a string or struct :param handle: The handle to query for the info :param option: The (int) option to get :return: A string, or one of the InternetCertificateInfo or InternetProxyInfo structs'
def read_option(self, handle, option):
option_buffer_size = 8192 try_again = True while try_again: try_again = False to_read_was_read = wintypes.DWORD(option_buffer_size) option_buffer = ctypes.create_string_buffer(option_buffer_size) ref = ctypes.byref(option_buffer) success = wininet.InternetQueryOptionA...
'Parses HTTP headers into two dict objects :param output: An array of header lines :return: A tuple of (general, headers) where general is a dict with the keys: `version` - HTTP version number (string) `status` - HTTP status code (integer) `message` - HTTP status message (string) And headers is a dict with the keys bei...
def parse_headers(self, output):
general = {'version': '0.9', 'status': 200, 'message': 'OK'} headers = {} for line in output: line = line.lstrip() if (line.find('HTTP/') == 0): match = re.match('HTTP/(\\d\\.\\d)\\s+(\\d+)\\s+(.*)$', line) if match: general['version'] = match.group(1)...
'Creates a list of packages and what operation would be performed for each. Allows filtering by the applicable action or package name. Returns the information in a format suitable for displaying in the quick panel. :param ignore_actions: A list of actions to ignore packages by. Valid actions include: `install`, `upgrad...
def make_package_list(self, ignore_actions=[], override_action=None, ignore_packages=[]):
packages = self.manager.list_available_packages() installed_packages = self.manager.list_packages() package_list = [] for package in sorted(iter(packages.keys()), key=(lambda s: s.lower())): if (ignore_packages and (package in ignore_packages)): continue package_entry = [pack...
'Quick panel user selection handler - disables a package, installs or upgrades it, then re-enables the package :param picked: An integer of the 0-based package name index from the presented list. -1 means the user cancelled.'
def on_done(self, picked):
if (picked == (-1)): return name = self.package_list[picked][0] if (name in self.disable_packages(name, 'install')): def on_complete(): self.reenable_package(name, 'install') else: on_complete = None thread = PackageInstallerThread(self.manager, name, on_complete)...
':param manager: An instance of :class:`PackageManager` :param package: The string package name to install/upgrade :param on_complete: A callback to run after installing/upgrading the package :param pause: If we should pause before upgrading to allow a package to be fully disabled.'
def __init__(self, manager, package, on_complete, pause=False):
self.package = package self.manager = manager self.on_complete = on_complete self.pause = pause threading.Thread.__init__(self)
'Indicates if this provider can handle the provided repo'
@classmethod def match_url(cls, repo):
return (re.search('^https?://github.com/[^/]+/?$', repo) is not None)
'Go out and perform HTTP operations, caching the result'
def prefetch(self):
[name for (name, info) in self.get_packages()]
'List of any URLs that could not be accessed while accessing this repository :raises: DownloaderException: when there is an issue download package info ClientException: when there is an issue parsing package info :return: A generator of ("https://github.com/user/repo", Exception()) tuples'
def get_failed_sources(self):
return self.failed_sources.items()
'For API-compatibility with RepositoryProvider'
def get_broken_packages(self):
return {}.items()