Inmanta API reference

This page describes parts of the compiler that provide a stable API that could be used from modules.

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.

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=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)[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) → None[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.

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.execute.util.Unknown(source)[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: bool = True, 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, enum.Enum, 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, **kwargs) → 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, **kwargs) → 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, **kwargs) → 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, exc_info=True, **kwargs) → 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, **kwargs) → 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, enum.Enum, uuid.UUID, inmanta.types.StrictNonIntBool, int, float, datetime.datetime, str]]]]) → None
update_changes(changes: Dict[str, Tuple[Union[BaseModel, enum.Enum, uuid.UUID, inmanta.types.StrictNonIntBool, int, float, datetime.datetime, str], Union[BaseModel, enum.Enum, 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, **kwargs) → 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: 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_process_events() → bool[source]

Can this handler process events? This is a more generic version of the reload mechanism.

See the ResourceHandler.process_events() for more details about this mechanism.

Returns

Return true if this handler processes events.

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[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]
do_changes(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource, changes: dict) → 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[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.

process_events(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource, events: dict) → None[source]

Process events generated by changes to required resources. Override this method to process events in a handler.

The default implementation provides the reload mechanism. It will call do_reload when the handler can_reload() and if at least one of the dependents have successfully deployed and there were changes. Make sure to call this method from a subclass if the reload behaviour is required.

This method is called for all dependents of the given resource (inverse of the requires relationship) that have send_event set to true and for which a deploy was started. These are the only conditions, even if all dependents have failed or no changes were deployed. It is up to the handler to filter out irrelevant events.

In case of partial deployments (e.g. incremental deploy), only those resources that are being deployed will produce an event. I.e. it is possible to receive less events then expected.

In case of failure of agent, server or the system being managed, delivery of events can not be guaranteed. Update events can be lost unrecoverably in case the agent or server fails after the update was performed, but before the event was emitted. In the current implementation, start of a new deploy while another is in progress can also causes updates to be lost.

However, while event delivery can not be guaranteed, convergence to the desired state can be reliably detected. If the record of the convergence is lost, it will be retried until it is recorded. For strong behavioral guarantees, it is better to rely on desired state than on events.

Events are best used to accelerate convergence. For example, cross agent dependencies primarily make use of the deployment log on the server to determine if their dependencies are in their desired state. To speed up convergence, events are sent to notify other agents of relevant changes to resources they depend on.

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

  • resource – The resource to process the events for.

  • dict – A dict with events of the resource the given resource requires. The keys of the dict are the resources. Each value is a dict with the items status (const.ResourceState), changes (dict) and change (const.Change). The value is also defined by inmanta.data.model.Event

run_sync(func: Callable[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: 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_process_events() → bool

Can this handler process events? This is a more generic version of the reload mechanism.

See the ResourceHandler.process_events() for more details about this mechanism.

Returns

Return true if this handler processes events.

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

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.

do_changes(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource, changes: dict) → 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

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.

process_events(ctx: inmanta.agent.handler.HandlerContext, resource: inmanta.resources.Resource, events: dict) → None

Process events generated by changes to required resources. Override this method to process events in a handler.

The default implementation provides the reload mechanism. It will call do_reload when the handler can_reload() and if at least one of the dependents have successfully deployed and there were changes. Make sure to call this method from a subclass if the reload behaviour is required.

This method is called for all dependents of the given resource (inverse of the requires relationship) that have send_event set to true and for which a deploy was started. These are the only conditions, even if all dependents have failed or no changes were deployed. It is up to the handler to filter out irrelevant events.

In case of partial deployments (e.g. incremental deploy), only those resources that are being deployed will produce an event. I.e. it is possible to receive less events then expected.

In case of failure of agent, server or the system being managed, delivery of events can not be guaranteed. Update events can be lost unrecoverably in case the agent or server fails after the update was performed, but before the event was emitted. In the current implementation, start of a new deploy while another is in progress can also causes updates to be lost.

However, while event delivery can not be guaranteed, convergence to the desired state can be reliably detected. If the record of the convergence is lost, it will be retried until it is recorded. For strong behavioral guarantees, it is better to rely on desired state than on events.

Events are best used to accelerate convergence. For example, cross agent dependencies primarily make use of the deployment log on the server to determine if their dependencies are in their desired state. To speed up convergence, events are sent to notify other agents of relevant changes to resources they depend on.

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

  • resource – The resource to process the events for.

  • dict – A dict with events of the resource the given resource requires. The keys of the dict are the resources. Each value is a dict with the items status (const.ResourceState), changes (dict) and change (const.Change). The value is also defined by inmanta.data.model.Event

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[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, 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

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: Dict[str, str] = None, cwd: str = None, timeout: 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

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.

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.

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, 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.