volttron.platform package

Core package.

volttron.platform.get_address()[source]

Return the VIP address of the platform If the VOLTTRON_VIP_ADDR environment variable is set, it used. Otherwise, it is derived from get_home().

volttron.platform.get_examples(agent_dir)[source]
volttron.platform.get_home()[source]

Return the home directory with user and variables expanded.

If the VOLTTRON_HOME environment variable is set, it used. Otherwise, the default value of ‘~/.volttron’ is used.

volttron.platform.get_ops(agent_dir=None)[source]
volttron.platform.get_services_core(agent_dir=None)[source]
volttron.platform.get_volttron_data()[source]
volttron.platform.get_volttron_root()[source]

Returns the root folder where the volttron code base resideds on disk.

Returns:absolute path to root folder
volttron.platform.is_instance_running(volttron_home=None)[source]
volttron.platform.set_home(home=None)[source]

Set the home directory with user and variables expanded.

If the home is sent in, it used. Otherwise, the default value of ‘~/.volttron’ is used.

Subpackages

Submodules

volttron.platform.aip module

Component for the instantiation and packaging of agents.

class volttron.platform.aip.AIPplatform(env, **kwargs)[source]

Bases: object

Manages the main workflow of receiving and sending agents.

active_agents()[source]
agent_dir(agent_uuid)[source]
agent_identity(agent_uuid)[source]

Return the identity of the agent that is installed.

The IDENTITY file is written to the agent’s install directory the the first time the agent is installed. This function reads that file and returns the read value.

@param agent_uuid: @return:

agent_name(agent_uuid)[source]
agent_priority(agent_uuid)[source]
agent_status(agent_uuid)[source]
agent_tag(agent_uuid)[source]
agent_uuid_from_pid(pid)[source]
agent_version(agent_uuid)[source]
agent_versions()[source]
autostart()[source]
check_resources(execreqs)[source]
clear_status(clear_all=False)[source]
config_dir
finish()[source]
get_agent_identity_to_uuid_mapping()[source]
get_agent_keystore(agent_uuid)[source]
get_all_agent_identities()[source]
get_execreqs(agent_uuid)[source]
install_agent(agent_wheel, vip_identity=None, publickey=None, secretkey=None)[source]
install_dir
land_agent(agent_wheel)[source]
list_agents()[source]
prioritize_agent(agent_uuid, priority='50')[source]
publish_address
remove_agent(agent_uuid, remove_auth=True)[source]
run_dir
setup()[source]

Creates paths for used directories for the instance.

shutdown()[source]
start_agent(agent_uuid)[source]
status_agents()[source]
stop_agent(agent_uuid)[source]
subscribe_address
tag_agent(agent_uuid, tag)[source]
class volttron.platform.aip.ExecutionEnvironment[source]

Bases: object

Environment reserved for agent execution.

Deleting ExecutionEnvironment objects should cause the process to end and all resources to be returned to the system.

execute(*args, **kwargs)[source]
class volttron.platform.aip.IgnoreErrno(errno, *more)[source]

Bases: object

ignore = []
volttron.platform.aip.log_entries(name, agent, pid, level, stream)[source]
volttron.platform.aip.log_stream(name, agent, pid, path, stream)[source]
volttron.platform.aip.process_wait(p)[source]

volttron.platform.async module

Run gevent Greenlets in their own threads.

Supports killing threads and executing callbacks from other threads.

class volttron.platform.async.AsyncCall(hub=None)[source]

Bases: object

Send functions to another thread’s gevent hub for execution.

send(receiver, func, *args, **kwargs)[source]

Send a function to the hub to be called there.

All the arguments to this method are placed in a queue and the hub is signaled that a function is ready. When the hub switches to this handler, the functions are iterated over, each being called with its results sent to the receiver.

func is called with args and kwargs in the thread of the associated hub. If receiver is None, results are ignored and errors are printed when exceptions occur. Otherwise, receiver is called with the 2-tuple (exc_info, result). If an unhandled exception occurred, exc_info is the 3-tuple returned by sys.exc_info() and result is None. Otherwise exc_info is None and the result is func’s return value.

Note that receiver is called from the hub’s thread and may need to be injected into the thread of the receiver.

class volttron.platform.async.Threadlet(*args, **kwargs)[source]

Bases: threading.Thread

A subclass of threading.Thread supporting gevent Greenlets.

The run method is executed in the thread’s main greenlet and the thread will exit when that method returns. Other threads may run callbacks within this thread using the send() method. Unlike the base class, threading.Thread, daemon is set by default.

kill(exception=<class 'greenlet.GreenletExit'>)[source]

Raise GreenletExit or other exception in the main greenlet.

send(callback, *args, **kwargs)[source]

Execute callback in this thread’s hub.

exception volttron.platform.async.GreenletExit

Bases: exceptions.BaseException

volttron.platform.auth module

class volttron.platform.auth.AuthEntry(domain=None, address=None, mechanism='CURVE', credentials=None, user_id=None, groups=None, roles=None, capabilities=None, comments=None, enabled=True, **kwargs)[source]

Bases: object

An authentication entry contains fields for authenticating and granting permissions to an agent that connects to the platform.

Parameters:
  • domain (str) – Name assigned to locally bound address
  • address (str) – Remote address of the agent
  • mechanism (str) – Authentication mechanism, valid options are ‘NULL’ (no authentication), ‘PLAIN’ (username/password), ‘CURVE’ (CurveMQ public/private keys)
  • credentials (str) – Value depends on mechanism parameter: None if mechanism is ‘NULL’; password if mechanism is ‘PLAIN’; encoded public key if mechanism is ‘CURVE’ (see volttron.platform.vip.socket.encode_key() for method to encode public key)
  • user_id (str) – Name to associate with agent (Note: this does not have to match the agent’s VIP identity)
  • capabilities (list) – Authorized capabilities for this agent
  • roles (list) – Authorized roles for this agent. (Role names map to a set of capabilities)
  • groups (list) – Authorized groups for this agent. (Group names map to a set of roles)
  • comments (str) – Comments to associate with entry
  • enabled (bool) – Entry will only be used if this value is True
  • kwargs – These extra arguments will be ignored
add_capabilities(capabilities)[source]
match(domain, address, mechanism, credentials)[source]
static valid_credentials(cred, mechanism='CURVE')[source]

Raises AuthEntryInvalid if credentials are invalid

static valid_mechanism(mechanism)[source]

Raises AuthEntryInvalid if mechanism is invalid

exception volttron.platform.auth.AuthEntryInvalid[source]

Bases: volttron.platform.auth.AuthException

Exception for invalid AuthEntry objects

exception volttron.platform.auth.AuthException[source]

Bases: exceptions.Exception

General exception for any auth error

class volttron.platform.auth.AuthFile(auth_file=None)[source]

Bases: object

add(auth_entry, overwrite=False)[source]

Adds an AuthEntry to the auth file

Parameters:
  • auth_entry (AuthEntry) – authentication entry
  • overwrite (bool) – set to true to overwrite matching entries

Warning

If overwrite is set to False and if auth_entry matches an existing entry then this method will raise AuthFileEntryAlreadyExists

find_by_credentials(credentials)[source]

Find all entries that have the given credentials

Parameters:credentials (str) – The credentials to search for
Returns:list of entries
Return type:list
read()[source]

Gets the allowed entries, groups, and roles from the auth file.

Returns:tuple of allow-entries-list, groups-dict, roles-dict
Return type:tuple
read_allow_entries()[source]

Gets the allowed entries from the auth file.

Returns:list of allow-entries
Return type:list
remove_by_credentials(credentials)[source]

Removes entry from auth file by credential

Para credential:
 entries will this credential will be removed
remove_by_index(index)[source]

Removes entry from auth file by index

Parameters:index (int) – index of entry to remove

Warning

Calling with out-of-range index will raise AuthFileIndexError

remove_by_indices(indices)[source]

Removes entry from auth file by indices

Parameters:indices (list) – list of indicies of entries to remove

Warning

Calling with out-of-range index will raise AuthFileIndexError

set_groups(groups)[source]

Define the mapping of group names to role lists

Parameters:groups (dict) – dict where the keys are group names and the values are lists of capability names

Warning

Calling with invalid groups will raise ValueError

set_roles(roles)[source]

Define the mapping of role names to capability lists

Parameters:roles – dict where the keys are role names and the values are lists of group names

Warning

Calling with invalid roles will raise ValueError

update_by_index(auth_entry, index)[source]

Updates entry will given auth entry at given index

Parameters:
  • auth_entry (AuthEntry) – new authorization entry
  • index (int) – index of entry to update

Warning

Calling with out-of-range index will raise AuthFileIndexError

version
exception volttron.platform.auth.AuthFileEntryAlreadyExists(indicies, message=None)[source]

Bases: volttron.platform.auth.AuthFileIndexError

Exception if adding an entry that already exists

exception volttron.platform.auth.AuthFileIndexError(indices, message=None)[source]

Bases: volttron.platform.auth.AuthException, exceptions.IndexError

Exception for invalid indices provided to AuthFile

exception volttron.platform.auth.AuthFileUserIdAlreadyExists(user_id, indicies, message=None)[source]

Bases: volttron.platform.auth.AuthFileEntryAlreadyExists

Exception if adding an entry that has a taken user_id

class volttron.platform.auth.AuthService(auth_file, protected_topics_file, setup_mode, aip, *args, **kwargs)[source]

Bases: volttron.platform.vip.agent.Agent

authenticate(domain, address, mechanism, credentials)[source]
get_authorization_failures()[source]
get_authorizations(user_id)[source]

RPC method

Gets capabilities, groups, and roles for a given user.

Parameters:user_id (str) – user id field from VOLTTRON Interconnect Protocol
Returns:tuple of capabiliy-list, group-list, role-list
Return type:tuple
get_capabilities(user_id)[source]

RPC method

Gets capabilities for a given user.

Parameters:user_id (str) – user id field from VOLTTRON Interconnect Protocol
Returns:list of capabilities
Return type:list
get_groups(user_id)[source]

RPC method

Gets groups for a given user.

Parameters:user_id (str) – user id field from VOLTTRON Interconnect Protocol
Returns:list of groups
Return type:list
get_protected_topics()[source]
get_roles(user_id)[source]

RPC method

Gets roles for a given user.

Parameters:user_id (str) – user id field from VOLTTRON Interconnect Protocol
Returns:list of roles
Return type:list
get_user_to_capabilities()[source]

RPC method

Gets a mapping of all users to their capabiliites.

Returns:mapping of users to capabilities
Return type:dict
read_auth_file()[source]
setup_zap(sender, **kwargs)[source]
stop_zap(sender, **kwargs)[source]
unbind_zap(sender, **kwargs)[source]
zap_loop(sender, **kwargs)[source]
class volttron.platform.auth.List[source]

Bases: list

match(value)[source]
class volttron.platform.auth.String[source]

Bases: unicode

match(value)[source]
volttron.platform.auth.dump_user(*args)[source]
volttron.platform.auth.isregex(obj)[source]
volttron.platform.auth.load_user(string)[source]

volttron.platform.config module

Advanced argument parser.

Fully compatible with argparse, and can be used as a drop-in replacement, with the added ability add options from configuration files and environment variables. The default order of precedense is command-line > environment > config file > defaults. The only change which can be made to this order is to instruct the configuration file action to add options inline rather than at the beginning, causing configuration options to be parsed after environment variables and in the order encountered.

class volttron.platform.config.AddConstAction(option_strings, dest, const=1, type=<type 'int'>, default=None, required=False, help=None)[source]

Bases: argparse.Action

Add a constant value to the option.

class volttron.platform.config.ArgumentParser(*args, **kwargs)[source]

Bases: argparse.ArgumentParser

add_help_argument(*args, **kwargs)[source]
add_version_argument(*args, **kwargs)[source]
get_switch(action, value, option_string)[source]

Convert argument-less options when they have an argument.

Useful for allowing options in a configuration file and environment variables to be set or unset based on an argument which looks like a boolean. To be invert-able, the action must set its inverse attribute to an option that will invert the meaning.

preprocess_option(action, namespace, arg_strings, option_string)[source]

Pre-process an action.

If an action has a preprocess attribute which evaluates to True, then execute the action now. This type of action is expected to return None if it is to remain in the argument list unchanged. Otherwise, it should return two lists: the first will be appended to the configuration arguments and the second will replace the processed arguments.

volttron.platform.config.CaseInsensitiveConfigFileAction(ConfigFileAction)[source]
class volttron.platform.config.ConfigFileAction(option_strings, dest, required=False, help=None, metavar=None, **kwargs)[source]

Bases: argparse.Action

Read a configuration file and add it to the arguments to be parsed.

The file should contain one “long option” per line, with or without the leading option characters (usually –), and otherwise entered as on the command-line with shell-style quoting. Lines beginning with a hash (#) or semicolon (;) and empty lines are ignored. Hashes (#) may also be used to comment option lines, excluding everything from the comment character to the end of the line. Key-value options may be separated by =, : or whitespace.

By default, INI-style section markers are ignored. If, however, a program wants only to use settings in certain sections, it may pass a list of sections to allow. All other sections will be ignored. Section names are case-sensitive. The special None section will include global values which appear in the file before and section is declared.

Options which set their config flag to False will not be allowed in configuration files. A default value can be set on the parser with the allow_in_config option.

If ignore_unknown is True, lines containing an unknown option key will be ignored. Otherwise, an error will be issued (default behavior). Options read from the configuration file will normally be added before those for environment variables and other command-line arguments and in the order encountered to maintain the normal order of precedence. If inline is True, the configuration options will be inserted in place of the configuration option and will be processed after environment variables.

itersettings(parser, conffile)[source]
class volttron.platform.config.DebugArgumentParser(*args, **kwargs)[source]

Bases: volttron.platform.config.TrackingArgumentParser

Write options to stderr as they are added to the namespace.

This includes the source of the change. It does not include defaults.

post_action(action, parser, namespace, values, option_string, source)[source]
class volttron.platform.config.ListAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)[source]

Bases: argparse.Action

Action to store space or comma separated lists.

split(value)[source]
class volttron.platform.config.SubParsersAction(option_strings, prog, parser_class, dest='==SUPPRESS==', help=None, metavar=None)[source]

Bases: argparse._SubParsersAction

class volttron.platform.config.TrackingArgumentParser(*args, **kwargs)[source]

Bases: volttron.platform.config.ArgumentParser

Wrap up calls to actions to pre- and post-handlers.

This class is useful as a base class for debugging parsers.

post_action(action, parser, namespace, values, option_string, source)[source]
pre_action(action, parser, namespace, values, option_string, source)[source]
class volttron.platform.config.TrackingString[source]

Bases: str

String subclass that allows attaching source information.

volttron.platform.config.env_var_formatter(formatter_class=<class 'argparse.HelpFormatter'>)[source]

Decorator to automatically add env_var documentation to help.

volttron.platform.config.expandall(string)[source]

volttron.platform.control module

class volttron.platform.control.Agent(name, tag, uuid, vip_identity)

Bases: tuple

name

Alias for field number 0

tag

Alias for field number 1

uuid

Alias for field number 2

vip_identity

Alias for field number 3

class volttron.platform.control.ControlConnection(address, peer='control', publickey=None, secretkey=None, serverkey=None)[source]

Bases: object

call(method, *args, **kwargs)[source]
call_no_get(method, *args, **kwargs)[source]
kill(*args, **kwargs)[source]
notify(method, *args, **kwargs)[source]
server
class volttron.platform.control.ControlService(aip, *args, **kwargs)[source]

Bases: volttron.platform.vip.agent.Agent

agent_name(uuid)[source]
agent_status(uuid)[source]
agent_version(uuid)[source]
agent_versions()[source]
agent_vip_identity(uuid)[source]

Lookup the agent’s vip identity based upon it’s uuid.

@param uuid: @return:

clear_status(clear_all=False)[source]
get_all_agent_publickeys()[source]

RPC method to retrieve the public keys of all of the agents installed on the VOLTTRON instance.

This method does not differentiate between running and not running agents.

Note

This method will only retrieve a publickey for an installed agents. It is recommended that dynamic agents use the context of the containing agent’s publickey for connections to external instances.

Returns:mapping of identity to agent publickey
Return type:dict
install_agent(filename, channel_name, vip_identity=None, publickey=None, secretkey=None)[source]

Installs an agent on the instance instance.

The installation of an agent through this method involves sending the binary data of the agent file through a channel. The following example is the protocol for sending the agent across the wire:

Example Protocol:

# client creates channel to this agent (control)
channel = agent.vip.channel('control', 'channel_name')

# Begin sending data
sha512 = hashlib.sha512()
while True:
    request, file_offset, chunk_size = channel.recv_multipart()

    # Control has all of the file. Send hash for for it to verify.
    if request == b'checksum':
        channel.send(hash)
    assert request == b'fetch'

    # send a chunk of the file
    file_offset = int(file_offset)
    chunk_size = int(chunk_size)
    file.seek(file_offset)
    data = file.read(chunk_size)
    sha512.update(data)
    channel.send(data)

agent_uuid = agent_uuid.get(timeout=10)
# close and delete the channel
channel.close(linger=0)
del channel
:param:string:filename:
The name of the agent packaged file that is being written.
:param:string:channel_name:
The name of the channel that the agent file will be sent on.
:param:string:publickey:
Encoded public key the installed agent will use
:param:string:secretkey:
Encoded secret key the installed agent will use
install_agent_local(filename, vip_identity=None, publickey=None, secretkey=None)[source]
list_agents()[source]
prioritize_agent(uuid, priority='50')[source]
remove_agent(uuid, remove_auth=True)[source]
restart_agent(uuid)[source]
serverkey()[source]
shutdown()[source]
start_agent(uuid)[source]
status_agents()[source]
stop_agent(uuid)[source]
stop_platform()[source]
tag_agent(uuid, tag)[source]
volttron.platform.control.add_auth(opts)[source]

Add authorization entry.

If all options are None, then use interactive ‘wizard.’

volttron.platform.control.add_config_to_store(opts)[source]
volttron.platform.control.add_group(opts)[source]
volttron.platform.control.add_role(opts)[source]
volttron.platform.control.add_server_key(opts)[source]
volttron.platform.control.agent_health(opts)[source]
volttron.platform.control.backup_agent_data(output_filename, source_dir)[source]
volttron.platform.control.clear_status(opts)[source]
volttron.platform.control.create_cgroups(opts)[source]
volttron.platform.control.delete_config_from_store(opts)[source]
volttron.platform.control.disable_agent(opts)[source]
volttron.platform.control.do_stats(opts)[source]
volttron.platform.control.edit_config(opts)[source]
volttron.platform.control.enable_agent(opts)[source]
volttron.platform.control.escape(pattern)[source]
volttron.platform.control.filter_agent(agents, pattern, opts)[source]
volttron.platform.control.filter_agents(agents, patterns, opts)[source]
volttron.platform.control.find_agent_data_dir(opts, agent_uuid)[source]
volttron.platform.control.gen_keypair(opts)[source]
volttron.platform.control.get_agent_publickey(opts)[source]
volttron.platform.control.get_config(opts)[source]
volttron.platform.control.get_filtered_agents(opts, agents=None)[source]
volttron.platform.control.get_keys(opts)[source]

Gets keys from keystore and known-hosts store

volttron.platform.control.install_agent(opts, publickey=None, secretkey=None, callback=None)[source]
volttron.platform.control.list_agents(opts)[source]
volttron.platform.control.list_auth(opts, indices=None)[source]
volttron.platform.control.list_groups(opts)[source]
volttron.platform.control.list_known_hosts(opts)[source]
volttron.platform.control.list_roles(opts)[source]
volttron.platform.control.list_store(opts)[source]
volttron.platform.control.log_to_file(file, level=30, handler_class=<class 'logging.StreamHandler'>)[source]

Direct log output to a file (or something like one).

volttron.platform.control.main(argv=['/home/docs/checkouts/readthedocs.org/user_builds/volttron/envs/releases-5.x/bin/sphinx-build', '-T', '-E', '-b', 'readthedocs', '-d', '_build/doctrees-readthedocs', '-D', 'language=en', '.', '_build/html'])[source]
volttron.platform.control.priority(value)[source]
volttron.platform.control.remove_agent(opts, remove_auth=True)[source]
volttron.platform.control.remove_auth(opts)[source]
volttron.platform.control.remove_group(opts)[source]
volttron.platform.control.remove_known_host(opts)[source]
volttron.platform.control.remove_role(opts)[source]
volttron.platform.control.restart_agent(opts)[source]
volttron.platform.control.restore_agent_data(source_file, output_dir)[source]
volttron.platform.control.run_agent(opts)[source]
volttron.platform.control.send_agent(opts)[source]
volttron.platform.control.show_serverkey(opts)[source]

write serverkey to standard out.

return 0 if success, 1 if false

volttron.platform.control.shutdown_agents(opts)[source]
volttron.platform.control.start_agent(opts)[source]
volttron.platform.control.status_agents(opts)[source]
volttron.platform.control.stop_agent(opts)[source]
volttron.platform.control.tag_agent(opts)[source]
volttron.platform.control.update_auth(opts)[source]
volttron.platform.control.update_group(opts)[source]
volttron.platform.control.update_role(opts)[source]
volttron.platform.control.upgrade_agent(opts)[source]

volttron.platform.instance_setup module

volttron.platform.instance_setup.add_fake_device_to_configstore()[source]
volttron.platform.instance_setup.do_listener(*args, **kwargs)[source]
volttron.platform.instance_setup.do_master_driver(*args, **kwargs)[source]
volttron.platform.instance_setup.do_platform_historian(*args, **kwargs)[source]
volttron.platform.instance_setup.do_vc(*args, **kwargs)[source]
volttron.platform.instance_setup.do_vcp(*args, **kwargs)[source]
volttron.platform.instance_setup.do_vip()[source]
volttron.platform.instance_setup.fail_if_instance_running()[source]
volttron.platform.instance_setup.fail_if_not_in_src_root()[source]
volttron.platform.instance_setup.installs(agent_dir, tag, identity=None, post_install_func=None)[source]
volttron.platform.instance_setup.is_valid_port(port)[source]
volttron.platform.instance_setup.is_valid_url(url, accepted_schemes)[source]
volttron.platform.instance_setup.main()[source]
volttron.platform.instance_setup.vc_config()[source]
volttron.platform.instance_setup.wizard()[source]

Routine for configuring an insalled volttron instance.

The function interactively sets up the instance for working with volttron central and the discovery service.

volttron.platform.jsonrpc module

Implementation of JSON-RPC 2.0 with support for bi-directional calls.

See http://www.jsonrpc.org/specification for the complete specification.

exception volttron.platform.jsonrpc.Error(code, message, data=None)[source]

Bases: exceptions.Exception

Raised when a recoverable JSON-RPC protocol error occurs.

exception volttron.platform.jsonrpc.MethodNotFound(code, message, data=None)[source]

Bases: volttron.platform.jsonrpc.Error

Raised when remote method is not implemented.

exception volttron.platform.jsonrpc.RemoteError(message, **exc_info)[source]

Bases: exceptions.Exception

Report the details of an error which occurred remotely.

Instances of this exception are usually created by exception_from_json(), which uses the ‘detail’ element of the JSON-RPC error for message, if it is set, otherwise the JSON-RPC error message. The exc_info argument is set from the ‘exception.py’ element associated with an error code of -32000 (UNHANDLED_EXCEPTION). Typical keys in exc_info are exc_type, exc_args, and exc_tb (if tracebacks are allowed) which are stringified versions of the tuple returned from sys.exc_info().

print_tb(file=<open file '<stderr>', mode 'w'>)[source]

Pretty print the traceback in the standard format.

class volttron.platform.jsonrpc.Dispatcher[source]

Bases: object

Parses and directs JSON-RPC 2.0 requests/responses.

Parses a JSON-RPC message conatained in a dictionary (JavaScript object) or a batch of messages (list of dictionaries) and dispatches them appropriately.

Subclasses must implement the serialize and deserialize methods with the JSON library of choice. The exception, result, error, method and batch handling methods should also be implemented.

batch(**kwds)[source]

Context manager for batch requests.

Entered before processing a batch request and exited afterward.

batch_call(requests)[source]

Create and return a request for a batch of method calls.

requests is an iterator of lists or tuples with 4 items each: ident, method, args, kwargs. These are the same 4 arguments required by the call() method. The first (ident) element may be None to indicate a notification.

call(ident, method, args=None, kwargs=None)[source]

Create and return a request for a single method call.

deserialize(json_string)[source]

Unpack a JSON string and return Python object(s).

dispatch(json_string, context=None)[source]

Dispatch a JSON-RPC message and return a response or None.

error(response, ident, code, message, data=None, context=None)[source]

Called when an error resposne is received.

exception(response, ident, message, context=None)[source]

Called for response errors.

Typically called when a response, such as an error, does not contain all the necessary members and sending an error to the remote peer is not possible. Also called when serializing a response fails.

method(request, ident, name, args, kwargs, batch=None, context=None)[source]

Called to get make method call and return results.

request is the original JSON request (as dict). name is the name of the method requested. Only one of args or kwargs will contain parameters. If method is being executed as part of a batch request, batch will be the value returned from the batch() context manager.

This method should raise NotImplementedError() if the method is unimplemented. Otherwise, it should return the result of the method call or raise an exception. If the raised exception has a traceback attribute, which should be a string (if set), it will be sent back in the returned error. An exc_info attribute may also be set which must be a dictionary and will be used as the basis for the exception.py member of the returned error.

notify(method, args=None, kwargs=None)[source]

Create and return a request for a single notification.

result(response, ident, result, context=None)[source]

Called when a result response is received.

serialize(json_obj)[source]

Pack compatible Python objects into and return JSON string.

volttron.platform.keystore module

Module for storing local public and secret keys and remote public keys

class volttron.platform.keystore.BaseJSONStore(filename, permissions=384)[source]

Bases: object

JSON-file-backed store for dictionaries

load()[source]
remove(key)[source]
store(data)[source]
update(new_data)[source]
class volttron.platform.keystore.KeyStore(filename=None)[source]

Bases: volttron.platform.keystore.BaseJSONStore

Handle generation, storage, and retrival of CURVE key pairs

generate()[source]

Generate and store new key pair

static generate_keypair_dict()[source]

Generate and return new keypair as dictionary

static get_default_path()[source]
isvalid()[source]

Check if key pair is valid

public

Return encoded public key

secret

Return encoded secret key

class volttron.platform.keystore.KnownHostsStore(filename=None)[source]

Bases: volttron.platform.keystore.BaseJSONStore

Handle storage and retrival of known hosts

add(addr, server_key)[source]
serverkey(addr)[source]

volttron.platform.main module

class volttron.platform.main.FramesFormatter(frames)[source]

Bases: object

class volttron.platform.main.LogLevelAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)[source]

Bases: argparse.Action

Action to set the log level of individual modules.

class volttron.platform.main.Monitor(sock)[source]

Bases: threading.Thread

Monitor thread to log connections.

run()[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

class volttron.platform.main.Router(local_address, addresses=(), context=None, secretkey=None, publickey=None, default_user_id=None, monitor=False, tracker=None, volttron_central_address=None, instance_name=None, bind_web_address=None, volttron_central_serverkey=None, protected_topics={}, external_address_file='', msgdebug=None)[source]

Bases: volttron.platform.vip.router.BaseRouter

Concrete VIP router.

ext_route(socket)[source]

Handler function for message received through external socket connection :param socket: socket :return:

handle_subsystem(frames, user_id)[source]

Handle additional subsystems and provide a response.

This method does nothing by default and may be implemented by subclasses to provide additional subsystems.

frames is a list of zmq.Frame objects with the following elements:

[SENDER, RECIPIENT, PROTOCOL, USER_ID, MSG_ID, SUBSYSTEM, …]

The return value should be None, if the subsystem is unknown, an empty list or False (or other False value) if the message was handled but does not require/generate a response, or a list of containing the following elements:

[RECIPIENT, SENDER, PROTOCOL, USER_ID, MSG_ID, SUBSYSTEM, …]
issue(topic, frames, extra=None)[source]
poll_sockets()[source]

Poll for incoming messages through router socket or other external socket connections

setup()[source]

Called from start() method to setup the socket.

Implement this method to bind the socket, set identities and options, etc.

volttron.platform.main.configure_logging(conf_path)[source]

Load logging configuration from a file.

Several formats are possible: ini, JSON, Python, and YAML. The ini format uses the standard Windows ini file format and is read in using logging.config.fileConfig(). The remaining formats will be read in according to the serialization format and the resulting dictionary will be passed to logging.config.dictConfig(). See the logging.config module for specifics on the two file and dict formats. Returns None on success, (path, exception) on error.

The default format is ini. Other formats will be selected based on the file extension. Each format can be forced, regardless of file extension, by prepending the path with the format name followed by a colon:

Examples:
config.json is loaded as JSON config.conf is loaded as ini json:config.conf is loaded as JSON

YAML formatted configuration files require the PyYAML package.

volttron.platform.main.log_to_file(file_, level=30, handler_class=<class 'logging.StreamHandler'>)[source]

Direct log output to a file (or something like one).

volttron.platform.main.main(argv=['/home/docs/checkouts/readthedocs.org/user_builds/volttron/envs/releases-5.x/bin/sphinx-build', '-T', '-E', '-b', 'readthedocs', '-d', '_build/doctrees-readthedocs', '-D', 'language=en', '.', '_build/html'])[source]
volttron.platform.main.start_volttron_process(opts)[source]

Start the main volttron process.

Typically this function is used from main.py and just uses the argparser’s Options arguments as inputs. It also can be called with a dictionary. In that case the dictionaries keys are mapped into a value that acts like the args options.

volttron.platform.packages module

class volttron.platform.packages.BasePackageVerifier(dist_info, **kwargs)[source]

Bases: object

Base class for implementing wheel package verification.

Verifies wheel packages as defined in PEP-427. May be inherited with minimal modifications to support different storage mechanisms, such as a filesystem, Zip file, or tarball. All paths are expected to be POSIX-style with forward-slashes. Subclasses should implement listdir and open and may override __init__, if needed.

As an extension of the original specification, multiple levels of RECORD files and signatures are supported by appending incrementing integers to the RECORD files. Verification happens in reverse order and later RECORD files should contain hashes of the previous RECORD and associated signature file(s).

get_records()[source]

Return a reverse sorted list of RECORD names from the package.

Returns all RECORD files in the dist_info directory.

iter_hashes(name='RECORD')[source]

Iterate over the files and hashes of a RECORD file.

The RECORD file with the given name will be iterated over yielding a three tuple with each iteration: filename (relative to the package), computed hash (just calculated), and expected hash (from RECORD file).

listdir(path)[source]

Return a possibly empty list of files from a directory.

This could return the contents of a directory in an archive or whatever makes sense for the storage mechanism. Paths will typically be relative to the package, however, for installed packages, absolute paths are possible.

open(path, mode='r')[source]

Return a file-like object for the given file.

mode is interpreted the same as for the built-in open and will be either ‘r’ or ‘rb’. Only the __iter__(), read(), and close() methods are used.

class volttron.platform.packages.VolttronPackageWheelFileNoSign(filename, **kwargs)[source]

Bases: wheel.install.WheelFile

AGENT_DATA_ZIP = 'agent_data.zip'
add_files(files_to_add=None, basedir='.')[source]
contains(path)[source]

Does the wheel contain the specified path?

pop_record_and_files()[source]

Pop off the last record file and files listed in it.

Only removes files that are not listed in remaining records.

pop_records_file()[source]

Pop off the last records file that was added

remove_files(files)[source]

Relative to files in the package, ie: ./dist-info/config.

unpack(dest='.')[source]
class volttron.platform.packages.ZipPackageVerifier(zip_path, mode='r', **kwargs)[source]

Bases: volttron.platform.packages.BasePackageVerifier

Verify files of a Zip file.

listdir(path)[source]

Return a possibly empty list of files from a directory.

This could return the contents of a directory in an archive or whatever makes sense for the storage mechanism. Paths will typically be relative to the package, however, for installed packages, absolute paths are possible.

open(path, mode='r')[source]

Return a file-like object for the given file.

mode is interpreted the same as for the built-in open and will be either ‘r’ or ‘rb’. Only the __iter__(), read(), and close() methods are used.

class volttron.platform.packages.UnpackedPackage(base_directory)[source]

Bases: object

Represents an package unpacked into a directory.

Allows one access to the package metadata and methods to repack.

metadata

Parse package.dist-info/metadata.json and return a dictionary.

package_name
repack(dest=None, exclude=None)[source]

Recreate the package from the RECORD files.

Put the package in the directory given by dest or in the current directory if dest is None. If exclude is given, do not add files for RECORD files in exclude. Returns the path to the new package.

version
wheel_name
wheelmeta

Parse package.dist-info/WHEEL and return a dictionary.

volttron.platform.packaging module

Agent packaging and signing support.

exception volttron.platform.packaging.AgentPackageError[source]

Bases: exceptions.Exception

Raised for errors during packaging, extraction and signing.

volttron.platform.packaging.add_files_to_package(package, files=None)[source]
volttron.platform.packaging.create_package(agent_package_dir, wheelhouse, identity=None)[source]

Creates a packaged whl file from the passed agent_package_dir.

If the passed directory doesn’t exist or there isn’t a setup.py file the directory then AgentPackageError is raised.

Parameters
agent_package_dir - The directory to package in the wheel file. signature - An optional signature file to sign the RECORD file.
Returns
string - The full path to the created whl file.
volttron.platform.packaging.extract_package(wheel_file, install_dir, include_uuid=False, specific_uuid=None)[source]

Extract a wheel file to the specified location.

If include_uuid is True then a uuid will be generated under the passed location directory.

The agent final directory will be based upon the wheel’s data directory name in the following formats:

if include_uuid == True
    install_dir/uuid/datadir_name
else
    install_dir/datadir_name
Parameters:
  • wheel_file – The wheel file to extract.
  • install_dir – The root directory where to extract the wheel
  • include_uuid – Auto-generates a uuuid under install_dir to place the wheel file data
  • specific_uuid – A specific uuid to use for extracting the agent.
Returns:

The folder where the wheel was extracted.

volttron.platform.packaging.init_agent(target_directory, module_name, template_name, silent, identity)[source]
volttron.platform.packaging.log_to_file(file, level=30, handler_class=<class 'logging.StreamHandler'>)[source]

Direct log output to a file (or something like one).

volttron.platform.packaging.main(argv=['/home/docs/checkouts/readthedocs.org/user_builds/volttron/envs/releases-5.x/bin/sphinx-build', '-T', '-E', '-b', 'readthedocs', '-d', '_build/doctrees-readthedocs', '-D', 'language=en', '.', '_build/html'])[source]
volttron.platform.packaging.repackage(directory, dest=None)[source]

Repack an wheel unpacked into the given directory.

All files in the RECORD files are added back to the wheel, which is written in the current working directory if dest is None or in the directory given by dest otherwise.

volttron.platform.resmon module

Resource Monitor

The resource monitor manages resources assigned to the platform, assigns resources to agent execution environments, and monitors those resources for abuse.

There will typically be only a single resource monitor that is instantiated and then set using set_resource_monitor(). Other modules may then just import the module and call the module-level functions without worrying about where to find the monitor instance.

exception volttron.platform.resmon.ResourceError[source]

Bases: exceptions.Exception

Exception raised for errors relating to this module.

class volttron.platform.resmon.ExecutionEnvironment[source]

Bases: object

Environment reserved for agent execution.

Deleting ExecutionEnvironment objects should cause the process to end and all resources to be returned to the system.

execute(*args, **kwargs)[source]
class volttron.platform.resmon.ResourceMonitor(env, **kwargs)[source]

Bases: object

check_hard_resources(contract)[source]

Test contract against hard resources and return failed terms.

contract should be a dictionary of terms and conditions that are being requested. If all terms can be met, None is returned. Otherwise, a dictionary is returned with the terms that failed along with hints on values that would cause the terms to succeed, if any. The contract is tested against the platform’s hard capabilities and static resources.

get_static_resources(query_items=None)[source]

Return a dictionary of hard capabilities and static resources.

query_items is a list of resources the requester is interested in; only items in the list will appear in the returned dictionary. If query_items is not passed or is None, all items should be returned.

The returned dictionary contains the requested items that are available and their associated values and/or limits.

Examples of static resources:
architecture kernel version distribution (lsb_release) installed software
reserve_soft_resources(contract)[source]

Test contract against soft resources and reserve resources.

contract should be a dictionary of terms and conditions to test against the platform’s soft capabilities and dynamic resources.

A 2-tuple is returned: (reservation, failed_terms). If reservation is None, no resources were reserved and failed_terms is a dictionary that can be consulted for the terms that must be modified for a reservation to succeed. Otherwise, reservation will be a ExecutionEnvironment object that can later be used to execute an agent and failed_terms will be None.

volttron.platform.store module

class volttron.platform.store.ConfigStoreService(*args, **kwargs)[source]

Bases: volttron.platform.vip.agent.Agent

delete(identity, config_name, trigger_callback=False, send_update=True)[source]
delete_config(config_name, trigger_callback=False, send_update=True)[source]

Called by an Agent to delete a configuration.

get_configs()[source]

Called by an Agent at startup to trigger initial configuration state push.

manage_delete_config(identity, config_name)[source]
manage_delete_store(identity)[source]
manage_get(identity, config_name, raw=True)[source]
manage_get_metadata(identity, config_name)[source]
manage_list_configs(identity)[source]
manage_list_stores()[source]
manage_store(identity, config_name, raw_contents, config_type='raw')[source]
set_config(config_name, contents, trigger_callback=False, send_update=True)[source]
store_config(identity, config_name, contents, trigger_callback=False, send_update=True)[source]
volttron.platform.store.process_raw_config(config_string, config_type='raw')[source]

Parses raw config string into python objects

volttron.platform.store.process_store(identity, store)[source]

Parses raw store data and returns contents. Called at startup to initialize the parsed version of the store.

volttron.platform.storeutils module

volttron.platform.storeutils.check_for_recursion(new_config_name, new_config, existing_configs)[source]

Returns a set of config files referenced in this configuration

volttron.platform.storeutils.strip_config_name(config_name)[source]

volttron.platform.vpm module

volttron.platform.web module

exception volttron.platform.web.CouldNotRegister[source]

Bases: exceptions.StandardError

exception volttron.platform.web.DiscoveryError[source]

Bases: exceptions.StandardError

Raised when a different volttron central tries to register.

class volttron.platform.web.DiscoveryInfo(**kwargs)[source]

Bases: object

A DiscoveryInfo class.

The DiscoveryInfo class provides a wrapper around the return values from a call to the /discovery/ endpoint of the `volttron.platform.web.

static request_discovery_info(web_address)[source]

Construct a DiscoveryInfo object.

Requests a response from discovery_address and constructs a DiscoveryInfo object with the returned json.

Parameters:web_address – An http(s) address with volttron running.
Returns:
exception volttron.platform.web.DuplicateEndpointError[source]

Bases: exceptions.StandardError

class volttron.platform.web.MasterWebService(serverkey, identity, address, bind_web_address, aip, volttron_central_address=None, **kwargs)[source]

Bases: volttron.platform.vip.agent.Agent

The service that is responsible for managing and serving registered pages

Agents can register either a directory of files to serve or an rpc method that will be called during the request process.

app_routing(env, start_response)[source]

The main routing function that maps the incoming request to a response.

Depending on the registered routes map the request data onto an rpc function or a specific named file.

create_raw_response(res, start_response)[source]
create_response(res, start_response)[source]
get_bind_web_address()[source]
get_serverkey()[source]
get_volttron_central_address()[source]

Return address of external Volttron Central

Note: this only applies to Volltron Central agents that are running on a different platform.

register_agent_route(regex, fn)[source]

Register an agent route to an exported function.

When a http request is executed and matches the passed regular expression then the function on peer is executed.

register_endpoint(endpoint, res_type)[source]

RPC method to register a dynamic route.

Parameters:endpoint
Returns:
register_path_route(regex, root_dir)[source]
register_websocket(endpoint)[source]
remove_unconnnected_routes()[source]
startupagent(sender, **kwargs)[source]
unregister_all_agent_routes()[source]
unregister_websocket(endpoint)[source]
websocket_send(endpoint, message)[source]
class volttron.platform.web.VolttronWebSocket(*args, **kwargs)[source]

Bases: ws4py.websocket.WebSocket

closed(code, reason='A client left the room without a proper explanation.')[source]

Called when the websocket stream and connection are finally closed. The provided code is status set by the other point and reason is a human readable message.

See also

Defined Status Codes http://tools.ietf.org/html/rfc6455#section-7.4.1

opened()[source]

Called by the server when the upgrade handshake has succeeded.

received_message(m)[source]

Called whenever a complete message, binary or text, is received and ready for application’s processing.

The passed message is an instance of messaging.TextMessage or messaging.BinaryMessage.

Note

You should override this method in your subclass.

class volttron.platform.web.WebApplicationWrapper(masterweb, host, port)[source]

Bases: object

A container class that will hold all of the applications registered with it. The class provides a contianer for managing the routing of websocket, static content, and rpc function calls.

client_closed(client, endpoint, identity, reason='Client left without proper explaination')[source]
client_opened(client, endpoint, identity)[source]
client_received(endpoint, message)[source]
create_ws_endpoint(endpoint, identity)[source]
destroy_ws_endpoint(endpoint)[source]
favicon(environ, start_response)[source]

Don’t care about favicon, let’s send nothing.

websocket_send(endpoint, message)[source]
class volttron.platform.web.WebResponse(status, data, headers)[source]

Bases: object

The WebResponse object is a serializable representation of a response to an http(s) client request that can be transmitted through the RPC subsystem to the appropriate platform’s MasterWebAgent

process_data(data)[source]
process_headers(headers)[source]
volttron.platform.web.build_vip_address_string(vip_root, serverkey, publickey, secretkey)[source]

Build a full vip address string based upon the passed arguments

All arguments are required to be non-None in order for the string to be created successfully.

:raises ValueError if one of the parameters is None.

volttron.platform.web.is_ip_private(vip_address)[source]

Determines if the passed vip_address is a private ip address or not.

Parameters:vip_address – A valid ip address.
Returns:True if an internal ip address.