Programmatic API reference

This page describes parts of inmanta code base that provide a stable API that could be used from modules or extensions.

Warning

Only those parts explicitly mentioned here are part of the API. They provide a stable interface. Other parts of the containing modules provide no such guarantees.

Constants

class inmanta.const.LogLevel(value)[source]

Bases: str, enum.Enum

Log levels used for various parts of the inmanta orchestrator.

CRITICAL = 'CRITICAL'
DEBUG = 'DEBUG'
ERROR = 'ERROR'
INFO = 'INFO'
TRACE = 'TRACE'
WARNING = 'WARNING'
from_int() inmanta.const.LogLevel[source]

This methods is an example of construction of a LogLevel value from an integer

from_str() inmanta.const.LogLevel[source]

This methods is an example of construction of a LogLevel value from a string

property to_int: int
class inmanta.const.ResourceAction(value)[source]

Bases: str, enum.Enum

Enumeration of all resource actions.

deploy = 'deploy'
dryrun = 'dryrun'
getfact = 'getfact'
other = 'other'
pull = 'pull'
push = 'push'
store = 'store'

Compiler exceptions

class inmanta.ast.CompilerException(msg: str)[source]

Bases: Exception, inmanta.ast.export.Exportable

Base class for exceptions generated by the compiler

class inmanta.parser.ParserException(location: inmanta.ast.Range, value, msg: Optional[str] = None)[source]

Bases: inmanta.ast.CompilerException

Exception occurring during the parsing of the code

class inmanta.ast.RuntimeException(stmt: Optional[inmanta.ast.Locatable], msg: str)[source]

Bases: inmanta.ast.CompilerException

Baseclass for exceptions raised by the compiler after parsing is complete.

class inmanta.ast.ExternalException(stmt: inmanta.ast.Locatable, msg: str, cause: Exception)[source]

Bases: inmanta.ast.RuntimeException

When a plugin call produces an exception that is not a RuntimeException, it is wrapped in an ExternalException to make it conform to the expected interface

class inmanta.ast.ExplicitPluginException(stmt: inmanta.ast.Locatable, msg: str, cause: PluginException)[source]

Bases: inmanta.ast.ExternalException

Base exception for wrapping an explicit inmanta.plugins.PluginException raised from a plugin call.

Plugins

class inmanta.plugins.Context(resolver: inmanta.execute.runtime.Resolver, queue: inmanta.execute.runtime.QueueScheduler, owner: FunctionCall, plugin: Plugin, result: inmanta.execute.runtime.ResultVariable)[source]

An instance of this class is used to pass context to the plugin

emit_expression(stmt: ExpressionStatement) None[source]

Add a new statement

get_client() inmanta.protocol.endpoints.Client[source]
get_compiler() Compiler[source]
get_data_dir() str[source]

Get the path to the data dir (and create if it does not exist yet

get_environment_id() str[source]
get_queue_scheduler() inmanta.execute.runtime.QueueScheduler[source]
get_resolver() inmanta.execute.runtime.Resolver[source]
get_sync_client() inmanta.protocol.endpoints.SyncClient[source]
get_type(name: inmanta.ast.LocatableString) inmanta.ast.type.Type[source]

Get a type from the configuration model.

run_sync(function: Callable[..., T], timeout: int = 5) T[source]

Execute the async function and return its result. This method takes care of starting and stopping the ioloop. The main use for this function is to use the inmanta internal rpc to communicate with the server.

Parameters
  • function – The async function to execute. This function should return a yieldable object.

  • timeout – A timeout for the async function.

Returns

The result of the async call.

Raises

ConnectionRefusedError – When the function timeouts this exception is raised.

inmanta.plugins.plugin(function: Optional[Callable] = None, commands: Optional[List[str]] = None, emits_statements: bool = False, allow_unknown: bool = False) Callable[source]

Python decorator to register functions with inmanta as plugin

Parameters
  • function – The function to register with inmanta. This is the first argument when it is used as decorator.

  • commands – A list of command paths that need to be available. Inmanta raises an exception when the command is not available.

  • emits_statements – Set to true if this plugin emits new statements that the compiler should execute. This is only required for complex plugins such as integrating a template engine.

  • allow_unknown – Set to true if this plugin accepts Unknown values as valid input.

class inmanta.plugins.PluginException(message: str)[source]

Base class for custom exceptions raised from a plugin.

class inmanta.plugins.PluginMeta(name: str, bases: Tuple[type, ...], dct: Dict[str, object])[source]

Bases: type

A metaclass that keeps track of concrete plugin subclasses. This class is responsible for all plugin registration.

classmethod add_function(plugin_class: Type[inmanta.plugins.Plugin]) None[source]

Add a function plugin class

classmethod clear(inmanta_module: Optional[str] = None) None[source]

Clears registered plugin functions.

Parameters

inmanta_module – Clear plugin functions for a specific inmanta module. If omitted, clears all registered plugin functions.

classmethod get_functions() Dict[str, Type[inmanta.plugins.Plugin]][source]

Get all functions that are registered

Resources

inmanta.resources.resource(name: str, id_attribute: str, agent: str)[source]

A decorator that registers a new resource. The decorator must be applied to classes that inherit from Resource

Parameters
  • name – The name of the entity in the configuration model it creates a resources from. For example std::File

  • id_attribute – The attribute of this resource that uniquely identifies a resource on an agent. This attribute can be mapped.

  • agent – This string indicates how the agent of this resource is determined. This string points to an attribute, but it can navigate relations (this value cannot be mapped). For example, the agent argument could be host.name

class inmanta.resources.Resource(_id: inmanta.resources.Id)[source]

Plugins should inherit resource from this class so a resource from a model can be serialized and deserialized.

Such as class is registered when the resource() decorator is used. Each class needs to indicate the fields the resource will have with a class field named “fields”. A metaclass merges all fields lists from the class itself and all superclasses. If a field it not available directly in the model object the serializer will look for static methods in the class with the name “get_$fieldname”.

clone(**kwargs: Any) inmanta.resources.Resource[source]

Create a clone of this resource. The given kwargs can be used to override attributes.

Returns

The cloned resource

class inmanta.resources.PurgeableResource(_id: inmanta.resources.Id)[source]

See std::PurgeableResource for more information.

class inmanta.resources.ManagedResource(_id: inmanta.resources.Id)[source]

See std::ManagedResource for more information.

class inmanta.resources.IgnoreResourceException[source]

Throw this exception when a resource should not be included by the exported.

class inmanta.resources.Id(entity_type: str, agent_name: str, attribute: str, attribute_value: str, version: int = 0)[source]

A unique id that identifies a resource that is managed by an agent

classmethod parse_id(resource_id: Union[ResourceVersionIdStr, ResourceIdStr]) inmanta.resources.Id[source]

Parse the resource id and return the type, the hostname and the resource identifier.

resource_str() ResourceIdStr[source]
class inmanta.execute.util.Unknown(source: object)[source]

An instance of this class is used to indicate that this value can not be determined yet.

Parameters

source – The source object that can determine the value

Handlers

inmanta.agent.handler.cache(func: Optional[T_FUNC] = None, ignore: List[str] = [], timeout: int = 5000, for_version: bool = True, cache_none: bool = True, cacheNone: Optional[bool] = None, call_on_delete: Optional[Callable[Any, None]] = None) Union[T_FUNC, Callable[T_FUNC, T_FUNC]][source]

decorator for methods in resource handlers to provide caching

this decorator works similar to memoization: when the decorate method is called, its return value is cached, for subsequent calls, the cached value is used instead of the actual value

The name of the method + the arguments of the method form the cache key

If an argument named version is present and for_version is True, the cache entry is flushed after this version has been deployed If an argument named resource is present, it is assumed to be a resource and its ID is used, without the version information

Parameters
  • timeout – the number of second this cache entry should live

  • for_version – if true, this value is evicted from the cache when this deploy is ready

  • ignore – a list of argument names that should not be part of the cache key

  • cache_none – cache returned none values

  • call_on_delete – A callback function that is called when the value is removed from the cache, with the value as argument.

inmanta.agent.handler.provider(resource_type: str, name: str) None[source]

A decorator that registers a new handler.

Parameters
  • resource_type – The type of the resource this handler provides an implementation for. For example, std::File

  • name – A name to reference this provider.

class inmanta.agent.handler.SkipResource[source]

Bases: Exception

A handler should raise this exception when a resource should be skipped. The resource will be marked as skipped instead of failed.

class inmanta.agent.handler.ResourcePurged[source]

If the read_resource() method raises this exception, the agent will mark the current state of the resource as purged.

class inmanta.agent.handler.HandlerContext(resource: inmanta.resources.Resource, dry_run: bool = False, action_id: Optional[uuid.UUID] = None, logger: Optional[logging.Logger] = None)[source]

Context passed to handler methods for state related “things”

add_change(name: str, desired: object, current: object = None) None[source]

Report a change of a field. This field is added to the set of updated fields

Parameters
  • name – The name of the field that was updated

  • desired – The desired value to which the field was updated (or should be updated)

  • current – The value of the field before it was updated

add_changes(**kwargs: Union[BaseModel, uuid.UUID, inmanta.types.StrictNonIntBool, int, float, datetime.datetime, str]) None[source]

Report a list of changes at once as kwargs

Parameters
  • key – The name of the field that was updated. This field is also added to the set of updated fields

  • value – The desired value of the field.

To report the previous value of the field, use the add_change method

critical(msg: str, *args: object, **kwargs: object) None[source]

Log ‘msg % args’ with severity ‘CRITICAL’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.critical("Houston, we have a %s", "major disaster", exc_info=1)

debug(msg: str, *args: object, **kwargs: object) None[source]

Log ‘msg % args’ with severity ‘DEBUG’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

Keyword arguments should be JSON serializable.

logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)

error(msg: str, *args: object, **kwargs: object) None[source]

Log ‘msg % args’ with severity ‘ERROR’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.error("Houston, we have a %s", "major problem", exc_info=1)

exception(msg: str, *args: object, exc_info: bool = True, **kwargs: object) None[source]

Convenience method for logging an ERROR with exception information.

fields_updated(fields: str) None[source]

Report that fields have been updated

info(msg: str, *args: object, **kwargs: object) None[source]

Log ‘msg % args’ with severity ‘INFO’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

Keyword arguments should be JSON serializable.

logger.info("Houston, we have a %s", "interesting problem", exc_info=1)

is_dry_run() bool[source]

Is this a dryrun?

set_fact(fact_id: str, value: str) None[source]

Send a fact to the Inmanta server.

Parameters
  • fact_id – The name of the fact.

  • value – The actual value of the fact.

set_status(status: inmanta.const.ResourceState) None[source]

Set the status of the handler operation.

update_changes(changes: Dict[str, inmanta.data.model.AttributeStateChange]) None[source]
update_changes(changes: Dict[str, Dict[str, Optional[Union[BaseModel, uuid.UUID, inmanta.types.StrictNonIntBool, int, float, datetime.datetime, str]]]]) None
update_changes(changes: Dict[str, Tuple[Union[BaseModel, uuid.UUID, inmanta.types.StrictNonIntBool, int, float, datetime.datetime, str], Union[BaseModel, uuid.UUID, inmanta.types.StrictNonIntBool, int, float, datetime.datetime, str]]]) None

Update the changes list with changes

Parameters

changes – This should be a dict with a value a dict containing “current” and “desired” keys

warning(msg: str, *args: object, **kwargs: object) None[source]

Log ‘msg % args’ with severity ‘WARNING’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

Keyword arguments should be JSON serializable.

logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)

class inmanta.agent.handler.ResourceHandler(agent: inmanta.agent.agent.AgentInstance, io: Optional[IOBase] = None)[source]

A baseclass for classes that handle resources. New handler are registered with the provider() decorator.

The implementation of a handler should use the self._io instance to execute io operations. This io objects makes abstraction of local or remote operations. See LocalIO for the available operations.

Parameters
  • agent – The agent that is executing this handler.

  • io – The io object to use.

_diff(current: inmanta.resources.Resource, desired: inmanta.resources.Resource) Dict[str, Dict[str, Any]][source]

Calculate the diff between the current and desired resource state.

Parameters
  • current – The current state of the resource

  • desired – The desired state of the resource

Returns

A dict with key the name of the field and value another dict with “current” and “desired” as keys for fields that require changes.

available(resource: inmanta.resources.Resource) bool[source]

Returns true if this handler is available for the given resource

Parameters

resource – Is this handler available for the given resource?

Returns

Available or not?

can_reload() bool[source]

Can this handler reload?

Returns

Return true if this handler needs to reload on requires changes.

check_facts(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource) Dict[str, object][source]

This method is called by the agent to query for facts. It runs pre() and post(). This method calls facts() to do the actually querying.

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to query facts for.

Returns

A dict with fact names as keys and facts values.

check_resource(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource) inmanta.resources.Resource[source]

Check the current state of a resource

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to check the current state of.

Returns

A resource to represents the current state. Use the clone() to create clone of the given resource that can be modified.

close() None[source]
deploy(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource, requires: Dict[ResourceIdStr, inmanta.const.ResourceState]) None[source]

This method is always be called by the agent, even when one of the requires of the given resource failed to deploy. The default implementation of this method will deploy the given resource when all its requires were deployed successfully. Override this method if a different condition determines whether the resource should deploy.

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to deploy

  • requires – A dictionary mapping the resource id of each dependency of the given resource to its resource state.

do_changes(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource, changes: Dict[str, Dict[str, object]]) None[source]

Do the changes required to bring the resource on this system in the state of the given resource.

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to check the current state of.

  • changes – The changes that need to occur as reported by list_changes()

do_reload(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource) None[source]

Perform a reload of this resource.

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to reload.

execute(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource, dry_run: bool = False) None[source]

Update the given resource. This method is called by the agent. Most handlers will not override this method and will only override check_resource(), optionally list_changes() and do_changes()

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to check the current state of.

  • dry_run – True will only determine the required changes but will not execute them.

facts(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource) Dict[str, object][source]

Override this method to implement fact querying. A queried fact can be reported back in two different ways: either via the return value of this method or by adding the fact to the HandlerContext via the set_fact() method. pre() and post() are called before and after this method.

Parameters
  • ctx – Context object to report changes, logs and facts to the agent and server.

  • resource – The resource to query facts for.

Returns

A dict with fact names as keys and facts values.

get_client() inmanta.protocol.endpoints.SessionClient[source]

Get the client instance that identifies itself with the agent session.

Returns

A client that is associated with the session of the agent that executes this handler.

get_file(hash_id: str) Optional[bytes][source]

Retrieve a file from the fileserver identified with the given id. The convention is to use the sha1sum of the content to identify it.

Parameters

hash_id – The id of the content/file to retrieve from the server.

Returns

The content in the form of a bytestring or none is the content does not exist.

list_changes(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource) Dict[str, Dict[str, Any]][source]

Returns the changes required to bring the resource on this system in the state described in the resource entry. This method calls check_resource()

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to check the current state of.

Returns

A dict with key the name of the field and value another dict with “current” and “desired” as keys for fields that require changes.

post(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource) None[source]

Method executed after an operation. Override this method to run after an operation.

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to query facts for.

pre(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource) None[source]

Method executed before a handler operation (Facts, dryrun, real deployment, …) is executed. Override this method to run before an operation.

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to query facts for.

run_sync(func: Callable[Awaitable[T]]) T[source]

Run a the given async function on the ioloop of the agent. It will block the current thread until the future resolves.

Parameters

func – A function that returns a yieldable future.

Returns

The result of the async function.

set_cache(cache: inmanta.agent.cache.AgentCache) None[source]
stat_file(hash_id: str) bool[source]

Check if a file exists on the server. This method does and async call to the server and blocks on the result.

Parameters

hash_id – The id of the file on the server. The convention is the use the sha1sum of the content as id.

Returns

True if the file is available on the server.

upload_file(hash_id: str, content: bytes) None[source]

Upload a file to the server

Parameters
  • hash_id – The id to identify the content. The convention is to use the sha1sum of the content to identify it.

  • content – A byte string with the content

class inmanta.agent.handler.CRUDHandler(agent: inmanta.agent.agent.AgentInstance, io: Optional[IOBase] = None)[source]

This handler base class requires CRUD methods to be implemented: create, read, update and delete. Such a handler only works on purgeable resources.

available(resource: inmanta.resources.Resource) bool

Returns true if this handler is available for the given resource

Parameters

resource – Is this handler available for the given resource?

Returns

Available or not?

calculate_diff(ctx: inmanta.agent.handler.HandlerContext, current: inmanta.resources.Resource, desired: inmanta.resources.Resource) Dict[str, Dict[str, Any]][source]

Calculate the diff between the current and desired resource state.

Parameters
  • ctx – Context can be used to get values discovered in the read method. For example, the id used in API calls. This context should also be used to let the handler know what changes were made to the resource.

  • current – The current state of the resource

  • desired – The desired state of the resource

Returns

A dict with key the name of the field and value another dict with “current” and “desired” as keys for fields that require changes.

can_reload() bool

Can this handler reload?

Returns

Return true if this handler needs to reload on requires changes.

check_facts(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource) Dict[str, object]

This method is called by the agent to query for facts. It runs pre() and post(). This method calls facts() to do the actually querying.

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to query facts for.

Returns

A dict with fact names as keys and facts values.

check_resource(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource) inmanta.resources.Resource

Check the current state of a resource

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to check the current state of.

Returns

A resource to represents the current state. Use the clone() to create clone of the given resource that can be modified.

close() None
create_resource(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.PurgeableResource) None[source]

This method is called by the handler when the resource should be created.

Parameters
  • context – Context can be used to get values discovered in the read method. For example, the id used in API calls. This context should also be used to let the handler know what changes were made to the resource.

  • resource – The desired resource state.

delete_resource(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.PurgeableResource) None[source]

This method is called by the handler when the resource should be deleted.

Parameters
  • ctx – Context can be used to get values discovered in the read method. For example, the id used in API calls. This context should also be used to let the handler know what changes were made to the resource.

  • resource – The desired resource state.

deploy(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource, requires: Dict[ResourceIdStr, inmanta.const.ResourceState]) None

This method is always be called by the agent, even when one of the requires of the given resource failed to deploy. The default implementation of this method will deploy the given resource when all its requires were deployed successfully. Override this method if a different condition determines whether the resource should deploy.

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to deploy

  • requires – A dictionary mapping the resource id of each dependency of the given resource to its resource state.

do_changes(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource, changes: Dict[str, Dict[str, object]]) None

Do the changes required to bring the resource on this system in the state of the given resource.

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to check the current state of.

  • changes – The changes that need to occur as reported by list_changes()

do_reload(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource) None

Perform a reload of this resource.

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to reload.

execute(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource, dry_run: Optional[bool] = None) None[source]

Update the given resource. This method is called by the agent. Override the CRUD methods of this class.

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to check the current state of.

  • dry_run – True will only determine the required changes but will not execute them.

facts(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource) Dict[str, object]

Override this method to implement fact querying. A queried fact can be reported back in two different ways: either via the return value of this method or by adding the fact to the HandlerContext via the set_fact() method. pre() and post() are called before and after this method.

Parameters
  • ctx – Context object to report changes, logs and facts to the agent and server.

  • resource – The resource to query facts for.

Returns

A dict with fact names as keys and facts values.

get_client() inmanta.protocol.endpoints.SessionClient

Get the client instance that identifies itself with the agent session.

Returns

A client that is associated with the session of the agent that executes this handler.

get_file(hash_id: str) Optional[bytes]

Retrieve a file from the fileserver identified with the given id. The convention is to use the sha1sum of the content to identify it.

Parameters

hash_id – The id of the content/file to retrieve from the server.

Returns

The content in the form of a bytestring or none is the content does not exist.

list_changes(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource) Dict[str, Dict[str, Any]]

Returns the changes required to bring the resource on this system in the state described in the resource entry. This method calls check_resource()

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to check the current state of.

Returns

A dict with key the name of the field and value another dict with “current” and “desired” as keys for fields that require changes.

post(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource) None

Method executed after an operation. Override this method to run after an operation.

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to query facts for.

pre(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource) None

Method executed before a handler operation (Facts, dryrun, real deployment, …) is executed. Override this method to run before an operation.

Parameters
  • ctx – Context object to report changes and logs to the agent and server.

  • resource – The resource to query facts for.

read_resource(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.PurgeableResource) None[source]

This method reads the current state of the resource. It provides a copy of the resource that should be deployed, the method implementation should modify the attributes of this resource to the current state.

Parameters
  • ctx – Context can be used to pass value discovered in the read method to the CUD methods. For example, the id used in API calls

  • resource – A clone of the desired resource state. The read method need to set values on this object.

Raises
  • SkipResource – Raise this exception when the handler should skip this resource

  • ResourcePurged – Raise this exception when the resource does not exist yet.

run_sync(func: Callable[Awaitable[T]]) T

Run a the given async function on the ioloop of the agent. It will block the current thread until the future resolves.

Parameters

func – A function that returns a yieldable future.

Returns

The result of the async function.

set_cache(cache: inmanta.agent.cache.AgentCache) None
stat_file(hash_id: str) bool

Check if a file exists on the server. This method does and async call to the server and blocks on the result.

Parameters

hash_id – The id of the file on the server. The convention is the use the sha1sum of the content as id.

Returns

True if the file is available on the server.

update_resource(ctx: inmanta.agent.handler.HandlerContext, changes: Dict[str, Dict[str, Any]], resource: inmanta.resources.PurgeableResource) None[source]

This method is called by the handler when the resource should be updated.

Parameters
  • ctx – Context can be used to get values discovered in the read method. For example, the id used in API calls. This context should also be used to let the handler know what changes were made to the resource.

  • changes – A map of resource attributes that should be changed. Each value is a tuple with the current and the desired value.

  • resource – The desired resource state.

upload_file(hash_id: str, content: bytes) None

Upload a file to the server

Parameters
  • hash_id – The id to identify the content. The convention is to use the sha1sum of the content to identify it.

  • content – A byte string with the content

class inmanta.agent.io.local.LocalIO(uri: str, config: Dict[str, Optional[str]])[source]

This class provides handler IO methods

This class is part of the stable API.

chmod(path: str, permissions: str) None[source]

Change the permissions

Parameters
  • path (str) – The path of the file or directory to change the permission of.

  • permissions (str) – An octal string with the permission to set.

chown(path: str, user: Optional[str] = None, group: Optional[str] = None) None[source]

Change the ownership of a file.

Parameters
  • path (str) – The path of the file or directory to change the ownership of.

  • user (str) – The user to change to

  • group (str) – The group to change to

close() None

Close any resources

file_exists(path: str) bool[source]

Check if a given file exists

Parameters

path (str) – The path to check if it exists.

Returns

Returns true if the file exists

Return type

bool

file_stat(path: str) Dict[str, Union[int, str]][source]

Do a stat call on a file

Parameters

path (str) – The file or direct to stat

Returns

A dict with the owner, group and permissions of the given path

Return type

dict[str, str]

hash_file(path: str) str[source]

Return the sha1sum of the file at path

Parameters

path (str) – The path of the file to hash the content of

Returns

The sha1sum in a hex string

Return type

str

is_remote() bool[source]

Are operation executed remote

Returns

Returns true if the io operations are remote.

Return type

bool

Is the given path a symlink

Parameters

path (str) – The path of the symlink

Returns

Returns true if the given path points to a symlink

Return type

str

mkdir(path: str) None[source]

Create a directory

Parameters

path (str) – Create this directory. The parent needs to exist.

put(path: str, content: str) None[source]

Put the given content at the given path

Parameters
  • path (str) – The location where to write the file

  • content (bytes) – The binarystring content to write to the file.

read(path: str) str[source]

Read in the file in path and return its content as string

Parameters

path (str) – The path of the file to read.

Returns

The string content of the file

Return type

string

read_binary(path: str) bytes[source]

Read in the file in path and return its content as a bytestring

Parameters

path (str) – The path of the file to read.

Returns

The byte content of the file

Return type

bytes

Return the target of the path

Parameters

path (str) – The symlink to get the target for.

Returns

The target of the symlink

Return type

str

remove(path: str) None[source]

Remove a file

Parameters

path (str) – The path of the file to remove.

rmdir(path: str) None[source]

Remove a directory

Parameters

path (str) – The directory to remove

run(command: str, arguments: List[str] = [], env: Optional[Dict[str, str]] = None, cwd: Optional[str] = None, timeout: Optional[int] = None) Tuple[str, str, int][source]

Execute a command with the given argument and return the result

Parameters
  • command (str) – The command to execute.

  • arguments (list) – The arguments of the command

  • env (dict) – A dictionary with environment variables.

  • cwd (str) – The working dir to execute the command in.

  • timeout (int) – The timeout for this command. This parameter is ignored if the command is executed remotely with a python 2 interpreter.

Returns

A tuple with (stdout, stderr, returncode)

Return type

tuple

Symlink source to target

Parameters
  • source (str) – Create a symlink of this path to target

  • target (str) – The path of the symlink to create

Export

@inmanta.export.dependency_manager(function: Callable[[Dict[str, inmanta.ast.entity.Entity], Dict[inmanta.resources.Id, inmanta.resources.Resource]], None]) None[source]

Register a function that manages dependencies in the configuration model that will be deployed.

Attributes

class inmanta.ast.attribute.Attribute(entity: Entity, value_type: Type, name: str, location: inmanta.ast.Location, multi: bool = False, nullable: bool = False)[source]

The attribute base class for entity attributes.

Parameters

entity – The entity this attribute belongs to

get_type() Type[source]

Get the type of this attribute.

property type: Type

Get the type of this attribute.

validate(value: object) None[source]

Validate a value that is going to be assigned to this attribute. Raises a inmanta.ast.RuntimeException if validation fails.

class inmanta.ast.attribute.RelationAttribute(entity: Entity, value_type: Type, name: str, location: inmanta.ast.Location)[source]

Bases: inmanta.ast.attribute.Attribute

An attribute that is a relation

Modules

class inmanta.module.InstallMode(value)[source]

Bases: str, enum.Enum

The module install mode determines what version of a module should be selected when a module is downloaded.

master = 'master'

For V1 modules: Use the module’s master branch. For V2 modules: Equivalent to InstallMode.prerelease

prerelease = 'prerelease'

Similar to InstallMode.release but prerelease versions are allowed as well.

release = 'release'

Only use a released version that is compatible with the current compiler and any version constraints defined in the requires lists for the project or any other modules (see ProjectMetadata, ModuleV1Metadata and ModuleV2Metadata).

A module is considered released in the following situations:
  • For V1 modules: There is a tag on a commit. This tag is a valid, pep440 compliant version identifier and it’s not a

    prelease version.

  • For V2 modules: The python package was published on a Python package repository, the version identifier is pep440

    compliant and is not a prerelease version.

inmanta.module.INSTALL_OPTS: List[str] = ['release', 'prerelease', 'master']

List of possible module install modes, kept for backwards compatibility. New code should use InstallMode instead.

class inmanta.module.InvalidModuleException(msg: str)[source]

This exception is raised if a module is invalid.

class inmanta.module.InvalidMetadata(msg: str, validation_error: Optional[pydantic.error_wrappers.ValidationError] = None)[source]

This exception is raised if the metadata file of a project or module is invalid.

class inmanta.module.ModuleLike(path: str)[source]

Bases: abc.ABC, Generic[TMetadata]

Commons superclass for projects and modules, which are both versioned by git

Variables

name – The name for this module like instance, in the context of the Inmanta DSL.

abstract classmethod from_path(path: str) Optional[inmanta.module.ModuleLike][source]

Get a concrete module like instance from a path. Returns None when no project or module is present at the given path.

property metadata: TMetadata
class inmanta.module.Module(project: Optional[inmanta.module.Project], path: str)[source]

Bases: inmanta.module.ModuleLike[TModuleMetadata], abc.ABC

This class models an inmanta configuration module

abstract classmethod from_path(path: str) Optional[inmanta.module.Module][source]

Get a concrete module like instance from a path. Returns None when no project or module is present at the given path.

get_plugin_files() Iterator[Tuple[Path, ModuleName]][source]

Returns a tuple (absolute_path, fq_mod_name) of all python files in this module.

unload() None[source]

Unloads this module instance from the project, the registered plugins and the loaded Python modules.

inmanta.module.ModuleName

alias of str

class inmanta.module.ModuleV1(project: Optional[inmanta.module.Project], path: str)[source]

Bases: inmanta.module.Module[inmanta.module.ModuleV1Metadata], inmanta.module.ModuleLikeWithYmlMetadataFile

classmethod from_path(path: str) Optional[TModule][source]

Get a concrete module like instance from a path. Returns None when no project or module is present at the given path.

class inmanta.module.ModuleV2(project: Optional[inmanta.module.Project], path: str, is_editable_install: bool = False, installed_version: Optional[packaging.version.Version] = None)[source]

Bases: inmanta.module.Module[inmanta.module.ModuleV2Metadata]

classmethod from_path(path: str) Optional[TModule][source]

Get a concrete module like instance from a path. Returns None when no project or module is present at the given path.

is_editable() bool[source]

Returns True iff this module has been installed in editable mode.

class inmanta.module.ModuleSource(*args, **kwds)[source]

Bases: Generic[TModule]

get_installed_module(project: Optional[inmanta.module.Project], module_name: str) Optional[TModule][source]

Returns a module object for a module if it is installed.

Parameters
  • project – The project associated with the module.

  • module_name – The name of the module.

class inmanta.module.ModuleV2Source(urls: List[str])[source]

Bases: inmanta.module.ModuleSource[ModuleV2]

inmanta.module.Path

alias of str

class inmanta.loader.PluginModuleFinder(modulepaths: List[str])[source]

Bases: importlib.abc.Finder

Custom module finder which handles V1 Inmanta modules. V2 modules are handled using the standard Python finder. This finder is stored as the last entry in meta_path, as such that the default Python Finders detect V2 modules first.

classmethod reset() None[source]

Remove the PluginModuleFinder from sys.meta_path.

inmanta.loader.unload_inmanta_plugins(inmanta_module: Optional[str] = None) None[source]

Unloads Python modules associated with inmanta modules (inmanta_plugins submodules).

Parameters

inmanta_module – Unload the Python modules for a specific inmanta module. If omitted, unloads the Python modules for all inmanta modules.

Project

class inmanta.module.Project(path: str, autostd: bool = True, main_file: str = 'main.cf', venv_path: Optional[str] = None)[source]

Bases: inmanta.module.ModuleLike[inmanta.module.ProjectMetadata], inmanta.module.ModuleLikeWithYmlMetadataFile

An inmanta project

Variables
  • modules – The collection of loaded modules for this project.

  • module_source – The v2 module source for this project.

classmethod get(main_file: str = 'main.cf') inmanta.module.Project[source]

Get the instance of the project

install_modules() None[source]

Installs all modules, both v1 and v2.

load(install: bool = False) None[source]

Load this project’s AST and plugins.

Parameters

install – Whether to install the project’s modules before attempting to load it.

classmethod set(project: inmanta.module.Project, *, clean: bool = True) None[source]

Set the instance of the project.

Parameters

clean – Clean up all side effects of any previously loaded projects. Clears the registered plugins and loaded Python plugins packages.

class inmanta.module.ProjectNotFoundException(msg: str)[source]

Bases: inmanta.ast.CompilerException

This exception is raised when inmanta is unable to find a valid project

Python Environment

inmanta.env.mock_process_env(*, python_path: Optional[str] = None, env_path: Optional[str] = None) None[source]

Overrides the process environment information. This forcefully sets the environment that is recognized as the outer Python environment. This function should only be called when a Python environment has been set up dynamically and this environment should be treated as if this process was spawned from it, and even then with great care.

Parameters
  • python_path – The path to the python binary. Only one of python_path and env_path should be set.

  • env_path – The path to the python environment directory. Only one of python_path and env_path should be set.

class inmanta.env.VirtualEnv(env_path: str)[source]

Creates and uses a virtual environment for this process. This virtualenv inherits from the previously active one.

init_env() None[source]

Initialize the virtual environment.

use_virtual_env() None[source]

Activate the virtual environment.

Typing

The inmanta.ast.type module contains a representation of inmanta types, as well as validation logic for those types.

class inmanta.ast.type.Type[source]

This class is the abstract base class for all types in the Inmanta DSL that represent basic data. These are types that are not relations. Instances of subclasses represent a type in the Inmanta language.

get_base_type() inmanta.ast.type.Type[source]

Returns the base type for this type, i.e. the plain type without modifiers such as expressed by [] and ? in the DSL.

is_primitive() bool[source]

Returns true iff this type is a primitive type, i.e. number, string, bool.

type_string() Optional[str][source]

Returns the type string as expressed in the Inmanta DSL, if this type can be expressed in the DSL. Otherwise returns None.

validate(value: object) bool[source]

Validate the given value to check if it satisfies the constraints associated with this type. Returns true iff validation succeeds, otherwise raises a inmanta.ast.RuntimeException.

with_base_type(base_type: inmanta.ast.type.Type) inmanta.ast.type.Type[source]

Returns the type formed by replacing this type’s base type with the supplied type.

class inmanta.ast.type.NullableType(element_type: inmanta.ast.type.Type)[source]

Bases: inmanta.ast.type.Type

Represents a nullable type in the Inmanta DSL. For example NullableType(Number()) represents number?.

class inmanta.ast.type.Primitive[source]

Bases: inmanta.ast.type.Type

Abstract base class representing primitive types.

cast(value: object) object[source]

Cast a value to this type. If the value can not be cast, raises a inmanta.ast.RuntimeException.

class inmanta.ast.type.Number[source]

Bases: inmanta.ast.type.Primitive

This class represents an integer or float in the configuration model. On these numbers the following operations are supported:

+, -, /, *

class inmanta.ast.type.Integer[source]

Bases: inmanta.ast.type.Number

An instance of this class represents the int type in the configuration model.

class inmanta.ast.type.Bool[source]

Bases: inmanta.ast.type.Primitive

This class represents a simple boolean that can hold true or false.

class inmanta.ast.type.String[source]

Bases: inmanta.ast.type.Primitive

This class represents a string type in the configuration model.

class inmanta.ast.type.Union(types: List[inmanta.ast.type.Type])[source]

Bases: inmanta.ast.type.Type

Instances of this class represent a union of multiple types.

class inmanta.ast.type.Literal[source]

Bases: inmanta.ast.type.Union

Instances of this class represent a literal in the configuration model. A literal is a primitive or a list or dict where all values are literals themselves.

class inmanta.ast.type.List[source]

Bases: inmanta.ast.type.Type

Instances of this class represent a list type containing any types of values.

class inmanta.ast.type.TypedList(element_type: inmanta.ast.type.Type)[source]

Bases: inmanta.ast.type.List

Instances of this class represent a list type containing any values of type element_type. For example TypedList(Number()) represents number[].

class inmanta.ast.type.LiteralList[source]

Bases: inmanta.ast.type.TypedList

Instances of this class represent a list type containing only Literal values. This is the list type in the DSL

class inmanta.ast.type.Dict[source]

Bases: inmanta.ast.type.Type

Instances of this class represent a dict type with any types of values.

class inmanta.ast.type.TypedDict(element_type: inmanta.ast.type.Type)[source]

Bases: inmanta.ast.type.Dict

Instances of this class represent a dict type containing only values of type element_type.

class inmanta.ast.type.LiteralDict[source]

Bases: inmanta.ast.type.TypedDict

Instances of this class represent a dict type containing only Literal values. This is the dict type in the DSL

class inmanta.ast.type.ConstraintType(namespace: inmanta.ast.Namespace, name: str)[source]

Bases: inmanta.ast.type.NamedType

A type that is based on a primitive type but defines additional constraints on this type. These constraints only apply on the value of the type.

inmanta.ast.type.TYPES

Maps Inmanta DSL types to their internal representation. For each key, value pair, value.type_string() is guaranteed to return key.

Note

The type classes themselves do not represent inmanta types, their instances do. For example, the type representation for the inmanta type number is Number(), not Number.

Protocol

class inmanta.protocol.common.Result(code: int = 0, result: Optional[Dict[str, Any]] = None)[source]

A result of a method call

code

The result code of the method call.

property result: Optional[Dict[str, Any]]

Data

Warning

In contrast to the rest of this section, the data API interface is subject to change. It is documented here because it is currently the only available API to interact with the data framework. A restructure of the data framework is expected at some point. Until then, this API should be considered unstable.

inmanta.data.TBaseDocument : typing.TypeVar

TypeVar with BaseDocument bound.

class inmanta.data.BaseDocument(from_postgres: bool = False, **kwargs: object)[source]

A base document in the database. Subclasses of this document determine collections names. This type is mainly used to bundle query methods and generate validate and query methods for optimized DB access. This is not a full ODM.

async classmethod get_by_id(doc_id: uuid.UUID, connection: Optional[asyncpg.connection.Connection] = None) Optional[TBaseDocument][source]

Get a specific document based on its ID

Returns

An instance of this class with its fields filled from the database.

async classmethod get_list(order_by_column: Optional[str] = None, order: str = 'ASC', limit: Optional[int] = None, offset: Optional[int] = None, no_obj: bool = False, connection: Optional[asyncpg.connection.Connection] = None, **query: object) List[TBaseDocument][source]

Get a list of documents matching the filter args

class inmanta.data.Compile(from_postgres: bool = False, **kwargs: object)[source]

Bases: inmanta.data.BaseDocument

A run of the compiler

Parameters
  • environment – The environment this resource is defined in

  • requested – Time the compile was requested

  • started – Time the compile started

  • completed – Time to compile was completed

  • do_export – should this compiler perform an export

  • force_update – should this compile definitely update

  • metadata – exporter metadata to be passed to the compiler

  • environment_variables – environment variables to be passed to the compiler

  • succes – was the compile successful

  • handled – were all registered handlers executed?

  • version – version exported by this compile

  • remote_id – id as given by the requestor, used by the requestor to distinguish between different requests

  • compile_data – json data as exported by compiling with the –export-compile-data parameter

  • substitute_compile_id – id of this compile’s substitute compile, i.e. the compile request that is similar to this one that actually got compiled.

async classmethod get_substitute_by_id(compile_id: uuid.UUID) Optional[inmanta.data.Compile][source]

Get a compile’s substitute compile if it exists, otherwise get the compile by id.

Parameters

compile_id – The id of the compile for which to get the substitute compile.

Returns

The compile object for compile c2 that is the substitute of compile c1 with the given id. If c1 does not have a substitute, returns c1 itself.

to_dto() inmanta.data.model.CompileRun[source]
class inmanta.data.ConfigurationModel(**kwargs: object)[source]

Bases: inmanta.data.BaseDocument

A specific version of the configuration model. Any transactions that update ResourceAction, Resource, Parameter and/or ConfigurationModel should acquire their locks in that order.

Parameters
  • version – The version of the configuration model, represented by a unix timestamp.

  • environment – The environment this configuration model is defined in

  • date – The date this configuration model was created

  • released – Is this model released and available for deployment?

  • deployed – Is this model deployed?

  • result – The result of the deployment. Success or error.

  • version_info – Version metadata

  • total – The total number of resources

async classmethod get_versions(environment: uuid.UUID, start: int = 0, limit: int = 100000) List[inmanta.data.ConfigurationModel][source]

Get all versions for an environment ordered descending

class inmanta.data.Environment(from_postgres: bool = False, **kwargs: object)[source]

Bases: inmanta.data.BaseDocument

A deployment environment of a project

Parameters
  • id – A unique, machine generated id

  • name – The name of the deployment environment.

  • project – The project this environment belongs to.

  • repo_url – The repository url that contains the configuration model code for this environment

  • repo_branch – The repository branch that contains the configuration model code for this environment

  • settings – Key/value settings for this environment

  • last_version – The last version number that was reserved for this environment

class inmanta.data.Report(from_postgres: bool = False, **kwargs: object)[source]

Bases: inmanta.data.BaseDocument

A report of a substep of compilation

Parameters
  • started – when the substep started

  • completed – when it ended

  • command – the command that was executed

  • name – The name of this step

  • errstream – what was reported on system err

  • outstream – what was reported on system out

class inmanta.data.Resource(from_postgres: bool = False, **kwargs: object)[source]

Bases: inmanta.data.BaseDocument

A specific version of a resource. This entity contains the desired state of a resource. Any transactions that update Resource should adhere to the locking order described in inmanta.data.ConfigurationModel.

Parameters
  • environment – The environment this resource version is defined in

  • rid – The id of the resource and its version

  • resource – The resource for which this defines the state

  • model – The configuration model (versioned) this resource state is associated with

  • attributes – The state of this version of the resource

  • attribute_hash – hash of the attributes, excluding requires, provides and version, used to determine if a resource describes the same state across versions

  • resource_id_value – The attribute value from the resource id

async classmethod get_resources_for_version(environment: uuid.UUID, version: int, agent: Optional[str] = None, no_obj: bool = False) List[inmanta.data.Resource][source]
class inmanta.data.ResourceAction(from_postgres: bool = False, **kwargs: object)[source]

Bases: inmanta.data.BaseDocument

Log related to actions performed on a specific resource version by Inmanta. Any transactions that update ResourceAction should adhere to the locking order described in inmanta.data.ConfigurationModel

Parameters
  • environment – The environment this action belongs to.

  • version – The version of the configuration model this action belongs to.

  • resource_version_ids – The resource version ids of the resources this action relates to.

  • action_id – This id distinguishes the actions from each other. Action ids have to be unique per environment.

  • action – The action performed on the resource

  • started – When did the action start

  • finished – When did the action finish

  • messages – The log messages associated with this action

  • status – The status of the resource when this action was finished

  • changes – A dict with key the resource id and value a dict of fields -> value. Value is a dict that can contain old and current keys and the associated values. An empty dict indicates that the field was changed but not data was provided by the agent.

  • change – The change result of an action

async classmethod get_logs_for_version(environment: uuid.UUID, version: int, action: Optional[str] = None, limit: int = 0) List[inmanta.data.ResourceAction][source]
class inmanta.data.model.BaseModel[source]

Bases: pydantic.main.BaseModel

Base class for all data objects in Inmanta

class Config[source]

Pydantic config.

use_enum_values = True
inmanta.data.model.ResourceIdStr

The resource id without the version

alias of str

inmanta.data.model.ResourceVersionIdStr

The resource id with the version included.

alias of str

Domain conversion

This section describes methods for converting values between the plugin domain and the internal domain. This conversion is performed automatically for plugin arguments and return values so it is only required when bypassing the usual plugin workflow by calling internal methods directly.

class inmanta.execute.proxy.DynamicProxy[source]

This class wraps an object and makes sure that a model is never modified by native code.

classmethod return_value(value: object) Union[None, str, Tuple[object, ...], int, float, inmanta.execute.proxy.DynamicProxy][source]

Converts a value from the internal domain to the plugin domain.

classmethod unwrap(item: object) object[source]

Converts a value from the plugin domain to the internal domain.

Rest API

The rest API is also available as a swagger spec

The (v2) API endpoints that offer paging, sorting and filtering follow a convention. They share the following parameters:

limit

specifies the page size, so the maximum number of items returned from the query

start and first_id

These parameters define the lower limit for the page,

end and last_id

These parameters define the upper limit for the page (only one of the (start, first_id), (end, last_id) pairs should be specified at the same time).

Note

The return value of these methods contain a links tag, with the urls of the next and prev pages, so for simply going through the pages a client only needs to follow these links.

filter

The filter parameter is used for filtering the result set.

Filters should be specified with the syntax ?filter.<filter_key>=value.

It’s also possible to provide multiple values for the same filter, in this case results are returned, if they match any of these filter values: ?filter.<filter_key>=value&filter.<filter_key>=value2

Multiple different filters narrow the results however (they are treated as an ‘AND’ operator). For example ?filter.<filter_key>=value&filter.<filter_key2>=value2 returns results that match both filters.

The documentation of each method describes the supported filters.

sort

The sort parameter describes how the result set should be sorted.

It should follow the pattern ?<attribute_to_sort_by>.<order>, for example ?value.desc (case insensitive).

The documentation of each method describes the supported attributes to sort by.

Module defining the v1 rest api

inmanta.protocol.methods.clear_environment(id: uuid.UUID)[source]

Clear all data from this environment.

Parameters

id – The uuid of the environment.

Raises
  • NotFound – The given environment doesn’t exist.

  • Forbidden – The given environment is protected.

inmanta.protocol.methods.create_environment(project_id: uuid.UUID, name: str, repository: Optional[str] = None, branch: Optional[str] = None, environment_id: Optional[uuid.UUID] = None)[source]

Create a new environment

Parameters
  • project_id – The id of the project this environment belongs to

  • name – The name of the environment

  • repository – The url (in git form) of the repository

  • branch – The name of the branch in the repository

  • environment_id – A unique environment id, if none an id is allocated by the server

inmanta.protocol.methods.create_project(name: str, project_id: Optional[uuid.UUID] = None)[source]

Create a new project

Parameters
  • name – The name of the project

  • project_id – A unique uuid, when it is not provided the server generates one

inmanta.protocol.methods.create_token(tid: uuid.UUID, client_types: list, idempotent: bool = True)[source]

Create or get a new token for the given client types. Tokens generated with this call are scoped to the current environment.

Parameters
  • tid – The environment id

  • client_types – The client types for which this token is valid (api, agent, compiler)

  • idempotent – The token should be idempotent, such tokens do not have an expire or issued at set so their value will not change.

inmanta.protocol.methods.decomission_environment(id: uuid.UUID, metadata: Optional[dict] = None)[source]

Decommision an environment. This is done by uploading an empty model to the server and let purge_on_delete handle removal.

Parameters
  • id – The uuid of the environment.

  • metadata – Optional metadata associated with the decommissioning

Raises
  • NotFound – The given environment doesn’t exist.

  • Forbidden – The given environment is protected.

inmanta.protocol.methods.delete_environment(id: uuid.UUID)[source]

Delete the given environment and all related data.

Parameters

id – The uuid of the environment.

Raises
  • NotFound – The given environment doesn’t exist.

  • Forbidden – The given environment is protected.

inmanta.protocol.methods.delete_param(tid: uuid.UUID, id: str, resource_id: Optional[str] = None)[source]

Delete a parameter on the server

Parameters
  • tid – The id of the environment

  • id – The name of the parameter

  • resource_id – The resource id of the parameter

inmanta.protocol.methods.delete_project(id: uuid.UUID)[source]

Delete the given project and all related data

inmanta.protocol.methods.delete_setting(tid: uuid.UUID, id: str)[source]

Delete a value

inmanta.protocol.methods.delete_version(tid: uuid.UUID, id: int)[source]

Delete a particular version and resources

Parameters
  • tid – The id of the environment

  • id – The id of the version to retrieve

inmanta.protocol.methods.deploy(tid: uuid.UUID, agent_trigger_method: inmanta.const.AgentTriggerMethod = AgentTriggerMethod.push_full_deploy, agents: Optional[list] = None)[source]

Notify agents to perform a deploy now.

Parameters
  • tid – The id of the environment.

  • agent_trigger_method – Indicates whether the agents should perform a full or an incremental deploy.

  • agents – Optional, names of specific agents to trigger

inmanta.protocol.methods.diff(a: str, b: str)[source]

Returns the diff of the files with the two given ids

inmanta.protocol.methods.do_dryrun(tid: uuid.UUID, id: uuid.UUID, agent: str, version: int)[source]

Do a dryrun on an agent

Parameters
  • tid – The environment id

  • id – The id of the dryrun

  • agent – The agent to do the dryrun for

  • version – The version of the model to dryrun

inmanta.protocol.methods.dryrun_list(tid: uuid.UUID, version: Optional[int] = None)[source]

Create a list of dry runs

Parameters
  • tid – The id of the environment

  • version – Only for this version

inmanta.protocol.methods.dryrun_report(tid: uuid.UUID, id: uuid.UUID)[source]

Create a dryrun report

Parameters
  • tid – The id of the environment

  • id – The version dryrun to report

inmanta.protocol.methods.dryrun_request(tid: uuid.UUID, id: int)[source]

Do a dryrun

Parameters
  • tid – The id of the environment

  • id – The version of the CM to deploy

inmanta.protocol.methods.dryrun_update(tid: uuid.UUID, id: uuid.UUID, resource: str, changes: dict)[source]

Store dryrun results at the server

Parameters
  • tid – The id of the environment

  • id – The version dryrun to report

  • resource – The id of the resource

  • changes – The required changes

inmanta.protocol.methods.get_agent_process(id: uuid.UUID)[source]

Return a detailed report for a node

Parameters

id – The session id of the agent

Returns

The requested node

inmanta.protocol.methods.get_code(tid: uuid.UUID, id: int, resource: str)[source]

Get the code for a given version of the configuration model

Parameters
  • tid – The environment the code belongs to

  • id – The id (version) of the configuration model

inmanta.protocol.methods.get_compile_queue(tid: uuid.UUID) List[inmanta.data.model.CompileRun][source]

Get the current compiler queue on the server

inmanta.protocol.methods.get_environment(id: uuid.UUID, versions: Optional[int] = None, resources: Optional[int] = None)[source]

Get an environment and all versions associated

Parameters
  • id – The id of the environment to return

  • versions – Include this many available version for this environment.

  • resources – Include this many available resources for this environment.

inmanta.protocol.methods.get_file(id: str)[source]

Retrieve a file

Parameters

id – The id of the file to retrieve

inmanta.protocol.methods.get_param(tid: uuid.UUID, id: str, resource_id: Optional[str] = None)[source]

Get a parameter from the server.

Parameters
  • tid – The id of the environment

  • id – The name of the parameter

  • resource_id – Optionally, scope the parameter to resource (fact), if the resource id should not contain a version, the latest version is used

Returns

Returns the following status codes: 200: The parameter content is returned 404: The parameter is not found and unable to find it because its resource is not known to the server 410: The parameter has expired 503: The parameter is not found but its value is requested from an agent

inmanta.protocol.methods.get_parameter(tid: uuid.UUID, agent: str, resource: dict)[source]

Get all parameters/facts known by the agents for the given resource

Parameters
  • tid – The environment

  • agent – The agent to get the parameters from

  • resource – The resource to query the parameters from

inmanta.protocol.methods.get_project(id: uuid.UUID)[source]

Get a project and a list of the ids of all environments

inmanta.protocol.methods.get_report(id: uuid.UUID)[source]

Get a compile report from the server

Parameters

id – The id of the compile and its reports to fetch.

inmanta.protocol.methods.get_reports(tid: uuid.UUID, start: Optional[str] = None, end: Optional[str] = None, limit: Optional[int] = None)[source]

Return compile reports newer then start

Parameters
  • tid – The id of the environment to get a report from

  • start – Reports after start

  • end – Reports before end

  • limit – Maximum number of results, up to a maximum of 1000

inmanta.protocol.methods.get_resource(tid: uuid.UUID, id: str, logs: Optional[bool] = None, status: Optional[bool] = None, log_action: Optional[inmanta.const.ResourceAction] = None, log_limit: int = 0)[source]

Return a resource with the given id.

Parameters
  • tid – The id of the environment this resource belongs to

  • id – Get the resource with the given id

  • logs – Include the logs in the response

  • status – Only return the status of the resource

  • log_action – The log action to include, leave empty/none for all actions. Valid actions are one of the action strings in const.ResourceAction

  • log_limit – Limit the number of logs included in the response, up to a maximum of 1000. To retrieve more entries, use /api/v2/resource_actions (get_resource_actions())

inmanta.protocol.methods.get_resources_for_agent(tid: uuid.UUID, agent: str, sid: Optional[uuid.UUID] = None, version: Optional[int] = None, incremental_deploy: bool = False)[source]

Return the most recent state for the resources associated with agent, or the version requested

Parameters
  • tid – The id of the environment this resource belongs to

  • agent – The agent

  • sid – Session id of the agent (transparently added by agent client)

  • version – The version to retrieve. If none, the latest available version is returned. With a specific version that version is returned, even if it has not been released yet.

  • incremental_deploy – Indicates whether the server should only return the resources that changed since the previous deployment.

inmanta.protocol.methods.get_server_status() inmanta.data.model.StatusResponse[source]

Get the status of the server

inmanta.protocol.methods.get_setting(tid: uuid.UUID, id: str)[source]

Get a value

inmanta.protocol.methods.get_state(tid: uuid.UUID, sid: uuid.UUID, agent: str)[source]

Get the state for this agent.

returns a map {

enabled: bool

}

inmanta.protocol.methods.get_status()[source]

A call from the server to the agent to report its status to the server

Returns

A map with report items

inmanta.protocol.methods.get_version(tid: uuid.UUID, id: int, include_logs: Optional[bool] = None, log_filter: Optional[str] = None, limit: Optional[int] = None)[source]

Get a particular version and a list of all resources in this version

Parameters
  • tid – The id of the environment

  • id – The id of the version to retrieve

  • include_logs – If true, a log of all operations on all resources is included

  • log_filter – Filter log to only include actions of the specified type

  • limit – The maximal number of actions to return per resource (starting from the latest), up to a maximum of 1000. To retrieve more entries, use /api/v2/resource_actions (get_resource_actions())

inmanta.protocol.methods.heartbeat(sid: uuid.UUID, tid: uuid.UUID, endpoint_names: list, nodename: str, no_hang: bool = False)[source]

Send a heartbeat to the server

Paran sid

The session ID used by this agent at this moment

Parameters
  • tid – The environment this node and its agents belongs to

  • endpoint_names – The names of the endpoints on this node

  • nodename – The name of the node from which the heart beat comes

  • no_hang – don’t use this call for long polling, but for connectivity check

also registered as API method, because it is called with an invalid SID the first time

inmanta.protocol.methods.heartbeat_reply(sid: uuid.UUID, reply_id: uuid.UUID, data: dict)[source]

Send a reply back to the server

Parameters
  • sid – The session ID used by this agent at this moment

  • reply_id – The id data is a reply to

  • data – The data as a response to the reply

async inmanta.protocol.methods.ignore_env(obj: Any, metadata: dict) Any[source]

This mapper only adds an env all for authz

inmanta.protocol.methods.is_compiling(id: uuid.UUID)[source]

Is a compiler running for the given environment

Parameters

id – The environment id

inmanta.protocol.methods.list_agent_processes(environment: Optional[uuid.UUID] = None, expired: bool = True, start: Optional[uuid.UUID] = None, end: Optional[uuid.UUID] = None, limit: Optional[int] = None)[source]

Return a list of all nodes and the agents for these nodes

Parameters
  • environment – An optional environment. If set, only the agents that belong to this environment are returned

  • expired – Optional, also show expired processes, otherwise only living processes are shown.

  • start – Agent processes after start (sorted by sid in ASC)

  • end – Agent processes before end (sorted by sid in ASC)

  • limit – Maximum number of results, up to a maximum of 1000

Raises
  • BadRequest – limit parameter can not exceed 1000

  • NotFound – The given environment id does not exist!

Returns

A list of nodes

inmanta.protocol.methods.list_agents(tid: uuid.UUID, start: Optional[str] = None, end: Optional[str] = None, limit: Optional[int] = None)[source]

List all agent for an environment

Parameters
  • tid – The environment the agents are defined in

  • start – Agent after start (sorted by name in ASC)

  • end – Agent before end (sorted by name in ASC)

  • limit – Maximum number of results, up to a maximum of 1000

Raises
  • BadRequest – limit parameter can not exceed 1000

  • NotFound – The given environment id does not exist!

inmanta.protocol.methods.list_environments()[source]

Create a list of environments

inmanta.protocol.methods.list_params(tid: uuid.UUID, query: dict = {})[source]

List/query parameters in this environment

Parameters
  • tid – The id of the environment

  • query – A query to match against metadata

inmanta.protocol.methods.list_projects()[source]

Create a list of projects

inmanta.protocol.methods.list_settings(tid: uuid.UUID)[source]

List the settings in the current environment

inmanta.protocol.methods.list_versions(tid: uuid.UUID, start: Optional[int] = None, limit: Optional[int] = None)[source]

Returns a list of all available versions

Parameters
  • tid – The id of the environment

  • start – Optional, parameter to control the amount of results that are returned. 0 is the latest version.

  • limit – Optional, parameter to control the amount of results returned, up to a maximum of 1000.

inmanta.protocol.methods.modify_environment(id: uuid.UUID, name: str, repository: Optional[str] = None, branch: Optional[str] = None)[source]

Modify the given environment

Parameters
  • id – The id of the environment

  • name – The name of the environment

  • repository – The url (in git form) of the repository

  • branch – The name of the branch in the repository

inmanta.protocol.methods.modify_project(id: uuid.UUID, name: str)[source]

Modify the given project

inmanta.protocol.methods.notify_change(id: uuid.UUID, update: bool = True, metadata: dict = {})[source]

Notify the server that the repository of the environment with the given id, has changed.

Parameters
  • id – The id of the environment

  • update – Update the model code and modules. Default value is true

  • metadata – The metadata that indicates the source of the compilation trigger.

inmanta.protocol.methods.notify_change_get(id: uuid.UUID, update: bool = True)[source]

Simplified GET version of the POST method

inmanta.protocol.methods.put_version(tid: uuid.UUID, version: int, resources: list, resource_state: dict = {}, unknowns: Optional[list] = None, version_info: Optional[dict] = None, compiler_version: Optional[str] = None)[source]

Store a new version of the configuration model

The version number must be obtained through the reserve_version call

Parameters
  • tid – The id of the environment

  • version – The version of the configuration model

  • resources – A list of all resources in the configuration model (deployable)

  • resource_state – A dictionary with the initial const.ResourceState per resource id

  • unknowns – A list of unknown parameters that caused the model to be incomplete

  • version_info – Module version information

  • compiler_version – version of the compiler, if not provided, this call will return an error

inmanta.protocol.methods.release_version(tid: uuid.UUID, id: int, push: bool = False, agent_trigger_method: Optional[inmanta.const.AgentTriggerMethod] = None)[source]

Release version of the configuration model for deployment.

Parameters
  • tid – The id of the environment

  • id – The version of the CM to deploy

  • push – Notify all agents to deploy the version

  • agent_trigger_method – Indicates whether the agents should perform a full or an incremental deploy when push is true.

inmanta.protocol.methods.resource_action_update(tid: uuid.UUID, resource_ids: list, action_id: uuid.UUID, action: inmanta.const.ResourceAction, started: Optional[datetime.datetime] = None, finished: Optional[datetime.datetime] = None, status: Optional[inmanta.const.ResourceState] = None, messages: list = [], changes: dict = {}, change: Optional[inmanta.const.Change] = None, send_events: bool = False)[source]

Send a resource update to the server

Parameters
  • tid – The id of the environment this resource belongs to

  • resource_ids – The resource with the given resource_version_id id from the agent

  • action_id – A unique id to indicate the resource action that has be updated

  • action – The action performed

  • started – The timestamp when this action was started. When this action (action_id) has not been saved yet, started has to be defined.

  • finished – The timestamp when this action was finished. Afterwards, no changes with the same action_id can be stored. The status field also has to be set.

  • status – The current status of the resource (if known)

  • messages – A list of log entries to add to this entry.

:param change:s A dict of changes to this resource. The key of this dict indicates the attributes/fields that

have been changed. The value contains the new value and/or the original value.

Parameters
  • change – The result of the changes

  • send_events – [DEPRECATED] The value of this field is not used anymore.

inmanta.protocol.methods.resource_event(tid: uuid.UUID, id: str, resource: str, send_events: bool, state: inmanta.const.ResourceState, change: inmanta.const.Change, changes={})[source]

Tell an agent a resource it waits for has been updated

Parameters
  • tid – The environment this agent is defined in

  • id – The name of the agent

  • resource – The resource ID of the resource being updated

  • send_events – [DEPRECATED] The value of this field is not used anymore.

  • state – State the resource acquired (deployed, skipped, canceled)

  • change – The change that was made to the resource

  • changes – The changes made to the resource

inmanta.protocol.methods.set_param(tid: uuid.UUID, id: str, source: inmanta.const.ParameterSource, value: str, resource_id: Optional[str] = None, metadata: dict = {}, recompile: bool = False)[source]

Set a parameter on the server. If the parameter is an tracked unknown, it will trigger a recompile on the server. Otherwise, if the value is changed and recompile is true, a recompile is also triggered.

Parameters
  • tid – The id of the environment

  • id – The name of the parameter

  • resource_id – Optionally, scope the parameter to resource (fact)

  • source – The source of the parameter.

  • value – The value of the parameter

  • metadata – metadata about the parameter

  • recompile – Whether to trigger a recompile

inmanta.protocol.methods.set_parameters(tid: uuid.UUID, parameters: list)[source]

Set a parameter on the server

Parameters
  • tid – The id of the environment

  • parameters – A list of dicts with the following keys: - id The name of the parameter - source The source of the parameter. Valid values are defined in the ParameterSource enum (see: inmanta/const.py) - value The value of the parameter - resource_id Optionally, scope the parameter to resource (fact) - metadata metadata about the parameter

inmanta.protocol.methods.set_setting(tid: uuid.UUID, id: str, value: Union[uuid.UUID, inmanta.types.StrictNonIntBool, int, float, datetime.datetime, str, Dict[str, Any]])[source]

Set a value

inmanta.protocol.methods.set_state(agent: str, enabled: bool)[source]

Set the state of the agent.

inmanta.protocol.methods.stat_file(id: str)[source]

Does the file exist

Parameters

id – The id of the file to check

inmanta.protocol.methods.stat_files(files: list)[source]

Check which files exist in the given list

Parameters

files – A list of file id to check

Returns

A list of files that do not exist.

inmanta.protocol.methods.trigger(tid: uuid.UUID, id: str, incremental_deploy: bool)[source]

Request an agent to reload resources

Parameters
  • tid – The environment this agent is defined in

  • id – The name of the agent

  • incremental_deploy – Indicates whether the agent should perform an incremental deploy or a full deploy

inmanta.protocol.methods.trigger_agent(tid: uuid.UUID, id: str)[source]

Request the server to reload an agent

Parameters
  • tid – The environment this agent is defined in

  • id – The name of the agent

Returns

The requested node

inmanta.protocol.methods.upload_code(tid: uuid.UUID, id: int, resource: str, sources: dict)[source]

Upload the supporting code to the server

Parameters
  • tid – The environment the code belongs to

  • id – The id (version) of the configuration model

  • sources – The source files that contain handlers and inmanta plug-ins {code_hash:(file_name, provider.__module__, source_code, [req])}

inmanta.protocol.methods.upload_code_batched(tid: uuid.UUID, id: int, resources: dict)[source]

Upload the supporting code to the server

Parameters
  • tid – The environment the code belongs to

  • id – The id (version) of the configuration model

  • resource – a dict mapping resources to dicts mapping file names to file hashes

inmanta.protocol.methods.upload_file(id: str, content: str)[source]

Upload a new file

Parameters
  • id – The id of the file

  • content – The base64 encoded content of the file

Module defining the v2 rest api

inmanta.protocol.methods_v2.agent_action(tid: uuid.UUID, name: str, action: inmanta.const.AgentAction) None[source]

Execute an action on an agent

Parameters
  • tid – The environment this agent is defined in.

  • name – The name of the agent.

  • action – The type of action that should be executed on an agent. * pause: A paused agent cannot execute any deploy operations. * unpause: A unpaused agent will be able to execute deploy operations.

Raises

Forbidden – The given environment has been halted.

inmanta.protocol.methods_v2.all_agents_action(tid: uuid.UUID, action: inmanta.const.AgentAction) None[source]

Execute an action on all agents in the given environment.

Parameters
  • tid – The environment of the agents.

  • action – The type of action that should be executed on the agents * pause: A paused agent cannot execute any deploy operations. * unpause: A unpaused agent will be able to execute deploy operations.

Raises

Forbidden – The given environment has been halted.

inmanta.protocol.methods_v2.compile_details(tid: uuid.UUID, id: uuid.UUID) inmanta.data.model.CompileDetails[source]
Returns

The details of a compile

Raises

NotFound – This exception is raised when the referenced environment or compile is not found

inmanta.protocol.methods_v2.environment_clear(id: uuid.UUID) None[source]

Clear all data from this environment.

Parameters

id – The uuid of the environment.

Raises
  • NotFound – The given environment doesn’t exist.

  • Forbidden – The given environment is protected.

inmanta.protocol.methods_v2.environment_create(project_id: uuid.UUID, name: str, repository: Optional[str] = None, branch: Optional[str] = None, environment_id: Optional[uuid.UUID] = None) inmanta.data.model.Environment[source]

Create a new environment

Parameters
  • project_id – The id of the project this environment belongs to

  • name – The name of the environment

  • repository – The url (in git form) of the repository

  • branch – The name of the branch in the repository

  • environment_id – A unique environment id, if none an id is allocated by the server

inmanta.protocol.methods_v2.environment_create_token(tid: uuid.UUID, client_types: List[str], idempotent: bool = True) str[source]

Create or get a new token for the given client types. Tokens generated with this call are scoped to the current environment.

Parameters
  • tid – The environment id

  • client_types – The client types for which this token is valid (api, agent, compiler)

  • idempotent – The token should be idempotent, such tokens do not have an expire or issued at set so their value will not change.

inmanta.protocol.methods_v2.environment_decommission(id: uuid.UUID, metadata: Optional[inmanta.data.model.ModelMetadata] = None) int[source]

Decommission an environment. This is done by uploading an empty model to the server and let purge_on_delete handle removal.

Parameters
  • id – The uuid of the environment.

  • metadata – Optional metadata associated with the decommissioning

Raises
  • NotFound – The given environment doesn’t exist.

  • Forbidden – The given environment is protected.

inmanta.protocol.methods_v2.environment_delete(id: uuid.UUID) None[source]

Delete the given environment and all related data.

Parameters

id – The uuid of the environment.

Raises
  • NotFound – The given environment doesn’t exist.

  • Forbidden – The given environment is protected.

inmanta.protocol.methods_v2.environment_get(id: uuid.UUID) inmanta.data.model.Environment[source]

Get an environment and all versions associated

Parameters

id – The id of the environment to return

inmanta.protocol.methods_v2.environment_list() List[inmanta.data.model.Environment][source]

Create a list of environments

inmanta.protocol.methods_v2.environment_modify(id: uuid.UUID, name: str, repository: Optional[str] = None, branch: Optional[str] = None, project_id: Optional[uuid.UUID] = None) inmanta.data.model.Environment[source]

Modify the given environment

Parameters
  • id – The id of the environment

  • name – The name of the environment

  • repository – The url (in git form) of the repository

  • branch – The name of the branch in the repository

  • project_id – The id of the project the environment belongs to

Raises
  • BadRequest – When the parameters supplied are not valid.

  • NotFound – The given environment doesn’t exist.

inmanta.protocol.methods_v2.environment_setting_delete(tid: uuid.UUID, id: str) inmanta.protocol.common.ReturnValue[None][source]

Delete a value

inmanta.protocol.methods_v2.environment_setting_get(tid: uuid.UUID, id: str) inmanta.data.model.EnvironmentSettingsReponse[source]

Get a value

inmanta.protocol.methods_v2.environment_settings_list(tid: uuid.UUID) inmanta.data.model.EnvironmentSettingsReponse[source]

List the settings in the current environment

inmanta.protocol.methods_v2.environment_settings_set(tid: uuid.UUID, id: str, value: Union[inmanta.types.StrictNonIntBool, int, str, Dict[str, Union[str, int, inmanta.types.StrictNonIntBool]]]) inmanta.protocol.common.ReturnValue[None][source]

Set a value

inmanta.protocol.methods_v2.get_agent_process_details(tid: uuid.UUID, id: uuid.UUID, report: bool = False) inmanta.data.model.AgentProcess[source]

Get the details of an agent process

Parameters
  • tid – Id of the environment

  • id – The id of the specific agent process

  • report – Whether to include a report from the agent or not

Returns

The details of an agent process

Raises

NotFound – This exception is raised when the referenced environment or agent process is not found

inmanta.protocol.methods_v2.get_agents(tid: uuid.UUID, limit: Optional[int] = None, start: Optional[Union[datetime.datetime, bool, str]] = None, end: Optional[Union[datetime.datetime, bool, str]] = None, first_id: Optional[str] = None, last_id: Optional[str] = None, filter: Optional[Dict[str, List[str]]] = None, sort: str = 'name.asc') List[inmanta.data.model.Agent][source]

Get all of the agents in the given environment :param tid: The id of the environment the agents should belong to :param limit: Limit the number of agents that are returned :param start: The lower limit for the order by column (exclusive). :param first_id: The name to use as a continuation token for paging, in combination with the ‘start’ value,

because the order by column might contain non-unique values

Parameters
  • last_id

    The name to use as a continuation token for paging, in combination with the ‘end’ value, because the order by column might contain non-unique values

    Only one of ‘start’ and ‘end’ should be specified at the same time.

  • end – The upper limit for the order by column (exclusive). Only one of ‘start’ and ‘end’ should be specified at the same time.

  • filter – Filter the list of returned agents. Filtering by ‘name’, ‘process_name’ and ‘status’ is supported.

  • sort – Return the results sorted according to the parameter value. Sorting by ‘name’, ‘process_name’, ‘status’, ‘paused’ and ‘last_failover’ is supported. The following orders are supported: ‘asc’, ‘desc’

Returns

A list of all matching agents

Raises
  • NotFound – This exception is raised when the referenced environment is not found

  • BadRequest – When the parameters used for filtering, sorting or paging are not valid

inmanta.protocol.methods_v2.get_api_docs(format: Optional[inmanta.const.ApiDocsFormat] = ApiDocsFormat.swagger) inmanta.protocol.common.ReturnValue[Union[inmanta.protocol.openapi.model.OpenAPI, str]][source]

Get the OpenAPI definition of the API :param format: Use ‘openapi’ to get the schema in json format, leave empty or use ‘swagger’ to get the Swagger-UI view

inmanta.protocol.methods_v2.get_compile_data(id: uuid.UUID) Optional[inmanta.data.model.CompileData][source]

Get the compile data for the given compile request.

Parameters

id – The id of the compile.

inmanta.protocol.methods_v2.get_compile_reports(tid: uuid.UUID, limit: Optional[int] = None, first_id: Optional[uuid.UUID] = None, last_id: Optional[uuid.UUID] = None, start: Optional[datetime.datetime] = None, end: Optional[datetime.datetime] = None, filter: Optional[Dict[str, List[str]]] = None, sort: str = 'requested.desc') List[inmanta.data.model.CompileReport][source]

Get the compile reports from an environment :param tid: The id of the environment :param limit: Limit the number of instances that are returned :param first_id: The id to use as a continuation token for paging, in combination with the ‘start’ value,

because the order by column might contain non-unique values

Parameters
  • last_id – The id to use as a continuation token for paging, in combination with the ‘end’ value, because the order by column might contain non-unique values

  • start – The lower limit for the order by column (exclusive). Only one of ‘start’ and ‘end’ should be specified at the same time.

  • end – The upper limit for the order by column (exclusive). Only one of ‘start’ and ‘end’ should be specified at the same time.

  • filter

    Filter the list of returned compile reports. Filters should be specified with the syntax ?filter.<filter_key>=value, for example ?filter.success=True It’s also possible to provide multiple values for the same filter, in this case resources are returned, if they match any of these filter values. For example: ?filter.requested=ge:2021-08-18T09:21:30.568353&filter.requested=lt:2021-08-18T10:21:30.568353 returns compile reports that were requested between the specified dates. Multiple different filters narrow the results however (they are treated as an ‘AND’ operator). For example ?filter.success=True&filter.completed=True returns compile reports that are completed and successful. The following options are available: success: whether the compile was successful or not started: whether the compile has been started or not completed: whether the compile has been completed or not requested: return the logs matching the timestamp constraints. Valid constraints are of the form

    ”<lt|le|gt|ge>:<x>”. The expected format is YYYY-MM-DDTHH:mm:ss.ssssss, so an ISO-8601 datetime string, in UTC timezone. Specifying microseconds is optional. For example: ?filter.requested=ge:2021-08-18T09:21:30.568353&filter.requested=lt:2021-08-18T10:21:30. Multiple constraints can be specified, in which case only compile reports that match all constraints will be returned.

  • sort – Return the results sorted according to the parameter value. It should follow the pattern ?sort=<attribute_to_sort_by>.<order>, for example ?sort=requested.desc (case insensitive). Only sorting by the requested timestamp is supported. The following orders are supported: ‘asc’, ‘desc’

Returns

A list of all matching compile reports

Raises
  • NotFound – This exception is raised when the referenced environment is not found

  • BadRequest – When the parameters used for filtering, sorting or paging are not valid

inmanta.protocol.methods_v2.get_fact(tid: uuid.UUID, rid: ResourceIdStr, id: uuid.UUID) inmanta.data.model.Parameter[source]

Get one specific fact :param tid: The id of the environment :param rid: The id of the resource :param id: The id of the fact :return: A specific fact corresponding to the id :raise NotFound: This status code is returned when the referenced environment or fact is not found

inmanta.protocol.methods_v2.get_facts(tid: uuid.UUID, rid: ResourceIdStr) List[inmanta.data.model.Parameter][source]

Get the facts related to a specific resource :param tid: The id of the environment :param rid: Id of the resource :return: The facts related to this resource :raise NotFound: This status code is returned when the referenced environment is not found

inmanta.protocol.methods_v2.get_resource_actions(tid: uuid.UUID, resource_type: Optional[str] = None, agent: Optional[str] = None, attribute: Optional[str] = None, attribute_value: Optional[str] = None, log_severity: Optional[str] = None, limit: Optional[int] = 0, action_id: Optional[uuid.UUID] = None, first_timestamp: Optional[datetime.datetime] = None, last_timestamp: Optional[datetime.datetime] = None) inmanta.protocol.common.ReturnValue[List[inmanta.data.model.ResourceAction]][source]

Return resource actions matching the search criteria.

Parameters
  • tid – The id of the environment this resource belongs to

  • resource_type – The resource entity type that should be queried

  • agent – Agent name that is used to filter the results

  • attribute – Attribute name used for filtering

  • attribute_value – Attribute value used for filtering. Attribute and attribute value should be supplied together.

  • log_severity – Only include ResourceActions which have a log message with this severity.

  • limit – Limit the number of resource actions included in the response, up to 1000

  • action_id – Start the query from this action_id. To be used in combination with either the first or last timestamp.

  • first_timestamp – Limit the results to resource actions that started later than the value of this parameter (exclusive)

  • last_timestamp – Limit the results to resource actions that started earlier than the value of this parameter (exclusive). Only the first_timestamp or last_timestamp parameter should be supplied

Returns

the list of matching Resource Actions in a descending order according to the ‘started’ timestamp. If a limit was specified, also return the links to the next and previous pages. The “next” page always refers to the actions that started earlier, while the “prev” page refers to actions that started later.

Raises

BadRequest – When the supplied parameters are not valid.

inmanta.protocol.methods_v2.get_resource_events(tid: uuid.UUID, rvid: ResourceVersionIdStr) Dict[ResourceIdStr, List[inmanta.data.model.ResourceAction]][source]

Return relevant events for a resource, i.e. all deploy actions for each of its dependencies since this resources’ last deploy or all deploy actions if this resources hasn’t been deployed before. The resource actions are sorted in descending order according to their started timestamp.

Parameters
  • tid – The id of the environment this resource belongs to

  • rvid – The id of the resource to get events for.

Raises

BadRequest – When this endpoint in called while the resource with the given resource version is not in the deploying state.

inmanta.protocol.methods_v2.halt_environment(tid: uuid.UUID) None[source]

Halt all orchestrator operations for an environment. The environment will enter a state where all agents are paused and can not be unpaused. Incoming compile requests will still be queued but compilation will halt. Normal operation can be restored using the resume_environment endpoint.

Parameters

tid – The environment id

Raises

NotFound – The given environment doesn’t exist.

inmanta.protocol.methods_v2.project_create(name: str, project_id: Optional[uuid.UUID] = None) inmanta.data.model.Project[source]

Create a new project

Parameters
  • name – The name of the project

  • project_id – A unique uuid, when it is not provided the server generates one

inmanta.protocol.methods_v2.project_delete(id: uuid.UUID) None[source]

Delete the given project and all related data

inmanta.protocol.methods_v2.project_get(id: uuid.UUID) inmanta.data.model.Project[source]

Get a project and a list of the ids of all environments

inmanta.protocol.methods_v2.project_list() List[inmanta.data.model.Project][source]

Create a list of projects

inmanta.protocol.methods_v2.project_modify(id: uuid.UUID, name: str) inmanta.data.model.Project[source]

Modify the given project

inmanta.protocol.methods_v2.reserve_version(tid: uuid.UUID) int[source]

Reserve a version number in this environment.

inmanta.protocol.methods_v2.resource_deploy_done(tid: uuid.UUID, rvid: ResourceVersionIdStr, action_id: uuid.UUID, status: inmanta.const.ResourceState, messages: List[inmanta.data.model.LogLine] = [], changes: Dict[str, inmanta.data.model.AttributeStateChange] = {}, change: Optional[inmanta.const.Change] = None) None[source]

Report to the server that an agent has finished the deployment of a certain resource.

Parameters
  • tid – The id of the environment the resource belongs to

  • rvid – The resource version id of the resource for which the deployment is finished.

  • action_id – A unique ID associated with this resource deployment action. This should be the same ID that was passed to the /resource/<resource_id>/deploy/start API call.

  • status – The current status of the resource (if known)

  • messages – A list of log entries produced by the deployment action.

  • changes – A dict of changes to this resource. The key of this dict indicates the attributes/fields that have been changed. The value contains the new value and/or the original value.

  • change – The type of change that was done the given resource.

inmanta.protocol.methods_v2.resource_deploy_start(tid: uuid.UUID, rvid: ResourceVersionIdStr, action_id: uuid.UUID) Dict[ResourceVersionIdStr, inmanta.const.ResourceState][source]

Report to the server that the agent will start the deployment of the given resource.

Parameters
  • tid – The id of the environment the resource belongs to

  • rvid – The resource version id of the resource for which the deployment will start

  • action_id – A unique id used to track the action of this deployment

Returns

A dict mapping the resource version id of each dependency of resource_id to the last deployment status of that resource.

inmanta.protocol.methods_v2.resource_details(tid: uuid.UUID, rid: ResourceIdStr) inmanta.data.model.ResourceDetails[source]
Returns

The details of the latest released version of a resource

Raises

NotFound – This exception is raised when the referenced environment or resource is not found

inmanta.protocol.methods_v2.resource_did_dependency_change(tid: uuid.UUID, rvid: ResourceVersionIdStr) bool[source]

Returns True iff this resources’ events indicate a change in its dependencies since the resource’s last deployment.

Parameters
  • tid – The id of the environment this resource belongs to

  • rvid – The id of the resource.

Raises

BadRequest – When this endpoint in called while the resource with the given resource version is not in the deploying state.

inmanta.protocol.methods_v2.resource_history(tid: uuid.UUID, rid: ResourceIdStr, limit: Optional[int] = None, first_id: Optional[str] = None, last_id: Optional[str] = None, start: Optional[datetime.datetime] = None, end: Optional[datetime.datetime] = None, sort: str = 'date.desc') List[inmanta.data.model.ResourceHistory][source]
Parameters
  • tid – The id of the environment this resource belongs to

  • rid – The id of the resource

  • limit – Limit the number of instances that are returned

  • first_id – The attribute_hash to use as a continuation token for paging, in combination with the ‘start’ value, because the order by column might contain non-unique values

  • last_id – The attribute_hash to use as a continuation token for paging, in combination with the ‘end’ value, because the order by column might contain non-unique values

  • start – The lower limit for the order by column (exclusive). Only one of ‘start’ and ‘end’ should be specified at the same time.

  • end – The upper limit for the order by column (exclusive). Only one of ‘start’ and ‘end’ should be specified at the same time.

  • sort – Return the results sorted according to the parameter value. It should follow the pattern <attribute_to_sort_by>.<order>, for example date.desc (case insensitive). Sorting by date is supported. The following orders are supported: ‘asc’, ‘desc’

Returns

The history of a resource, according to its attributes

Raises
  • NotFound – This exception is raised when the referenced environment is not found

  • BadRequest – When the parameters used for sorting or paging are not valid

inmanta.protocol.methods_v2.resource_list(tid: uuid.UUID, limit: Optional[int] = None, first_id: Optional[ResourceVersionIdStr] = None, last_id: Optional[ResourceVersionIdStr] = None, start: Optional[str] = None, end: Optional[str] = None, filter: Optional[Dict[str, List[str]]] = None, sort: str = 'resource_type.desc', deploy_summary: bool = False) List[inmanta.data.model.LatestReleasedResource][source]
Parameters
  • tid – The id of the environment this resource belongs to

  • limit – Limit the number of instances that are returned

  • first_id – The resource_version_id to use as a continuation token for paging, in combination with the ‘start’ value, because the order by column might contain non-unique values

  • last_id – The resource_version_id to use as a continuation token for paging, in combination with the ‘end’ value, because the order by column might contain non-unique values

  • start – The lower limit for the order by column (exclusive). Only one of ‘start’ and ‘end’ should be specified at the same time.

  • end – The upper limit for the order by column (exclusive). Only one of ‘start’ and ‘end’ should be specified at the same time.

  • filter – Filter the list of returned resources. Filters should be specified with the syntax ?filter.<filter_key>=value, for example ?filter.status=deployed It’s also possible to provide multiple values for the same filter, in this case resources are returned, if they match any of these filter values. For example: ?filter.status=deployed&filter.status=available returns instances with either of the statuses deployed or available. Multiple different filters narrow the results however (they are treated as an ‘AND’ operator). For example filter.status=deployed&filter.agent=internal returns resources with ‘deployed’ status, where the ‘agent’ is set to ‘internal_agent’. The following options are available: agent: filter by the agent of the resource resource_type: filter by the type of the resource resource_id_value: filter by the attribute values of the resource status: filter by the current status of the resource The values for the ‘agent’, ‘resource_type’ and ‘value’ filters are matched partially.

  • sort – Return the results sorted according to the parameter value. It should follow the pattern <attribute_to_sort_by>.<order>, for example resource_type.desc (case insensitive). The following sorting attributes are supported: ‘resource_type’, ‘agent’, ‘resource_id_value’, ‘status’. The following orders are supported: ‘asc’, ‘desc’

  • deploy_summary – If set to true, returns a summary of the deployment status of the resources in the environment in the metadata, describing how many resources are in each state as well as the total number of resources. The summary does not take into account the current filters or paging parameters. Orphaned resources are not included in the summary

Returns

A list of all matching released resources

Raises
  • NotFound – This exception is raised when the referenced environment is not found

  • BadRequest – When the parameters used for filtering, sorting or paging are not valid

inmanta.protocol.methods_v2.resource_logs(tid: uuid.UUID, rid: ResourceIdStr, limit: Optional[int] = None, start: Optional[datetime.datetime] = None, end: Optional[datetime.datetime] = None, filter: Optional[Dict[str, List[str]]] = None, sort: str = 'timestamp.desc') List[inmanta.data.model.ResourceLog][source]

Get the logs of a specific resource :param tid: The id of the environment this resource belongs to :param rid: The id of the resource :param limit: Limit the number of instances that are returned :param start: The lower limit for the order by column (exclusive).

Only one of ‘start’ and ‘end’ should be specified at the same time.

Parameters
  • end – The upper limit for the order by column (exclusive). Only one of ‘start’ and ‘end’ should be specified at the same time.

  • filter

    Filter the list of returned logs. Filters should be specified with the syntax ?filter.<filter_key>=value, for example ?filter.minimal_log_level=INFO It’s also possible to provide multiple values for the same filter, in this case resources are returned, if they match any of these filter values. For example: ?filter.action=pull&filter.action=deploy returns logs with either of the actions pull or deploy. Multiple different filters narrow the results however (they are treated as an ‘AND’ operator). For example filter.minimal_log_level=INFO&filter.action=deploy returns logs with ‘deploy’ action, where the ‘log_level’ is at least ‘INFO’. The following options are available: action: filter by the action of the log timestamp: return the logs matching the timestamp constraints. Valid constraints are of the form

    ”<lt|le|gt|ge>:<x>”. The expected format is YYYY-MM-DDTHH:mm:ss.ssssss, so an ISO-8601 datetime string, in UTC timezone. For example: ?filter.timestamp=ge:2021-08-18T09:21:30.568353&filter.timestamp=lt:2021-08-18T10:21:30.568353. Multiple constraints can be specified, in which case only log messages that match all constraints will be returned.

    message: filter by the content of the log messages. Partial matches are allowed. (case-insensitive) minimal_log_level: filter by the log level of the log messages. The filter specifies the minimal level, so messages with either this level, or a higher severity level are going to be included in the result. For example, for filter.minimal_log_level=INFO, the log messages with level INFO, WARNING, ERROR, CRITICAL all match the query.

  • sort – Return the results sorted according to the parameter value. It should follow the pattern <attribute_to_sort_by>.<order>, for example timestamp.desc (case insensitive). The only sorting by timestamp is supported. The following orders are supported: ‘asc’, ‘desc’

Returns

A list of all matching resource logs

Raises
  • NotFound – This exception is raised when the referenced environment is not found

  • BadRequest – When the parameters used for filtering, sorting or paging are not valid

inmanta.protocol.methods_v2.resume_environment(tid: uuid.UUID) None[source]

Resume all orchestrator operations for an environment. Resumes normal environment operation and unpauses all agents that were active when the environment was halted.

Parameters

tid – The environment id

Raises

NotFound – The given environment doesn’t exist.

inmanta.protocol.methods_v2.update_agent_map(agent_map: Dict[str, str]) None[source]

Notify an agent about the fact that the autostart_agent_map has been updated.

Parameters

agent_map – The content of the new autostart_agent_map