cloudvision.cvlib package
Submodules
cloudvision.cvlib.action module
- class cloudvision.cvlib.action.Action(name: str, actionId: str, context: ActionContext = ActionContext.Unknown, args: Dict[str, str] | None = None, ccId: str | None = None, stageId: str | None = None)[source]
Bases:
object
Object to store common change control action script arguments: - name: Name of the action currently running - context: Enum for the context in which the action is running,
e.g. Action that is running is a change control action
id: ID of the action currently running
args: String -> String dictionary of the args associated with the action
ccId: ID of the change control, if applicable
stageId: ID of the current stage of the change control, if applicable
- getCCStartTime(cvClient: GRPCClient)[source]
Queries the cloudvision database for the change control start time :param cvClient: context.getCvClient() client :return: nanosecond start timestamp of the change control
cloudvision.cvlib.changecontrol module
- class cloudvision.cvlib.changecontrol.ChangeControl(ccId: str | None = None, stageId: str | None = None, args: Dict[str, str] | None = None)[source]
Bases:
object
(Deprecated) Please use ctx.action instead for various field information Object to store common change control action script arguments: - ccId: ID of the change control, if applicable - stageId: ID of the current stage of the change control, if applicable - args: Dict of user-defined/script defined arguments that are passed in
- getStartTime(cvClient: GRPCClient)[source]
Queries the cloudvision database for the change control start time :param cvClient: context.getCvClient() client :return: nanosecond start timestamp of the change control
cloudvision.cvlib.connections module
- class cloudvision.cvlib.connections.AuthAndEndpoints(apiserverAddr: str | None = None, serviceAddr: str | None = None, serviceCACert: str | None = None, aerisCACert: str | None = None, commandEndpoint: str | None = None, logEndpoint: str | None = None, connectionTimeout: int | None = 250, cliTimeout: int | None = 200, testAddresses: Dict[str, str] | None = None)[source]
Bases:
object
Object to store auth and endpoint information for use in the context object - apiserverAddr: Address of the CloudVision apiserver - serviceAddr: Address of the CloudVision service proxy server, e.g. ambassador address - cacert: Path to local CA Cert, used for establishing CV grpc connections - commandEndpoint: Service endpoint where command requests are posted to - logEndpoint: Service endpoint where log requests are posted to - connectionTimeout: Timeout value for connections to endpoints in seconds - cliTimeout: Timeout value for cli commands invoked by connections - testAddresses: Api addresses to use when execution is in a test context
cloudvision.cvlib.constants module
cloudvision.cvlib.context module
- class cloudvision.cvlib.context.Context(user: User, device: Device | None = None, action: Action | None = None, changeControl: ChangeControl | None = None, studio: Studio | None = None, execution: Execution | None = None, connections: AuthAndEndpoints | None = None, logger: Logger | None = None, loggingLevel: LoggingLevel | None = None)[source]
Bases:
object
Context object that stores a number of system and user-defined parameters: - user: Info on the user executing this script - device: Info on the device the script is operating on, if applicable - action: Info on the action associated with the current context, if applicable - changeControl: Common change-control script parameters (Deprecated, use action) - studio: Common studio parameters - execution: Info on the standalone execution context - connections: Object storing connection info used by the context, e.g. apiserver address - logger: Logging functions to be used by the context
- Get(path: List[str], keys: List[str] = [], dataset: str = 'analytics')[source]
Get issues a get request to the provided path/key(s) combo, and returns the contents of that path as a dictionary. Wildcarding is not advised as the returned dictionary is only a single level deep, so adding wildcards will cause overwrites in the results.
Params: - path: The path to issue the get to, in the form of a list of strings - keys: The key(s) to get at the path. Defaults to all keys - dataset: The dataset to issue the get to. Defaults to the analytics dataset
- alog(message, userName=None, customKey=None, tags: Dict[str, str] = None, ignoreFailures=False)[source]
Creates an audit log entry in CloudVision, with the provided info. The context’s associated device name and id will be added to the audit log metadata if it is available in the context.
Note: This method is a no-op when run in a Studio template rendering context. Use the preferred ctx.info, ctx.error, ctx.debug etc. logging methods there instead.
- Parameters:
message – The string message for the audit log entry
userName – The user to make the audit log entry under. If unspecified, will use the context’s user’s username
customKey – A custom key that will be used to alias the audit log entry if provided
tags – A string dictionary of additional custom tags to add to the audit log entry. The action ID is always added as a tag to the audit log
ignoreFailures – Prevents logging exceptions from being raised
- benchmarkingOn()[source]
Turns on benchmarking to collect stats such as time consumed in a routine of the template To use add the following lines into the template:
ctx.benchmarkingOn() - place this as the first line after imports in the template @ctx.benchmark - decorate the functions of the template to be benchmarked ctx.benchmarkDump() - place this as the last line in the template
- cleanup()[source]
Cleans up open channels and other connections Called by the script execution infra once a script or template has been executed
- clear(path: List, keys: List = [], fullPathOnly: bool = False)[source]
clear issues deletes to the backend data store for cleanup, where retrieve with delete is not required or not suitable. By default, it walks upwards through each element in the path provided and issues a delete-all at each sub-path to purge the information store. The fullPathOnly flag can be set to true to only issue a deletes to the full path, instead of at all sub-paths in the path. A list of keys to specifically delete can be provided to only delete those fields.
NOTE: While this function accepts wildcards, note that using them may impact other storage paths used in other actions.
Params: - path: The path where the data should be purged, in the form of a list
of strings or Connector Wildcards.
keys: The list of keys to delete. Defaults to a delete-all.
- fullPathOnly: Boolean flag marking whether a delete-all should only be issued
to the store for full path. By default, deletes are issued at all sub-paths.
- critical(msg, ignoreFailures=False, tags: Dict[str, str] = None)[source]
Creates a critical level log :param msg: The string message for the log entry :param ignoreFailures: Prevents logging exceptions from being raised :param tags: A string dictionary of additional custom tags to add to the log
entry. Some system tags are always inserted, e.g. buildID when logging is done in a studio context.
- debug(msg, ignoreFailures=False, tags: Dict[str, str] = None)[source]
Creates a debug level log if the context’s logging level is set to allow for it If the logging level is higher, is a no-op :param msg: The string message for the log entry :param ignoreFailures: Prevents logging exceptions from being raised :param tags: A string dictionary of additional custom tags to add to the log
entry. Some system tags are always inserted, e.g. buildID when logging is done in a studio context.
- static doWithTimeout(f, timeout: int)[source]
Takes a function and a timeout in seconds. Will call and return the result of f, but raises a cvlib.TimeoutExpiry exception if it runs longer than <timeout> NOTE: If there is an attempt to recursively call this function, an InvalidContextException will be raised.
- error(msg, ignoreFailures=False, tags: Dict[str, str] = None)[source]
Creates an error level log if the context’s logging level is set to allow for it If the logging level is higher, is a no-op :param msg: The string message for the log entry :param ignoreFailures: Prevents logging exceptions from being raised :param tags: A string dictionary of additional custom tags to add to the log
entry. Some system tags are always inserted, e.g. buildID when logging is done in a studio context.
- getApiClient(stub)[source]
Instantiates a resource api client to the service server based on the current user auth token and passed stub :param: stub of the resource api to connect to :return: resource api client to the passed stub
- getCvClient()[source]
Instantiates a cloudvision connector client to the cv database based on the current user auth token :return: cloudvision Connector client
- getDeviceHostname(device: Device = None)[source]
Returns the hostname of the device associated to the context. Retrieves that information if the context device doesn’t have it
- getDevicesByTag(tag: Tag, inTopology: bool = True)[source]
Returns list of devices that have the user tag assigned to them. If tag.value is unspecified then returns devices having that label assigned. By default only devices in the topology are returned.
- getInterfacesByTag(tag: Tag, inTopology: bool = True)[source]
Returns list of interfaces that have the user tag assigned to them. If tag.value is unspecified then returns interfaces having that label assigned. By default only interfaces in the topology are returned.
- httpGet(path: str)[source]
Issues a https GET to a given endpoint in CloudVision and returns the json content if there are no errors
- httpGetConfig(path: str)[source]
Issues a http get to retrieve the device config content at a cvp url and formats it.
- info(msg, ignoreFailures=False, tags: Dict[str, str] = None)[source]
Creates an info level log if the context’s logging level is set to allow for it If the logging level is higher, is a no-op :param msg: The string message for the log entry :param ignoreFailures: Prevents logging exceptions from being raised :param tags: A string dictionary of additional custom tags to add to the log
entry. Some system tags are always inserted, e.g. buildID when logging is done in a studio context.
- initializeStudioCtxFromArgs()[source]
initializeStudioCtxFromArgs associates studio(s) and a workspace with the current context from argument information available in the current context’s action class. This allows for actions such as Studio Autofill Actions and Studio Build Hook Actions to associate a studio with their active contexts, allowing them to access various helper methods that require the presence of a studio or workspace with the active context, such as those offered by the tags class.
NOTE: Will raise InvalidContextException if called and either a studio is already bound to the context or no action is available in the context
- retrieve(path: List[str] = [], customKey='', delete=True)[source]
retrieve gets the passed key’s data from the provided path from the Database store.
NOTE: This function is only available to those with read permissions to the ‘action’ path in the cvp dataset (granted by the action module), as that is where the store is.
Params: - path: The path where the data is stored at, in the form of a list
of strings. If this argument is omitted, a generic path will be created for use. All paths have “action/tmp” as the root.
- customKey: The key where the data is stored at in the path. If this argument
is omitted, a generic string key will be created for use.
- delete: Boolean flag marking whether a delete should be issued to the
store for the key/path combo to clean up after use. Deleting once the contents have been retrieved is the default.
Raises InvalidContextException if not enough context information is present to create a generic key/path (if required)
- runDeviceCmds(commandsList: List[str], device: Device | None = None, fmt='json', validateResponse=True, timeout=300)[source]
Sends a post request to DI, encodes commandsList in message body. Receives output of cli commands from DI as json object.
- Parameters:
commandsList
device – device that the commands are run on. Defaults to the context change control device if unspecified
validateResponse – Validates that the commands ran successfully. Defaults to true and will raise an exception in the case an error message is present in the command response. Can be set to false to allow commands to run without raising any resultant error as an exception, e.g. device reboot commands can cause heartbeat error messages in the response, but we can discard them as the device will reboot.
- Returns:
json object containing output of commandsList (if validateResponse is True) OR raw request response (if validateResponse is False)
- Raises:
InvalidContextException when context is invalid for execution of device commands requests.ConnectionError if connection cannot be established to the command endpoint address HTTPError if the status code from the command request is not a 200 DeviceCommandsFailed if validating command responses and the contents contain an error code/message (can occur if request is a 200)
- setLoggingLevel(loggingLevel: LoggingLevel)[source]
Takes a logging level value and applies it for use in logging call checks
- setTopology(topology: Topology)[source]
Sets the topology of the context. Called during context initialisation during script execution, to set the Topology to that of the Inventory and Topology Studio. Does not need to be called by the script writers.
- store(data, path: List[str] = [], customKey='')[source]
store puts the passed data into a path in the Database
NOTE: This function is only available to those with write permissions to the ‘action’ path in the cvp dataset (granted by the action module), as that is where the store is.
This should be used in conjunction with the retrieve method to ensure that the entry is cleaned up after use.
Params: - data: The data to store - path: The path to store the data at, in the form of a list of strings.
If this argument is omitted, a generic path will be created for use. All paths have “action/tmp” as the root.
- customKey: The key to store the data at in the path. If this argument is
omitted, a generic string key will be created for use.
Raises InvalidContextException if not enough context information is present to create a generic key/path (if required)
- trace(msg, ignoreFailures=False, tags: Dict[str, str] = None)[source]
Creates a trace level log if the context’s logging level is set to allow for it If the logging level is higher, is a no-op :param msg: The string message for the log entry :param ignoreFailures: Prevents logging exceptions from being raised :param tags: A string dictionary of additional custom tags to add to the log
entry. Some system tags are always inserted, e.g. buildID when logging is done in a studio context.
- warning(msg, ignoreFailures=False, tags: Dict[str, str] = None)[source]
Creates a warning level log if the context’s logging level is set to allow for it If the logging level is higher, is a no-op :param msg: The string message for the log entry :param ignoreFailures: Prevents logging exceptions from being raised :param tags: A string dictionary of additional custom tags to add to the log
entry. Some system tags are always inserted, e.g. buildID when logging is done in a studio context.
cloudvision.cvlib.device module
- class cloudvision.cvlib.device.Device(deviceId: str | None = None, ip: str | None = None, deviceMac: str | None = None, hostName: str | None = None, modelName: str | None = None)[source]
Bases:
object
Object to store device information - ip: IP address of device - deviceId: ID of the device - deviceMac: Mac address of the device - hostName: Hostname of the device - modelName: Model name of the device
- getInterface(name)[source]
Returns a particular named interface from the interfaces assigned to the Device object
- getInterfacesByTag(ctx, tag: Tag, inTopology: bool = True)[source]
Returns list of interfaces that have the user tag assigned to them. If tag.value is unspecified then returns interfaces having that label assigned. By default only interfaces in the topology are returned.
- getSingleTag(ctx, label: str, required: bool = True)[source]
Returns a Tag of the label assigned to the device. Raises TagTooManyValuesException if there are multiple tags of the label assigned. Raises TagMissingException if required is True and the tag is missing. Returns None if required is False and the tag is missing.
- class cloudvision.cvlib.device.Interface(name: str, device: Device)[source]
Bases:
object
Object to store interface related information - name: The name of the interface - device: The device that the interface is on
- getSingleTag(ctx, label: str, required: bool = True)[source]
Returns a Tag of the label assigned to the interface. Raises TagTooManyValuesException if there are multiple tags of the label assigned. Raises TagMissingException if required is True and the tag is missing. Returns None if required is False and the tag is missing.
cloudvision.cvlib.exceptions module
- exception cloudvision.cvlib.exceptions.ActionFailed(message: str = '')[source]
Bases:
ScriptException
Exception to raise if you wish to fail a script or autofill action being executed.
For the case of a script action, e.g. CCA, it means that the user has declared that the action has failed due to some condition being met or missed. This is “expected” in the sense that the action did not hit an unexpected exception.
In the autofill action case, it means the autofill could not be completed due to some expected reason (e.g. could not reach IPAM or IPAM block was exhausted).
- exception cloudvision.cvlib.exceptions.AutofillActionException(message: str = 'cloudvision has encountered an autofill action error')[source]
Bases:
ScriptException
Overarching class for Autofill Action exceptions
- exception cloudvision.cvlib.exceptions.BatchException(message: str = 'Multiple errors encountered', cvErrors: List[str] = None)[source]
Bases:
ScriptException
Exception for when a script needs to raise multiple issues in a single error. This is useful for when scripts do all invariant checking at once, and tell the user about all the problems they’ve seen (instead of making the user fix one problem, rebuild to see the next problem, and repeat).
- exception cloudvision.cvlib.exceptions.CVException(message: str = 'cloudvision has encountered an error')[source]
Bases:
Exception
Overarching base exception class for all cloudvision exceptions
- exception cloudvision.cvlib.exceptions.ConnectionFailed(message: str = 'connection issue with the CloudVision API server')[source]
Bases:
CVException
Exception raised when a connection to the CloudVision API Server could not be established, or if it was unexpectedly closed
- exception cloudvision.cvlib.exceptions.DeviceCommandsFailed(message: str, errCode: int | None = None, errMsg: str | None = None)[source]
Bases:
ScriptException
Exception raised when device fails to run commands with ctx.runDeviceCmds. This is separate to the commands on the device themselves failing. This can be caused by the command request being invalid, not caused by invalid commands being issued message is the user-facing message for the exception errCode is the error code returned from the DI service errMsg is the message that the DI service returned with the error code
- exception cloudvision.cvlib.exceptions.InputEmptyException(message: str = 'attempted to access unpopulated input', members=None)[source]
Bases:
TemplateException
Exception for when an action/template script tries to access an input that wasn’t populated and that input was not optional or doesn’t have a default value. The members field is something that can be used to determine what input was missing. Members should be usable by the UI to guide users to the right section to fill out the missing input. For studios, this is only raised by the internal studios python library utilities.
For autofill actions, this could be useful for the autofill action to show that it can’t autofill because some of the existing inputs don’t make any sense. This also lets autofill actions act as validators (users press a button to validate in real time)
- class cloudvision.cvlib.exceptions.InputError(message: str = 'Error in input field', inputPath: List[str] = None, fieldId: str = None, members: List[str] = None)[source]
Bases:
object
This is the primary error that Studio Template writers would raise. It is raised manually by a template script if the set of inputs violates the script-author’s assumptions. - message: A user-friendly text message of the error - inputPath: The path to the field that is in error. It is a list of field names
(the “name” attribute in the schema) starting from the root. E.g.: [“networkConfig”, “0”, “config”, “monitoredHosts”, “1”]
fieldId: The unique ID of the field (the “id” attribute in the schema).
- members: A list of all members in a group-type input that are in conflict. inputs easily.
In most cases, a script will only specify a single member to show that inputA has a problem that the end user needs to fix. In certain cases, though, you may want to indicate to the end user that either inputA or inputB needs fixing, but both can’t coexist in their current form.
- exception cloudvision.cvlib.exceptions.InputErrorException(message: str = 'Error in input fields', inputErrors: List[InputError] = None)[source]
Bases:
TemplateException
Exception for when a user needs to raise an error with one or more InputError structures in it. For Studios, this is raised manually by a template script to report an error with one or more input values. It allows for errors in multiple input fields to be reported at once. These errors are displayed to the user in the Studio UI.
- exception cloudvision.cvlib.exceptions.InputException(message: str = 'Error encountered with inputs', inputPath: List[str] = None, err=None)[source]
Bases:
AutofillActionException
Superclass for autofill input exceptions
- exception cloudvision.cvlib.exceptions.InputNotFoundException(inputPath: List[str] = None, err=None)[source]
Bases:
InputException
Exception raised when an input path does not exist in the provided studio inputs
- exception cloudvision.cvlib.exceptions.InputRequestException(inputPath: List[str] = None, err=None)[source]
Bases:
InputException
Exception raised when an request to get studio inputs fails
- exception cloudvision.cvlib.exceptions.InputUpdateException(inputPath: List[str] = None, err=None)[source]
Bases:
InputException
Exception raised when an update made to studio inputs fails
- exception cloudvision.cvlib.exceptions.InvalidContextException(message: str)[source]
Bases:
CVException
Exception raised when context methods are called invalidly
- exception cloudvision.cvlib.exceptions.InvalidCredentials(message: str = 'provided credentials were not valid')[source]
Bases:
CVException
Exception raised if provided credentials are invalid
- exception cloudvision.cvlib.exceptions.InvalidTopologyException(errors)[source]
Bases:
CVException
Exception class raised when topology model contains invalid configuration
- exception cloudvision.cvlib.exceptions.IpErrorException(message: str)[source]
Bases:
CVException
Exception raised for IP addressing errors
- exception cloudvision.cvlib.exceptions.IpHostIndexException(network, num_hosts: int, index: int, hostname: str = None, poolname: str = None)[source]
Bases:
IpErrorException
Exception raised when host indexing into a subnet is invalid
- exception cloudvision.cvlib.exceptions.IpNetworkOverlapException(network1, network2, hostname: str = None, poolname: str = None)[source]
Bases:
IpErrorException
Exception raised when networks unexpectedly overlap
- exception cloudvision.cvlib.exceptions.IpSubnetIndexException(network, subnet_mask: int, num_subnets: int, index: int, hostname: str = None, poolname: str = None)[source]
Bases:
IpErrorException
Exception raised when subnet indexing into a subnet pool is invalid
- exception cloudvision.cvlib.exceptions.LoggingFailed(message: str = '')[source]
Bases:
ScriptException
Exception raised when a logging request fails.
- exception cloudvision.cvlib.exceptions.ScriptException(message: str = 'cloudvision has encountered a script error')[source]
Bases:
CVException
Overarching class for Script exceptions
- exception cloudvision.cvlib.exceptions.TagErrorException(message: str)[source]
Bases:
CVException
Exception raised for tag errors
- exception cloudvision.cvlib.exceptions.TagInvalidTypeException(label: str, devId: str, valType: str, currVals: List[str] = None)[source]
Bases:
TagErrorException
Exception raised when a tag value is not of the correct type
- exception cloudvision.cvlib.exceptions.TagInvalidValuesException(label: str, devId: str, allowedVals: List[str] = None, currVals: List[str] = None)[source]
Bases:
TagErrorException
Exception raised when a tag has invalid values assigned to a device
- exception cloudvision.cvlib.exceptions.TagMissingException(label: str, devId: str, intfId: str = None)[source]
Bases:
TagErrorException
Exception raised when a tag is missing from a device
- exception cloudvision.cvlib.exceptions.TagOperationException(label: str, value: str, operation: str, devId: str = None, intfId: str = None)[source]
Bases:
TagErrorException
Exception raised when an attempted tag operation is invalid
- exception cloudvision.cvlib.exceptions.TagTooManyValuesException(label: str, devId: str, currVals: List[str] = None, intfId: str = None)[source]
Bases:
TagErrorException
Exception raised when a tag has too many values assigned to a device
- exception cloudvision.cvlib.exceptions.TemplateException(message: str = 'cloudvision has encountered a template error')[source]
Bases:
ScriptException
Overarching class for Template exceptions
- exception cloudvision.cvlib.exceptions.TemplateTypeNotSupported(message: str = 'Unsupported template type', templateType=None)[source]
Bases:
TemplateException
Exception for when a template type is not supported
- exception cloudvision.cvlib.exceptions.TimeoutExpiry[source]
Bases:
ScriptException
Exception to raise when alarm signals are used in scripts as timers so that script writers do not need to define their own exceptions for use in that situation. Users should raise and catch this exception in the signal handler so that they can be sure no other exception occurred while the timer was running
cloudvision.cvlib.execution module
cloudvision.cvlib.id_allocator module
- class cloudvision.cvlib.id_allocator.IdAllocator(start: int = 1, end: int = 65000, idLabel: str = 'id', groupLabel: str = 'devices')[source]
Bases:
object
Object to generate unique integer ids, eg. used for generating nodeIds. Can also be used for checking manually entered ids for duplicates. - start: starting value of id range - end: ending value of id range The following are only used if checking duplicate id errors: - idNames: optional name associated with ids - idLabel: name describing id type - groupLabel: name describing what is being id’d
cloudvision.cvlib.iputils module
- cloudvision.cvlib.iputils.get_ip_from_subnet(network, index: int, hostname: str = None, poolname: str = None)[source]
cloudvision.cvlib.logger module
- class cloudvision.cvlib.logger.Logger(alog: Callable[[Any, str, str | None, str | None, Dict[str, str] | None], None], trace: Callable[[Any, str, Dict[str, str] | None], None], debug: Callable[[Any, str, Dict[str, str] | None], None], info: Callable[[Any, str, Dict[str, str] | None], None], warning: Callable[[Any, str, Dict[str, str] | None], None], error: Callable[[Any, str, Dict[str, str] | None], None], critical: Callable[[Any, str, Dict[str, str] | None], None])[source]
Bases:
object
Logger object that stores a number of user-defined logging functions Due to context being pickled at certain execution stages of actions/studios, a normal python logger cannot be used. Minimum required call signatures are described by the init function, where ‘Any’ denotes the context being passed to avoid cyclical imports - alog: Function to be used for audit log insertion - trace: Function to be used for trace level logging - debug: Function to be used for debug level logging - info: Function to be used for info level logging - warning: Function to be used for warning level logging - error: Function to be used for error level logging - critical: Function to be used for critical level logging
cloudvision.cvlib.studio module
- cloudvision.cvlib.studio.GetOneWithWS(apiClientGetter, stateStub, stateGetReq, configStub, confGetReq)[source]
For Studio APIs, the state for a particular workspace can be difficult to determine. A state for a particular workspace only exists if an update has occurred for that workspace. State may exist in mainline, or the configuration change in the workspace may have explicitly deleted the state.
- GetOneWithWS does the following to try and provide state for the get request:
Do a get on the X state endpoint in the particular workspace for the desired state
If the state does NOT exist, issue another get on the X state endpoint for the mainline state.
If the state DOES exist there, check the X configuration endpoint of the workspace to see if the state has been explicitly deleted there.
Params: - apiClientGetter: The API client getter, i.e. ctx.getApiClient - stateStub: The stub for the state endpoint - stateGetReq: A workspace-aware get request to be made to the state client for the
desired workspace. It is assumed that the get request has a key field “workspace_id”, such that mainline can be queried in the case that the workspace query does not return anything.
configStub: The stub for the config endpoint
- confGetReq: A workspace-aware get request to be made to the config client for the
desired workspace.
Returns: - The request’s value, or None if the resource has been deleted
- class cloudvision.cvlib.studio.Studio(workspaceId: str, studioId: str, inputs=None, deviceIds=None, logger=None, execId=None, buildId=None)[source]
Bases:
object
Object to store studio context: - workspaceId: Id of the workspace - studioId: Id of the studio - inputs: inputs provided to the studio - deviceIds: Ids of the devices associated with this studio - logger: The logger to be used with this studio - execId: Id of the execution - buildId: Id of the studio build
- class cloudvision.cvlib.studio.StudioCustomData(context)[source]
Bases:
object
Object to store studio custom data context: - context: stores system and user-defined parameters. - chunk_size: chunk size of stored data.
- retrieve(studioId: str = '', path: List[str] = [], searchKey: str = '')[source]
retrieve gets the custom data from a path and key written by a studio in the Database. Params: - studioId: The studioId of studio that generates the data to be retrieved. - path: The path to get the data from, path is a list of strings. - key: The key to get the data from in the path.
- store(data: str = '', path: List[str] = [], key: str = '')[source]
store puts the passed studio custom data into a path in the Database. The data is stored in 1MB chunks.
Params: - data: The string data to be stored. - path: The path to store the data at, in the form of a list of strings.
paths have “workspace/<wsId>/build/<buildId>/studio/<studioId>/customData” as the root.
key: The key to store the data at in the path.
- cloudvision.cvlib.studio.extractInputElems(inputs, inputPath: List[str], elems: List[str] = [], tagElems: List[str] = [])[source]
Takes lists of elements and tag elements, and traverses through the input tree towards the Input path, extracting the most recent matching values for these elements from the inputs.
Returns these results in a single dict, so overwriting of results will occur if specified elements/tag elements have the same name in the inputs tree
- cloudvision.cvlib.studio.extractStudioInfoFromArgs(args: Dict)[source]
Studio Autofill actions contains studio related information in their arguments, but a studio is not instantiated and associated with the context. As these actions require interfacing with studio APIs, this function extracts the studio info (verifies this info is valid if needed) and returns it to the user in the order below.
These are (All return values may be None in the case the field is not present); - StudioID: The ID of the studio associated with the action - WorkspaceID: The ID of the workspace associated with the - InputPath: The string path elements leading to the input element in the action
NOTE: Input paths containing array/list indices will be stringified, so use caution when iterating through the input tree using this. These are not converted to integer values as they could clash with elements containing only numbers. The extractInputElems method accounts for this and is suggested over manually traversing the tree looking for elements
- cloudvision.cvlib.studio.getSimpleResolverQueryValue(query: str)[source]
Autofill action arguments may be resolver queries. In these cases the string argument is in the form of “<tag>:<Value>” or more complex queries such as “<tag>:<ValueA> OR <tag>:<ValueB>”. This function is designed to extract the query values from a simple query.
Params: - query: The simple query string, e.g. “<tag>:<Value>”
Returns: - The query value, e.g. “<Value>” from the above example.
Raises an InputException in the case where the passed query is not parsable as a simple query
- cloudvision.cvlib.studio.getStudioInputs(clientGetter, studioId: str, workspaceId: str, path: List[str] = [])[source]
Uses the passed ctx.getApiClient function reference to issue get the current input state for given combination of studioId, workspaceId and path. Path MUST be a non-None list, omitting this argument retrieves the full studio input tree. This function falls back to mainline state at workspace creation time (or last rebase time) to build up the state should the workspace studio state not be created yet and checks to see if any deletes would affect the requested input.
Raises an InputNotFoundException if the input requested does not exist.
- cloudvision.cvlib.studio.get_tag_value_from_resolver(resolver: Dict) str [source]
Return the value in single-tag resolver
- cloudvision.cvlib.studio.mergeStudioInputs(rootInputs: Any, path: List[Any], inputsToInsert: Any)[source]
Due to grpc messaging limits, large inputs may be sent out to get requests in chunks, and should be retrieved with a GetAll to ensure all inputs for a given studio are received.
In the case where a studio resource returns inputs in multiple responses, they need to be spliced together to form a cohesive input object.
Params: - rootInputs: The root object to insert the new inputs into - path: The path in the rootInputs to insert the inputs into - inputsToInsert: The inputs to insert into the root inputs
Returns: - The updated root inputs
- cloudvision.cvlib.studio.setStudioInput(clientGetter, studioId: str, workspaceId: str, inputPath: List[str], value: str, remove: bool = False)[source]
Uses the passed ctx.getApiClient function reference to issue a set to the Studio inputs rAPI with the associated input path and value
- cloudvision.cvlib.studio.setStudioInputs(clientGetter, studioId: str, workspaceId: str, inputs: List[Tuple])[source]
Uses the passed ctx.getApiClient function reference to issue a setSome to the Studio inputs rAPI with the associated InputsConfig
The inputs list should contain tuples of a fixed size, either with a length of 2 or a length of 3. Tuple: (Path, Inputs) or (Path, Inputs, Remove) a mixed list [(path, value, remove), (path, value),..] is supported
The value doesn’t matter if the remove flag is True
cloudvision.cvlib.topology module
- class cloudvision.cvlib.topology.Connection(sourceDevice, sourceInterface, destDevice, destInterface)[source]
Bases:
object
cloudvision.cvlib.user module
cloudvision.cvlib.utils module
- cloudvision.cvlib.utils.extractJSONEncodedListArg(listArg: str)[source]
Extracts a string arg in JSON-encoded list form and converts it to a list for use
- Parameters:
listArg (str) – The stringified list
- cloudvision.cvlib.utils.queryCCStartTime(client: GRPCClient, ccId: str)[source]
cloudvision.cvlib.workspace module
- class cloudvision.cvlib.workspace.Workspace(workspaceId: str, studioIds: List[str] = [], buildId: str | None = None)[source]
Bases:
object
Object to store workspace context: - id: Id of the workspace - studioIds: Ids of the studios edited in the associated workspace - buildId: Id of the workspace build
- cloudvision.cvlib.workspace.getWorkspaceLastSynced(clientGetter, workspaceId: str)[source]
Gets the lastRebasedAt timestamp for the given workspace, or if that’s null, the createdAt timestamp of the workspace. This function allows for workspace-aware resource apis to gather accurate data when needing to fall back to mainline for building accurate state in a workspace.
- Params:
clientGetter: The API client getter, i.e. ctx.getApiClient workspaceId: The ID of the workspace to retrieve the timestamp for
- Returns:
Timestamp object of the workspace’s last rebased time, or created at time
- Raises:
CVException – If the workspace does not exist, or is mainline