text
stringlengths
81
112k
Deletion of a project is done through sending a **DELETE** request to the project instance URI. Please note, that if a project has connected instances, deletion request will fail with 409 response code. Valid request example (token is user specific): .. code-block:: http DELETE /a...
A list of users connected to the project def users(self, request, uuid=None): """ A list of users connected to the project """ project = self.get_object() queryset = project.get_users() # we need to handle filtration manually because we want to filter only project users, not projects. ...
User list is available to all authenticated users. To get a list, issue authenticated **GET** request against */api/users/*. User list supports several filters. All filters are set in HTTP query section. Field filters are listed below. All of the filters apart from ?organization are usi...
User fields can be updated by account owner or user with staff privilege (is_staff=True). Following user fields can be updated: - organization (deprecated, use `organization plugin <http://waldur_core-organization.readthedocs.org/en/stable/>`_ instead) - full_name - native_nam...
To change a user password, submit a **POST** request to the user's RPC URL, specifying new password by staff user or account owner. Password is expected to be at least 7 symbols long and contain at least one number and at least one lower or upper case. Example of a valid request: ...
Project permissions expresses connection of user to a project. User may have either project manager or system administrator permission in the project. Use */api/project-permissions/* endpoint to maintain project permissions. Note that project permissions can be viewed and modified only by custo...
To remove a user from a project, delete corresponding connection (**url** field). Successful deletion will return status code 204. .. code-block:: http DELETE /api/project-permissions/42/ HTTP/1.1 Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b Host: e...
Each customer is associated with a group of users that represent customer owners. The link is maintained through **api/customer-permissions/** endpoint. To list all visible links, run a **GET** query against a list. Response will contain a list of customer owners and their brief data. ...
To remove a user from a customer owner group, delete corresponding connection (**url** field). Successful deletion will return status code 204. .. code-block:: http DELETE /api/customer-permissions/71/ HTTP/1.1 Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b ...
Available request parameters: - ?type=type_of_statistics_objects (required. Have to be from the list: 'customer', 'project') - ?from=timestamp (default: now - 30 days, for example: 1415910025) - ?to=timestamp (default: now, for example: 1415912625) - ?datapoints=how many data points hav...
To get a list of SSH keys, run **GET** against */api/keys/* as authenticated user. A new SSH key can be created by any active users. Example of a valid request: .. code-block:: http POST /api/keys/ HTTP/1.1 Content-Type: application/json Accept: application/json ...
To get a list of service settings, run **GET** against */api/service-settings/* as an authenticated user. Only settings owned by this user or shared settings will be listed. Supported filters are: - ?name=<text> - partial matching used for searching - ?type=<type> - choices: OpenStack,...
Only staff can update shared settings, otherwise user has to be an owner of the settings. def can_user_update_settings(request, view, obj=None): """ Only staff can update shared settings, otherwise user has to be an owner of the settings.""" if obj is None: return # TODO [TM:3/21/1...
To update service settings, issue a **PUT** or **PATCH** to */api/service-settings/<uuid>/* as a customer owner. You are allowed to change name and credentials only. Example of a request: .. code-block:: http PATCH /api/service-settings/9079705c17d64e6aa0af2e619b0e0702/ HTTP/1.1 ...
This endpoint returns allocation of resources for current service setting. Answer is service-specific dictionary. Example output for OpenStack: * vcpu - maximum number of vCPUs (from hypervisors) * vcpu_quota - maximum number of vCPUs(from quotas) * vcpu_usage - current number of used v...
To get a list of supported resources' actions, run **OPTIONS** against */api/<resource_url>/* as an authenticated user. It is possible to filter and order by resource-specific fields, but this filters will be applied only to resources that support such filtering. For example it is possible to s...
Count resources by type. Example output: .. code-block:: javascript { "Amazon.Instance": 0, "GitLab.Project": 3, "Azure.VirtualMachine": 0, "DigitalOcean.Droplet": 0, "OpenStack.Instance": 0, "GitLab.Gr...
Filter services by type ^^^^^^^^^^^^^^^^^^^^^^^ It is possible to filter services by their types. Example: /api/services/?service_type=DigitalOcean&service_type=OpenStack def list(self, request, *args, **kwargs): """ Filter services by type ^^^^^^^^^^^^^^^^^^^^^^^ ...
To list all services without regard to its type, run **GET** against */api/services/* as an authenticated user. To list services of specific type issue **GET** to specific endpoint from a list above as a customer owner. Individual endpoint used for every service type. To create a service, issu...
Allow to execute action only if service settings are not shared or user is staff def _require_staff_for_shared_settings(request, view, obj=None): """ Allow to execute action only if service settings are not shared or user is staff """ if obj is None: return if obj.settings.shared a...
To get a list of resources available for import, run **GET** against */<service_endpoint>/link/* as an authenticated user. Optionally project_uuid parameter can be supplied for services requiring it like OpenStack. To import (link with Waldur) resource issue **POST** against the same endpoint w...
Unlink all related resources, service project link and service itself. def unlink(self, request, uuid=None): """ Unlink all related resources, service project link and service itself. """ service = self.get_object() service.unlink_descendants() self.perform_destroy(servi...
To get a list of connections between a project and an service, run **GET** against service_project_link_url as authenticated user. Note that a user can only see connections of a project where a user has a role. If service has `available_for_all` flag, project-service connections are created automatical...
To remove a link, issue **DELETE** to URL of the corresponding connection as stuff user or customer owner. def retrieve(self, request, *args, **kwargs): """ To remove a link, issue **DELETE** to URL of the corresponding connection as stuff user or customer owner. """ return super(BaseSe...
Fetch ancestors quotas that have the same name and are registered as aggregator quotas. def get_aggregator_quotas(self, quota): """ Fetch ancestors quotas that have the same name and are registered as aggregator quotas. """ ancestors = quota.scope.get_quota_ancestors() aggregator_quotas = [] ...
Adds a new event handler. def subscribe(self, handler): """Adds a new event handler.""" assert callable(handler), "Invalid handler %s" % handler self.handlers.append(handler)
*Safely* triggers the event by invoking all its handlers, even if few of them raise an exception. If a set of exceptions is raised during handler invocation sequence, this method rethrows the first one. :param args: the arguments to invoke event handlers with. def safe_trigger(self, *...
Attaches the handler to the specified event. @param event: event to attach the handler to. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param handler: event handler. ...
Detaches the handler from the specified event. @param event: event to detach the handler to. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param handler: event handler. ...
Triggers the specified event by invoking EventHook.trigger under the hood. @param event: event to trigger. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @param args: event arg...
Safely triggers the specified event by invoking EventHook.safe_trigger under the hood. @param event: event to trigger. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. @p...
Gets or creates a new event hook for the specified event (key). This method treats qcore.EnumBase-typed event keys specially: enum_member.name is used as key instead of enum instance in case such a key is passed. Note that on/off/trigger/safe_trigger methods rely on this method, ...
Invitation lifetime must be specified in Waldur Core settings with parameter "INVITATION_LIFETIME". If invitation creation time is less than expiration time, the invitation will set as expired. def cancel_expired_invitations(invitations=None): """ Invitation lifetime must be specified in Waldur Core settin...
Lookup sighash from 4bytes.directory, create a pseudo api and try to decode it with the parsed abi. May return multiple results as sighashes may collide. :param s: bytes input :return: pseudo abi for method def get_pseudo_abi_for_input(s, timeout=None, proxies=None): """ Lookup ...
Prepare the contract json abi for sighash lookups and fast access :param jsonabi: contracts abi in json format :return: def _prepare_abi(self, jsonabi): """ Prepare the contract json abi for sighash lookups and fast access :param jsonabi: contracts abi in json format :...
Describe the input bytesequence (constructor arguments) s based on the loaded contract abi definition :param s: bytes constructor arguments :return: AbiMethod instance def describe_constructor(self, s): """ Describe the input bytesequence (constructor arguments) s based on the...
Describe the input bytesequence s based on the loaded contract abi definition :param s: bytes input :return: AbiMethod instance def describe_input(self, s): """ Describe the input bytesequence s based on the loaded contract abi definition :param s: bytes input :return:...
Return a new AbiMethod object from an input stream :param s: binary input :return: new AbiMethod object matching the provided input stream def from_input_lookup(s): """ Return a new AbiMethod object from an input stream :param s: binary input :return: new AbiMethod objec...
Raises an AssertionError if expected is not actual. def assert_is(expected, actual, message=None, extra=None): """Raises an AssertionError if expected is not actual.""" assert expected is actual, _assert_fail_message( message, expected, actual, "is not", extra )
Raises an AssertionError if expected is actual. def assert_is_not(expected, actual, message=None, extra=None): """Raises an AssertionError if expected is actual.""" assert expected is not actual, _assert_fail_message( message, expected, actual, "is", extra )
Raises an AssertionError if value is not an instance of type(s). def assert_is_instance(value, types, message=None, extra=None): """Raises an AssertionError if value is not an instance of type(s).""" assert isinstance(value, types), _assert_fail_message( message, value, types, "is not an instance of", ...
Raises an AssertionError if expected != actual. If tolerance is specified, raises an AssertionError if either - expected or actual isn't a number, or - the difference between expected and actual is larger than the tolerance. def assert_eq(expected, actual, message=None, tolerance=None, extra=None): ""...
Asserts that two dictionaries are equal, producing a custom message if they are not. def assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]): """Asserts that two dictionaries are equal, producing a custom message if they are not.""" assert_is_instance(expected, dict) assert_is_instance(ac...
Raises an AssertionError if left_hand <= right_hand. def assert_gt(left, right, message=None, extra=None): """Raises an AssertionError if left_hand <= right_hand.""" assert left > right, _assert_fail_message(message, left, right, "<=", extra)
Raises an AssertionError if left_hand < right_hand. def assert_ge(left, right, message=None, extra=None): """Raises an AssertionError if left_hand < right_hand.""" assert left >= right, _assert_fail_message(message, left, right, "<", extra)
Raises an AssertionError if left_hand >= right_hand. def assert_lt(left, right, message=None, extra=None): """Raises an AssertionError if left_hand >= right_hand.""" assert left < right, _assert_fail_message(message, left, right, ">=", extra)
Raises an AssertionError if left_hand > right_hand. def assert_le(left, right, message=None, extra=None): """Raises an AssertionError if left_hand > right_hand.""" assert left <= right, _assert_fail_message(message, left, right, ">", extra)
Raises an AssertionError if obj is not in seq. def assert_in(obj, seq, message=None, extra=None): """Raises an AssertionError if obj is not in seq.""" assert obj in seq, _assert_fail_message(message, obj, seq, "is not in", extra)
Raises an AssertionError if obj is in iter. def assert_not_in(obj, seq, message=None, extra=None): """Raises an AssertionError if obj is in iter.""" # for very long strings, provide a truncated error if isinstance(seq, six.string_types) and obj in seq and len(seq) > 200: index = seq.find(obj) ...
Raises an AssertionError if obj is not in seq using assert_eq cmp. def assert_in_with_tolerance(obj, seq, tolerance, message=None, extra=None): """Raises an AssertionError if obj is not in seq using assert_eq cmp.""" for i in seq: try: assert_eq(obj, i, tolerance=tolerance, message=message,...
Raises an AssertionError if substring is not a substring of subject. def assert_is_substring(substring, subject, message=None, extra=None): """Raises an AssertionError if substring is not a substring of subject.""" assert ( (subject is not None) and (substring is not None) and (subject....
Raises an AssertionError if substring is a substring of subject. def assert_is_not_substring(substring, subject, message=None, extra=None): """Raises an AssertionError if substring is a substring of subject.""" assert ( (subject is not None) and (substring is not None) and (subject.find...
Raises an AssertionError if the objects contained in expected are not equal to the objects contained in actual without regard to their order. This takes quadratic time in the umber of elements in actual; don't use it for very long lists. def assert_unordered_list_eq(expected, actual, message=None): "...
Execute function only if one of input parameters is not empty def _execute_if_not_empty(func): """ Execute function only if one of input parameters is not empty """ def wrapper(*args, **kwargs): if any(args[1:]) or any(kwargs.items()): return func(*args, **kwargs) return wrapper
Prepare body for elasticsearch query Search parameters ^^^^^^^^^^^^^^^^^ These parameters are dictionaries and have format: <term>: [<value 1>, <value 2> ...] should_terms: it resembles logical OR must_terms: it resembles logical AND must_not_terms: it resembles logical...
Execute high level-operation def execute(cls, instance, async=True, countdown=2, is_heavy_task=False, **kwargs): """ Execute high level-operation """ cls.pre_apply(instance, async=async, **kwargs) result = cls.apply_signature(instance, async=async, countdown=countdown, ...
Serialize input data and apply signature def apply_signature(cls, instance, async=True, countdown=None, is_heavy_task=False, **kwargs): """ Serialize input data and apply signature """ serialized_instance = utils.serialize_instance(instance) signature = cls.get_task_signature(instance, seriali...
Synchronously execute callback def _apply_callback(cls, callback, result): """ Synchronously execute callback """ if not callback.immutable: callback.args = (result.id, ) + callback.args callback.apply()
Returns description in format: * entity human readable name * docstring def get_entity_description(entity): """ Returns description in format: * entity human readable name * docstring """ try: entity_name = entity.__name__.strip('_') except AttributeError: # entit...
Returns validators description in format: ### Validators: * validator1 name * validator1 docstring * validator2 name * validator2 docstring def get_validators_description(view): """ Returns validators description in format: ### Validators: * validator1 name * validator1 docst...
Returns actions permissions description in format: * permission1 name * permission1 docstring * permission2 name * permission2 docstring def get_actions_permission_description(view, method): """ Returns actions permissions description in format: * permission1 name * permission1 docst...
Returns permissions description in format: ### Permissions: * permission1 name * permission1 docstring * permission2 name * permission2 docstring def get_permissions_description(view, method): """ Returns permissions description in format: ### Permissions: * permission1 name ...
Returns validation description in format: ### Validation: validate method docstring * field1 name * field1 validation docstring * field2 name * field2 validation docstring def get_validation_description(view, method): """ Returns validation description in format: ### Validation: ...
Returns field type/possible values. def get_field_type(field): """ Returns field type/possible values. """ if isinstance(field, core_filters.MappedMultipleChoiceFilter): return ' | '.join(['"%s"' % f for f in sorted(field.mapped_to_model)]) if isinstance(field, OrderingFilter) or isinstance...
Checks whether Link action is disabled. def is_disabled_action(view): """ Checks whether Link action is disabled. """ if not isinstance(view, core_views.ActionsViewSet): return False action = getattr(view, 'action', None) return action in view.disabled_actions if action is not None els...
Return a list of the valid HTTP methods for this endpoint. def get_allowed_methods(self, callback): """ Return a list of the valid HTTP methods for this endpoint. """ if hasattr(callback, 'actions'): return [method.upper() for method in callback.actions.keys() if method != '...
Given a callback, return an actual view instance. def create_view(self, callback, method, request=None): """ Given a callback, return an actual view instance. """ view = super(WaldurSchemaGenerator, self).create_view(callback, method, request) if is_disabled_action(view): ...
Determine a link description. This will be based on the method docstring if one exists, or else the class docstring. def get_description(self, path, method, view): """ Determine a link description. This will be based on the method docstring if one exists, or else the c...
Return a list of `coreapi.Field` instances corresponding to any request body input, as determined by the serializer class. def get_serializer_fields(self, path, method, view): """ Return a list of `coreapi.Field` instances corresponding to any request body input, as determined by the se...
Delete error message if instance state changed from erred def delete_error_message(sender, instance, name, source, target, **kwargs): """ Delete error message if instance state changed from erred """ if source != StateMixin.States.ERRED: return instance.error_message = '' instance.save(update_f...
read __init__.py def find_version(*file_paths): """ read __init__.py """ file_path = os.path.join(*file_paths) with open(file_path, 'r') as version_file: line = version_file.readline() while line: if line.startswith('__version__'): version_match = re.sear...
This decorator prints entry and exit message when the decorated method is called, as well as call arguments, result and thrown exception (if any). :param enter: indicates whether entry message should be printed. :param exit: indicates whether exit message should be printed. :return: decorated funct...
Instantiates an enum with an arbitrary value. def _make_value(self, value): """Instantiates an enum with an arbitrary value.""" member = self.__new__(self, value) member.__init__(value) return member
Creates a new enum type based on this one (cls) and adds newly passed members to the newly created subclass of cls. This method helps to create enums having the same member values as values of other enum(s). :param name: name of the newly created type :param members: 1) a dict ...
Parses an enum member name or value into an enum member. Accepts the following types: - Members of this enum class. These are returned directly. - Integers. If there is an enum member with the integer as a value, that member is returned. - Strings. If there is an enum member with the st...
Parses a flag integer or string into a Flags instance. Accepts the following types: - Members of this enum class. These are returned directly. - Integers. These are converted directly into a Flags instance with the given name. - Strings. The function accepts a comma-delimited list of fl...
To get a list of price estimates, run **GET** against */api/price-estimates/* as authenticated user. You can filter price estimates by scope type, scope URL, customer UUID. `scope_type` is generic type of object for which price estimate is calculated. Currently there are following types: custom...
To get a list of price list items, run **GET** against */api/price-list-items/* as an authenticated user. def list(self, request, *args, **kwargs): """ To get a list of price list items, run **GET** against */api/price-list-items/* as an authenticated user. """ return super(PriceListIte...
Run **POST** request against */api/price-list-items/* to create new price list item. Customer owner and staff can create price items. Example of request: .. code-block:: http POST /api/price-list-items/ HTTP/1.1 Content-Type: application/json Accept: applic...
Run **PATCH** request against */api/price-list-items/<uuid>/* to update price list item. Only item_type, key value and units can be updated. Only customer owner and staff can update price items. def update(self, request, *args, **kwargs): """ Run **PATCH** request against */api/price-li...
Run **DELETE** request against */api/price-list-items/<uuid>/* to delete price list item. Only customer owner and staff can delete price items. def destroy(self, request, *args, **kwargs): """ Run **DELETE** request against */api/price-list-items/<uuid>/* to delete price list item. Only...
To get a list of default price list items, run **GET** against */api/default-price-list-items/* as authenticated user. Price lists can be filtered by: - ?key=<string> - ?item_type=<string> has to be from list of available item_types (available options: 'flavor', 'storage', ...
To get a list of price list items, run **GET** against */api/merged-price-list-items/* as authenticated user. If service is not specified default price list items are displayed. Otherwise service specific price list items are displayed. In this case rendered object contains {"is_manuall...
A remote notebook finder. Place a `*` into a url to generalize the finder. It returns a context manager def Remote(path=None, loader=Notebook, **globals): """A remote notebook finder. Place a `*` into a url to generalize the finder. It returns a context manager """ class Remote(RemoteMixin, lo...
Get permission checks that will be executed for current action. def get_permission_checks(self, request, view): """ Get permission checks that will be executed for current action. """ if view.action is None: return [] # if permissions are defined for view directly - ...
Registers the function to the server's default fixed function manager. def add_function(self, function): """ Registers the function to the server's default fixed function manager. """ #noinspection PyTypeChecker if not len(self.settings.FUNCTION_MANAGERS): raise Conf...
When ElasticSearch analyzes string, it breaks it into parts. In order make query for not-analyzed exact string values, we should use subfield instead. The index template for Elasticsearch 5.0 has been changed. The subfield for string multi-fields has changed from .raw to .keyword Thus workaround for b...
Creates a decorator function that applies the decorator_cls that was passed in. def decorate(decorator_cls, *args, **kwargs): """Creates a decorator function that applies the decorator_cls that was passed in.""" global _wrappers wrapper_cls = _wrappers.get(decorator_cls, None) if wrapper_cls is None: ...
States that method is deprecated. :param replacement_description: Describes what must be used instead. :return: the original method with modified docstring. def deprecated(replacement_description): """States that method is deprecated. :param replacement_description: Describes what must be used instea...
Decorator that can convert the result of a function call. def convert_result(converter): """Decorator that can convert the result of a function call.""" def decorate(fn): @inspection.wraps(fn) def new_fn(*args, **kwargs): return converter(fn(*args, **kwargs)) return new_fn...
Decorator for retrying a function if it throws an exception. :param exception_cls: an exception type or a parenthesized tuple of exception types :param max_tries: maximum number of times this function can be executed. Must be at least 1. :param sleep: number of seconds to sleep between function retries de...
Converts a context manager into a decorator. This decorator will run the decorated function in the context of the manager. :param ctxt: Context to run the function in. :return: Wrapper around the original function. def decorator_of_context_manager(ctxt): """Converts a context manager into a decor...
A helper function, gets standard information from the error. def get_error(self, error): """ A helper function, gets standard information from the error. """ error_type = type(error) if error.error_type == ET_CLIENT: error_type_name = 'Client' else: ...
Get error messages about object and his ancestor quotas that will be exceeded if quota_delta will be added. raise_exception - if True QuotaExceededException will be raised if validation fails quota_deltas - dictionary of quotas deltas, example: { 'ram': 1024, 'storage': ...
Return dictionary with sum of all scopes' quotas. Dictionary format: { 'quota_name1': 'sum of limits for quotas with such quota_name1', 'quota_name1_usage': 'sum of usages for quotas with such quota_name1', ... } All `scopes` have to be instances of t...
To get a list of events - run **GET** against */api/events/* as authenticated user. Note that a user can only see events connected to objects she is allowed to see. Sorting is supported in ascending and descending order by specifying a field to an **?o=** parameter. By default events are sorted...
To get a count of events - run **GET** against */api/events/count/* as authenticated user. Endpoint support same filters as events list. Response example: .. code-block:: javascript {"count": 12321} def count(self, request, *args, **kwargs): """ To get a count of ...
To get a historical data of events amount - run **GET** against */api/events/count/history/*. Endpoint support same filters as events list. More about historical data - read at section *Historical data*. Response example: .. code-block:: javascript [ { ...
Returns a list of scope types acceptable by events filter. def scope_types(self, request, *args, **kwargs): """ Returns a list of scope types acceptable by events filter. """ return response.Response(utils.get_scope_types_mapping().keys())
To get a list of alerts, run **GET** against */api/alerts/* as authenticated user. Alert severity field can take one of this values: "Error", "Warning", "Info", "Debug". Field scope will contain link to object that cause alert. Context - dictionary that contains information about all related to...