Developer Interfaces
This part of the documentation covers all the interfaces of vmt-connect.
Main Module
Import:
vmtconnect
Connections
Connection
- class vmtconnect.Connection(host=None, username=None, password=None, auth=None, base_url=None, req_versions=None, disable_hateoas=True, ssl=True, verify=False, cert=None, headers=None, use_session=True, proxies=None)
Turbonomic instance connection class
The primary API interface. In addition to the noted method parameters, each method also supports a per call fetch_all flag, as well as a pager flag. Each of these override the connection global property, and will be safely ignored if the endpoint does not support, or does not require paging the results. Additionally, you may pass
requests.Request
keyword arguments to each call if required (e.g. timeout). Care should be taken, as some parameters will break vmt-connect calls if they conflict with existing headers, or alter expected results.- Parameters
host (str, optional) – The hostname or IP address to connect to. (default: localhost)
username (str, optional) – Username to authenticate with.
password (str, optional) – Password to authenticate with.
auth (str, optional) – Pre-encoded ‘Basic Authentication’ string which may be used in place of a
username
andpassword
pair.base_url (str, optional) – Base endpoint path to use. (default: /vmturbo/rest/)
req_versions (
VersionSpec
, optional) – Versions requirements object.disable_hateoas (bool, optional) – Removes HATEOAS navigation links. (default:
True
)ssl (bool, optional) – Use SSL or not. (default:
True
)verify (string, optional) – SSL certificate bundle path. (default:
False
)cert (string, optional) – Local client side certificate file.
headers (dict, optional) – Dicitonary of additional persistent headers.
use_session (bool, optional) – If set to
True
, arequests.Session
will be created, otherwise individualrequests.Request
calls will be made. (default:True
)proxies (dict, optional) – Dictionary of proxy definitions.
- last_response
The last response object received.
- Type
- proxies
Dictionary of proxies to use. You can also configure proxies using the HTTP_PROXY and HTTPS_PROXY environment variables.
- Type
- Raises
VMTConnectionError – If connection to the server failed.
VMTUnknownVersion – When unable to determine the API base path.
HTTP401Error – When access is denied.
Notes
The default minimum version for classic builds is 6.1.x, and for XL it is 7.21.x Using a previous version will trigger a version warning. To avoid this warning, you will need to explicitly pass in a
VersionSpec
object for the version desired.Beginning with v6.0 of Turbonomic, HTTP redirects to a self-signed HTTPS connection. Because of this, vmt-connect defaults to using SSL. Versions prior to 6.0 using HTTP will need to manually set ssl to
False
. If verify is given a path to a directory, the directory must have been processed using the c_rehash utility supplied with OpenSSL. For client side certificates using cert: the private key to your local certificate must be unencrypted. Currently, Requests, which vmt-connect relies on, does not support using encrypted keys. Requests uses certificates from the package certifi which should be kept up to date.The /api/v2 path was added in 6.4, and the /api/v3 path was added in XL branch 7.21. The XL API is not intended to be an extension of the Classic API, though there is extensive parity. vmt-connect will attempt to detect which API you are connecting to and adjust accordingly where possible.
XL uses OID identifiers internally instead of UUID identifiers. The change generally does not affect the API, the UUID label is still used, although the structure of the IDs is different.
- add_group(dto)
Raw group creation method.
- add_static_group(name, type, members=None)
Creates a static group.
- add_static_group_members(uuid, members=None)
Add members to an existing static group.
- add_template(dto)
Creates a template based on the supplied DTO object.
- Parameters
dto (obj) – Template definition
- Returns
Template object in
dict
form.
- del_group(uuid)
Removes a group.
- Parameters
uuid (str) – UUID of the group to be removed.
- Returns
True
on success, False otherwise.
- del_market(uuid, scenario=False)
Removes a market, and optionally the associated scenario.
- del_scenario(uuid)
Removes a scenario.
- Parameters
uuid (str) – UUID of the scenario to be removed.
- Returns
True
on success, False otherwise.
- get_actions(market='Market', uuid=None, **kwargs)
Returns a list of actions.
The get_actions method returns a list of actions from a given market, or can be used to lookup a specific action by its uuid. The options are mutually exclusive, and a uuid will override a market lookup. If neither parameter is provided, all actions from the real-time market will be listed.
- get_cached_inventory(id, uuid=None, **kwargs)
Returns the entities inventory from cache, populating the cache if necessary. The ID provided should be either a market ID, or one of the alternative inventory IDs:
__clusters - Clusters
__groups - Groups
__group_entities - Group entities
__group_members - Group members
- get_clusters(uuid=None, cache=False, **kwargs)
Returns a list of clusters
- get_current_user(**kwargs)
Returns the current user.
- Returns
A list of one user object in
dict
form.
- get_datacenters(uuid=None, market='Market', **kwargs)
Returns a list of datacenters in the given market.
- get_datastores(uuid=None, market='Market', **kwargs)
Returns a list of datastores in the given market.
- get_entities(type=None, uuid=None, detail=False, market='Market', cache=False, **kwargs)
Returns a list of entities in the given market.
- Parameters
type (str, optional) – Entity type to filter on.
uuid (str, optional) – Specific UUID to lookup.
detail (bool, optional) – Include entity aspect details. This parameter works only when specifying an entity UUID. (default:
False
)market (str, optional) – Market to query. (default:
Market
)cache (bool, optional) – If true, will retrieve entities from the market cache. (default:
False
)
- Returns
A list of entities in
dict
form.
- get_entity_actions(uuid, **kwargs)
Returns a list of entity actions.
- Parameters
uuid (str) – Entity UUID.
- Returns
A list containing all actions for the given the entity.
- get_entity_by_remoteid(remote_id, target_name=None, target_uuid=None, **kwargs)
Returns a list of entities from the real-time market for a given remoteId
- get_entity_cluster(uuid, cache=False, **kwargs)
Get the cluster an entity belongs to.
- get_entity_groups(uuid, **kwargs)
Returns a list of groups the entity belongs to.
- Parameters
uuid (str) – Entity UUID.
- Returns
A list containing groups the entity belongs to.
- get_entity_stats(scope, start_date=None, end_date=None, stats=None, related_type=None, dto=None, **kwargs)
Returns stats for the specific scope of entities.
Provides entity level stats with filtering. If using the DTO keyword, all other parameters save kwargs will be ignored.
- Parameters
scope (list) – List of entities to scope to.
start_date (int, optional) – Unix timestamp in miliseconds. Uses current time if blank.
end_date (int, optional) – Unix timestamp in miliseconds. Uses current time if blank.
stats (list, optional) – List of stats classes to retrieve.
related_type (str, optional) – Related entity type to pull stats for.
dto (dict, optional) – Complete JSON DTO of the stats required.
- Returns
A list of stats for all periods between start and end dates.
- get_group_actions(uuid, **kwargs)
Returns a list of group actions.
- Parameters
uuid (str) – Group UUID.
- Returns
A list containing all actions for the given the group.
- get_group_by_name(name, **kwargs)
Returns the first group that match name.
- get_group_entities(uuid, cache=False, **kwargs)
Returns a detailed list of member entities that belong to the group.
- get_group_members(uuid, cache=False, **kwargs)
Returns a list of members that belong to the group.
- get_group_stats(uuid, stats_filter=None, start_date=None, end_date=None, **kwargs)
Returns the aggregated statistics for a group.
- Parameters
- Returns
A list containing the group stats in
dict
form.
- get_groups(uuid=None, cache=False, **kwargs)
Returns a list of groups in the given market
- get_market_entities(uuid='Market', **kwargs)
Returns a list of entities in the given market.
- get_market_entities_stats(uuid='Market', filter=None, **kwargs)
Returns a list of market entity statistics.
- get_market_state(uuid='Market', **kwargs)
Returns the state of a market.
- Parameters
uuid (str, optional) – Market UUID. (default: Market)
- Returns
A string representation of the market state.
- get_market_stats(uuid='Market', filter=None, **kwargs)
Returns a list of market statistics.
- get_markets(uuid=None, **kwargs)
Returns a list of markets.
- get_physicalmachines(uuid=None, market='Market', **kwargs)
Returns a list of hosts in the given market.
- get_scenarios(uuid=None, **kwargs)
Returns a list of scenarios.
- get_supplychains(uuids, types=None, states=None, detail=None, environment=None, aspects=None, health=False, **kwargs)
Returns a set of supplychains for the given uuid.
- Parameters
uuids (list) – List of UUIDs to query.
types (list, optional) – List of entity types.
states – (list, optional): List of entity states to filter by.
detail – (str, optional): Entity detail level.
environment – (str, optional): Environment to filter by.
aspects – (list, optional): List of entity aspects to filter by.
health – (bool, optional): If
True
entity health information will included. (default:False
)
- get_target_actions(uuid, **kwargs)
Returns a list actions on a target.
- Parameters
uuid (str) – Entity UUID.
- Returns
A list containing all actions for entities of the given the target.
- get_target_for_entity(uuid=None, name=None, type='VirtualMachine', **kwargs)
Returns a list of templates.
- Parameters
- Returns
A list of targets for an entity in
dict
form.
Notes
Use of UUIDs is strongly encouraged to avoid collisions. Only one parameter is required. If both are supplied, uuid overrides. If a name lookup returns multiple entities, only the first is returned.
- get_targets(uuid=None, **kwargs)
Returns a list of targets.
- get_template_by_name(name, **kwargs)
Returns a template by name.
- get_templates(uuid=None, **kwargs)
Returns a list of templates.
- get_users(uuid=None, **kwargs)
Returns a list of users.
- get_virtualmachines(uuid=None, market='Market', **kwargs)
Returns a list of virtual machines in the given market.
- is_xl()
Checks if the connection is to an XL or Classic type instance.
- Returns
True
if connected to an XL instance,False
otherwise.
- request(path, method='GET', query='', dto=None, **kwargs)
Constructs and sends an appropriate HTTP request.
Most responses will be returned as a list of one or more objects, as parsed from the JSON response. As of v3.2.0 you may request a
Pager
instance instead. The pager and fetch_all parameters may be used to alter the response behaviour.- Parameters
path (str) – API resource to utilize, relative to
base_path
.method (str, optional) – HTTP method to use for the request. (default: GET)
query (dict, optional) – A dictionary of key-value paires to attach. A single pre-processed string may also be used, for backwards compatibility.
dto (str, optional) – Data transfer object to send to the server.
pager (bool, optional) – If set to
True
, aPager
instance will be returned, instead of a single response of the cursor. (default:False
)fetch_all (bool, optional) – If set to
True
, will fetch all results into a single response when a cursor is returned, otherwise only the current result set is returned. This option overrides the pager parameter. (default:False
)limit (int, optional) – Sets the response limit for a single call. This overrides results_limit, if it is also set.
nocache (bool, optional) – If set to
True
, responses will not be cached in thelast_response
attribute. (default:False
)**kwargs – Additional
requests.Request
keyword arguments.
Notes
The fetch_all parameter default was changed in v3.2 from
True
toFalse
with the addition of thePager
response class. String based query parameters are deprecated, use dictionaries.
- request_check_error(response)
Checks a request response for common errors and raises their corresponding exception.
- Raises
HTTPError – All unhandled non 200 level HTTP codes.
HTTP400Error – All unhandled 400 level client errors.
HTTP401Error – When access to the resource is not authorized.
HTTP404Error – When requested resource is not found.
HTTP500Error – All unhandled 500 level server errors.
HTTP502Error – When a gateway times out.
HTTP503Error – When a service is unavailable.
- search(**kwargs)
Raw search method.
Provides a basic interface for issuing direct queries to the Turbonomic search endpoint. There are three sets of possible parameters, which must not be mixed.
- Parameters
Set –
q (str, optional) – Query string.
types (list) – Types of entities to return. Must include either types or group_type.
scopes (list, optional) – Entities to scope to.
state (str, optional) – State filter.
environment_type (str, optional) – Environment filter.
group_type (str) – Group type filter. Must include either types or group_type.
detail_type (str, optional) – Entity detail filter.
entity_types (list, optional) – Member entity types filter.
probe_types (list, optional) – Target probe type filter.
regex (bool, optional) – Flag for regex query string searching.
query_type (str, optional) – Specifies the type of query.
Set –
uuid (str) – UUID of an object to lookup.
Set –
dto (str) – JSON representation of the StatScopesApiInputDTO.
- Returns
A list of search results.
See also
https://turbonomic.github.io/vmt-connect/start.html#turbonomic-rest-api-guides
Search criteria list: http://<host>/vmturbo/rest/search/criteria
- search_by_name(name, type=None, case_sensitive=False, from_cache=False, **kwargs)
Searches for an entity by name.
- Parameters
name (str) – Display name of the entity to search for.
type (str, optional) – One or more entity classifications to aid in searching. If None, all types are searched via consecutive requests.
case_sensitive (bool, optional) – Search case sensitivity. (default:
False
)from_cache (bool, optional) – Uses the cached inventory if set. (default:
False
)
Notes
The option from_cache is deprecated, and will be removed in a future version. This is due primarily to large memory concerns on XL instances. Pagination should be used instead.
- Returns
A list of matching results.
- update_action(uuid, accept)
Update a manual action by accepting or rejecting it.
- update_static_group_members(uuid, members, name=None, type=None)
Update static group members by fully replacing it.
Session
- class vmtconnect.Session(*args, **kwargs)
Bases:
Connection
Alias for
Connection
to provide convenience.See
Connection
for parameter details.Notes
The value for the
session
property will always be set toTrue
when usingSession
Response Handlers
Pager
- class vmtconnect.Pager(conn, response, filter=None, filter_float=False, **kwargs)
API request pager class
A
Pager
is a special request handler which permits the processing of pagedrequest()
results, keeping state between each successive call. Although you can instantiate aPager
directly, it is strongly recommended to request one by addingpager=True
to your existingConnection
method call.- Parameters
conn (
Connection
) – Connection object to associate the pager to.response (
requests.Response
) – Requestsrequests.Response
object to build the pager from. This must be the object, and not the JSON parsed output.filter (dict) – Filter to apply to results.
**kwargs – Additional
requests.Request
keyword arguments.
- response
Most recent response object.
- Type
- Raises
VMTNextCursorMissingError – When cursor headers are broken or missing.
Notes
The use of the
all
property negates all memory savings by caching all responses before returning any results. This should be used sparringly to prevent unnecessary and excessive memory usage for extremely large datasets.Some versions of Turbonomic have endpoints that return malformed, or non-working pagination headers. These are chiefly XL versions prior to 7.21.2.
It is possible a cursor may expire before you’ve processed all results for extremely large sets. A
VMTNextCursorMissingError
will be returned when the cursor is no longer availble. Therefore, you should always catch this error type when working with aPager
.
Versioning
Version
- class vmtconnect.Version(version)
Turbonomic instance version object
The
Version
object contains instance version information, and equivalent Turbonomic version information in the case of a white label product.- Parameters
version (obj) – Version object returned by Turbonomic instance.
- Raises
VMTUnknownVersion – When version data cannot be parsed.
VersionSpec
- class vmtconnect.VersionSpec(versions=None, exclude=None, required=True, snapshot=False, cmp_base=True)
Turbonomic version specification object
The
VersionSpec
object contains version compatibility and requirements information. Versions must be in dotted format, and may optionally have a ‘+’ postfix to indicate versions greater than or equal to are acceptable. If using ‘+’, you only need to specify the minimum version required, as all later versions will be accepted independent of minor release branch. E.g. 6.0+ includes 6.1, 6.2, and all later branches.Examples
VersionSpec([‘6.0+’], exclude=[‘6.0.1’, ‘6.1.2’, ‘6.2.5’, ‘6.3.0’])
VersionSpec([‘7.21+’], snapshot=True)
- Parameters
versions (list, optional) – A list of acceptable versions.
exclude (list, optional) – A list of versions to explicitly exclude.
required (bool, optional) – If set to True, an error is thrown if no matching version is found when
check()
is run. (Default:True
)snapshot (bool, optional) – If set to True, will permit connection to snapshot builds tagged with ‘-SNAPSHOT’. (Default:
False
)cmp_base (bool, optional) – If
True
, white label versions will be translated to their corresponding base Turbonomic version prior to comparison. IfFalse
, only the explicit product version will be compared. (Default:True
)
- Raises
VMTFormatError – If the version format cannot be parsed.
VMTVersionError – If version requirement is not met.
Notes
The Turbonomic API is not a well versioned REST API, and each release is treated as if it were a separate API, while retaining the name of “API 2.0” to distinguish it from the “API 1.0” implementation available prior to the Turbonomic HTML UI released with v6.0 of the core product.
As of v3.2.0 required now defaults to
True
.- check(version)
Checks a
Version
for validity against theVersionSpec
.- Parameters
version (obj) – The
Version
to check.- Returns
True if valid, False if the version is excluded or not found.
- Raises
VMTVersionError – If version requirement is not met.
Utilities
- vmtconnect.enumerate_stats(data, entity=None, period=None, stat=None)
Provided as an alias for backwards compatibility only.
Exceptions
- exception vmtconnect.VMTConnectionError
Base connection exception class.
- exception vmtconnect.VMTVersionError(message=None)
Incompatible version error.
- exception vmtconnect.VMTUnknownVersion
Unknown version.
- exception vmtconnect.VMTVersionWarning
Generic version warning.
- exception vmtconnect.VMTMinimumVersionWarning
Minimum version warnings.
- exception vmtconnect.VMTFormatError
Generic format error.
- exception vmtconnect.VMTNextCursorMissingError
Raised if the paging cursor header is not provided when expected
- exception vmtconnect.HTTPError
Raised when an blocking or unknown HTTP error is returned.
- exception vmtconnect.HTTP400Error
Raised when an HTTP 400 error is returned.
- exception vmtconnect.HTTP401Error
Raised when access fails, due to bad login or insufficient permissions.
- exception vmtconnect.HTTP404Error
Raised when a requested resource cannot be located.
- exception vmtconnect.HTTP500Error
Raised when an HTTP 500 error is returned.
- exception vmtconnect.HTTP502Error
Raised when an HTTP 502 Bad Gateway error is returned. In most cases this indicates a timeout issue with synchronous calls to Turbonomic and can be safely ignored.
- exception vmtconnect.HTTP503Error
Raised when an HTTP 503 Service Unavailable error is returned. Subsequent calls should be expected to fail, and this should be treated as terminal to the session.
- exception vmtconnect.HTTPWarning
Raised when an HTTP error can always be safely ignored.
Deprecated Interfaces
- class vmtconnect.VMTConnection(*args, **kwargs)
Alias for
Connection
to provide backwards compatibility.See
Connection
for parameter details.Notes
The value for
session
will default toTrue
when usingVMTConnection
Warning
Deprecated. Use
Connection
orSession
instead.
- class vmtconnect.VMTVersion(versions=None, exclude=None, require=False)
Alias for
VersionSpec
to provide backwards compatibility.Warning
Deprecated. Use
VersionSpec
instead.
Security Module
Import:
vmtconnect.security
Classes
Credential
- class vmtconnect.security.Credential(key=None, cred=None)
Credentials for authenticating to the Turbonomic API.
Upon initialization
Credential
will check the key filepath, and if present the key will be read into memory; otherwise a new key will be randomly generated.- Parameters
- create(message=None, key=None, overwrite=False)
Create and save to file a new cipher key and encrypted message.
- Parameters
key (str) – Cipher key to use for encryption. If null, a new key will be generated. (default:
None
)message (str) – Message to be encrypted. If null, you will be prompted for a username and password pair interactively.
overwrite (bool) – If
True
existing key or message data will be overwritten. (default:False
)
- decrypt(token=None, key=None)
Decrypt the token using the given key, and return the message. If the token file was provided at init, it will be used here, otherwise a valid token must be supplied.
- encrypt(message, key=None)
Encrypt the given message with the given key and return the token.
- get()
Retrieve and decrypt credentials
- Returns
Credentials in the form of a Base64 auth string.
- get_cipher(key=None)
Returns a Fernet cipher for the given key
- new_key()
Generate a new key.
- prompt_credentials()
Retrieves a new set of credentials from the user, returning a Base64 auth string response.
- set(message, key=None, overwrite=False)
Encrypt the given message with the specified key, and save each to their respective files.
Utility Module
Import:
vmtconnect.util
- vmtconnect.util.enumerate_stats(data, entity=None, period=None, stat=None)
Enumerates stats endpoint results
Provides an iterator for more intuitive and cleaner parsing of nested statistics results. Each iteration returns a tuple containing the statistics period date timestamp, as well as the next individual statistic entry as a dictionary.
- Parameters
data (list) – Stats endpoint data results to parse.
entity (function, optional) – Optional entity level filter function.
period (function, optional) – Optional period level filter function.
stat (function, optional) – Optional statistic level filter function.
Notes
Filter functions must return
True
, to continue processing, orFalse
to skip processing the current level element.Examples
# filter stats for a specific ID desired_id = '284552108476721' enumerate_stats(data, entity=lambda x: x['uuid'] == desired_uuid) # filter specific stats for all IDs blacklist = ['Ballooning'] enumerate_stats(data, stat=lambda x: x['name'] not in blacklist)
- vmtconnect.util.mem_cast(value, unit=None, src=None)
Converts memory from one unit of measure to another. Values are interpreted as base 2 values (JEDEC memory standard), not SI values.
- Parameters
value (string) – Base value, represented as a string.
unit (string) – Destination value to convert to. (default:
G
)src (string) – Source value unit of measure to convert from. (default:
b
)
- vmtconnect.util.to_defaultdict(factory, data)
Convert a list or dictionary to a defaultdict object
- Parameters
factory (obj) – Used as the default value.
data (obj) – List or dict to convert.