brewtils.rest package

Submodules

brewtils.rest.client module

class brewtils.rest.client.RestClient(*args, **kwargs)[source]

Bases: object

HTTP client for communicating with Beer-garden.

The is the low-level client responsible for making the actual REST calls. Other clients (e.g. brewtils.rest.easy_client.EasyClient) build on this by providing useful abstractions.

Parameters:
  • bg_host (str) – Beer-garden hostname
  • bg_port (int) – Beer-garden port
  • bg_url_prefix (str) – URL path that will be used as a prefix when communicating with Beer-garden. Useful if Beer-garden is running on a URL other than ‘/’.
  • ssl_enabled (bool) – Whether to use SSL for Beer-garden communication
  • ca_cert (str) – Path to certificate file containing the certificate of the authority that issued the Beer-garden server certificate
  • ca_verify (bool) – Whether to verify Beer-garden server certificate
  • client_cert (str) – Path to client certificate to use when communicating with Beer-garden
  • api_version (int) – Beer-garden API version to use
  • client_timeout (int) – Max time to wait for Beer-garden server response
  • username (str) – Username for Beer-garden authentication
  • password (str) – Password for Beer-garden authentication
  • access_token (str) – Access token for Beer-garden authentication
  • refresh_token (deprecated) – Refresh token for Beer-garden authentication
JSON_HEADERS = {'Accept': 'text/plain', 'Content-type': 'application/json'}
LATEST_VERSION = 1
can_connect(**kwargs)[source]

Determine if a connection to the Beer-garden server is possible

Parameters:**kwargs – Keyword arguments to pass to Requests session call
Returns:A bool indicating if the connection attempt was successful. Will return False only if a ConnectionError is raised during the attempt. Any other exception will be re-raised.
Raises:requests.exceptions.RequestException – The connection attempt resulted in an exception that indicates something other than a basic connection error. For example, an error with certificate verification.
delete_chunked_file(*args, **kwargs)[source]

Performs a GET on the specific File URL

Parameters:
  • file_id – File ID
  • **kwargs – Query parameters to be used in the GET request
Returns:

Requests Response object

delete_file(*args, **kwargs)[source]

Performs a DELETE on the specific File URL

Parameters:file_id – File ID
Returns:Requests Response object
delete_garden(*args, **kwargs)[source]

Performs a DELETE on a Garden URL

Parameters:garden_name – Name of Garden to delete
Returns:Requests Response object
delete_instance(*args, **kwargs)[source]

Performs a DELETE on an Instance URL

Parameters:instance_id – Instance ID
Returns:Requests Response object
delete_job(*args, **kwargs)[source]

Performs a DELETE on a Job URL

Parameters:job_id – Job ID
Returns:Requests Response object
delete_queue(*args, **kwargs)[source]

Performs a DELETE on a specific Queue URL

Parameters:queue_name – Queue name
Returns:Requests Response object
delete_queues(*args, **kwargs)[source]

Performs a DELETE on the Queues URL

Returns:Requests Response object
delete_system(*args, **kwargs)[source]

Performs a DELETE on a System URL

Parameters:system_id – System ID
Returns:Requests Response object
get_chunked_file(*args, **kwargs)[source]

Performs a GET on the specific File URL

Parameters:
  • file_id – File ID
  • **kwargs – Query parameters to be used in the GET request
Returns:

Requests Response object

get_command(*args, **kwargs)[source]

Performs a GET on the Command URL

Parameters:command_id – Command ID
Returns:Requests Response object
get_commands(*args, **kwargs)[source]

Performs a GET on the Commands URL

Returns:Requests Response object
get_config(*args, **kwargs)[source]

Perform a GET to the config URL

Parameters:**kwargs (deprecated) – Unused. Accepted for compatibility.
Returns:Requests Response object
get_file(*args, **kwargs)[source]

Performs a GET on the specific File URL

Parameters:
  • file_id – File ID
  • **kwargs – Query parameters to be used in the GET request
Returns:

Requests Response object

get_garden(*args, **kwargs)[source]

Performs a GET on the Garden URL

Parameters:
  • garden_name – Name of garden to retreive
  • **kwargs – Query parameters to be used in the GET request
Returns:

Requests Response object

get_gardens(*args, **kwargs)[source]

Preform a GET on the Garden URL

This fetches all gardens.

Returns:Requests Response object
get_instance(*args, **kwargs)[source]

Performs a GET on the Instance URL

Parameters:instance_id – Instance ID
Returns:Requests Response object
get_job(*args, **kwargs)[source]

Performs a GET on the Job URL

Parameters:job_id – Job ID
Returns:Requests Response object
get_jobs(*args, **kwargs)[source]

Performs a GET on the Jobs URL.

Parameters:**kwargs – Query parameters to be used in the GET request
Returns:Requests Response object
get_logging_config(*args, **kwargs)[source]

Perform a GET to the logging config URL

Parameters:**kwargs – Query parameters to be used in the GET request
Returns:Requests Response object
get_queues(*args, **kwargs)[source]

Performs a GET on the Queues URL

Returns:Requests Response object
get_request(*args, **kwargs)[source]

Performs a GET on the Request URL

Parameters:request_id – Request ID
Returns:Requests Response object
get_requests(*args, **kwargs)[source]

Performs a GET on the Requests URL

Parameters:**kwargs – Query parameters to be used in the GET request
Returns:Requests Response object
get_system(*args, **kwargs)[source]

Performs a GET on the System URL

Parameters:
  • system_id – System ID
  • **kwargs – Query parameters to be used in the GET request
Returns:

Requests Response object

get_systems(*args, **kwargs)[source]

Perform a GET on the System collection URL

Parameters:**kwargs – Query parameters to be used in the GET request
Returns:Requests Response object
get_tokens(username=None, password=None)[source]

Use a username and password to get access and refresh tokens

Parameters:
  • username – Beergarden username
  • password – Beergarden password
Returns:

Requests Response object

get_user(*args, **kwargs)[source]

Performs a GET on the specific User URL

Parameters:user_identifier – User ID or username
Returns:Requests Response object
get_version(*args, **kwargs)[source]

Perform a GET to the version URL

Parameters:**kwargs (deprecated) – Unused. Accepted for compatibility.
Returns:Requests Response object
patch_admin(*args, **kwargs)[source]

Performs a PATCH on the admin URL

Parameters:payload – Serialized PatchOperation
Returns:Requests Response object
patch_garden(*args, **kwargs)[source]

Perform a PATCH on a Garden URL

Parameters:
  • garden_name – Garden name
  • payload – Serialized patch operation
Returns:

Request Response object

patch_instance(*args, **kwargs)[source]

Performs a PATCH on the instance URL

Parameters:
  • instance_id – Instance ID
  • payload – Serialized PatchOperation
Returns:

Requests Response object

patch_job(*args, **kwargs)[source]

Performs a PATCH on the Job URL

Parameters:
  • job_id – Job ID
  • payload – Serialized PatchOperation
Returns:

Requests Response object

patch_request(*args, **kwargs)[source]

Performs a PATCH on the Request URL

Parameters:
  • request_id – Request ID
  • payload – Serialized PatchOperation
Returns:

Requests Response object

patch_system(*args, **kwargs)[source]

Performs a PATCH on a System URL

Parameters:
  • system_id – System ID
  • payload – Serialized PatchOperation
Returns:

Requests Response object

post_chunked_file(*args, **kwargs)[source]

Performs a POST on the file URL.

Parameters:
  • fd – A file descriptor
  • file_params – Metadata about the file
  • current_position – The current cursor position for the file object
Returns:

A Requests Response object

post_event(*args, **kwargs)[source]

Performs a POST on the event URL

Parameters:
  • payload – Serialized new event definition
  • publishers – Array of publishers to use
Returns:

Requests Response object

post_execute_job(job_id, reset_interval=False)[source]

Performs a POST on the Job Execute URL

Parameters:
  • job_id – The ID of the Job
  • reset_interval – Sets interval of job to restart now
Returns:

Request Response object

post_export_jobs(*args, **kwargs)[source]

Perform a POST on the Job export URL.

Parameters:payload – Serialized list of Jobs
Returns:Requests Response object
post_file(*args, **kwargs)[source]

Performs a PUT on the file URL

Parameters:data – Data bytes
Returns:A Requests Response object
post_forward(*args, **kwargs)[source]

Performs a POST on the Forward URL

Parameters:
  • payload – The operation to be executed
  • **kwargs – Keyword arguments to pass to Requests session call
Returns:

The API response

post_gardens(*args, **kwargs)[source]

Performs a POST on the Garden URL

Parameters:payload – New Garden definition
Returns:Requests Response object
post_import_jobs(*args, **kwargs)[source]

Perform a POST on the Job import URL.

Parameters:payload – Serialized list of job definitions
Returns:Requests Response object
post_jobs(*args, **kwargs)[source]

Performs a POST on the Job URL

Parameters:payload – New Job definition
Returns:Requests Response object
post_requests(*args, **kwargs)[source]

Performs a POST on the Request URL

Parameters:
  • payload – New Request definition
  • **kwargs – Extra request parameters
Keyword Arguments:
 
  • blocking – Wait for request to complete
  • timeout – Maximum seconds to wait
Returns:

Requests Response object

post_systems(*args, **kwargs)[source]

Performs a POST on the System URL

Parameters:payload – New System definition
Returns:Requests Response object
class brewtils.rest.client.TimeoutAdapter(**kwargs)[source]

Bases: requests.adapters.HTTPAdapter

Transport adapter with a default request timeout

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

Sends PreparedRequest object with specified timeout.

brewtils.rest.client.enable_auth(method)[source]

Decorate methods with this to enable using authentication

brewtils.rest.easy_client module

class brewtils.rest.easy_client.EasyClient(*args, **kwargs)[source]

Bases: object

Client for simplified communication with Beergarden

This class is intended to be a middle ground between the RestClient and SystemClient. It provides a ‘cleaner’ interface to some common Beergarden operations than is exposed by the lower-level RestClient. On the other hand, the SystemClient is much better for generating Beergarden Requests.

Parameters:
  • bg_host (str) – Beer-garden hostname
  • bg_port (int) – Beer-garden port
  • bg_url_prefix (str) – URL path that will be used as a prefix when communicating with Beer-garden. Useful if Beer-garden is running on a URL other than ‘/’.
  • ssl_enabled (bool) – Whether to use SSL for Beer-garden communication
  • ca_cert (str) – Path to certificate file containing the certificate of the authority that issued the Beer-garden server certificate
  • ca_verify (bool) – Whether to verify Beer-garden server certificate
  • client_cert (str) – Path to client certificate to use when communicating with Beer-garden
  • api_version (int) – Beer-garden API version to use
  • client_timeout (int) – Max time to wait for Beer-garden server response
  • username (str) – Username for Beer-garden authentication
  • password (str) – Password for Beer-garden authentication
  • access_token (str) – Access token for Beer-garden authentication
  • refresh_token (str) – Refresh token for Beer-garden authentication
can_connect(**kwargs)[source]

Determine if the Beergarden server is responding.

Parameters:**kwargs – Keyword arguments passed to the underlying Requests method
Returns:A bool indicating if the connection attempt was successful. Will return False only if a ConnectionError is raised during the attempt. Any other exception will be re-raised.
Raises:requests.exceptions.RequestException – The connection attempt resulted in an exception that indicates something other than a basic connection error. For example, an error with certificate verification.
clear_all_queues()[source]

Cancel and remove all Requests in all queues

Returns:True if the clear was successful
Return type:bool
clear_queue(queue_name)[source]

Cancel and remove all Requests from a message queue

Parameters:queue_name (str) – The name of the queue to clear
Returns:True if the clear was successful
Return type:bool
create_garden(garden)[source]

Create a new Garden

Parameters:garden (Garden) – The Garden to create
Returns:The newly-created Garden
Return type:Garden
create_job(job)[source]

Create a new Job

Parameters:job (Job) – New Job definition
Returns:The newly-created Job
Return type:Job
create_request(request, **kwargs)[source]

Create a new Request

Parameters:
  • request – New request definition
  • **kwargs – Extra request parameters
Keyword Arguments:
 
  • blocking (bool) – Wait for request to complete before returning
  • timeout (int) – Maximum seconds to wait for completion
Returns:

The newly-created Request

Return type:

Request

create_system(system)[source]

Create a new System

Parameters:system (System) – The System to create
Returns:The newly-created system
Return type:System
delete_chunked_file(file_id)[source]

Delete a given file on the Beer Garden server.

Parameters:file_id – The beer garden-assigned file id.
Returns:The API response
download_bytes(file_id)[source]

Download bytes

Parameters:file_id – Id of bytes to download
Returns:The bytes data
download_chunked_file(file_id)[source]

Download a chunked file from the Beer Garden server.

Parameters:file_id – The beer garden-assigned file id.
Returns:A file object
download_file(file_id, path)[source]

Download a file

Parameters:
  • file_id – The File id.
  • path – Location for downloaded file
Returns:

Path to downloaded file

execute_job(job_id, reset_interval=False)[source]

Execute a Job

Parameters:
  • job_id (str) – The Job ID
  • reset_interval (bool) – Restarts the job’s interval time to now if the job’s trigger is an interval
Returns:

The returned request

Return type:

Request

export_jobs(job_id_list=None)[source]

Export jobs from an optional job ID list.

If job_id_list is None or empty, definitions for all jobs are returned.

Parameters:job_id_list – A list of job IDS, optional
Returns:A list of job definitions
find_jobs(**kwargs)[source]

Find Jobs using keyword arguments as search parameters

Parameters:**kwargs – Search parameters
Returns:List of Jobs matching the search parameters
Return type:List[Job]
find_requests(**kwargs)[source]

Find Requests using keyword arguments as search parameters

Parameters:**kwargs – Search parameters
Returns:List of Systems matching the search parameters
Return type:List[Request]
find_systems(**kwargs)[source]

Find Systems using keyword arguments as search parameters

Parameters:**kwargs – Search parameters
Returns:List of Systems matching the search parameters
Return type:List[System]
find_unique_request(**kwargs)[source]

Find a unique request

Note

If ‘id’ is a given keyword argument then all other parameters will be ignored.

Parameters:**kwargs – Search parameters
Returns:The Request if found, None otherwise
Return type:Request, None
Raises:FetchError – More than one matching Request was found
find_unique_system(**kwargs)[source]

Find a unique system

Note

If ‘id’ is a given keyword argument then all other parameters will be ignored.

Parameters:**kwargs – Search parameters
Returns:The System if found, None otherwise
Return type:System, None
Raises:FetchError – More than one matching System was found
forward(operation, **kwargs)[source]

Forwards an Operation

Parameters:
  • operation – The Operation to be forwarded
  • **kwargs – Keyword arguments to pass to Requests session call
Returns:

The API response

get_config()[source]

Get configuration

Returns:Configuration dictionary
Return type:dict
get_garden(garden_name)[source]

Get a Garden

Parameters:garden_name – Name of garden to retrieve
Returns:The Garden
get_gardens()[source]

Get all Gardens.

Returns:A list of all the Gardens
get_instance(instance_id)[source]

Get an Instance

Parameters:instance_id – The Id
Returns:The Instance
get_instance_status(instance_id)[source]

Get an Instance’s status

Parameters:instance_id – The Id
Returns:The Instance’s status
get_logging_config(system_name=None, local=False)[source]

Get a logging configuration

Note that the system_name is not relevant and is only provided for backward-compatibility.

Parameters:system_name (str) – UNUSED
Returns:The configuration object
Return type:dict
get_queues()[source]

Retrieve all queue information

Returns:List of all Queues
Return type:List[Queue]
get_request(request_id)[source]

Get a Request

Parameters:request_id – The Id
Returns:The Request
get_system(system_id)[source]

Get a Garden

Parameters:system_id – The Id
Returns:The System
get_user(user_identifier)[source]

Find a user

Parameters:user_identifier (str) – User ID or username
Returns:The User
Return type:Principal
get_version(**kwargs)[source]

Get Bartender, Brew-view, and API version information

Parameters:**kwargs – Extra parameters
Returns:Response object with version information in the body
Return type:dict
import_jobs(job_list)[source]

Import job definitions from a list of Jobs.

Parameters:job_list – A list of jobs to import
Returns:A list of the job IDs created
initialize_instance(instance_id, runner_id=None)[source]

Start an Instance

Parameters:
  • instance_id (str) – The Instance ID
  • runner_id (str) – The PluginRunner ID, if any
Returns:

The updated Instance

Return type:

Instance

instance_heartbeat(instance_id)[source]

Send an Instance heartbeat

Parameters:instance_id (str) – The Instance ID
Returns:True if the heartbeat was successful
Return type:bool
pause_job(job_id)[source]

Pause a Job

Parameters:job_id (str) – The Job ID
Returns:The updated Job
Return type:Job
publish_event(*args, **kwargs)[source]

Publish a new event

Parameters:
  • *args – If a positional argument is given it’s assumed to be an Event and will be used
  • **kwargs – Will be used to construct a new Event to publish if no Event is given in the positional arguments
Keyword Arguments:
 

_publishers (Optional[List[str]]) – List of publisher names. If given the Event will only be published to the specified publishers. Otherwise all publishers known to Beergarden will be used.

Returns:

True if the publish was successful

Return type:

bool

remove_garden(garden_name)[source]

Remove a unique Garden

Parameters:garden_name (String) – Name of Garden to remove
Returns:True if removal was successful
Return type:bool
Raises:NotFoundError – Couldn’t find a Garden matching given name
remove_instance(instance_id)[source]

Remove an Instance

Parameters:instance_id (str) – The Instance ID
Returns:True if the remove was successful
Return type:bool
remove_job(job_id)[source]

Remove a unique Job

Parameters:job_id (str) – The Job ID
Returns:True if removal was successful
Return type:bool
Raises:DeleteError – Couldn’t remove Job
remove_system(**kwargs)[source]

Remove a unique System

Parameters:**kwargs – Search parameters
Returns:True if removal was successful
Return type:bool
Raises:FetchError – Couldn’t find a System matching given parameters
rescan()[source]

Rescan local plugin directory

Returns:True if rescan was successful
Return type:bool
resume_job(job_id)[source]

Resume a Job

Parameters:job_id (str) – The Job ID
Returns:The updated Job
Return type:Job
update_garden(garden)[source]
update_instance(instance_id, **kwargs)[source]

Update an Instance status

Parameters:

instance_id (str) – The Instance ID

Keyword Arguments:
 
  • new_status (str) – The new status
  • metadata (dict) – Will be added to existing instance metadata
Returns:

The updated Instance

Return type:

Instance

update_instance_status(instance_id, new_status)[source]

Get an Instance’s status

Parameters:
  • instance_id (str) – The Instance ID
  • new_status (str) – The new status
Returns:

The updated Instance

Return type:

Instance

update_request(request_id, status=None, output=None, error_class=None)[source]

Update a Request

Parameters:
  • request_id (str) – The Request ID
  • status (Optional[str]) – New Request status
  • output (Optional[str]) – New Request output
  • error_class (Optional[str]) – New Request error class
Returns:

The updated response

Return type:

Response

update_system(system_id, new_commands=None, **kwargs)[source]

Update a System

Parameters:
  • system_id (str) – The System ID
  • new_commands (Optional[List[Command]]) – New System commands
Keyword Arguments:
 
  • add_instance (Instance) – An Instance to append
  • metadata (dict) – New System metadata
  • description (str) – New System description
  • display_name (str) – New System display name
  • icon_name (str) – New System icon name
  • template (str) – New System template
Returns:

The updated system

Return type:

System

upload_bytes(data)[source]

Upload a file

Parameters:data – The bytes to upload
Returns:The bytes Resolvable
upload_chunked_file(file_to_upload, desired_filename=None, file_params=None)[source]

Upload a given file to the Beer Garden server.

Parameters:
  • file_to_upload – Can either be an open file descriptor or a path.
  • desired_filename – The desired filename, if none is provided it
  • use the basename of the file_to_upload (will) –
  • file_params – The metadata surrounding the file. Valid Keys: See brewtils File model
Returns:

A BG file ID.

upload_file(path)[source]

Upload a file

Parameters:path – Path to file
Returns:The file Resolvable
who_am_i()[source]

Find user using the current set of credentials

Returns:The User
Return type:Principal
brewtils.rest.easy_client.get_easy_client(**kwargs)[source]

Easy way to get an EasyClient

The benefit to this method over creating an EasyClient directly is that this method will also search the environment for parameters. Kwargs passed to this method will take priority, however.

Parameters:**kwargs – Options for configuring the EasyClient
Returns:The configured client
Return type:brewtils.rest.easy_client.EasyClient
brewtils.rest.easy_client.handle_response_failure(response, default_exc=<class 'brewtils.errors.RestError'>, raise_404=True)[source]

Deal with a response with non-2xx status code

Parameters:
  • response – The response object
  • default_exc – The exception to raise if no specific exception is warranted
  • raise_404 – If True a response with status code 404 will raise a NotFoundError. If False the method will return None.
Returns:

None - this function will always raise

Raises:
  • NotFoundError – Status code 404 and raise_404 is True
  • WaitExceededError – Status code 408
  • ConflictError – Status code 409
  • TooLargeError – Status code 413
  • ValidationError – Any other 4xx status codes
  • RestConnectionError – Status code 503
  • default_exc – Any other status code
brewtils.rest.easy_client.wrap_response(return_boolean=False, parse_method=None, parse_many=False, default_exc=<class 'brewtils.errors.RestError'>, raise_404=True)[source]

Decorator to consolidate response parsing and error handling

Parameters:
  • return_boolean – If True, a successful response will also return True
  • parse_method – Response json will be passed to this method of the SchemaParser
  • parse_many – Will be passed as the ‘many’ parameter when parsing the response
  • default_exc – Will be passed to handle_response_failure for failed responses
  • raise_404 – Will be passed to handle_response_failure for failed responses
Returns:

  • True if return_boolean is True and the response status code is 2xx.
  • The response object if return_boolean is False and parse_method is “”
  • A parsed Brewtils model if return_boolean is False and parse_method is defined

Raises:

RestError – The response has a non-2xx status code. Note that the specific exception raised depends on the response status code and the argument passed as the default_exc parameter.

brewtils.rest.system_client module

class brewtils.rest.system_client.SystemClient(*args, **kwargs)[source]

Bases: object

High-level client for generating requests for a Beer-garden System.

SystemClient creation:

This class is intended to be the main way to create Beer-garden requests. Create an instance with Beer-garden connection information and a system name:

client = SystemClient(
    system_name='example_system',
    system_namespace='default',
    bg_host="host",
    bg_port=2337,
)

Note: Passing an empty string as the system_namespace parameter will evalutate to the local garden’s default namespace.

Pass additional keyword arguments for more granularity:

version_constraint:
Allows specifying a particular system version. Can be a version literal (‘1.0.0’) or the special value ‘latest.’ Using ‘latest’ will allow the SystemClient to retry a request if it fails due to a missing system (see Creating Requests).
default_instance:
The instance name to use when creating a request if no other instance name is specified. Since each request must be addressed to a specific instance this is a convenience to prevent needing to specify the instance for each request.
always_update:
If True the SystemClient will always attempt to reload the system definition before making a request. This is useful to ensure Requests are always made against the latest version of the system. If not set the System definition will be loaded when making the first request and will only be reloaded if a Request fails.
Loading the System:
The System definition is lazily loaded, so nothing happens until the first attempt to send a Request. At that point the SystemClient will query Beer-garden to get a system definition that matches the system_name and version_constraint. If no matching System can be found a FetchError will be raised. If always_update was set to True this will happen before making each request, not only the first.
Making a Request:

The standard way to create and send requests is by calling object attributes:

request = client.example_command(param_1='example_param')

In the normal case this will block until the request completes. Request completion is determined by periodically polling Beer-garden to check the Request status. The time between polling requests starts at 0.5s and doubles each time the request has still not completed, up to max_delay. If a timeout was specified and the Request has not completed within that time a ConnectionTimeoutError will be raised.

It is also possible to create the SystemClient in non-blocking mode by specifying blocking=False. In this case the request creation will immediately return a Future and will spawn a separate thread to poll for Request completion. The max_concurrent parameter is used to control the maximum threads available for polling.

# Create a SystemClient with blocking=False
client = SystemClient(
    system_name='example_system',
    system_namespace='default',
    bg_host="localhost",
    bg_port=2337,
    blocking=False,
)

# Create and send 5 requests without waiting for request completion
futures = [client.example_command(param_1=number) for number in range(5)]

# Now wait on all requests to complete
concurrent.futures.wait(futures)

If the request creation process fails (e.g. the command failed validation) and version_constraint is ‘latest’ then the SystemClient will check to see if a newer version is available, and if so it will attempt to make the request on that version. This is so users of the SystemClient that don’t necessarily care about the target system version don’t need to be restarted every time the target system is updated.

It’s also possible to control what happens when a Request results in an ERROR. If the raise_on_error parameter is set to False (the default) then Requests that are not successful simply result in a Request with a status of ERROR, and it is the plugin developer’s responsibility to check for this case. However, if raise_on_error is set to True then this will result in a RequestFailedError being raised. This will happen regardless of the value of the blocking flag.

Tweaking Beer-garden Request Parameters:

There are several parameters that control how beer-garden routes / processes a request. To denote these as intended for Beer-garden itself (rather than a parameter to be passed to the Plugin) prepend a leading underscore to the argument name.

Sending to another instance:

request = client.example_command(
    _instance_name="instance_2", param_1="example_param"
)

Request with a comment:

request = client.example_command(
    _comment="I'm a beer-garden comment!", param_1="example_param"
)

Without the leading underscore the arguments would be treated the same as “param_1” - another parameter to be passed to the plugin.

Request that raises:

client = SystemClient(
    system_name="foo",
    system_namespace='default',
    bg_host="localhost",
    bg_port=2337,
)

try:
    client.command_that_errors(_raise_on_error=True)
except RequestFailedError:
    print("I could have just ignored this")
Parameters:
  • system_name (str) – Name of the System to make Requests on
  • system_namespace (str) – Namespace of the System to make Requests on
  • version_constraint (str) – System version to make Requests on. Can be specific (‘1.0.0’) or ‘latest’.
  • default_instance (str) – Name of the Instance to make Requests on
  • always_update (bool) – Whether to check if a newer version of the System exists before making each Request. Only relevant if version_constraint='latest'
  • timeout (int) – Seconds to wait for a request to complete. ‘None’ means wait forever.
  • max_delay (int) – Maximum number of seconds to wait between status checks for a created request
  • blocking (bool) – Flag indicating whether creation will block until the Request is complete or return a Future that will complete when the Request does
  • max_concurrent (int) – Maximum number of concurrent requests allowed. Only has an effect when blocking=False.
  • raise_on_error (bool) – Flag controlling whether created Requests that complete with an ERROR state should raise an exception
  • bg_host (str) – Beer-garden hostname
  • bg_port (int) – Beer-garden port
  • bg_url_prefix (str) – URL path that will be used as a prefix when communicating with Beer-garden. Useful if Beer-garden is running on a URL other than ‘/’.
  • ssl_enabled (bool) – Whether to use SSL for Beer-garden communication
  • ca_cert (str) – Path to certificate file containing the certificate of the authority that issued the Beer-garden server certificate
  • ca_verify (bool) – Whether to verify Beer-garden server certificate
  • client_cert (str) – Path to client certificate to use when communicating with Beer-garden
  • api_version (int) – Beer-garden API version to use
  • client_timeout (int) – Max time to wait for Beer-garden server response
  • username (str) – Username for Beer-garden authentication
  • password (str) – Password for Beer-garden authentication
  • access_token (str) – Access token for Beer-garden authentication
  • refresh_token (str) – Refresh token for Beer-garden authentication
bg_default_instance
bg_system
create_bg_request(command_name, **kwargs)[source]

Create a callable that will execute a Beer-garden request when called.

Normally you interact with the SystemClient by accessing attributes, but there could be certain cases where you want to create a request without sending it.

Example:

client = SystemClient(host, port, 'system', blocking=False)

# Create two callables - one with a parameter and one without
uncreated_requests = [
    client.create_bg_request('command_1', arg_1='Hi!'),
    client.create_bg_request('command_2'),
]

# Calling creates and sends the request
# The result of each is a future because blocking=False on the SystemClient
futures = [req() for req in uncreated_requests]

# Wait for all the futures to complete
concurrent.futures.wait(futures)
Parameters:
  • command_name (str) – Name of the Command to send
  • kwargs (dict) – Will be passed as parameters when creating the Request
Returns:

Partial that will create and execute a Beer-garden request when called

Raises:

AttributeError – System does not have a Command with the given command_name

load_bg_system()[source]

Query beer-garden for a System definition

This method will make the query to beer-garden for a System matching the name and version constraints specified during SystemClient instance creation.

If this method completes successfully the SystemClient will be ready to create and send Requests.

Returns:None
Raises:FetchError – Unable to find a matching System
send_bg_request(*args, **kwargs)[source]

Actually create a Request and send it to Beer-garden

Note

This method is intended for advanced use only, mainly cases where you’re using the SystemClient without a predefined System. It assumes that everything needed to construct the request is being passed in kwargs. If this doesn’t sound like what you want you should check out create_bg_request.

Parameters:
  • args (list) – Unused. Passing positional parameters indicates a bug
  • kwargs (dict) – All necessary request parameters, including Beer-garden internal parameters
Returns:

A completed Request object blocking=False: A future that will be completed when the Request does

Return type:

blocking=True

Raises:

ValidationError – Request creation failed validation on the server

Module contents

brewtils.rest.normalize_url_prefix(url_prefix)[source]

Enforce a consistent URL representation

The normalized prefix will begin and end with ‘/’. If there is no prefix the normalized form will be ‘/’.

Examples

INPUT NORMALIZED
None ‘/’
‘’ ‘/’
‘/’ ‘/’
‘example’ ‘/example/’
‘/example’ ‘/example/’
‘example/’ ‘/example/’
‘/example/’ ‘/example/’
Parameters:url_prefix (str) – The prefix
Returns:The normalized prefix
Return type:str