signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
---|---|---|---|
def run_async(**kwargs): | r = init_runner(**kwargs)<EOL>runner_thread = threading.Thread(target=r.run)<EOL>runner_thread.start()<EOL>return runner_thread, r<EOL> | Runs an Ansible Runner task in the background which will start immediately. Returns the thread object and a Runner object.
This uses the same parameters as :py:func:`ansible_runner.interface.run`
:returns: A tuple containing a :py:class:`threading.Thread` object and a :py:class:`ansible_runner.runner.Runner` object | f871:m2 |
def event_callback(self, event_data): | self.last_stdout_update = time.time()<EOL>job_events_path = os.path.join(self.config.artifact_dir, '<STR_LIT>')<EOL>if not os.path.exists(job_events_path):<EOL><INDENT>os.mkdir(job_events_path, <NUM_LIT>)<EOL><DEDENT>if '<STR_LIT>' in event_data:<EOL><INDENT>filename = '<STR_LIT>'.format(event_data['<STR_LIT>'])<EOL>partial_filename = os.path.join(self.config.artifact_dir,<EOL>'<STR_LIT>',<EOL>filename)<EOL>full_filename = os.path.join(self.config.artifact_dir,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(event_data['<STR_LIT>'],<EOL>event_data['<STR_LIT>']))<EOL>try:<EOL><INDENT>event_data.update(dict(runner_ident=str(self.config.ident)))<EOL>try:<EOL><INDENT>with codecs.open(partial_filename, '<STR_LIT:r>', encoding='<STR_LIT:utf-8>') as read_file:<EOL><INDENT>partial_event_data = json.load(read_file)<EOL><DEDENT>event_data.update(partial_event_data)<EOL>if self.remove_partials:<EOL><INDENT>os.remove(partial_filename)<EOL><DEDENT><DEDENT>except IOError:<EOL><INDENT>debug("<STR_LIT>".format(partial_filename))<EOL><DEDENT>if self.event_handler is not None:<EOL><INDENT>should_write = self.event_handler(event_data)<EOL><DEDENT>else:<EOL><INDENT>should_write = True<EOL><DEDENT>for plugin in ansible_runner.plugins:<EOL><INDENT>ansible_runner.plugins[plugin].event_handler(self.config, event_data)<EOL><DEDENT>if should_write:<EOL><INDENT>with codecs.open(full_filename, '<STR_LIT:w>', encoding='<STR_LIT:utf-8>') as write_file:<EOL><INDENT>os.chmod(full_filename, stat.S_IRUSR | stat.S_IWUSR)<EOL>json.dump(event_data, write_file)<EOL><DEDENT><DEDENT><DEDENT>except IOError as e:<EOL><INDENT>debug("<STR_LIT>".format(e))<EOL><DEDENT><DEDENT> | Invoked for every Ansible event to collect stdout with the event data and store it for
later use | f872:c0:m1 |
def run(self): | self.status_callback('<STR_LIT>')<EOL>stdout_filename = os.path.join(self.config.artifact_dir, '<STR_LIT>')<EOL>command_filename = os.path.join(self.config.artifact_dir, '<STR_LIT>')<EOL>try:<EOL><INDENT>os.makedirs(self.config.artifact_dir, mode=<NUM_LIT>)<EOL><DEDENT>except OSError as exc:<EOL><INDENT>if exc.errno == errno.EEXIST and os.path.isdir(self.config.artifact_dir):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>os.close(os.open(stdout_filename, os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR))<EOL>command = [a.decode('<STR_LIT:utf-8>') if six.PY2 else a for a in self.config.command]<EOL>with codecs.open(command_filename, '<STR_LIT:w>', encoding='<STR_LIT:utf-8>') as f:<EOL><INDENT>os.chmod(command_filename, stat.S_IRUSR | stat.S_IWUSR)<EOL>json.dump(<EOL>{'<STR_LIT>': command,<EOL>'<STR_LIT>': self.config.cwd,<EOL>'<STR_LIT>': self.config.env}, f, ensure_ascii=False<EOL>)<EOL><DEDENT>if self.config.ident is not None:<EOL><INDENT>cleanup_artifact_dir(os.path.join(self.config.artifact_dir, "<STR_LIT:..>"), self.config.rotate_artifacts)<EOL><DEDENT>stdout_handle = codecs.open(stdout_filename, '<STR_LIT:w>', encoding='<STR_LIT:utf-8>')<EOL>stdout_handle = OutputEventFilter(stdout_handle, self.event_callback, self.config.suppress_ansible_output, output_json=self.config.json_mode)<EOL>if not isinstance(self.config.expect_passwords, collections.OrderedDict):<EOL><INDENT>expect_passwords = collections.OrderedDict(self.config.expect_passwords)<EOL><DEDENT>password_patterns = list(expect_passwords.keys())<EOL>password_values = list(expect_passwords.values())<EOL>env = {<EOL>ensure_str(k): ensure_str(v) if k != '<STR_LIT>' and isinstance(v, six.text_type) else v<EOL>for k, v in self.config.env.items()<EOL>}<EOL>self.status_callback('<STR_LIT>')<EOL>self.last_stdout_update = time.time()<EOL>try:<EOL><INDENT>child = pexpect.spawn(<EOL>command[<NUM_LIT:0>],<EOL>command[<NUM_LIT:1>:],<EOL>cwd=self.config.cwd,<EOL>env=env,<EOL>ignore_sighup=True,<EOL>encoding='<STR_LIT:utf-8>',<EOL>echo=False,<EOL>use_poll=self.config.pexpect_use_poll,<EOL>)<EOL>child.logfile_read = stdout_handle<EOL><DEDENT>except pexpect.exceptions.ExceptionPexpect as e:<EOL><INDENT>child = collections.namedtuple(<EOL>'<STR_LIT>', '<STR_LIT>'<EOL>)(<EOL>exitstatus=<NUM_LIT>,<EOL>isalive=lambda: False<EOL>)<EOL>def _decode(x):<EOL><INDENT>return x.decode('<STR_LIT:utf-8>') if six.PY2 else x<EOL><DEDENT>events_directory = os.path.join(self.config.artifact_dir, '<STR_LIT>')<EOL>if not os.path.exists(events_directory):<EOL><INDENT>os.mkdir(events_directory, <NUM_LIT>)<EOL><DEDENT>stdout_handle.write(_decode(str(e)))<EOL>stdout_handle.write(_decode('<STR_LIT:\n>'))<EOL><DEDENT>job_start = time.time()<EOL>while child.isalive():<EOL><INDENT>result_id = child.expect(password_patterns,<EOL>timeout=self.config.pexpect_timeout,<EOL>searchwindowsize=<NUM_LIT:100>)<EOL>password = password_values[result_id]<EOL>if password is not None:<EOL><INDENT>child.sendline(password)<EOL>self.last_stdout_update = time.time()<EOL><DEDENT>if self.cancel_callback:<EOL><INDENT>try:<EOL><INDENT>self.canceled = self.cancel_callback()<EOL><DEDENT>except Exception as e:<EOL><INDENT>raise CallbackError("<STR_LIT>".format(e))<EOL><DEDENT><DEDENT>if self.config.job_timeout and not self.canceled and (time.time() - job_start) > self.config.job_timeout:<EOL><INDENT>self.timed_out = True<EOL><DEDENT>if self.canceled or self.timed_out or self.errored:<EOL><INDENT>Runner.handle_termination(child.pid, is_cancel=self.canceled)<EOL><DEDENT>if self.config.idle_timeout and (time.time() - self.last_stdout_update) > self.config.idle_timeout:<EOL><INDENT>Runner.handle_termination(child.pid, is_cancel=False)<EOL>self.timed_out = True<EOL><DEDENT><DEDENT>stdout_handle.flush()<EOL>stdout_handle.close()<EOL>if self.canceled:<EOL><INDENT>self.status_callback('<STR_LIT>')<EOL><DEDENT>elif child.exitstatus == <NUM_LIT:0> and not self.timed_out:<EOL><INDENT>self.status_callback('<STR_LIT>')<EOL><DEDENT>elif self.timed_out:<EOL><INDENT>self.status_callback('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>self.status_callback('<STR_LIT>')<EOL><DEDENT>self.rc = child.exitstatus if not (self.timed_out or self.canceled) else <NUM_LIT><EOL>for filename, data in [<EOL>('<STR_LIT:status>', self.status),<EOL>('<STR_LIT>', self.rc),<EOL>]:<EOL><INDENT>artifact_path = os.path.join(self.config.artifact_dir, filename)<EOL>if not os.path.exists(artifact_path):<EOL><INDENT>os.close(os.open(artifact_path, os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR))<EOL><DEDENT>with open(artifact_path, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(str(data))<EOL><DEDENT><DEDENT>if self.config.directory_isolation_path and self.config.directory_isolation_cleanup:<EOL><INDENT>shutil.rmtree(self.config.directory_isolation_path)<EOL><DEDENT>if self.finished_callback is not None:<EOL><INDENT>try:<EOL><INDENT>self.finished_callback(self)<EOL><DEDENT>except Exception as e:<EOL><INDENT>raise CallbackError("<STR_LIT>".format(e))<EOL><DEDENT><DEDENT>return self.status, self.rc<EOL> | Launch the Ansible task configured in self.config (A RunnerConfig object), returns once the
invocation is complete | f872:c0:m3 |
@property<EOL><INDENT>def stdout(self):<DEDENT> | stdout_path = os.path.join(self.config.artifact_dir, '<STR_LIT>')<EOL>if not os.path.exists(stdout_path):<EOL><INDENT>raise AnsibleRunnerException("<STR_LIT>")<EOL><DEDENT>return open(os.path.join(self.config.artifact_dir, '<STR_LIT>'), '<STR_LIT:r>')<EOL> | Returns an open file handle to the stdout representing the Ansible run | f872:c0:m4 |
@property<EOL><INDENT>def events(self):<DEDENT> | event_path = os.path.join(self.config.artifact_dir, '<STR_LIT>')<EOL>if not os.path.exists(event_path):<EOL><INDENT>raise AnsibleRunnerException("<STR_LIT>")<EOL><DEDENT>dir_events = os.listdir(event_path)<EOL>dir_events_actual = []<EOL>for each_file in dir_events:<EOL><INDENT>if re.match("<STR_LIT>", each_file):<EOL><INDENT>dir_events_actual.append(each_file)<EOL><DEDENT><DEDENT>dir_events_actual.sort(key=lambda filenm: int(filenm.split("<STR_LIT:->", <NUM_LIT:1>)[<NUM_LIT:0>]))<EOL>for event_file in dir_events_actual:<EOL><INDENT>with codecs.open(os.path.join(event_path, event_file), '<STR_LIT:r>', encoding='<STR_LIT:utf-8>') as event_file_actual:<EOL><INDENT>event = json.load(event_file_actual)<EOL><DEDENT>yield event<EOL><DEDENT> | A generator that will return all ansible job events in the order that they were emitted from Ansible
Example:
{
"event":"runner_on_ok",
"uuid":"00a50d9c-161a-4b74-b978-9f60becaf209",
"stdout":"ok: [localhost] => {\\r\\n \\" msg\\":\\"Test!\\"\\r\\n}",
"counter":6,
"pid":740,
"created":"2018-04-05T18:24:36.096725",
"end_line":10,
"start_line":7,
"event_data":{
"play_pattern":"all",
"play":"all",
"task":"debug",
"task_args":"msg=Test!",
"remote_addr":"localhost",
"res":{
"msg":"Test!",
"changed":false,
"_ansible_verbose_always":true,
"_ansible_no_log":false
},
"pid":740,
"play_uuid":"0242ac11-0002-443b-cdb1-000000000006",
"task_uuid":"0242ac11-0002-443b-cdb1-000000000008",
"event_loop":null,
"playbook_uuid":"634edeee-3228-4c17-a1b4-f010fdd42eb2",
"playbook":"test.yml",
"task_action":"debug",
"host":"localhost",
"task_path":"/tmp/demo/project/test.yml:3"
}
} | f872:c0:m5 |
@property<EOL><INDENT>def stats(self):<DEDENT> | last_event = list(filter(lambda x: '<STR_LIT>' in x and x['<STR_LIT>'] == '<STR_LIT>',<EOL>self.events))<EOL>if not last_event:<EOL><INDENT>return None<EOL><DEDENT>last_event = last_event[<NUM_LIT:0>]['<STR_LIT>']<EOL>return dict(skipped=last_event['<STR_LIT>'],<EOL>ok=last_event['<STR_LIT>'],<EOL>dark=last_event['<STR_LIT>'],<EOL>failures=last_event['<STR_LIT>'],<EOL>processed=last_event['<STR_LIT>'])<EOL> | Returns the final high level stats from the Ansible run
Example:
{'dark': {}, 'failures': {}, 'skipped': {}, 'ok': {u'localhost': 2}, 'processed': {u'localhost': 1}} | f872:c0:m6 |
def host_events(self, host): | all_host_events = filter(lambda x: '<STR_LIT>' in x and '<STR_LIT:host>' in x['<STR_LIT>'] and x['<STR_LIT>']['<STR_LIT:host>'] == host,<EOL>self.events)<EOL>return all_host_events<EOL> | Given a host name, this will return all task events executed on that host | f872:c0:m7 |
@classmethod<EOL><INDENT>def handle_termination(cls, pid, is_cancel=True):<DEDENT> | try:<EOL><INDENT>main_proc = psutil.Process(pid=pid)<EOL>child_procs = main_proc.children(recursive=True)<EOL>for child_proc in child_procs:<EOL><INDENT>try:<EOL><INDENT>os.kill(child_proc.pid, signal.SIGKILL)<EOL><DEDENT>except (TypeError, OSError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>os.kill(main_proc.pid, signal.SIGKILL)<EOL><DEDENT>except (TypeError, psutil.Error, OSError):<EOL><INDENT>try:<EOL><INDENT>os.kill(pid, signal.SIGKILL)<EOL><DEDENT>except (OSError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT> | Internal method to terminate a subprocess spawned by `pexpect` representing an invocation of runner.
:param pid: the process id of the running the job.
:param is_cancel: flag showing whether this termination is caused by
instance's cancel_flag. | f872:c0:m8 |
def get_fact_cache(self, host): | if self.config.fact_cache_type != '<STR_LIT>':<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>fact_cache = os.path.join(self.config.fact_cache, host)<EOL>if os.path.exists(fact_cache):<EOL><INDENT>with open(fact_cache) as f:<EOL><INDENT>return json.loads(f.read())<EOL><DEDENT><DEDENT>return {}<EOL> | Get the entire fact cache only if the fact_cache_type is 'jsonfile' | f872:c0:m9 |
def set_fact_cache(self, host, data): | if self.config.fact_cache_type != '<STR_LIT>':<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>fact_cache = os.path.join(self.config.fact_cache, host)<EOL>if not os.path.exists(os.path.dirname(fact_cache)):<EOL><INDENT>os.makedirs(os.path.dirname(fact_cache), mode=<NUM_LIT>)<EOL><DEDENT>with open(fact_cache, '<STR_LIT:w>') as f:<EOL><INDENT>return f.write(json.dumps(data))<EOL><DEDENT> | Set the entire fact cache data only if the fact_cache_type is 'jsonfile' | f872:c0:m10 |
def refresh(self, force=False): | if self._is_token_expired() or force:<EOL><INDENT>tokens = self._get_refresh_access()<EOL>self.access_token = tokens['<STR_LIT>']<EOL>self.refresh_token = tokens['<STR_LIT>']<EOL>self._set_access_credentials()<EOL><DEDENT> | Refreshes the `access_token` and sets the praw instance `reddit_client`
with a valid one.
:param force: Boolean. Refresh will be done only when last refresh was
done before `EXPIRY_DURATION`, which is 3500 seconds. However
passing `force` will overrides this and refresh operation will be
done everytime. | f894:c0:m7 |
def get_access_codes(self): | return {'<STR_LIT>': self.access_token,<EOL>'<STR_LIT>': self.refresh_token}<EOL> | Returns the `access_token` and `refresh_token`.
:returns: A dictionary containing `access_token` and `refresh_token`. | f894:c0:m8 |
def start(self): | global CODE<EOL>url = self._get_auth_url()<EOL>webbrowser.open(url)<EOL>tornado.ioloop.IOLoop.current().start()<EOL>self.code = CODE<EOL> | Starts the `PrawOAuth2Server` server. It will open the default
web browser and it will take you to Reddit's authorization page,
asking you to authorize your Reddit account(or account of the bot's)
with your app(or bot script). Once authorized successfully, it will
show `successful` message in web browser. | f896:c1:m4 |
def get_access_codes(self): | return self.reddit_client.get_access_information(code=self.code)<EOL> | Returns the `access_token` and `refresh_token`. Obviously, this
method should be called after `start`.
:returns: A dictionary containing `access_token` and `refresh_token`. | f896:c1:m5 |
def get_files_recursive(path, match='<STR_LIT>'): | matches = []<EOL>for root, dirnames, filenames in os.walk(path):<EOL><INDENT>for filename in fnmatch.filter(filenames, match):<EOL><INDENT>matches.append(os.path.join(root, filename))<EOL><DEDENT><DEDENT>return matches<EOL> | Perform a recursive search to find all the files matching the
specified search criteria.
:param path: Path to begin the recursive search.
:param match: String/Regex used to match files with a pattern.
:return: Full path of all the files found.
:rtype: list | f907:m0 |
def get_filename(file): | if not os.path.exists(file):<EOL><INDENT>return None<EOL><DEDENT>return "<STR_LIT>" % os.path.splitext(file)<EOL> | Safe method to retrieve only the name of the file.
:param file: Path of the file to retrieve the name from.
:return: None if the file is non-existant, otherwise the filename (extension included)
:rtype: None, str | f907:m1 |
def import_module_from_file(full_path_to_module): | if inspect.ismodule(full_path_to_module):<EOL><INDENT>return full_path_to_module<EOL><DEDENT>module = None<EOL>try:<EOL><INDENT>module_dir, module_file = os.path.split(full_path_to_module)<EOL>module_name, module_ext = os.path.splitext(module_file)<EOL>spec = spec_from_file_location(module_name, full_path_to_module)<EOL>module = spec.loader.load_module()<EOL><DEDENT>except Exception as ec:<EOL><INDENT>print(ec)<EOL><DEDENT>finally:<EOL><INDENT>return module<EOL><DEDENT> | Import a module given the full path/filename of the .py file
Python 3.4 | f907:m2 |
def activate(self): | raise NotImplementedError("<STR_LIT>" % self.name)<EOL> | Operations to perform whenever the plugin is activated.
:return: | f907:c1:m1 |
def deactivate(self): | raise NotImplementedError("<STR_LIT>" % self.name)<EOL> | Operations to perform whenever the plugin is deactivated.
:return: | f907:c1:m2 |
def perform(self, **kwargs): | raise NotImplementedError("<STR_LIT>" % self.name)<EOL> | Operations that will be performed when invoked.
This method is where the actual "use" logic of plugins will be defined.
:param kwargs:
:return: | f907:c1:m3 |
def register(self, plugin=None, plugin_file=None, directory=None, skip_types=None, override=False, activate=True): | <EOL>if not isinstance(skip_types, list):<EOL><INDENT>skip_types = [skip_types]<EOL>logger.debug("<STR_LIT>")<EOL><DEDENT>if skip_types is None:<EOL><INDENT>skip_types = [Plugin]<EOL><DEDENT>else:<EOL><INDENT>skip_types.append(Plugin)<EOL><DEDENT>if plugin is None and plugin_file is None and directory is None:<EOL><INDENT>raise PluginException("<STR_LIT>")<EOL><DEDENT>if directory is not None:<EOL><INDENT>plugins_in_dir = PluginManager.scan_for_plugins(directory)<EOL>for file, plugins in plugins_in_dir.items():<EOL><INDENT>if plugins is None:<EOL><INDENT>continue<EOL><DEDENT>for plugin in plugins:<EOL><INDENT>if plugin.name in self.plugins:<EOL><INDENT>if not override:<EOL><INDENT>logger.warn("<STR_LIT>" % plugin.name)<EOL>continue<EOL><DEDENT><DEDENT>if type(plugin) in skip_types:<EOL><INDENT>logger.warn(<EOL>"<STR_LIT>" % plugin.__class__.__name__)<EOL>continue<EOL><DEDENT>self.plugins[plugin.name] = plugin<EOL>logger.debug("<STR_LIT>" % (plugin.name, file, directory))<EOL>if activate:<EOL><INDENT>self.plugins[plugin.name].activate()<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if plugin_file is not None:<EOL><INDENT>if not inspect.ismodule(plugin_file):<EOL><INDENT>plugin_file = os.path.expanduser(plugin_file)<EOL>if not os.path.exists(plugin_file):<EOL><INDENT>raise FileNotFoundError("<STR_LIT>" % plugin_file)<EOL><DEDENT><DEDENT>plugins_in_file = PluginManager.get_plugins_in_module(plugin_file)<EOL>if plugins_in_file is None or len(plugins_in_file) == <NUM_LIT:0>:<EOL><INDENT>raise PluginException("<STR_LIT>" % plugin_file)<EOL><DEDENT>for fplugin in plugins_in_file:<EOL><INDENT>if fplugin.name in self.plugins:<EOL><INDENT>if not override:<EOL><INDENT>logger.warn("<STR_LIT>" % fplugin.name)<EOL>continue<EOL><DEDENT><DEDENT>if type(fplugin) in skip_types:<EOL><INDENT>logger.warn(<EOL>"<STR_LIT>" % fplugin.__class__.__name__)<EOL>continue<EOL><DEDENT>self.plugins[fplugin.name] = fplugin<EOL>logger.debug("<STR_LIT>" % (<EOL>fplugin.name, "<STR_LIT>" if inspect.ismodule(plugin_file) else "<STR_LIT:file>",<EOL>get_filename(plugin_file) if not inspect.ismodule(plugin_file) else plugin_file.__name__)<EOL>)<EOL>if activate:<EOL><INDENT>self.plugins[fplugin.name].activate()<EOL><DEDENT><DEDENT><DEDENT>if plugin is not None:<EOL><INDENT>if plugin.name in self.plugins:<EOL><INDENT>if override is False:<EOL><INDENT>return<EOL><DEDENT><DEDENT>self.plugins[plugin.name] = plugin<EOL>logger.debug("<STR_LIT>" % plugin.name)<EOL>if activate:<EOL><INDENT>self.plugins[plugin.name].activate()<EOL><DEDENT><DEDENT> | Register a plugin, or plugins to be managed and recognized by the plugin manager.
Will take a plugin instance, file where a plugin / plugin(s) reside, parent directory
that holds plugin(s), or sub-folders with plugin(s).
Will optionally "activate" the plugins, and perform any operations defined in their "activate" method.
:param plugin: Plugin Instance to register.
:param plugin_file: str: File (full path) to scan for Plugins.
:param directory: str: Directory to perform a recursive scan on for Plugins.
:param skip_types: list: Types of plugins to skip when found, during a scan / search.
:param override: bool: Whether or not to override registered plugin when it's being registered again.
:param activate: bool: Whether or not to activate the plugins upon registration.
:return: Does not Return. | f907:c2:m1 |
def unregister(self, plugin=None, plugin_file=None): | if plugin is None and plugin_file is None:<EOL><INDENT>for name, plugin in self.plugins.items():<EOL><INDENT>plugin.deactivate()<EOL>del self.plugins[name]<EOL><DEDENT>return<EOL><DEDENT>if plugin is not None:<EOL><INDENT>if plugin.name in self.plugins:<EOL><INDENT>plugin.deactivate()<EOL>del self.plugins[plugin.name]<EOL><DEDENT><DEDENT>if plugin_file is not None:<EOL><INDENT>plugs_in_file = PluginManager.get_plugins_in_module(plugin_file)<EOL>if plugs_in_file is None:<EOL><INDENT>return<EOL><DEDENT>for classPlugin in plugs_in_file:<EOL><INDENT>if not self.has_plugin(classPlugin.name, classPlugin):<EOL><INDENT>continue<EOL><DEDENT>self.get_plugin(classPlugin.name).deactivate()<EOL>del self.plugins[classPlugin.name]<EOL><DEDENT><DEDENT> | Unregister all plugins, or a specific plugin, via an instance, or file (path) containing plugin(s).
When this method is called without any arguments then all plugins will be deactivated.
:param plugin: Plugin to unregister.
:param plugin_file: File containing plugin(s) to unregister.
:return: Does not Return. | f907:c2:m3 |
def get_plugins(self, plugin_type=None): | if plugin_type is None:<EOL><INDENT>return self.plugins.values()<EOL><DEDENT>plugin_list = []<EOL>for name, plugin in self.plugins.items():<EOL><INDENT>if isinstance(plugin, plugin_type if inspect.isclass(plugin_type) else type(plugin_type)):<EOL><INDENT>plugin_list.append(plugin)<EOL><DEDENT><DEDENT>return plugin_list<EOL> | Retrieve a list of plugins in the PluginManager.
All plugins if no arguments are provides, or of the specified type.
:param plugin_type: list: Types of plugins to retrieve from the plugin manager.
:return: Plugins being managed by the Manager (optionally of the desired plugin_type).
:rtype: list | f907:c2:m4 |
def get_plugin(self, name): | if not self.has_plugin(name):<EOL><INDENT>return None<EOL><DEDENT>return self.plugins[name]<EOL> | Retrieve a registered plugin by its name.
:param name: Name of the plugin to retrieve.
:return: None if the manager has no plugin of the given name, otherwise the plugin instance matching the given name.
:rtype: None / Plugin | f907:c2:m5 |
def has_plugin(self, name=None, plugin_type=None): | <EOL>if name is None and plugin_type is None:<EOL><INDENT>return len(self.plugins) > <NUM_LIT:0><EOL><DEDENT>if name is not None and plugin_type is not None:<EOL><INDENT>return name in self.plugins and isinstance(self.plugins[name],<EOL>plugin_type if inspect.isclass(plugin_type) else type(<EOL>plugin_type))<EOL><DEDENT>if plugin_type is not None:<EOL><INDENT>return len(<EOL>self.get_plugins(plugin_type=plugin_type if inspect.isclass(plugin_type) else type(plugin_type))) > <NUM_LIT:0><EOL><DEDENT>return name in self.plugins<EOL> | Check if the manager has a plugin / plugin(s), either by its name, type, or simply checking if the
manager has any plugins registered in it.
Utilizing the name argument will check if a plugin with that name exists in the manager.
Using both the name and plugin_type arguments will check if a plugin with that name, and type, exists.
Using only the plugin_type argument will check if any plugins matching the type specified are registered
in the plugin manager.
:param name: Name of the plugin to check for.
:param plugin_type: Plugin Type to check for.
:return: | f907:c2:m6 |
@staticmethod<EOL><INDENT>def scan_for_plugins(directory):<DEDENT> | if not os.path.exists(os.path.expanduser(directory)):<EOL><INDENT>raise FileNotFoundError("<STR_LIT>" % directory)<EOL><DEDENT>files_in_dir = get_files_recursive(directory)<EOL>plugins = {}<EOL>for file in files_in_dir:<EOL><INDENT>plugins_in_module = PluginManager.get_plugins_in_module(file, suppress=True)<EOL>if plugins_in_module is None:<EOL><INDENT>continue<EOL><DEDENT>plugins[file] = plugins_in_module<EOL><DEDENT>return plugins<EOL> | Scan a directory for modules that contains plugin(s).
:param directory: Path of the folder/directory to scan.
:return: Dictionary of file (key) and plugins (value), where the key is the path of the module and value is a list of plugins inside that module.
:rtype: dict | f907:c2:m8 |
@staticmethod<EOL><INDENT>def get_plugins_in_module(module_path, suppress=False):<DEDENT> | module = module_path if inspect.ismodule(module_path) else import_module_from_file(module_path)<EOL>if module is None:<EOL><INDENT>if suppress is False:<EOL><INDENT>raise PluginException("<STR_LIT>" % module)<EOL><DEDENT>return None<EOL><DEDENT>plugin_list = []<EOL>for name, obj in inspect.getmembers(module):<EOL><INDENT>attr = getattr(module, name)<EOL>if isinstance(attr, Plugin):<EOL><INDENT>plugin_list.append(attr)<EOL><DEDENT><DEDENT>return plugin_list<EOL> | Inspect a module, via its path, and retrieve a list of the plugins inside the module.
:param module_path: Path of the module to inspect.
:param suppress: Whether or not to suppresss exceptions.
:raises: PluginException
:return: A list of all the plugins inside the specified module.
:rtype: list | f907:c2:m9 |
def create(self, uri, buffer="<STR_LIT>", interval=<NUM_LIT:10>): | return self._http_client.put_json("<STR_LIT>".format(self.short_name), {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": uri,<EOL>"<STR_LIT>": buffer,<EOL>"<STR_LIT>": interval,<EOL>}<EOL>})<EOL> | Create a subscription with this short name and the provided parameters
For more information on what the parameters required here mean, please
refer to the `WVA Documentation <http://goo.gl/DRcOQf>`_.
:raises WVAError: If there is a problem creating the new subscription | f911:c0:m1 |
def delete(self): | return self._http_client.delete("<STR_LIT>".format(self.short_name))<EOL> | Delete this subscription
:raises WVAError: If there is a problem deleting the subscription | f911:c0:m2 |
def get_metadata(self): | return self._http_client.get("<STR_LIT>".format(self.short_name))["<STR_LIT>"]<EOL> | Get the metadata that is available for this subscription
The metadata for a subscription is a dictionary like the following. Details
on the elements may be found in the `WVA documentation <http://goo.gl/DRcOQf>`_::
{
'buffer': 'queue',
'interval': 10,
'uri': 'vehicle/data/TripDistance'
}
:raises WVAError: if there is a problem querying the WVA for the metadata
:returns: A dictionary containing the metadata for this subscription | f911:c0:m3 |
@click.group()<EOL>@click.option('<STR_LIT>', default=True, help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', default=None, help='<STR_LIT>')<EOL>@click.option('<STR_LIT>', default=None, help='<STR_LIT>')<EOL>@click.option('<STR_LIT>', default=None, help='<STR_LIT>')<EOL>@click.option("<STR_LIT>", default="<STR_LIT>", help='<STR_LIT>')<EOL>@click.pass_context<EOL>def cli(ctx, hostname, username, password, config_dir, https): | ctx.is_root = True<EOL>ctx.user_values_entered = False<EOL>ctx.config_dir = os.path.abspath(os.path.expanduser(config_dir))<EOL>ctx.config = load_config(ctx)<EOL>ctx.hostname = hostname<EOL>ctx.username = username<EOL>ctx.password = password<EOL>ctx.https = https<EOL>ctx.wva = None<EOL> | Command-line interface for interacting with a WVA device | f912:m10 |
@cli.group()<EOL>@click.pass_context<EOL>def cliconfig(ctx): | View and clear CLI config | f912:m11 |
|
@cliconfig.command()<EOL>@click.pass_context<EOL>def show(ctx): | cli_pprint(get_root_ctx(ctx).config)<EOL> | Show the current configuration | f912:m12 |
@cliconfig.command()<EOL>@click.pass_context<EOL>def clear(ctx): | clear_config(get_root_ctx(ctx))<EOL> | Clear the local WVA configuration
Note that this command does not impact any settings on any WVA device and
only impacts that locally stored settings used by the tool. This configuration
is usually stored in ~/.wva/config.json and includes the WVA hostname, username,
and password settings. | f912:m13 |
@cli.command()<EOL>@click.argument('<STR_LIT>')<EOL>@click.pass_context<EOL>def get(ctx, uri): | http_client = get_wva(ctx).get_http_client()<EOL>cli_pprint(http_client.get(uri))<EOL> | Perform an HTTP GET of the provided URI
The URI provided is relative to the /ws base to allow for easy navigation of
the resources exposed by the WVA. Example Usage::
\b
$ wva get /
{'ws': ['vehicle',
'hw',
'config',
'state',
'files',
'alarms',
'subscriptions',
'password']}
$ wva get /vehicle
{'vehicle': ['vehicle/ecus', 'vehicle/data', 'vehicle/dtc']}
$ wva get /vehicle/ecus
{'ecus': ['vehicle/ecus/can0ecu0', 'vehicle/ecus/can0ecu251']}
$ wva get /vehicle/ecus/can0ecu0
{'can0ecu0': ['vehicle/ecus/can0ecu0/name',
'vehicle/ecus/can0ecu0/address',
'vehicle/ecus/can0ecu0/function',
'vehicle/ecus/can0ecu0/bus',
'vehicle/ecus/can0ecu0/channel',
'vehicle/ecus/can0ecu0/make',
'vehicle/ecus/can0ecu0/model',
'vehicle/ecus/can0ecu0/serial_number',
'vehicle/ecus/can0ecu0/unit_number',
'vehicle/ecus/can0ecu0/VIN']}
$ wva get /vehicle/ecus/can0ecu0/bus
{'bus': 'J1939'} | f912:m14 |
@cli.command()<EOL>@click.argument('<STR_LIT>')<EOL>@click.pass_context<EOL>def delete(ctx, uri): | http_client = get_wva(ctx).get_http_client()<EOL>cli_pprint(http_client.delete(uri))<EOL> | DELETE the specified URI
Example:
\b
$ wva get files/userfs/WEB/python
{'file_list': ['files/userfs/WEB/python/.ssh',
'files/userfs/WEB/python/README.md']}
$ wva delete files/userfs/WEB/python/README.md
''
$ wva get files/userfs/WEB/python
{'file_list': ['files/userfs/WEB/python/.ssh']} | f912:m15 |
@cli.command()<EOL>@click.argument('<STR_LIT>')<EOL>@click.argument('<STR_LIT>', type=click.File())<EOL>@click.pass_context<EOL>def post(ctx, uri, input_file): | http_client = get_wva(ctx).get_http_client()<EOL>cli_pprint(http_client.post(uri, input_file.read()))<EOL> | POST file data to a specific URI
Note that POST is not used for most web services URIs. Instead,
PUT is used for creating resources. | f912:m16 |
@cli.command()<EOL>@click.argument('<STR_LIT>')<EOL>@click.argument('<STR_LIT>', type=click.File())<EOL>@click.pass_context<EOL>def put(ctx, uri, input_file): | http_client = get_wva(ctx).get_http_client()<EOL>cli_pprint(http_client.put(uri, input_file.read()))<EOL> | PUT file data to a specific URI
Example:
\b
$ wva get /files/userfs/WEB/python
{'file_list': ['files/userfs/WEB/python/.ssh']}
$ wva put /files/userfs/WEB/python/README.md README.md
''
$ wva get /files/userfs/WEB/python
{'file_list': ['files/userfs/WEB/python/.ssh',
'files/userfs/WEB/python/README.md']} | f912:m17 |
@cli.group()<EOL>@click.pass_context<EOL>def vehicle(ctx): | Vehicle Data Commands | f912:m18 |
|
@vehicle.command(short_help="<STR_LIT>")<EOL>@click.argument('<STR_LIT>')<EOL>@click.option('<STR_LIT>', default=False, help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', default=<NUM_LIT:1>, help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', default=<NUM_LIT:0.5>, help="<STR_LIT>")<EOL>@click.pass_context<EOL>def sample(ctx, element, timestamp, repeat, delay): | element = get_wva(ctx).get_vehicle_data_element(element)<EOL>for i in range(repeat):<EOL><INDENT>curval = element.sample()<EOL>if timestamp:<EOL><INDENT>print(("<STR_LIT>".format(curval.value, curval.timestamp.ctime())))<EOL><DEDENT>else:<EOL><INDENT>print(("<STR_LIT:{}>".format(curval.value)))<EOL><DEDENT>if i + <NUM_LIT:1> < repeat: <EOL><INDENT>time.sleep(delay)<EOL><DEDENT><DEDENT> | Sample the value of a vehicle data element
This command allows for the current value of a vehicle data element
to be sampled:
\b
$ wva vehicle sample VehicleSpeed
168.15329
Optionally, the value may be samples multiple times:
\b
$ wva vehicle sample VehicleSpeed --repeat 10 --delay 1 --timestamp
148.076462 at Tue Mar 24 23:52:56 2015
145.564896 at Tue Mar 24 23:52:57 2015
143.057251 at Tue Mar 24 23:52:58 2015
138.03804 at Tue Mar 24 23:52:59 2015
135.526474 at Tue Mar 24 23:53:00 2015
133.018829 at Tue Mar 24 23:53:01 2015
130.507263 at Tue Mar 24 23:53:02 2015
127.999619 at Tue Mar 24 23:53:03 2015
125.48806 at Tue Mar 24 23:53:04 2015
122.976501 at Tue Mar 24 23:53:05 2015
For receiving large amounts of data on a periodic basis, use of subscriptions
and streams is enocuraged as it will be significantly more efficient. | f912:m20 |
@cli.group()<EOL>@click.pass_context<EOL>def subscriptions(ctx): | View and Edit subscriptions | f912:m21 |
|
@subscriptions.command()<EOL>@click.pass_context<EOL>def list(ctx): | wva = get_wva(ctx)<EOL>for subscription in wva.get_subscriptions():<EOL><INDENT>print((subscription.short_name))<EOL><DEDENT> | List short name of all current subscriptions | f912:m22 |
@subscriptions.command()<EOL>@click.argument("<STR_LIT>")<EOL>@click.pass_context<EOL>def delete(ctx, short_name): | wva = get_wva(ctx)<EOL>subscription = wva.get_subscription(short_name)<EOL>subscription.delete()<EOL> | Delete a specific subscription by short name | f912:m23 |
@subscriptions.command()<EOL>@click.pass_context<EOL>def clear(ctx): | wva = get_wva(ctx)<EOL>for subscription in wva.get_subscriptions():<EOL><INDENT>sys.stdout.write("<STR_LIT>".format(subscription.short_name))<EOL>sys.stdout.flush()<EOL>subscription.delete()<EOL>print("<STR_LIT>")<EOL><DEDENT> | Remove all registered subscriptions
Example:
\b
$ wva subscriptions clear
Deleting engineload... Done
Deleting fuelrate... Done
Deleting throttle... Done
Deleting rpm... Done
Deleting speedy... Done
To remove a specific subscription, use 'wva subscription remove <name>' instead. | f912:m24 |
@subscriptions.command()<EOL>@click.argument("<STR_LIT>")<EOL>@click.pass_context<EOL>def show(ctx, short_name): | wva = get_wva(ctx)<EOL>subscription = wva.get_subscription(short_name)<EOL>cli_pprint(subscription.get_metadata())<EOL> | Show metadata for a specific subscription
Example:
\b
$ wva subscriptions show speed
{'buffer': 'queue', 'interval': 5, 'uri': 'vehicle/data/VehicleSpeed'} | f912:m25 |
@subscriptions.command()<EOL>@click.argument("<STR_LIT>", "<STR_LIT>")<EOL>@click.argument("<STR_LIT>", "<STR_LIT>")<EOL>@click.option("<STR_LIT>", default=<NUM_LIT>, help="<STR_LIT>")<EOL>@click.option("<STR_LIT>", default="<STR_LIT>")<EOL>@click.pass_context<EOL>def add(ctx, short_name, uri, interval, buffer): | wva = get_wva(ctx)<EOL>subscription = wva.get_subscription(short_name)<EOL>subscription.create(uri, buffer, interval)<EOL> | Add a subscription with a given short_name for a given uri
This command can be used to create subscriptions to receive new pieces
of vehicle data on the stream channel on a periodic basis. By default,
subscriptions are buffered and have a 5 second interval:
\b
$ wva subscriptions add speed vehicle/data/VehicleSpeed
$ wva subscriptions show speed
{'buffer': 'queue', 'interval': 5, 'uri': 'vehicle/data/VehicleSpeed'}
These parameters can be modified by the use of optional arguments:
$ wva subscriptions add rpm vehicle/data/EngineSpeed --interval 1 --buffer discard
$ wva subscriptions show rpm
{'buffer': 'discard', 'interval': 1, 'uri': 'vehicle/data/EngineSpeed'}
To view the data coming in as a result of these subscriptions, one can use
either 'wva subscriptions listen' or 'wva subscriptions graph <name>'. | f912:m26 |
@subscriptions.command()<EOL>@click.pass_context<EOL>def listen(ctx): | wva = get_wva(ctx)<EOL>es = wva.get_event_stream()<EOL>def cb(event):<EOL><INDENT>cli_pprint(event)<EOL><DEDENT>es.add_event_listener(cb)<EOL>es.enable()<EOL>while True:<EOL><INDENT>time.sleep(<NUM_LIT:5>)<EOL><DEDENT> | Output the contents of the WVA event stream
This command shows the data being received from the WVA event stream based on
the subscriptions that have been set up and the data on the WVA vehicle bus.
\b
$ wva subscriptions listen
{'data': {'VehicleSpeed': {'timestamp': '2015-03-25T00:11:53Z',
'value': 198.272461},
'sequence': 124,
'short_name': 'speed',
'timestamp': '2015-03-25T00:11:53Z',
'uri': 'vehicle/data/VehicleSpeed'}}
{'data': {'EngineSpeed': {'timestamp': '2015-03-25T00:11:54Z',
'value': 6425.5},
'sequence': 274,
'short_name': 'rpm',
'timestamp': '2015-03-25T00:11:54Z',
'uri': 'vehicle/data/EngineSpeed'}}
...
^C
Aborted!
This command can be useful for debugging subscriptions or getting a quick
glimpse at what data is coming in to a WVA device. | f912:m27 |
@subscriptions.command()<EOL>@click.argument("<STR_LIT>", nargs=-<NUM_LIT:1>)<EOL>@click.option("<STR_LIT>", default=<NUM_LIT>, help="<STR_LIT>")<EOL>@click.option("<STR_LIT>", default=<NUM_LIT:1000>, help="<STR_LIT>")<EOL>@click.pass_context<EOL>def graph(ctx, items, seconds, ylim): | wva = get_wva(ctx)<EOL>es = wva.get_event_stream()<EOL>try:<EOL><INDENT>from wva import grapher<EOL><DEDENT>except ImportError:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>stream_grapher = grapher.WVAStreamGrapher(wva, items, seconds=seconds, ylim=ylim)<EOL>es.enable()<EOL>stream_grapher.run()<EOL><DEDENT> | Present a live graph of the incoming streaming data
This command requires that matplotlib be installed and accessible
to the application in order to work. The application reads
data from the WVA event stream and plots all data for specified
parameters within some time window. Subscriptions must be
set up prior to running this command for it to work.
As an example, let's say that I want to show the last 3 minutes (180 seconds)
of speed and rpm data for my device. In that case, I work set up my
subscriptions and execute the following...
\b
$ wva subscriptions graph --seconds=180 VehicleSpeed EngineSpeed | f912:m28 |
@cli.group()<EOL>@click.pass_context<EOL>def ssh(ctx): | Enable SSH access to a device | f912:m29 |
|
@ssh.command()<EOL>@click.option("<STR_LIT>", type=click.File(),<EOL>default=os.path.expanduser("<STR_LIT>"), help="<STR_LIT>")<EOL>@click.option("<STR_LIT>", default=False, help="<STR_LIT>")<EOL>@click.pass_context<EOL>def authorize(ctx, public_key, append): | wva = get_wva(ctx)<EOL>http_client = wva.get_http_client()<EOL>authorized_keys_uri = "<STR_LIT>"<EOL>authorized_key_contents = public_key<EOL>if append:<EOL><INDENT>try:<EOL><INDENT>existing_contents = http_client.get(authorized_keys_uri)<EOL>authorized_key_contents = "<STR_LIT>".format(existing_contents, public_key)<EOL><DEDENT>except WVAHttpNotFoundError:<EOL><INDENT>pass <EOL><DEDENT><DEDENT>http_client.put(authorized_keys_uri, authorized_key_contents)<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print(("<STR_LIT>".format(get_root_ctx(ctx).hostname)))<EOL> | Enable ssh login as the Python user for the current user
This command will create an authorized_keys file on the target device
containing the current users public key. This will allow ssh to
the WVA from this machine. | f912:m30 |
def sample(self): | <EOL>data = self._http_client.get("<STR_LIT>".format(self.name))[self.name]<EOL>dt = arrow.get(data["<STR_LIT>"]).datetime<EOL>value = data["<STR_LIT:value>"]<EOL>return VehicleDataSample(value, dt)<EOL> | Get the current value of this vehicle data element
The returned value will be a namedtuple with 'value' and
'timestamp' elements. Example::
speed_el = wva.get_vehicle_data_element('VehicleSpeed')
for i in xrange(10):
speed = speed_el.sample()
print("Speed: %0.2f @ %s" % (speed.value, speed.timestamp))
time.sleep(1) | f913:c0:m1 |
def raw_request(self, method, uri, **kwargs): | with warnings.catch_warnings(): <EOL><INDENT>warnings.simplefilter("<STR_LIT:ignore>", urllib3.exceptions.InsecureRequestWarning)<EOL>warnings.simplefilter("<STR_LIT:ignore>", urllib3.exceptions.InsecurePlatformWarning)<EOL>try:<EOL><INDENT>response = self._get_session().request(method, self._get_ws_url(uri), **kwargs)<EOL><DEDENT>except requests.RequestException as e:<EOL><INDENT>six.raise_from(WVAHttpRequestError(e), e)<EOL><DEDENT>else:<EOL><INDENT>return response<EOL><DEDENT><DEDENT> | Perform a WVA web services request and return the raw response object
:param method: The HTTP method to use when making this request
:param uri: The path past /ws to request. That is, the path requested for
a relpath of `a/b/c` would be `/ws/a/b/c`.
:raises WVAHttpSocketError: if there was an error making the HTTP request. That is,
the request was unable to make it to the WVA for some reason. | f921:c0:m11 |
def request(self, method, uri, **kwargs): | response = self.raw_request(method, uri, **kwargs)<EOL>if response.status_code != <NUM_LIT:200>:<EOL><INDENT>exception_class = HTTP_STATUS_EXCEPTION_MAP.get(response.status_code, WVAHttpError)<EOL>raise exception_class(response)<EOL><DEDENT>if response.headers.get("<STR_LIT>") == "<STR_LIT:application/json>":<EOL><INDENT>return json.loads(response.text)<EOL><DEDENT>else:<EOL><INDENT>return response.text<EOL><DEDENT> | Perform a WVA web services request and return the decoded value if successful
:param method: The HTTP method to use when making this request
:param uri: The path past /ws to request. That is, the path requested for
a relpath of `a/b/c` would be `/ws/a/b/c`.
:raises WVAHttpError: if a response is received but the success is non-success
:raises WVAHttpSocketError: if there was an error making the HTTP request. That is,
the request was unable to make it to the WVA for some reason.
:return: If the response content type is JSON, it will be deserialized and a
python dictionary containing the information from the json document will
be returned. If not a JSON response, a unicode string of the response
text will be returned. | f921:c0:m12 |
def delete(self, uri, **kwargs): | return self.request("<STR_LIT>", uri, **kwargs)<EOL> | DELETE the specified web service path
See :meth:`request` for additional details. | f921:c0:m13 |
def get(self, uri, **kwargs): | return self.request("<STR_LIT:GET>", uri, **kwargs)<EOL> | GET the specified web service path and return the decoded response contents
See :meth:`request` for additional details. | f921:c0:m14 |
def post(self, uri, data, **kwargs): | return self.request("<STR_LIT:POST>", uri, data=data, **kwargs)<EOL> | POST the provided data to the specified path
See :meth:`request` for additional details. The `data` parameter here is
expected to be a string type. | f921:c0:m15 |
def post_json(self, uri, data, **kwargs): | encoded_data = json.dumps(data)<EOL>kwargs.setdefault("<STR_LIT>", {}).update({<EOL>"<STR_LIT:Content-Type>": "<STR_LIT:application/json>", <EOL>})<EOL>return self.post(uri, data=encoded_data, **kwargs)<EOL> | POST the provided data as json to the specified path
See :meth:`request` for additional details. | f921:c0:m16 |
def put(self, uri, data, **kwargs): | return self.request("<STR_LIT>", uri, data=data, **kwargs)<EOL> | PUT the provided data to the specified path
See :meth:`request` for additional details. The `data` parameter here is
expected to be a string type. | f921:c0:m17 |
def put_json(self, uri, data, **kwargs): | encoded_data = json.dumps(data)<EOL>kwargs.setdefault("<STR_LIT>", {}).update({<EOL>"<STR_LIT:Content-Type>": "<STR_LIT:application/json>", <EOL>})<EOL>return self.put(uri, data=encoded_data, **kwargs)<EOL> | PUT the provided data as json to the specified path
See :meth:`request` for additional details. | f921:c0:m18 |
def emit_event(self, event): | with self._lock:<EOL><INDENT>listeners = list(self._event_listeners)<EOL><DEDENT>for cb in list(self._event_listeners):<EOL><INDENT>try:<EOL><INDENT>cb(event)<EOL><DEDENT>except:<EOL><INDENT>logger.exception("<STR_LIT>")<EOL><DEDENT><DEDENT> | Emit the specified event (notify listeners) | f924:c0:m1 |
def enable(self): | with self._lock:<EOL><INDENT>if self._event_listener_thread is None:<EOL><INDENT>self._event_listener_thread = WVAEventListenerThread(self, self._http_client)<EOL>self._event_listener_thread.start()<EOL><DEDENT><DEDENT> | Enable the stream thread
This operation will ensure that the thread that is responsible
for connecting to the WVA and triggering event callbacks is started.
This thread will continue to run and do what it needs to do to
maintain a connection to the WVA.
The status of the thread can be monitored by calling :meth:`get_status`. | f924:c0:m2 |
def disable(self): | with self._lock:<EOL><INDENT>if self._event_listener_thread is not None:<EOL><INDENT>self._event_listener_thread.stop()<EOL>self._event_listener_thread = None<EOL><DEDENT><DEDENT> | Disconnect from the event stream | f924:c0:m3 |
def get_status(self): | with self._lock:<EOL><INDENT>if self._event_listener_thread is None:<EOL><INDENT>return EVENT_STREAM_STATE_DISABLED<EOL><DEDENT>else:<EOL><INDENT>return self._event_listener_thread.get_state()<EOL><DEDENT><DEDENT> | Get the current status of the event stream system
The status will be one of the following:
- EVENT_STREAM_STATE_STOPPED: if the stream thread has not been enabled
- EVENT_STREAM_STATE_CONNECTING: the stream thread is running and
attempting to establish a connection to the WVA to receive events.
- EVENT_STREAM_STATE_CONNECTED: We are connected to the WVA and
receiving or ready to receive events. If no events are being
received, one should verify that vehicle data is being received
and there is an appropriate set of subscriptions set up. | f924:c0:m4 |
def add_event_listener(self, callback): | with self._lock:<EOL><INDENT>self._event_listeners.add(callback)<EOL><DEDENT> | Add a listener that will be called when events are received
This callback will be called when any event is received. The callback
will be called as follows and should have an appropriate shape::
callback(event)
Where event is a dictionary containg the event data as described in
the `WVA Documentation on Events <http://goo.gl/6vU5i1>`_.
.. note::
The event stream operates in its own thread of execution and event callbacks
will occur on the event stream thread. In order to avoid delay of delivery
of other events, one should avoid blocking in the callback. If there is
a large amount of work to do, it may make sense to use a Queue to pass
the event on to another thread of execution. | f924:c0:m5 |
def remove_event_listener(self, callback): | with self._lock:<EOL><INDENT>self._event_listeners.remove(callback)<EOL><DEDENT> | Remove the provided event listener callback | f924:c0:m6 |
def _parse_one_event(self): | <EOL>try:<EOL><INDENT>open_brace_idx = self._buf.index('<STR_LIT:{>')<EOL><DEDENT>except ValueError:<EOL><INDENT>self._buf = six.u('<STR_LIT>') <EOL><DEDENT>else:<EOL><INDENT>if open_brace_idx > <NUM_LIT:0>:<EOL><INDENT>self._buf = self._buf[open_brace_idx:]<EOL><DEDENT><DEDENT>try:<EOL><INDENT>event, idx = self._decoder.raw_decode(self._buf)<EOL>self._buf = self._buf[idx:]<EOL>return event<EOL><DEDENT>except ValueError:<EOL><INDENT>return None<EOL><DEDENT> | Parse the stream buffer and return either a single event or None | f924:c1:m2 |
def get_state(self): | return self._state<EOL> | Get the current state | f924:c1:m6 |
def stop(self): | self._stop_requested = True<EOL>self.join()<EOL> | Request that the event stream thread be stopped and wait for it to stop | f924:c1:m7 |
def get_http_client(self): | return self._http_client<EOL> | Get a direct reference to the http client used by this WVA instance | f925:c0:m9 |
def get_vehicle_data_element(self, name): | return VehicleDataElement(self._http_client, name)<EOL> | Return a :class:`VehicleDataElement` with the given name
For example, if I wanted to get information about the speed of a vehicle,
I could do so by doing the following::
speed = wva.get_vehicle_data_element("VehicleSpeed")
print(speed.get_value()) | f925:c0:m10 |
def get_vehicle_data_elements(self): | <EOL>elements = {}<EOL>for uri in self.get_http_client().get("<STR_LIT>").get("<STR_LIT:data>", []):<EOL><INDENT>name = uri.split("<STR_LIT:/>")[-<NUM_LIT:1>]<EOL>elements[name] = self.get_vehicle_data_element(name)<EOL><DEDENT>return elements<EOL> | Get a dictionary mapping names to :class:`VehicleData` instances
This result is based on the results of `GET /ws/vehicle/data` that returns a list
of URIs to each vehicle data element. The value is a handle for accessing
additional information about a particular data element.
:raises WVAError: In the event of a problem retrieving the list of data elements
:returns: A dictionary of element names mapped to :class:`VehicleDataElement` instances. | f925:c0:m11 |
def get_subscription(self, short_name): | return WVASubscription(self._http_client, short_name)<EOL> | Get the subscription with the provided short_name
:returns: A :class:`WVASubscription` instance bound for the specified short name | f925:c0:m12 |
def get_subscriptions(self): | <EOL>subscriptions = []<EOL>for uri in self.get_http_client().get("<STR_LIT>").get('<STR_LIT>'):<EOL><INDENT>subscriptions.append(self.get_subscription(uri.split("<STR_LIT:/>")[-<NUM_LIT:1>]))<EOL><DEDENT>return subscriptions<EOL> | Return a list of subscriptions currently active for this WVA device
:raises WVAError: if there is a problem getting the subscription list from the WVA
:returns: A list of :class:`WVASubscription` instances | f925:c0:m13 |
def get_event_stream(self): | if self._event_stream is None:<EOL><INDENT>self._event_stream = WVAEventStream(self._http_client)<EOL><DEDENT>return self._event_stream<EOL> | Get the event stream associated with this WVA
Note that this event stream is shared across all users of this WVA device
as the WVA only supports a single event stream.
:return: a new :class:`WVAEventStream` instance | f925:c0:m14 |
def main(): | logging.basicConfig(level=logging.INFO)<EOL>run_metrics = py_interop_run_metrics.run_metrics()<EOL>summary = py_interop_summary.run_summary()<EOL>valid_to_load = py_interop_run.uchar_vector(py_interop_run.MetricCount, <NUM_LIT:0>)<EOL>py_interop_run_metrics.list_summary_metrics_to_load(valid_to_load)<EOL>for run_folder_path in sys.argv[<NUM_LIT:1>:]:<EOL><INDENT>run_folder = os.path.basename(run_folder_path)<EOL>try:<EOL><INDENT>run_metrics.read(run_folder_path, valid_to_load)<EOL><DEDENT>except Exception as ex:<EOL><INDENT>logging.warn("<STR_LIT>"%(run_folder, str(ex)))<EOL>continue<EOL><DEDENT>py_interop_summary.summarize_run_metrics(run_metrics, summary)<EOL>error_rate_read_lane_surface = numpy.zeros((summary.size(), summary.lane_count(), summary.surface_count()))<EOL>for read_index in range(summary.size()):<EOL><INDENT>for lane_index in range(summary.lane_count()):<EOL><INDENT>for surface_index in range(summary.surface_count()):<EOL><INDENT>error_rate_read_lane_surface[read_index, lane_index, surface_index] =summary.at(read_index).at(lane_index).at(surface_index).error_rate().mean()<EOL><DEDENT><DEDENT><DEDENT>logging.info("<STR_LIT>"+run_folder)<EOL>for read_index in range(summary.size()):<EOL><INDENT>read_summary = summary.at(read_index)<EOL>logging.info("<STR_LIT>"+str(read_summary.read().number())+"<STR_LIT>"+str(error_rate_read_lane_surface[read_index, :, <NUM_LIT:0>].mean()))<EOL><DEDENT><DEDENT> | Retrieve run folder paths from the command line
Ensure only metrics required for summary are loaded
Load the run metrics
Calculate the summary metrics
Display error by lane, read | f930:m0 |
def get_version(): | version_py = os.path.join(os.path.dirname(__file__), '<STR_LIT>', '<STR_LIT>')<EOL>with open(version_py, '<STR_LIT:r>') as fh:<EOL><INDENT>for line in fh:<EOL><INDENT>if line.startswith('<STR_LIT>'):<EOL><INDENT>return line.split('<STR_LIT:=>')[-<NUM_LIT:1>].strip().replace('<STR_LIT:">', '<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>raise ValueError('<STR_LIT>'.format(version_py))<EOL> | Gets the current version of the package. | f933:m0 |
def generate_save_load(cls): | a = cls()<EOL>b = cls()<EOL>b.load(a.save())<EOL>return a.save(), b.save()<EOL> | Constructs an empty object and clones it from the serialized representation. | f934:m0 |
def login(self, email, password, android_id): | self._email = email<EOL>self._android_id = android_id<EOL>res = gpsoauth.perform_master_login(self._email, password, self._android_id)<EOL>if '<STR_LIT>' not in res:<EOL><INDENT>raise exception.LoginException(res.get('<STR_LIT>'), res.get('<STR_LIT>'))<EOL><DEDENT>self._master_token = res['<STR_LIT>']<EOL>self.refresh()<EOL>return True<EOL> | Authenticate to Google with the provided credentials.
Args:
email (str): The account to use.
password (str): The account password.
android_id (str): An identifier for this client.
Raises:
LoginException: If there was a problem logging in. | f935:c0:m1 |
def load(self, email, master_token, android_id): | self._email = email<EOL>self._android_id = android_id<EOL>self._master_token = master_token<EOL>self.refresh()<EOL>return True<EOL> | Authenticate to Google with the provided master token.
Args:
email (str): The account to use.
master_token (str): The master token.
android_id (str): An identifier for this client.
Raises:
LoginException: If there was a problem logging in. | f935:c0:m2 |
def getMasterToken(self): | return self._master_token<EOL> | Gets the master token.
Returns:
str: The account master token. | f935:c0:m3 |
def setMasterToken(self, master_token): | self._master_token = master_token<EOL> | Sets the master token. This is useful if you'd like to authenticate
with the API without providing your username & password.
Do note that the master token has full access to your account.
Args:
master_token (str): The account master token. | f935:c0:m4 |
def getEmail(self): | return self._email<EOL> | Gets the account email.
Returns:
str: The account email. | f935:c0:m5 |
def setEmail(self, email): | self._email = email<EOL> | Gets the account email.
Args:
email (str): The account email. | f935:c0:m6 |
def getAndroidId(self): | return self._android_id<EOL> | Gets the device id.
Returns:
str: The device id. | f935:c0:m7 |
def setAndroidId(self, android_id): | self._android_id = android_id<EOL> | Sets the device id.
Args:
android_id (str): The device id. | f935:c0:m8 |
def getAuthToken(self): | return self._auth_token<EOL> | Gets the auth token.
Returns:
Union[str, None]: The auth token. | f935:c0:m9 |
def refresh(self): | res = gpsoauth.perform_oauth(<EOL>self._email, self._master_token, self._android_id,<EOL>service=self._scopes,<EOL>app='<STR_LIT>',<EOL>client_sig='<STR_LIT>'<EOL>)<EOL>if '<STR_LIT>' not in res:<EOL><INDENT>if '<STR_LIT>' not in res:<EOL><INDENT>raise exception.LoginException(res.get('<STR_LIT>'))<EOL><DEDENT><DEDENT>self._auth_token = res['<STR_LIT>']<EOL>return self._auth_token<EOL> | Refresh the OAuth token.
Returns:
string: The auth token.
Raises:
LoginException: If there was a problem refreshing the OAuth token. | f935:c0:m10 |
def logout(self): | self._master_token = None<EOL>self._auth_token = None<EOL>self._email = None<EOL>self._android_id = None<EOL> | Log out of the account. | f935:c0:m11 |
def getAuth(self): | return self._auth<EOL> | Get authentication details for this API.
Args:
auth (APIAuth): The auth object | f935:c1:m1 |
def setAuth(self, auth): | self._auth = auth<EOL> | Set authentication details for this API.
Args:
auth (APIAuth): The auth object | f935:c1:m2 |
def send(self, **req_kwargs): | i = <NUM_LIT:0><EOL>while True:<EOL><INDENT>response = self._send(**req_kwargs).json()<EOL>if '<STR_LIT:error>' not in response:<EOL><INDENT>break<EOL><DEDENT>error = response['<STR_LIT:error>']<EOL>if error['<STR_LIT:code>'] != <NUM_LIT>:<EOL><INDENT>raise exception.APIException(error['<STR_LIT:code>'], error)<EOL><DEDENT>if i >= self.RETRY_CNT:<EOL><INDENT>raise exception.APIException(error['<STR_LIT:code>'], error)<EOL><DEDENT>logger.info('<STR_LIT>')<EOL>self._auth.refresh()<EOL>i += <NUM_LIT:1><EOL><DEDENT>return response<EOL> | Send an authenticated request to a Google API.
Automatically retries if the access token has expired.
Args:
**req_kwargs: Arbitrary keyword arguments to pass to Requests.
Return:
dict: The parsed JSON response.
Raises:
APIException: If the server returns an error.
LoginException: If :py:meth:`login` has not been called. | f935:c1:m3 |
def _send(self, **req_kwargs): | auth_token = self._auth.getAuthToken()<EOL>if auth_token is None:<EOL><INDENT>raise exception.LoginException('<STR_LIT>')<EOL><DEDENT>req_kwargs.setdefault('<STR_LIT>', {<EOL>'<STR_LIT>': '<STR_LIT>' + auth_token<EOL>})<EOL>return self._session.request(**req_kwargs)<EOL> | Send an authenticated request to a Google API.
Args:
**req_kwargs: Arbitrary keyword arguments to pass to Requests.
Return:
requests.Response: The raw response.
Raises:
LoginException: If :py:meth:`login` has not been called. | f935:c1:m4 |
def changes(self, target_version=None, nodes=None, labels=None): | if nodes is None:<EOL><INDENT>nodes = []<EOL><DEDENT>if labels is None:<EOL><INDENT>labels = []<EOL><DEDENT>current_time = time.time()<EOL>params = {<EOL>'<STR_LIT>': nodes,<EOL>'<STR_LIT>': _node.NodeTimestamps.int_to_str(current_time),<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': self._session_id,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>},<EOL>'<STR_LIT>': [<EOL>{'<STR_LIT:type>': '<STR_LIT>'}, <EOL>{'<STR_LIT:type>': '<STR_LIT>'}, <EOL>{'<STR_LIT:type>': '<STR_LIT>'}, <EOL>{'<STR_LIT:type>': '<STR_LIT>'}, <EOL>{'<STR_LIT:type>': '<STR_LIT>'}, <EOL>{'<STR_LIT:type>': '<STR_LIT>'}, <EOL>{'<STR_LIT:type>': '<STR_LIT>'}, <EOL>{'<STR_LIT:type>': '<STR_LIT>'}, <EOL>{'<STR_LIT:type>': '<STR_LIT>'}, <EOL>{'<STR_LIT:type>': '<STR_LIT>'}, <EOL>{'<STR_LIT:type>': '<STR_LIT>'}, <EOL>]<EOL>},<EOL>}<EOL>if target_version is not None:<EOL><INDENT>params['<STR_LIT>'] = target_version<EOL><DEDENT>if labels:<EOL><INDENT>params['<STR_LIT>'] = {<EOL>'<STR_LIT>': labels<EOL>}<EOL><DEDENT>logger.debug('<STR_LIT>', len(labels), len(nodes))<EOL>return self.send(<EOL>url=self._base_url + '<STR_LIT>',<EOL>method='<STR_LIT:POST>',<EOL>json=params<EOL>)<EOL> | Sync up (and down) all changes.
Args:
target_version (str): The local change version.
nodes (List[dict]): A list of nodes to sync up to the server.
labels (List[dict]): A list of labels to sync up to the server.
Return:
dict: Description of all changes.
Raises:
APIException: If the server returns an error. | f935:c2:m2 |
def get(self, blob): | return self._send(<EOL>url=self._base_url + blob.parent.server_id + '<STR_LIT:/>' + blob.server_id + '<STR_LIT>',<EOL>method='<STR_LIT:GET>',<EOL>allow_redirects=False<EOL>).headers.get('<STR_LIT>')<EOL> | Get the canonical link to a media blob.
Args:
blob (gkeepapi.node.Blob): The blob.
Returns:
str: A link to the media. | f935:c3:m1 |
def create(self): | params = {}<EOL>return self.send(<EOL>url=self._base_url + '<STR_LIT>',<EOL>method='<STR_LIT:POST>',<EOL>json=params<EOL>)<EOL> | Create a new reminder. | f935:c4:m1 |
def list(self, master=True): | params = {}<EOL>params.update(self.static_params)<EOL>if master:<EOL><INDENT>params.update({<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>},<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT>": False,<EOL>})<EOL><DEDENT>else:<EOL><INDENT>current_time = time.time()<EOL>start_time = int((current_time - (<NUM_LIT> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT>)) * <NUM_LIT:1000>)<EOL>end_time = int((current_time + (<NUM_LIT> * <NUM_LIT> * <NUM_LIT>)) * <NUM_LIT:1000>)<EOL>params.update({<EOL>"<STR_LIT>": {<EOL>"<STR_LIT>":"<STR_LIT>",<EOL>"<STR_LIT>": True,<EOL>},<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT>": start_time,<EOL>"<STR_LIT>": end_time,<EOL>"<STR_LIT>": [],<EOL>})<EOL><DEDENT>return self.send(<EOL>url=self._base_url + '<STR_LIT:list>',<EOL>method='<STR_LIT:POST>',<EOL>json=params<EOL>)<EOL> | List current reminders. | f935:c4:m2 |
def history(self, storage_version): | params = {<EOL>"<STR_LIT>": storage_version,<EOL>"<STR_LIT>": True,<EOL>}<EOL>params.update(self.static_params)<EOL>return self.send(<EOL>url=self._base_url + '<STR_LIT>',<EOL>method='<STR_LIT:POST>',<EOL>json=params<EOL>)<EOL> | Get reminder changes. | f935:c4:m3 |
def update(self): | params = {}<EOL>return self.send(<EOL>url=self._base_url + '<STR_LIT>',<EOL>method='<STR_LIT:POST>',<EOL>json=params<EOL>)<EOL> | Sync up changes to reminders. | f935:c4:m4 |
def login(self, username, password, state=None, sync=True): | auth = APIAuth(self.OAUTH_SCOPES)<EOL>ret = auth.login(username, password, get_mac())<EOL>if ret:<EOL><INDENT>self.load(auth, state, sync)<EOL><DEDENT>return ret<EOL> | Authenticate to Google with the provided credentials & sync.
Args:
email (str): The account to use.
password (str): The account password.
state (dict): Serialized state to load.
Raises:
LoginException: If there was a problem logging in. | f935:c5:m2 |
def resume(self, email, master_token, state=None, sync=True): | auth = APIAuth(self.OAUTH_SCOPES)<EOL>ret = auth.load(email, master_token, android_id=get_mac())<EOL>if ret:<EOL><INDENT>self.load(auth, state, sync)<EOL><DEDENT>return ret<EOL> | Authenticate to Google with the provided master token & sync.
Args:
email (str): The account to use.
master_token (str): The master token.
state (dict): Serialized state to load.
Raises:
LoginException: If there was a problem logging in. | f935:c5:m3 |