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>pa...
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 ==...
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><...
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...
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...
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.SI...
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...
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 operatio...
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` messa...
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)<EO...
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><IND...
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" met...
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]<...
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...
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><DEDEN...
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 ...
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 plug...
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><INDE...
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, ...
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>", h...
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',...
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/p...
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/user...
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(c...
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_...
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...
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/VehicleSp...
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', ...
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><DED...
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 ru...
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)<E...
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() pr...
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...
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 t...
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><INDE...
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...
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...
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 re...
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 ...
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._deco...
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 ...
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...
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><DEDE...
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(...
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>...
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><DE...
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 re...
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>'...
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. ...
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> ...
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