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 /api/projects/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
def destroy(self, request, *args, **kwargs):
"""
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 /api/projects/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
"""
return super(ProjectViewSet, self).destroy(request, *args, **kwargs)
|
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.
filter_backend = filters.UserConcatenatedNameOrderingBackend()
queryset = filter_backend.filter_queryset(request, queryset, self)
queryset = self.paginate_queryset(queryset)
serializer = self.get_serializer(queryset, many=True)
return self.get_paginated_response(serializer.data)
|
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
using case insensitive partial matching.
Several custom filters are supported:
- ?current - filters out user making a request. Useful for getting information about a currently logged in user.
- ?civil_number=XXX - filters out users with a specified civil number
- ?is_active=True|False - show only active (non-active) users
The user can be created either through automated process on login with SAML token, or through a REST call by a user
with staff privilege.
Example of a creation request is below.
.. code-block:: http
POST /api/users/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"username": "sample-user",
"full_name": "full name",
"native_name": "taisnimi",
"job_title": "senior cleaning manager",
"email": "example@example.com",
"civil_number": "12121212",
"phone_number": "",
"description": "",
"organization": "",
}
NB! Username field is case-insensitive. So "John" and "john" will be treated as the same user.
def list(self, request, *args, **kwargs):
"""
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
using case insensitive partial matching.
Several custom filters are supported:
- ?current - filters out user making a request. Useful for getting information about a currently logged in user.
- ?civil_number=XXX - filters out users with a specified civil number
- ?is_active=True|False - show only active (non-active) users
The user can be created either through automated process on login with SAML token, or through a REST call by a user
with staff privilege.
Example of a creation request is below.
.. code-block:: http
POST /api/users/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"username": "sample-user",
"full_name": "full name",
"native_name": "taisnimi",
"job_title": "senior cleaning manager",
"email": "example@example.com",
"civil_number": "12121212",
"phone_number": "",
"description": "",
"organization": "",
}
NB! Username field is case-insensitive. So "John" and "john" will be treated as the same user.
"""
return super(UserViewSet, self).list(request, *args, **kwargs)
|
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_name
- job_title
- phone_number
- email
Can be done by **PUT**ing a new data to the user URI, i.e. */api/users/<UUID>/* by staff user or account owner.
Valid request example (token is user specific):
.. code-block:: http
PUT /api/users/e0c058d06864441fb4f1c40dee5dd4fd/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"email": "example@example.com",
"organization": "Bells organization",
}
def retrieve(self, request, *args, **kwargs):
"""
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_name
- job_title
- phone_number
- email
Can be done by **PUT**ing a new data to the user URI, i.e. */api/users/<UUID>/* by staff user or account owner.
Valid request example (token is user specific):
.. code-block:: http
PUT /api/users/e0c058d06864441fb4f1c40dee5dd4fd/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"email": "example@example.com",
"organization": "Bells organization",
}
"""
return super(UserViewSet, self).retrieve(request, *args, **kwargs)
|
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:
.. code-block:: http
POST /api/users/e0c058d06864441fb4f1c40dee5dd4fd/password/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"password": "nQvqHzeP123",
}
def password(self, request, uuid=None):
"""
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:
.. code-block:: http
POST /api/users/e0c058d06864441fb4f1c40dee5dd4fd/password/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"password": "nQvqHzeP123",
}
"""
user = self.get_object()
serializer = serializers.PasswordSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
new_password = serializer.validated_data['password']
user.set_password(new_password)
user.save()
return Response({'detail': _('Password has been successfully updated.')},
status=status.HTTP_200_OK)
|
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 customer owners and staff users.
To list all visible permissions, run a **GET** query against a list.
Response will contain a list of project users and their brief data.
To add a new user to the project, **POST** a new relationship to */api/project-permissions/* endpoint specifying
project, user and the role of the user ('admin' or 'manager'):
.. code-block:: http
POST /api/project-permissions/ HTTP/1.1
Accept: application/json
Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b
Host: example.com
{
"project": "http://example.com/api/projects/6c9b01c251c24174a6691a1f894fae31/",
"role": "manager",
"user": "http://example.com/api/users/82cec6c8e0484e0ab1429412fe4194b7/"
}
def list(self, request, *args, **kwargs):
"""
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 customer owners and staff users.
To list all visible permissions, run a **GET** query against a list.
Response will contain a list of project users and their brief data.
To add a new user to the project, **POST** a new relationship to */api/project-permissions/* endpoint specifying
project, user and the role of the user ('admin' or 'manager'):
.. code-block:: http
POST /api/project-permissions/ HTTP/1.1
Accept: application/json
Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b
Host: example.com
{
"project": "http://example.com/api/projects/6c9b01c251c24174a6691a1f894fae31/",
"role": "manager",
"user": "http://example.com/api/users/82cec6c8e0484e0ab1429412fe4194b7/"
}
"""
return super(ProjectPermissionViewSet, self).list(request, *args, **kwargs)
|
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: example.com
def destroy(self, request, *args, **kwargs):
"""
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: example.com
"""
return super(ProjectPermissionViewSet, self).destroy(request, *args, **kwargs)
|
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 add a new user to the customer, **POST** a new relationship to **customer-permissions** endpoint:
.. code-block:: http
POST /api/customer-permissions/ HTTP/1.1
Accept: application/json
Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b
Host: example.com
{
"customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/",
"role": "owner",
"user": "http://example.com/api/users/82cec6c8e0484e0ab1429412fe4194b7/"
}
def list(self, request, *args, **kwargs):
"""
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 add a new user to the customer, **POST** a new relationship to **customer-permissions** endpoint:
.. code-block:: http
POST /api/customer-permissions/ HTTP/1.1
Accept: application/json
Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b
Host: example.com
{
"customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/",
"role": "owner",
"user": "http://example.com/api/users/82cec6c8e0484e0ab1429412fe4194b7/"
}
"""
return super(CustomerPermissionViewSet, self).list(request, *args, **kwargs)
|
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
Host: example.com
def retrieve(self, request, *args, **kwargs):
"""
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
Host: example.com
"""
return super(CustomerPermissionViewSet, self).retrieve(request, *args, **kwargs)
|
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 have to be in answer (default: 6)
Answer will be list of datapoints(dictionaries).
Each datapoint will contain fields: 'to', 'from', 'value'.
'Value' - count of objects, that were created between 'from' and 'to' dates.
Example:
.. code-block:: javascript
[
{"to": 471970877, "from": 1, "value": 5},
{"to": 943941753, "from": 471970877, "value": 0},
{"to": 1415912629, "from": 943941753, "value": 3}
]
def list(self, request, *args, **kwargs):
"""
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 have to be in answer (default: 6)
Answer will be list of datapoints(dictionaries).
Each datapoint will contain fields: 'to', 'from', 'value'.
'Value' - count of objects, that were created between 'from' and 'to' dates.
Example:
.. code-block:: javascript
[
{"to": 471970877, "from": 1, "value": 5},
{"to": 943941753, "from": 471970877, "value": 0},
{"to": 1415912629, "from": 943941753, "value": 3}
]
"""
return super(CreationTimeStatsView, self).list(request, *args, **kwargs)
|
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
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "ssh_public_key1",
"public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDURXDP5YhOQUYoDuTxJ84DuzqMJYJqJ8+SZT28
TtLm5yBDRLKAERqtlbH2gkrQ3US58gd2r8H9jAmQOydfvgwauxuJUE4eDpaMWupqquMYsYLB5f+vVGhdZbbzfc6DTQ2rY
dknWoMoArlG7MvRMA/xQ0ye1muTv+mYMipnd7Z+WH0uVArYI9QBpqC/gpZRRIouQ4VIQIVWGoT6M4Kat5ZBXEa9yP+9du
D2C05GX3gumoSAVyAcDHn/xgej9pYRXGha4l+LKkFdGwAoXdV1z79EG1+9ns7wXuqMJFHM2KDpxAizV0GkZcojISvDwuh
vEAFdOJcqjyyH4FOGYa8usP1 jhon@example.com",
}
def list(self, request, *args, **kwargs):
"""
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
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "ssh_public_key1",
"public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDURXDP5YhOQUYoDuTxJ84DuzqMJYJqJ8+SZT28
TtLm5yBDRLKAERqtlbH2gkrQ3US58gd2r8H9jAmQOydfvgwauxuJUE4eDpaMWupqquMYsYLB5f+vVGhdZbbzfc6DTQ2rY
dknWoMoArlG7MvRMA/xQ0ye1muTv+mYMipnd7Z+WH0uVArYI9QBpqC/gpZRRIouQ4VIQIVWGoT6M4Kat5ZBXEa9yP+9du
D2C05GX3gumoSAVyAcDHn/xgej9pYRXGha4l+LKkFdGwAoXdV1z79EG1+9ns7wXuqMJFHM2KDpxAizV0GkZcojISvDwuh
vEAFdOJcqjyyH4FOGYa8usP1 jhon@example.com",
}
"""
return super(SshKeyViewSet, self).list(request, *args, **kwargs)
|
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, DigitalOcean, Amazon, JIRA, GitLab, Oracle
- ?state=<state> - choices: New, Creation Scheduled, Creating, Sync Scheduled, Syncing, In Sync, Erred
- ?shared=<bool> - allows to filter shared service settings
def list(self, request, *args, **kwargs):
"""
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, DigitalOcean, Amazon, JIRA, GitLab, Oracle
- ?state=<state> - choices: New, Creation Scheduled, Creating, Sync Scheduled, Syncing, In Sync, Erred
- ?shared=<bool> - allows to filter shared service settings
"""
return super(ServiceSettingsViewSet, self).list(request, *args, **kwargs)
|
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/17] clean it up after WAL-634. Clean up service settings update tests as well.
if obj.customer and not obj.shared:
return permissions.is_owner(request, view, obj)
else:
return permissions.is_staff(request, view, obj)
|
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
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"username": "admin",
"password": "new_secret"
}
def update(self, request, *args, **kwargs):
"""
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
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"username": "admin",
"password": "new_secret"
}
"""
return super(ServiceSettingsViewSet, self).update(request, *args, **kwargs)
|
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 vCPUs
* ram - total size of memory for allocation (from hypervisors)
* ram_quota - maximum number of memory (from quotas)
* ram_usage - currently used memory size on all physical hosts
* storage - total available disk space on all physical hosts (from hypervisors)
* storage_quota - maximum number of storage (from quotas)
* storage_usage - currently used storage on all physical hosts
{
'vcpu': 10,
'vcpu_quota': 7,
'vcpu_usage': 5,
'ram': 1000,
'ram_quota': 700,
'ram_usage': 500,
'storage': 10000,
'storage_quota': 7000,
'storage_usage': 5000
}
def stats(self, request, uuid=None):
"""
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 vCPUs
* ram - total size of memory for allocation (from hypervisors)
* ram_quota - maximum number of memory (from quotas)
* ram_usage - currently used memory size on all physical hosts
* storage - total available disk space on all physical hosts (from hypervisors)
* storage_quota - maximum number of storage (from quotas)
* storage_usage - currently used storage on all physical hosts
{
'vcpu': 10,
'vcpu_quota': 7,
'vcpu_usage': 5,
'ram': 1000,
'ram_quota': 700,
'ram_usage': 500,
'storage': 10000,
'storage_quota': 7000,
'storage_usage': 5000
}
"""
service_settings = self.get_object()
backend = service_settings.get_backend()
try:
stats = backend.get_stats()
except ServiceBackendNotImplemented:
stats = {}
return Response(stats, status=status.HTTP_200_OK)
|
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 sort resource by ?o=ram, but SugarCRM crms
will ignore this ordering, because they do not support such option.
Filter resources by type or category
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
There are two query argument to select resources by their type.
- Specify explicitly list of resource types, for example:
/api/<resource_endpoint>/?resource_type=DigitalOcean.Droplet&resource_type=OpenStack.Instance
- Specify category, one of vms, apps, private_clouds or storages for example:
/api/<resource_endpoint>/?category=vms
Filtering by monitoring fields
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Resources may have SLA attached to it. Example rendering of SLA:
.. code-block:: javascript
"sla": {
"value": 95.0
"agreed_value": 99.0,
"period": "2016-03"
}
You may filter or order resources by SLA. Default period is current year and month.
- Example query for filtering list of resources by actual SLA:
/api/<resource_endpoint>/?actual_sla=90&period=2016-02
- Warning! If resource does not have SLA attached to it, it is not included in ordered response.
Example query for ordering list of resources by actual SLA:
/api/<resource_endpoint>/?o=actual_sla&period=2016-02
Service list is displaying current SLAs for each of the items. By default,
SLA period is set to the current month. To change the period pass it as a query argument:
- ?period=YYYY-MM - return a list with SLAs for a given month
- ?period=YYYY - return a list with SLAs for a given year
In all cases all currently running resources are returned, if SLA for the given period is
not known or not present, it will be shown as **null** in the response.
Resources may have monitoring items attached to it. Example rendering of monitoring items:
.. code-block:: javascript
"monitoring_items": {
"application_state": 1
}
You may filter or order resources by monitoring item.
- Example query for filtering list of resources by installation state:
/api/<resource_endpoint>/?monitoring__installation_state=1
- Warning! If resource does not have monitoring item attached to it, it is not included in ordered response.
Example query for ordering list of resources by installation state:
/api/<resource_endpoint>/?o=monitoring__installation_state
Filtering by tags
^^^^^^^^^^^^^^^^^
Resource may have tags attached to it. Example of tags rendering:
.. code-block:: javascript
"tags": [
"license-os:centos7",
"os-family:linux",
"license-application:postgresql",
"support:premium"
]
Tags filtering:
- ?tag=IaaS - filter by full tag name, using method OR. Can be list.
- ?rtag=os-family:linux - filter by full tag name, using AND method. Can be list.
- ?tag__license-os=centos7 - filter by tags with particular prefix.
Tags ordering:
- ?o=tag__license-os - order by tag with particular prefix. Instances without given tag will not be returned.
def list(self, request, *args, **kwargs):
"""
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 sort resource by ?o=ram, but SugarCRM crms
will ignore this ordering, because they do not support such option.
Filter resources by type or category
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
There are two query argument to select resources by their type.
- Specify explicitly list of resource types, for example:
/api/<resource_endpoint>/?resource_type=DigitalOcean.Droplet&resource_type=OpenStack.Instance
- Specify category, one of vms, apps, private_clouds or storages for example:
/api/<resource_endpoint>/?category=vms
Filtering by monitoring fields
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Resources may have SLA attached to it. Example rendering of SLA:
.. code-block:: javascript
"sla": {
"value": 95.0
"agreed_value": 99.0,
"period": "2016-03"
}
You may filter or order resources by SLA. Default period is current year and month.
- Example query for filtering list of resources by actual SLA:
/api/<resource_endpoint>/?actual_sla=90&period=2016-02
- Warning! If resource does not have SLA attached to it, it is not included in ordered response.
Example query for ordering list of resources by actual SLA:
/api/<resource_endpoint>/?o=actual_sla&period=2016-02
Service list is displaying current SLAs for each of the items. By default,
SLA period is set to the current month. To change the period pass it as a query argument:
- ?period=YYYY-MM - return a list with SLAs for a given month
- ?period=YYYY - return a list with SLAs for a given year
In all cases all currently running resources are returned, if SLA for the given period is
not known or not present, it will be shown as **null** in the response.
Resources may have monitoring items attached to it. Example rendering of monitoring items:
.. code-block:: javascript
"monitoring_items": {
"application_state": 1
}
You may filter or order resources by monitoring item.
- Example query for filtering list of resources by installation state:
/api/<resource_endpoint>/?monitoring__installation_state=1
- Warning! If resource does not have monitoring item attached to it, it is not included in ordered response.
Example query for ordering list of resources by installation state:
/api/<resource_endpoint>/?o=monitoring__installation_state
Filtering by tags
^^^^^^^^^^^^^^^^^
Resource may have tags attached to it. Example of tags rendering:
.. code-block:: javascript
"tags": [
"license-os:centos7",
"os-family:linux",
"license-application:postgresql",
"support:premium"
]
Tags filtering:
- ?tag=IaaS - filter by full tag name, using method OR. Can be list.
- ?rtag=os-family:linux - filter by full tag name, using AND method. Can be list.
- ?tag__license-os=centos7 - filter by tags with particular prefix.
Tags ordering:
- ?o=tag__license-os - order by tag with particular prefix. Instances without given tag will not be returned.
"""
return super(ResourceSummaryViewSet, self).list(request, *args, **kwargs)
|
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.Group": 8
}
def count(self, request):
"""
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.Group": 8
}
"""
queryset = self.filter_queryset(self.get_queryset())
return Response({SupportedServices.get_name_for_model(qs.model): qs.count()
for qs in queryset.querysets})
|
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
^^^^^^^^^^^^^^^^^^^^^^^
It is possible to filter services by their types. Example:
/api/services/?service_type=DigitalOcean&service_type=OpenStack
"""
return super(ServicesViewSet, self).list(request, *args, **kwargs)
|
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, issue a **POST** to specific endpoint from a list above as a customer owner.
Individual endpoint used for every service type.
You can create service based on shared service settings. Example:
.. code-block:: http
POST /api/digitalocean/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "Common DigitalOcean",
"customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/",
"settings": "http://example.com/api/service-settings/93ba615d6111466ebe3f792669059cb4/"
}
Or provide your own credentials. Example:
.. code-block:: http
POST /api/oracle/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "My Oracle",
"customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/",
"backend_url": "https://oracle.example.com:7802/em",
"username": "admin",
"password": "secret"
}
def list(self, request, *args, **kwargs):
"""
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, issue a **POST** to specific endpoint from a list above as a customer owner.
Individual endpoint used for every service type.
You can create service based on shared service settings. Example:
.. code-block:: http
POST /api/digitalocean/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "Common DigitalOcean",
"customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/",
"settings": "http://example.com/api/service-settings/93ba615d6111466ebe3f792669059cb4/"
}
Or provide your own credentials. Example:
.. code-block:: http
POST /api/oracle/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "My Oracle",
"customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/",
"backend_url": "https://oracle.example.com:7802/em",
"username": "admin",
"password": "secret"
}
"""
return super(BaseServiceViewSet, self).list(request, *args, **kwargs)
|
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 and not request.user.is_staff:
raise PermissionDenied(_('Only staff users are allowed to import resources from shared services.'))
|
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 with resource id.
.. code-block:: http
POST /api/openstack/08039f01c9794efc912f1689f4530cf0/link/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"backend_id": "bd5ec24d-9164-440b-a9f2-1b3c807c5df3",
"project": "http://example.com/api/projects/e5f973af2eb14d2d8c38d62bcbaccb33/"
}
def link(self, request, uuid=None):
"""
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 with resource id.
.. code-block:: http
POST /api/openstack/08039f01c9794efc912f1689f4530cf0/link/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"backend_id": "bd5ec24d-9164-440b-a9f2-1b3c807c5df3",
"project": "http://example.com/api/projects/e5f973af2eb14d2d8c38d62bcbaccb33/"
}
"""
service = self.get_object()
if self.request.method == 'GET':
try:
backend = self.get_backend(service)
try:
resources = backend.get_resources_for_import(**self.get_import_context())
except ServiceBackendNotImplemented:
resources = []
page = self.paginate_queryset(resources)
if page is not None:
return self.get_paginated_response(page)
return Response(resources)
except (ServiceBackendError, ValidationError) as e:
raise APIException(e)
else:
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
try:
resource = serializer.save()
except ServiceBackendError as e:
raise APIException(e)
resource_imported.send(
sender=resource.__class__,
instance=resource,
)
return Response(serializer.data, status=status.HTTP_200_OK)
|
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(service)
return Response(status=status.HTTP_204_NO_CONTENT)
|
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 automatically.
Otherwise, in order to be able to provision resources, service must first be linked to a project.
To do that, **POST** a connection between project and a service to service_project_link_url
as stuff user or customer owner.
def list(self, request, *args, **kwargs):
"""
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 automatically.
Otherwise, in order to be able to provision resources, service must first be linked to a project.
To do that, **POST** a connection between project and a service to service_project_link_url
as stuff user or customer owner.
"""
return super(BaseServiceProjectLinkViewSet, self).list(request, *args, **kwargs)
|
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(BaseServiceProjectLinkViewSet, self).retrieve(request, *args, **kwargs)
|
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 = []
for ancestor in ancestors:
for ancestor_quota_field in ancestor.get_quotas_fields(field_class=AggregatorQuotaField):
if ancestor_quota_field.get_child_quota_name() == quota.name:
aggregator_quotas.append(ancestor.quotas.get(name=ancestor_quota_field))
return 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, *args):
"""*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.
"""
error = None
# iterate over a copy of the original list because some event handlers
# may mutate the list
for handler in list(self.handlers):
try:
handler(*args)
except BaseException as e:
if error is None:
prepare_for_reraise(e)
error = e
if error is not None:
reraise(error)
|
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.
@return: self, so calls like this can be chained together.
def on(self, event, handler):
"""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.
@return: self, so calls like this can be chained together.
"""
event_hook = self.get_or_create(event)
event_hook.subscribe(handler)
return self
|
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.
@return: self, so calls like this can be chained together.
def off(self, 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.
@return: self, so calls like this can be chained together.
"""
event_hook = self.get_or_create(event)
event_hook.unsubscribe(handler)
return self
|
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 arguments.
@return: self, so calls like this can be chained together.
def trigger(self, event, *args):
"""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 arguments.
@return: self, so calls like this can be chained together.
"""
event_hook = self.get_or_create(event)
event_hook.trigger(*args)
return self
|
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.
@param args: event arguments.
@return: self, so calls like this can be chained together.
def safe_trigger(self, event, *args):
"""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.
@param args: event arguments.
@return: self, so calls like this can be chained together.
"""
event_hook = self.get_or_create(event)
event_hook.safe_trigger(*args)
return self
|
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,
so you can pass enum members there as well.
def get_or_create(self, event):
"""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,
so you can pass enum members there as well.
"""
if isinstance(event, EnumBase):
event = event.short_name
return self.__dict__.setdefault(event, EventHook())
|
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 settings with parameter
"INVITATION_LIFETIME". If invitation creation time is less than expiration time, the invitation will set as expired.
"""
expiration_date = timezone.now() - settings.WALDUR_CORE['INVITATION_LIFETIME']
if not invitations:
invitations = models.Invitation.objects.filter(state=models.Invitation.State.PENDING)
invitations = invitations.filter(created__lte=expiration_date)
invitations.update(state=models.Invitation.State.EXPIRED)
|
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 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
"""
sighash = Utils.bytes_to_str(s[:4])
for pseudo_abi in FourByteDirectory.get_pseudo_abi_for_sighash(sighash, timeout=timeout, proxies=proxies):
types = [ti["type"] for ti in pseudo_abi['inputs']]
try:
# test decoding
_ = decode_abi(types, s[4:])
yield pseudo_abi
except eth_abi.exceptions.DecodingError as e:
continue
|
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
:return:
"""
self.signatures = {}
for element_description in jsonabi:
abi_e = AbiMethod(element_description)
if abi_e["type"] == "constructor":
self.signatures[b"__constructor__"] = abi_e
elif abi_e["type"] == "fallback":
abi_e.setdefault("inputs", [])
self.signatures[b"__fallback__"] = abi_e
elif abi_e["type"] == "function":
# function and signature present
# todo: we could generate the sighash ourselves? requires keccak256
if abi_e.get("signature"):
self.signatures[Utils.str_to_bytes(abi_e["signature"])] = abi_e
elif abi_e["type"] == "event":
self.signatures[b"__event__"] = abi_e
else:
raise Exception("Invalid abi type: %s - %s - %s" % (abi_e.get("type"),
element_description, abi_e))
|
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 loaded contract
abi definition
:param s: bytes constructor arguments
:return: AbiMethod instance
"""
method = self.signatures.get(b"__constructor__")
if not method:
# constructor not available
m = AbiMethod({"type": "constructor", "name": "", "inputs": [], "outputs": []})
return m
types_def = method["inputs"]
types = [t["type"] for t in types_def]
names = [t["name"] for t in types_def]
if not len(s):
values = len(types) * ["<nA>"]
else:
values = decode_abi(types, s)
# (type, name, data)
method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list(
zip(types, names, values))]
return method
|
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: AbiMethod instance
"""
signatures = self.signatures.items()
for sighash, method in signatures:
if sighash is None or sighash.startswith(b"__"):
continue # skip constructor
if s.startswith(sighash):
s = s[len(sighash):]
types_def = self.signatures.get(sighash)["inputs"]
types = [t["type"] for t in types_def]
names = [t["name"] for t in types_def]
if not len(s):
values = len(types) * ["<nA>"]
else:
values = decode_abi(types, s)
# (type, name, data)
method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list(
zip(types, names, values))]
return method
else:
method = AbiMethod({"type": "fallback",
"name": "__fallback__",
"inputs": [], "outputs": []})
types_def = self.signatures.get(b"__fallback__", {"inputs": []})["inputs"]
types = [t["type"] for t in types_def]
names = [t["name"] for t in types_def]
values = decode_abi(types, s)
# (type, name, data)
method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list(
zip(types, names, values))]
return method
|
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 object matching the provided input stream
"""
for pseudo_abi in FourByteDirectory.get_pseudo_abi_for_input(s):
method = AbiMethod(pseudo_abi)
types_def = pseudo_abi["inputs"]
types = [t["type"] for t in types_def]
names = [t["name"] for t in types_def]
values = decode_abi(types, s[4:])
# (type, name, data)
method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list(
zip(types, names, values))]
return method
|
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", extra
)
|
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):
"""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.
"""
if tolerance is None:
assert expected == actual, _assert_fail_message(
message, expected, actual, "!=", extra
)
else:
assert isinstance(tolerance, _number_types), (
"tolerance parameter to assert_eq must be a number: %r" % tolerance
)
assert isinstance(expected, _number_types) and isinstance(
actual, _number_types
), (
"parameters must be numbers when tolerance is specified: %r, %r"
% (expected, actual)
)
diff = abs(expected - actual)
assert diff <= tolerance, _assert_fail_message(
message, expected, actual, "is more than %r away from" % tolerance, extra
)
|
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(actual, dict)
expected_keys = set(expected.keys())
actual_keys = set(actual.keys())
assert expected_keys <= actual_keys, "Actual dict at %s is missing keys: %r" % (
_dict_path_string(dict_path),
expected_keys - actual_keys,
)
assert actual_keys <= expected_keys, "Actual dict at %s has extra keys: %r" % (
_dict_path_string(dict_path),
actual_keys - expected_keys,
)
for k in expected_keys:
key_path = dict_path + [k]
assert_is_instance(
actual[k],
type(expected[k]),
extra="Types don't match for %s" % _dict_path_string(key_path),
)
assert_is_instance(
expected[k],
type(actual[k]),
extra="Types don't match for %s" % _dict_path_string(key_path),
)
if isinstance(actual[k], dict):
assert_dict_eq(
expected[k],
actual[k],
number_tolerance=number_tolerance,
dict_path=key_path,
)
elif isinstance(actual[k], _number_types):
assert_eq(
expected[k],
actual[k],
extra="Value doesn't match for %s" % _dict_path_string(key_path),
tolerance=number_tolerance,
)
else:
assert_eq(
expected[k],
actual[k],
extra="Value doesn't match for %s" % _dict_path_string(key_path),
)
|
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)
start_index = index - 50
if start_index > 0:
truncated = "(truncated) ..."
else:
truncated = ""
start_index = 0
end_index = index + len(obj) + 50
truncated += seq[start_index:end_index]
if end_index < len(seq):
truncated += "... (truncated)"
assert False, _assert_fail_message(message, obj, truncated, "is in", extra)
assert obj not in seq, _assert_fail_message(message, obj, seq, "is in", extra)
|
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, extra=extra)
return
except AssertionError:
pass
assert False, _assert_fail_message(message, obj, seq, "is not in", extra)
|
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.find(substring) != -1)
), _assert_fail_message(message, substring, subject, "is not in", extra)
|
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(substring) == -1)
), _assert_fail_message(message, substring, subject, "is in", extra)
|
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):
"""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.
"""
missing_in_actual = []
missing_in_expected = list(actual)
for x in expected:
try:
missing_in_expected.remove(x)
except ValueError:
missing_in_actual.append(x)
if missing_in_actual or missing_in_expected:
if not message:
message = (
"%r not equal to %r; missing items: %r in expected, %r in actual."
% (expected, actual, missing_in_expected, missing_in_actual)
)
assert False, message
|
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 NOT
search_text : string
Text for FTS(full text search)
start, end : datetime
Filter for event creation time
def prepare_search_body(self, should_terms=None, must_terms=None, must_not_terms=None, search_text='', start=None, end=None):
"""
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 NOT
search_text : string
Text for FTS(full text search)
start, end : datetime
Filter for event creation time
"""
self.body = self.SearchBody()
self.body.set_should_terms(should_terms)
self.body.set_must_terms(must_terms)
self.body.set_must_not_terms(must_not_terms)
self.body.set_search_text(search_text)
self.body.set_timestamp_filter(start, end)
self.body.prepare()
|
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,
is_heavy_task=is_heavy_task, **kwargs)
cls.post_apply(instance, async=async, **kwargs)
return result
|
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, serialized_instance, **kwargs)
link = cls.get_success_signature(instance, serialized_instance, **kwargs)
link_error = cls.get_failure_signature(instance, serialized_instance, **kwargs)
if async:
return signature.apply_async(link=link, link_error=link_error, countdown=countdown,
queue=is_heavy_task and 'heavy' or None)
else:
result = signature.apply()
callback = link if not result.failed() else link_error
if callback is not None:
cls._apply_callback(callback, result)
return result.get()
|
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:
# entity is a class instance
entity_name = entity.__class__.__name__
label = '* %s' % formatting.camelcase_to_spaces(entity_name)
if entity.__doc__ is not None:
entity_docstring = formatting.dedent(smart_text(entity.__doc__)).replace('\n', '\n\t')
return '%s\n * %s' % (label, entity_docstring)
return label
|
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 docstring
* validator2 name
* validator2 docstring
"""
action = getattr(view, 'action', None)
if action is None:
return ''
description = ''
validators = getattr(view, action + '_validators', [])
for validator in validators:
validator_description = get_entity_description(validator)
description += '\n' + validator_description if description else validator_description
return '### Validators:\n' + description if description else ''
|
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 docstring
* permission2 name
* permission2 docstring
"""
action = getattr(view, 'action', None)
if action is None:
return ''
if hasattr(view, action + '_permissions'):
permission_types = (action,)
elif method in SAFE_METHODS:
permission_types = ('safe_methods', '%s_extra' % action)
else:
permission_types = ('unsafe_methods', '%s_extra' % action)
description = ''
for permission_type in permission_types:
action_perms = getattr(view, permission_type + '_permissions', [])
for permission in action_perms:
action_perm_description = get_entity_description(permission)
description += '\n' + action_perm_description if description else action_perm_description
return description
|
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
* permission1 docstring
* permission2 name
* permission2 docstring
"""
if not hasattr(view, 'permission_classes'):
return ''
description = ''
for permission_class in view.permission_classes:
if permission_class == core_permissions.ActionsPermission:
actions_perm_description = get_actions_permission_description(view, method)
if actions_perm_description:
description += '\n' + actions_perm_description if description else actions_perm_description
continue
perm_description = get_entity_description(permission_class)
description += '\n' + perm_description if description else perm_description
return '### Permissions:\n' + description if description else ''
|
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:
validate method docstring
* field1 name
* field1 validation docstring
* field2 name
* field2 validation docstring
"""
if method not in ('PUT', 'PATCH', 'POST') or not hasattr(view, 'get_serializer'):
return ''
serializer = view.get_serializer()
description = ''
if hasattr(serializer, 'validate') and serializer.validate.__doc__ is not None:
description += formatting.dedent(smart_text(serializer.validate.__doc__))
for field in serializer.fields.values():
if not hasattr(serializer, 'validate_' + field.field_name):
continue
field_validation = getattr(serializer, 'validate_' + field.field_name)
if field_validation.__doc__ is not None:
docstring = formatting.dedent(smart_text(field_validation.__doc__)).replace('\n', '\n\t')
field_description = '* %s\n * %s' % (field.field_name, docstring)
description += '\n' + field_description if description else field_description
return '### Validation:\n' + description if description else ''
|
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(field, ChoiceFilter):
return ' | '.join(['"%s"' % f[0] for f in field.extra['choices']])
if isinstance(field, ChoiceField):
return ' | '.join(['"%s"' % f for f in sorted(field.choices)])
if isinstance(field, HyperlinkedRelatedField):
if field.view_name.endswith('detail'):
return 'link to %s' % reverse(field.view_name,
kwargs={'%s' % field.lookup_field: "'%s'" % field.lookup_field})
return reverse(field.view_name)
if isinstance(field, structure_filters.ServiceTypeFilter):
return ' | '.join(['"%s"' % f for f in SupportedServices.get_filter_mapping().keys()])
if isinstance(field, ResourceTypeFilter):
return ' | '.join(['"%s"' % f for f in SupportedServices.get_resource_models().keys()])
if isinstance(field, core_serializers.GenericRelatedField):
links = []
for model in field.related_models:
detail_view_name = core_utils.get_detail_view_name(model)
for f in field.lookup_fields:
try:
link = reverse(detail_view_name, kwargs={'%s' % f: "'%s'" % f})
except NoReverseMatch:
pass
else:
links.append(link)
break
path = ', '.join(links)
if path:
return 'link to any: %s' % path
if isinstance(field, core_filters.ContentTypeFilter):
return "string in form 'app_label'.'model_name'"
if isinstance(field, ModelMultipleChoiceFilter):
return get_field_type(field.field)
if isinstance(field, ListSerializer):
return 'list of [%s]' % get_field_type(field.child)
if isinstance(field, ManyRelatedField):
return 'list of [%s]' % get_field_type(field.child_relation)
if isinstance(field, ModelField):
return get_field_type(field.model_field)
name = field.__class__.__name__
for w in ('Filter', 'Field', 'Serializer'):
name = name.replace(w, '')
return FIELDS.get(name, name)
|
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 else False
|
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 != 'head']
return [
method for method in
callback.cls().allowed_methods if method not in ('OPTIONS', 'HEAD')
]
|
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):
view.exclude_from_schema = True
return 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 class docstring.
"""
description = super(WaldurSchemaGenerator, self).get_description(path, method, view)
permissions_description = get_permissions_description(view, method)
if permissions_description:
description += '\n\n' + permissions_description if description else permissions_description
if isinstance(view, core_views.ActionsViewSet):
validators_description = get_validators_description(view)
if validators_description:
description += '\n\n' + validators_description if description else validators_description
validation_description = get_validation_description(view, method)
if validation_description:
description += '\n\n' + validation_description if description else validation_description
return description
|
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 serializer class.
"""
if method not in ('PUT', 'PATCH', 'POST'):
return []
if not hasattr(view, 'get_serializer'):
return []
serializer = view.get_serializer()
if not isinstance(serializer, Serializer):
return []
fields = []
for field in serializer.fields.values():
if field.read_only or isinstance(field, HiddenField):
continue
required = field.required and method != 'PATCH'
description = force_text(field.help_text) if field.help_text else ''
field_type = get_field_type(field)
description += '; ' + field_type if description else field_type
field = coreapi.Field(
name=field.field_name,
location='form',
required=required,
description=description,
schema=schemas.field_to_schema(field),
)
fields.append(field)
return fields
|
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_fields=['error_message'])
|
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.search(
r"^__version__ = ['\"]([^'\"]*)['\"]",
line,
re.M
)
if version_match:
return version_match.group(1)
line = version_file.readline()
raise RuntimeError('Unable to find version string.')
|
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 function.
def trace(enter=False, exit=True):
"""
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 function.
"""
def decorate(fn):
@inspection.wraps(fn)
def new_fn(*args, **kwargs):
name = fn.__module__ + "." + fn.__name__
if enter:
print(
"%s(args = %s, kwargs = %s) <-" % (name, repr(args), repr(kwargs))
)
try:
result = fn(*args, **kwargs)
if exit:
print(
"%s(args = %s, kwargs = %s) -> %s"
% (name, repr(args), repr(kwargs), repr(result))
)
return result
except Exception as e:
if exit:
print(
"%s(args = %s, kwargs = %s) -> thrown %s"
% (name, repr(args), repr(kwargs), str(e))
)
raise
return new_fn
return decorate
|
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 or 2) a list of (name, value) tuples
and/or EnumBase instances describing new members
:return: newly created enum type.
def create(cls, name, members):
"""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 or 2) a list of (name, value) tuples
and/or EnumBase instances describing new members
:return: newly created enum type.
"""
NewEnum = type(name, (cls,), {})
if isinstance(members, dict):
members = members.items()
for member in members:
if isinstance(member, tuple):
name, value = member
setattr(NewEnum, name, value)
elif isinstance(member, EnumBase):
setattr(NewEnum, member.short_name, member.value)
else:
assert False, (
"members must be either a dict, "
+ "a list of (name, value) tuples, "
+ "or a list of EnumBase instances."
)
NewEnum.process()
# needed for pickling to work (hopefully); taken from the namedtuple implementation in the
# standard library
try:
NewEnum.__module__ = sys._getframe(1).f_globals.get("__name__", "__main__")
except (AttributeError, ValueError):
pass
return NewEnum
|
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 string as its name, that member is returned.
For integers and strings that don't correspond to an enum member, default is returned; if
no default is given the function raises KeyError instead.
Examples:
>>> class Color(Enum):
... red = 1
... blue = 2
>>> Color.parse(Color.red)
Color.red
>>> Color.parse(1)
Color.red
>>> Color.parse('blue')
Color.blue
def parse(cls, value, default=_no_default):
"""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 string as its name, that member is returned.
For integers and strings that don't correspond to an enum member, default is returned; if
no default is given the function raises KeyError instead.
Examples:
>>> class Color(Enum):
... red = 1
... blue = 2
>>> Color.parse(Color.red)
Color.red
>>> Color.parse(1)
Color.red
>>> Color.parse('blue')
Color.blue
"""
if isinstance(value, cls):
return value
elif isinstance(value, six.integer_types) and not isinstance(value, EnumBase):
e = cls._value_to_member.get(value, _no_default)
else:
e = cls._name_to_member.get(value, _no_default)
if e is _no_default or not e.is_valid():
if default is _no_default:
raise _create_invalid_value_error(cls, value)
return default
return e
|
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 flag names, corresponding to
members of the enum. These are all ORed together.
Examples:
>>> class Car(Flags):
... is_big = 1
... has_wheels = 2
>>> Car.parse(1)
Car.is_big
>>> Car.parse(3)
Car.parse('has_wheels,is_big')
>>> Car.parse('is_big,has_wheels')
Car.parse('has_wheels,is_big')
def parse(cls, value, default=_no_default):
"""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 flag names, corresponding to
members of the enum. These are all ORed together.
Examples:
>>> class Car(Flags):
... is_big = 1
... has_wheels = 2
>>> Car.parse(1)
Car.is_big
>>> Car.parse(3)
Car.parse('has_wheels,is_big')
>>> Car.parse('is_big,has_wheels')
Car.parse('has_wheels,is_big')
"""
if isinstance(value, cls):
return value
elif isinstance(value, int):
e = cls._make_value(value)
else:
if not value:
e = cls._make_value(0)
else:
r = 0
for k in value.split(","):
v = cls._name_to_member.get(k, _no_default)
if v is _no_default:
if default is _no_default:
raise _create_invalid_value_error(cls, value)
else:
return default
r |= v.value
e = cls._make_value(r)
if not e.is_valid():
if default is _no_default:
raise _create_invalid_value_error(cls, value)
return default
return e
|
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: customer, project, service, serviceprojectlink, resource.
`date` parameter accepts list of dates. `start` and `end` parameters together specify date range.
Each valid date should in format YYYY.MM
You can specify GET parameter ?depth to show price estimate children. For example with ?depth=2 customer
price estimate will shows its children - project and service and grandchildren - serviceprojectlink.
def list(self, request, *args, **kwargs):
"""
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: customer, project, service, serviceprojectlink, resource.
`date` parameter accepts list of dates. `start` and `end` parameters together specify date range.
Each valid date should in format YYYY.MM
You can specify GET parameter ?depth to show price estimate children. For example with ?depth=2 customer
price estimate will shows its children - project and service and grandchildren - serviceprojectlink.
"""
return super(PriceEstimateViewSet, self).list(request, *args, **kwargs)
|
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(PriceListItemViewSet, self).list(request, *args, **kwargs)
|
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: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"units": "per month",
"value": 100,
"service": "http://example.com/api/oracle/d4060812ca5d4de390e0d7a5062d99f6/",
"default_price_list_item": "http://example.com/api/default-price-list-items/349d11e28f634f48866089e41c6f71f1/"
}
def create(self, request, *args, **kwargs):
"""
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: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"units": "per month",
"value": 100,
"service": "http://example.com/api/oracle/d4060812ca5d4de390e0d7a5062d99f6/",
"default_price_list_item": "http://example.com/api/default-price-list-items/349d11e28f634f48866089e41c6f71f1/"
}
"""
return super(PriceListItemViewSet, self).create(request, *args, **kwargs)
|
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-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.
"""
return super(PriceListItemViewSet, self).update(request, *args, **kwargs)
|
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 customer owner and staff can delete price items.
"""
return super(PriceListItemViewSet, self).destroy(request, *args, **kwargs)
|
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', 'license-os', 'license-application', 'network', 'support')
- ?resource_type=<string> resource type, for example: 'OpenStack.Instance, 'Oracle.Database')
def list(self, request, *args, **kwargs):
"""
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', 'license-os', 'license-application', 'network', 'support')
- ?resource_type=<string> resource type, for example: 'OpenStack.Instance, 'Oracle.Database')
"""
return super(DefaultPriceListItemViewSet, self).list(request, *args, **kwargs)
|
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_manually_input": true}
In order to specify service pass query parameters:
- service_type (Azure, OpenStack etc.)
- service_uuid
Example URL: http://example.com/api/merged-price-list-items/?service_type=Azure&service_uuid=cb658b491f3644a092dd223e894319be
def list(self, request, *args, **kwargs):
"""
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_manually_input": true}
In order to specify service pass query parameters:
- service_type (Azure, OpenStack etc.)
- service_uuid
Example URL: http://example.com/api/merged-price-list-items/?service_type=Azure&service_uuid=cb658b491f3644a092dd223e894319be
"""
return super(MergedPriceListItemViewSet, self).list(request, *args, **kwargs)
|
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, loader):
...
return Remote(path=path, **globals)
|
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 - use them.
if hasattr(view, view.action + '_permissions'):
return getattr(view, view.action + '_permissions')
# otherwise return view-level permissions + extra view permissions
extra_permissions = getattr(view, view.action + 'extra_permissions', [])
if request.method in SAFE_METHODS:
return getattr(view, 'safe_methods_permissions', []) + extra_permissions
else:
return getattr(view, 'unsafe_methods_permissions', []) + extra_permissions
|
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 ConfigurationError(
'Where have the default function manager gone?!')
self.settings.FUNCTION_MANAGERS[0].add_function(function)
|
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 backward compatibility during migration is required.
See also: https://github.com/elastic/logstash/blob/v5.4.1/docs/static/breaking-changes.asciidoc
def format_raw_field(key):
"""
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 backward compatibility during migration is required.
See also: https://github.com/elastic/logstash/blob/v5.4.1/docs/static/breaking-changes.asciidoc
"""
subfield = django_settings.WALDUR_CORE.get('ELASTICSEARCH', {}).get('raw_subfield', 'keyword')
return '%s.%s' % (camel_case_to_underscore(key), subfield)
|
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:
class PythonWrapper(decorator_cls):
pass
wrapper_cls = PythonWrapper
wrapper_cls.__name__ = decorator_cls.__name__ + "PythonWrapper"
_wrappers[decorator_cls] = wrapper_cls
def decorator(fn):
wrapped = wrapper_cls(fn, *args, **kwargs)
_update_wrapper(wrapped, fn)
return wrapped
return decorator
|
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 instead.
:return: the original method with modified docstring.
"""
def decorate(fn_or_class):
if isinstance(fn_or_class, type):
pass # Can't change __doc__ of type objects
else:
try:
fn_or_class.__doc__ = "This API point is obsolete. %s\n\n%s" % (
replacement_description,
fn_or_class.__doc__,
)
except AttributeError:
pass # For Cython method descriptors, etc.
return fn_or_class
return decorate
|
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
return decorate
|
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
def retry(exception_cls, max_tries=10, sleep=0.05):
"""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
"""
assert max_tries > 0
def with_max_retries_call(delegate):
for i in xrange(0, max_tries):
try:
return delegate()
except exception_cls:
if i + 1 == max_tries:
raise
time.sleep(sleep)
def outer(fn):
is_generator = inspect.isgeneratorfunction(fn)
@functools.wraps(fn)
def retry_fun(*args, **kwargs):
return with_max_retries_call(lambda: fn(*args, **kwargs))
@functools.wraps(fn)
def retry_generator_fun(*args, **kwargs):
def get_first_item():
results = fn(*args, **kwargs)
for first_result in results:
return [first_result], results
return [], results
cache, generator = with_max_retries_call(get_first_item)
for item in cache:
yield item
for item in generator:
yield item
if not is_generator:
# so that qcore.inspection.get_original_fn can retrieve the original function
retry_fun.fn = fn
# Necessary for pickling of Cythonized functions to work. Cython's __reduce__
# method always returns the original name of the function.
retry_fun.__reduce__ = lambda: fn.__name__
return retry_fun
else:
retry_generator_fun.fn = fn
retry_generator_fun.__reduce__ = lambda: fn.__name__
return retry_generator_fun
return outer
|
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 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_fn(*outer_args, **outer_kwargs):
def decorator(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
with ctxt(*outer_args, **outer_kwargs):
return fn(*args, **kwargs)
return wrapper
return decorator
if getattr(ctxt, "__doc__", None) is None:
msg = "Decorator that runs the inner function in the context of %s"
decorator_fn.__doc__ = msg % ctxt
else:
decorator_fn.__doc__ = ctxt.__doc__
return decorator_fn
|
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:
error_type_name = 'Server'
return {
'type': error_type_name,
'name': error_type.__name__,
'prefix': getattr(error_type, '__module__', ''),
'message': unicode(error),
'params': error.args,
}
|
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': 2048,
...
}
Example of output:
['ram quota limit: 1024, requires: 2048(instance#1)', ...]
def validate_quota_change(self, quota_deltas, raise_exception=False):
"""
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': 2048,
...
}
Example of output:
['ram quota limit: 1024, requires: 2048(instance#1)', ...]
"""
errors = []
for name, delta in six.iteritems(quota_deltas):
quota = self.quotas.get(name=name)
if quota.is_exceeded(delta):
errors.append('%s quota limit: %s, requires %s (%s)\n' % (
quota.name, quota.limit, quota.usage + delta, quota.scope))
if not raise_exception:
return errors
else:
if errors:
raise exceptions.QuotaExceededException(_('One or more quotas were exceeded: %s') % ';'.join(errors))
|
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 the same model.
`fields` keyword argument defines sum of which fields of quotas will present in result.
def get_sum_of_quotas_as_dict(cls, scopes, quota_names=None, fields=['usage', 'limit']):
"""
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 the same model.
`fields` keyword argument defines sum of which fields of quotas will present in result.
"""
if not scopes:
return {}
if quota_names is None:
quota_names = cls.get_quotas_names()
scope_models = set([scope._meta.model for scope in scopes])
if len(scope_models) > 1:
raise exceptions.QuotaError(_('All scopes have to be instances of the same model.'))
filter_kwargs = {
'content_type': ct_models.ContentType.objects.get_for_model(scopes[0]),
'object_id__in': [scope.id for scope in scopes],
'name__in': quota_names
}
result = {}
if 'usage' in fields:
items = Quota.objects.filter(**filter_kwargs)\
.values('name').annotate(usage=Sum('usage'))
for item in items:
result[item['name'] + '_usage'] = item['usage']
if 'limit' in fields:
unlimited_quotas = Quota.objects.filter(limit=-1, **filter_kwargs)
unlimited_quotas = list(unlimited_quotas.values_list('name', flat=True))
for quota_name in unlimited_quotas:
result[quota_name] = -1
items = Quota.objects\
.filter(**filter_kwargs)\
.exclude(name__in=unlimited_quotas)\
.values('name')\
.annotate(limit=Sum('limit'))
for item in items:
result[item['name']] = item['limit']
return result
|
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 by @timestamp in descending order.
Run POST against */api/events/* to create an event. Only users with staff privileges can create events.
New event will be emitted with `custom_notification` event type.
Request should contain following fields:
- level: the level of current event. Following levels are supported: debug, info, warning, error
- message: string representation of event message
- scope: optional URL, which points to the loggable instance
Request example:
.. code-block:: javascript
POST /api/events/
Accept: application/json
Content-Type: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"level": "info",
"message": "message#1",
"scope": "http://example.com/api/customers/9cd869201e1b4158a285427fcd790c1c/"
}
def list(self, request, *args, **kwargs):
"""
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 by @timestamp in descending order.
Run POST against */api/events/* to create an event. Only users with staff privileges can create events.
New event will be emitted with `custom_notification` event type.
Request should contain following fields:
- level: the level of current event. Following levels are supported: debug, info, warning, error
- message: string representation of event message
- scope: optional URL, which points to the loggable instance
Request example:
.. code-block:: javascript
POST /api/events/
Accept: application/json
Content-Type: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"level": "info",
"message": "message#1",
"scope": "http://example.com/api/customers/9cd869201e1b4158a285427fcd790c1c/"
}
"""
self.queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(self.queryset)
if page is not None:
return self.get_paginated_response(page)
return response.Response(self.queryset)
|
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 events - run **GET** against */api/events/count/* as authenticated user.
Endpoint support same filters as events list.
Response example:
.. code-block:: javascript
{"count": 12321}
"""
self.queryset = self.filter_queryset(self.get_queryset())
return response.Response({'count': self.queryset.count()}, status=status.HTTP_200_OK)
|
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
[
{
"point": 141111111111,
"object": {
"count": 558
}
}
]
def count_history(self, request, *args, **kwargs):
"""
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
[
{
"point": 141111111111,
"object": {
"count": 558
}
}
]
"""
queryset = self.filter_queryset(self.get_queryset())
mapped = {
'start': request.query_params.get('start'),
'end': request.query_params.get('end'),
'points_count': request.query_params.get('points_count'),
'point_list': request.query_params.getlist('point'),
}
serializer = core_serializers.HistorySerializer(data={k: v for k, v in mapped.items() if v})
serializer.is_valid(raise_exception=True)
timestamp_ranges = [{'end': point_date} for point_date in serializer.get_filter_data()]
aggregated_count = queryset.aggregated_count(timestamp_ranges)
return response.Response(
[{'point': int(ac['end']), 'object': {'count': ac['count']}} for ac in aggregated_count],
status=status.HTTP_200_OK)
|
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 alert objects.
Alerts can be filtered by:
- ?severity=<severity> (can be list)
- ?alert_type=<alert_type> (can be list)
- ?scope=<url> concrete alert scope
- ?scope_type=<string> name of scope type (Ex.: instance, service_project_link, project...)
DEPRECATED use ?content_type instead
- ?created_from=<timestamp>
- ?created_to=<timestamp>
- ?closed_from=<timestamp>
- ?closed_to=<timestamp>
- ?from=<timestamp> - filter alerts that was active from given date
- ?to=<timestamp> - filter alerts that was active to given date
- ?opened - if this argument is in GET request endpoint will return only alerts that are not closed
- ?closed - if this argument is in GET request endpoint will return only alerts that are closed
- ?aggregate=aggregate_model_name (default: 'customer'. Have to be from list: 'customer', project')
- ?uuid=uuid_of_aggregate_model_object (not required. If this parameter will be defined - result ill contain only
object with given uuid)
- ?acknowledged=True|False - show only acknowledged (non-acknowledged) alerts
- ?content_type=<string> name of scope content type in format <app_name>.<scope_type>
(Ex.: structure.project, openstack.instance...)
- ?exclude_features=<feature> (can be list) - exclude alert from output if it's type corresponds o one of given features
Alerts can be ordered by:
-?o=severity - order by severity
-?o=created - order by creation time
.. code-block:: http
GET /api/alerts/
Accept: application/json
Content-Type: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
[
{
"url": "http://example.com/api/alerts/e80e48a4e58b48ff9a1320a0aa0d68ab/",
"uuid": "e80e48a4e58b48ff9a1320a0aa0d68ab",
"alert_type": "first_alert",
"message": "message#1",
"severity": "Debug",
"scope": "http://example.com/api/instances/9d1d7e03b0d14fd0b42b5f649dfa3de5/",
"created": "2015-05-29T14:24:27.342Z",
"closed": null,
"context": {
'customer_abbreviation': 'customer_abbreviation',
'customer_contact_details': 'customer details',
'customer_name': 'Customer name',
'customer_uuid': '53c6e86406e349faa7924f4c865b15ab',
'quota_limit': '131072.0',
'quota_name': 'ram',
'quota_usage': '131071',
'quota_uuid': 'f6ae2f7ca86f4e2f9bb64de1015a2815',
'scope_name': 'project X',
'scope_uuid': '0238d71ee1934bd2839d4e71e5f9b91a'
}
"acknowledged": true,
}
]
def list(self, request, *args, **kwargs):
"""
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 alert objects.
Alerts can be filtered by:
- ?severity=<severity> (can be list)
- ?alert_type=<alert_type> (can be list)
- ?scope=<url> concrete alert scope
- ?scope_type=<string> name of scope type (Ex.: instance, service_project_link, project...)
DEPRECATED use ?content_type instead
- ?created_from=<timestamp>
- ?created_to=<timestamp>
- ?closed_from=<timestamp>
- ?closed_to=<timestamp>
- ?from=<timestamp> - filter alerts that was active from given date
- ?to=<timestamp> - filter alerts that was active to given date
- ?opened - if this argument is in GET request endpoint will return only alerts that are not closed
- ?closed - if this argument is in GET request endpoint will return only alerts that are closed
- ?aggregate=aggregate_model_name (default: 'customer'. Have to be from list: 'customer', project')
- ?uuid=uuid_of_aggregate_model_object (not required. If this parameter will be defined - result ill contain only
object with given uuid)
- ?acknowledged=True|False - show only acknowledged (non-acknowledged) alerts
- ?content_type=<string> name of scope content type in format <app_name>.<scope_type>
(Ex.: structure.project, openstack.instance...)
- ?exclude_features=<feature> (can be list) - exclude alert from output if it's type corresponds o one of given features
Alerts can be ordered by:
-?o=severity - order by severity
-?o=created - order by creation time
.. code-block:: http
GET /api/alerts/
Accept: application/json
Content-Type: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
[
{
"url": "http://example.com/api/alerts/e80e48a4e58b48ff9a1320a0aa0d68ab/",
"uuid": "e80e48a4e58b48ff9a1320a0aa0d68ab",
"alert_type": "first_alert",
"message": "message#1",
"severity": "Debug",
"scope": "http://example.com/api/instances/9d1d7e03b0d14fd0b42b5f649dfa3de5/",
"created": "2015-05-29T14:24:27.342Z",
"closed": null,
"context": {
'customer_abbreviation': 'customer_abbreviation',
'customer_contact_details': 'customer details',
'customer_name': 'Customer name',
'customer_uuid': '53c6e86406e349faa7924f4c865b15ab',
'quota_limit': '131072.0',
'quota_name': 'ram',
'quota_usage': '131071',
'quota_uuid': 'f6ae2f7ca86f4e2f9bb64de1015a2815',
'scope_name': 'project X',
'scope_uuid': '0238d71ee1934bd2839d4e71e5f9b91a'
}
"acknowledged": true,
}
]
"""
return super(AlertViewSet, self).list(request, *args, **kwargs)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.