From b88a5dd5919a8b8ce2dbfdfce22ef44207665d89 Mon Sep 17 00:00:00 2001 From: Juan Leaniz Date: Thu, 1 Aug 2024 16:36:32 -0500 Subject: [PATCH] Update API client library (#1521) * Update API client library * Update version * Update client library * Revert this change --- .devcontainer/devcontainer.json | 41 +- turbinia/api/client/README.md | 13 +- .../api/client/docs/BaseRequestOptions.md | 2 +- .../api/client/docs/CompleteTurbiniaStats.md | 2 +- .../api/client/docs/HTTPValidationError.md | 2 +- turbinia/api/client/docs/LocationInner.md | 2 +- turbinia/api/client/docs/Request.md | 2 +- .../client/docs/TurbiniaConfigurationApi.md | 70 ++ .../api/client/docs/TurbiniaRequestsApi.md | 74 ++ turbinia/api/client/docs/TurbiniaTasksApi.md | 75 ++ turbinia/api/client/docs/ValidationError.md | 2 +- turbinia/api/client/pyproject.toml | 2 +- .../api/turbinia_configuration_api.py | 596 ++++++---- .../turbinia_api_lib/api/turbinia_jobs_api.py | 161 +-- .../api/turbinia_requests_api.py | 140 +++ .../api/turbinia_tasks_api.py | 141 +++ .../api/client/turbinia_api_lib/api_client.py | 1030 +++++++++-------- .../models/validation_error.py | 113 +- turbinia/api/utils.py | 2 +- 19 files changed, 1591 insertions(+), 879 deletions(-) diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 1e2742e23..06d57f220 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -11,23 +11,26 @@ "postStartCommand": "/etc/init.d/redis-server start", // Set *default* container specific settings.json values on container create. "mounts": ["source=/dev,target=/dev,type=bind"], - "settings": { - "terminal.integrated.shell.linux": "/bin/bash", - "terminal.integrated.env.linux": { - "PYTHONPATH": "${workspaceFolder}", - }, - "python.pythonPath": "/usr/bin/python3", - "python.linting.pylintEnabled": true, - "python.linting.enabled": true, - "editor.formatOnSave": true, - "python.formatting.provider": "yapf", - "python.formatting.yapfArgs": [ - "--style", - "${workspaceRoot}/.style.yapf" - ], - }, - // Add the IDs of extensions you want installed when the container is created. - "extensions": [ - "ms-python.python" - ], + "customizations": { + "vscode": { + "settings": { + "terminal.integrated.shell.linux": "/bin/bash", + "terminal.integrated.env.linux": { + "PYTHONPATH": "${workspaceFolder}", + }, + "python.pythonPath": "/usr/bin/python3", + "python.linting.enabled": true, + "editor.formatOnSave": true, + "python.formatting.provider": "yapf", + "python.formatting.yapfArgs": [ + "--style", + "${workspaceRoot}/.style.yapf" + ] + }, + // Add the IDs of extensions you want installed when the container is created. + "extensions": [ + "ms-python.python" + ] + } + } } \ No newline at end of file diff --git a/turbinia/api/client/README.md b/turbinia/api/client/README.md index 870645146..2e1c6ee90 100644 --- a/turbinia/api/client/README.md +++ b/turbinia/api/client/README.md @@ -5,7 +5,7 @@ This Python package is automatically generated by the [OpenAPI Generator](https: - API version: 1.0.0 - Package version: 1.0.0 -- Generator version: 7.4.0 +- Generator version: 7.7.0 - Build package: org.openapitools.codegen.languages.PythonPydanticV1ClientCodegen ## Requirements. @@ -76,12 +76,12 @@ with turbinia_api_lib.ApiClient(configuration) as api_client: api_instance = turbinia_api_lib.TurbiniaConfigurationApi(api_client) try: - # Get Request Options - api_response = api_instance.get_request_options() - print("The response of TurbiniaConfigurationApi->get_request_options:\n") + # Download Configuration + api_response = api_instance.download_config() + print("The response of TurbiniaConfigurationApi->download_config:\n") pprint(api_response) except ApiException as e: - print("Exception when calling TurbiniaConfigurationApi->get_request_options: %s\n" % e) + print("Exception when calling TurbiniaConfigurationApi->download_config: %s\n" % e) ``` @@ -91,6 +91,7 @@ All URIs are relative to *http://localhost* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*TurbiniaConfigurationApi* | [**download_config**](docs/TurbiniaConfigurationApi.md#download_config) | **GET** /api/config/download | Download Configuration *TurbiniaConfigurationApi* | [**get_request_options**](docs/TurbiniaConfigurationApi.md#get_request_options) | **GET** /api/config/request_options | Get Request Options *TurbiniaConfigurationApi* | [**get_version**](docs/TurbiniaConfigurationApi.md#get_version) | **GET** /api/config/version | Get Version *TurbiniaConfigurationApi* | [**read_config**](docs/TurbiniaConfigurationApi.md#read_config) | **GET** /api/config/ | Read Config @@ -106,8 +107,10 @@ Class | Method | HTTP request | Description *TurbiniaRequestResultsApi* | [**get_request_output**](docs/TurbiniaRequestResultsApi.md#get_request_output) | **GET** /api/result/request/{request_id} | Get Request Output *TurbiniaRequestResultsApi* | [**get_task_output**](docs/TurbiniaRequestResultsApi.md#get_task_output) | **GET** /api/result/task/{task_id} | Get Task Output *TurbiniaRequestsApi* | [**create_request**](docs/TurbiniaRequestsApi.md#create_request) | **POST** /api/request/ | Create Request +*TurbiniaRequestsApi* | [**get_request_report**](docs/TurbiniaRequestsApi.md#get_request_report) | **GET** /api/request/report/{request_id} | Get Request Markdown Report *TurbiniaRequestsApi* | [**get_request_status**](docs/TurbiniaRequestsApi.md#get_request_status) | **GET** /api/request/{request_id} | Get Request Status *TurbiniaRequestsApi* | [**get_requests_summary**](docs/TurbiniaRequestsApi.md#get_requests_summary) | **GET** /api/request/summary | Get Requests Summary +*TurbiniaTasksApi* | [**get_task_report**](docs/TurbiniaTasksApi.md#get_task_report) | **GET** /api/task/report/{task_id} | Get Task Report *TurbiniaTasksApi* | [**get_task_statistics**](docs/TurbiniaTasksApi.md#get_task_statistics) | **GET** /api/task/statistics | Get Task Statistics *TurbiniaTasksApi* | [**get_task_status**](docs/TurbiniaTasksApi.md#get_task_status) | **GET** /api/task/{task_id} | Get Task Status *TurbiniaTasksApi* | [**get_workers_status**](docs/TurbiniaTasksApi.md#get_workers_status) | **GET** /api/task/workers | Get Workers Status diff --git a/turbinia/api/client/docs/BaseRequestOptions.md b/turbinia/api/client/docs/BaseRequestOptions.md index 3b9d63f9c..ed6d1e91b 100644 --- a/turbinia/api/client/docs/BaseRequestOptions.md +++ b/turbinia/api/client/docs/BaseRequestOptions.md @@ -32,7 +32,7 @@ print BaseRequestOptions.to_json() # convert the object into a dict base_request_options_dict = base_request_options_instance.to_dict() # create an instance of BaseRequestOptions from a dict -base_request_options_form_dict = base_request_options.from_dict(base_request_options_dict) +base_request_options_from_dict = BaseRequestOptions.from_dict(base_request_options_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/turbinia/api/client/docs/CompleteTurbiniaStats.md b/turbinia/api/client/docs/CompleteTurbiniaStats.md index dcf5a37fd..115330388 100644 --- a/turbinia/api/client/docs/CompleteTurbiniaStats.md +++ b/turbinia/api/client/docs/CompleteTurbiniaStats.md @@ -28,7 +28,7 @@ print CompleteTurbiniaStats.to_json() # convert the object into a dict complete_turbinia_stats_dict = complete_turbinia_stats_instance.to_dict() # create an instance of CompleteTurbiniaStats from a dict -complete_turbinia_stats_form_dict = complete_turbinia_stats.from_dict(complete_turbinia_stats_dict) +complete_turbinia_stats_from_dict = CompleteTurbiniaStats.from_dict(complete_turbinia_stats_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/turbinia/api/client/docs/HTTPValidationError.md b/turbinia/api/client/docs/HTTPValidationError.md index 2ada76450..97b9fe03f 100644 --- a/turbinia/api/client/docs/HTTPValidationError.md +++ b/turbinia/api/client/docs/HTTPValidationError.md @@ -21,7 +21,7 @@ print HTTPValidationError.to_json() # convert the object into a dict http_validation_error_dict = http_validation_error_instance.to_dict() # create an instance of HTTPValidationError from a dict -http_validation_error_form_dict = http_validation_error.from_dict(http_validation_error_dict) +http_validation_error_from_dict = HTTPValidationError.from_dict(http_validation_error_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/turbinia/api/client/docs/LocationInner.md b/turbinia/api/client/docs/LocationInner.md index 6fa987f6e..899fb2138 100644 --- a/turbinia/api/client/docs/LocationInner.md +++ b/turbinia/api/client/docs/LocationInner.md @@ -20,7 +20,7 @@ print LocationInner.to_json() # convert the object into a dict location_inner_dict = location_inner_instance.to_dict() # create an instance of LocationInner from a dict -location_inner_form_dict = location_inner.from_dict(location_inner_dict) +location_inner_from_dict = LocationInner.from_dict(location_inner_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/turbinia/api/client/docs/Request.md b/turbinia/api/client/docs/Request.md index 5f1cd59a9..a23b2a5f6 100644 --- a/turbinia/api/client/docs/Request.md +++ b/turbinia/api/client/docs/Request.md @@ -24,7 +24,7 @@ print Request.to_json() # convert the object into a dict request_dict = request_instance.to_dict() # create an instance of Request from a dict -request_form_dict = request.from_dict(request_dict) +request_from_dict = Request.from_dict(request_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/turbinia/api/client/docs/TurbiniaConfigurationApi.md b/turbinia/api/client/docs/TurbiniaConfigurationApi.md index d9394966a..f99333e04 100644 --- a/turbinia/api/client/docs/TurbiniaConfigurationApi.md +++ b/turbinia/api/client/docs/TurbiniaConfigurationApi.md @@ -4,11 +4,81 @@ All URIs are relative to *http://localhost* Method | HTTP request | Description ------------- | ------------- | ------------- +[**download_config**](TurbiniaConfigurationApi.md#download_config) | **GET** /api/config/download | Download Configuration [**get_request_options**](TurbiniaConfigurationApi.md#get_request_options) | **GET** /api/config/request_options | Get Request Options [**get_version**](TurbiniaConfigurationApi.md#get_version) | **GET** /api/config/version | Get Version [**read_config**](TurbiniaConfigurationApi.md#read_config) | **GET** /api/config/ | Read Config +# **download_config** +> str download_config() + +Download Configuration + +Downloads the Turbinia configuration. + +### Example + +* OAuth Authentication (oAuth2): +```python +import time +import os +import turbinia_api_lib +from turbinia_api_lib.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = turbinia_api_lib.Configuration( + host = "http://localhost" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +configuration.access_token = os.environ["ACCESS_TOKEN"] + +# Enter a context with an instance of the API client +with turbinia_api_lib.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = turbinia_api_lib.TurbiniaConfigurationApi(api_client) + + try: + # Download Configuration + api_response = api_instance.download_config() + print("The response of TurbiniaConfigurationApi->download_config:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling TurbiniaConfigurationApi->download_config: %s\n" % e) +``` + + + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**str** + +### Authorization + +[oAuth2](../README.md#oAuth2) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/text + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful Response | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **get_request_options** > object get_request_options() diff --git a/turbinia/api/client/docs/TurbiniaRequestsApi.md b/turbinia/api/client/docs/TurbiniaRequestsApi.md index d51cc1555..df382bb84 100644 --- a/turbinia/api/client/docs/TurbiniaRequestsApi.md +++ b/turbinia/api/client/docs/TurbiniaRequestsApi.md @@ -5,6 +5,7 @@ All URIs are relative to *http://localhost* Method | HTTP request | Description ------------- | ------------- | ------------- [**create_request**](TurbiniaRequestsApi.md#create_request) | **POST** /api/request/ | Create Request +[**get_request_report**](TurbiniaRequestsApi.md#get_request_report) | **GET** /api/request/report/{request_id} | Get Request Markdown Report [**get_request_status**](TurbiniaRequestsApi.md#get_request_status) | **GET** /api/request/{request_id} | Get Request Status [**get_requests_summary**](TurbiniaRequestsApi.md#get_requests_summary) | **GET** /api/request/summary | Get Requests Summary @@ -84,6 +85,79 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **get_request_report** +> str get_request_report(request_id) + +Get Request Markdown Report + +Retrieves the markdown report for a Turbinia Request. Args: request (Request): FastAPI request object. request_id (str): A Turbinia request identifier. Raises: HTTPException: if another exception is caught. + +### Example + +* OAuth Authentication (oAuth2): +```python +import time +import os +import turbinia_api_lib +from turbinia_api_lib.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = turbinia_api_lib.Configuration( + host = "http://localhost" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +configuration.access_token = os.environ["ACCESS_TOKEN"] + +# Enter a context with an instance of the API client +with turbinia_api_lib.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = turbinia_api_lib.TurbiniaRequestsApi(api_client) + request_id = 'request_id_example' # str | + + try: + # Get Request Markdown Report + api_response = api_instance.get_request_report(request_id) + print("The response of TurbiniaRequestsApi->get_request_report:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling TurbiniaRequestsApi->get_request_report: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **request_id** | **str**| | + +### Return type + +**str** + +### Authorization + +[oAuth2](../README.md#oAuth2) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/text + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful Response | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **get_request_status** > object get_request_status(request_id) diff --git a/turbinia/api/client/docs/TurbiniaTasksApi.md b/turbinia/api/client/docs/TurbiniaTasksApi.md index e687d6b92..3f729c81b 100644 --- a/turbinia/api/client/docs/TurbiniaTasksApi.md +++ b/turbinia/api/client/docs/TurbiniaTasksApi.md @@ -4,11 +4,86 @@ All URIs are relative to *http://localhost* Method | HTTP request | Description ------------- | ------------- | ------------- +[**get_task_report**](TurbiniaTasksApi.md#get_task_report) | **GET** /api/task/report/{task_id} | Get Task Report [**get_task_statistics**](TurbiniaTasksApi.md#get_task_statistics) | **GET** /api/task/statistics | Get Task Statistics [**get_task_status**](TurbiniaTasksApi.md#get_task_status) | **GET** /api/task/{task_id} | Get Task Status [**get_workers_status**](TurbiniaTasksApi.md#get_workers_status) | **GET** /api/task/workers | Get Workers Status +# **get_task_report** +> object get_task_report(task_id) + +Get Task Report + +Retrieves the MarkDown report of a Turbinia task. Raises: HTTPException: if another exception is caught. + +### Example + +* OAuth Authentication (oAuth2): +```python +import time +import os +import turbinia_api_lib +from turbinia_api_lib.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = turbinia_api_lib.Configuration( + host = "http://localhost" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +configuration.access_token = os.environ["ACCESS_TOKEN"] + +# Enter a context with an instance of the API client +with turbinia_api_lib.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = turbinia_api_lib.TurbiniaTasksApi(api_client) + task_id = 'task_id_example' # str | + + try: + # Get Task Report + api_response = api_instance.get_task_report(task_id) + print("The response of TurbiniaTasksApi->get_task_report:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling TurbiniaTasksApi->get_task_report: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **task_id** | **str**| | + +### Return type + +**object** + +### Authorization + +[oAuth2](../README.md#oAuth2) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful Response | - | +**422** | Validation Error | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **get_task_statistics** > CompleteTurbiniaStats get_task_statistics(days=days, task_id=task_id, request_id=request_id, user=user) diff --git a/turbinia/api/client/docs/ValidationError.md b/turbinia/api/client/docs/ValidationError.md index f5748dac9..685426bed 100644 --- a/turbinia/api/client/docs/ValidationError.md +++ b/turbinia/api/client/docs/ValidationError.md @@ -23,7 +23,7 @@ print ValidationError.to_json() # convert the object into a dict validation_error_dict = validation_error_instance.to_dict() # create an instance of ValidationError from a dict -validation_error_form_dict = validation_error.from_dict(validation_error_dict) +validation_error_from_dict = ValidationError.from_dict(validation_error_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/turbinia/api/client/pyproject.toml b/turbinia/api/client/pyproject.toml index fe9200497..274e6c2b8 100644 --- a/turbinia/api/client/pyproject.toml +++ b/turbinia/api/client/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "turbinia-api-lib" -version = "1.0.4" +version = "1.0.5" description = "Turbinia API Server" authors = ["OpenAPI Generator Community "] license = "Apache License 2.0" diff --git a/turbinia/api/client/turbinia_api_lib/api/turbinia_configuration_api.py b/turbinia/api/client/turbinia_api_lib/api/turbinia_configuration_api.py index 7e7aeb5f9..e3d09a536 100644 --- a/turbinia/api/client/turbinia_api_lib/api/turbinia_configuration_api.py +++ b/turbinia/api/client/turbinia_api_lib/api/turbinia_configuration_api.py @@ -11,6 +11,7 @@ Do not edit the class manually. """ # noqa: E501 + import re # noqa: F401 import io import warnings @@ -19,6 +20,7 @@ from typing import Any + from turbinia_api_lib.api_client import ApiClient from turbinia_api_lib.api_response import ApiResponse from turbinia_api_lib.exceptions import ( # noqa: F401 @@ -28,20 +30,152 @@ class TurbiniaConfigurationApi: - """NOTE: This class is auto generated by OpenAPI Generator + """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ - def __init__(self, api_client=None) -> None: - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + @validate_arguments + def download_config(self, **kwargs) -> str: # noqa: E501 + """Download Configuration # noqa: E501 + + Downloads the Turbinia configuration. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.download_config(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: str + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the download_config_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.download_config_with_http_info(**kwargs) # noqa: E501 + + @validate_arguments + def download_config_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """Download Configuration # noqa: E501 + + Downloads the Turbinia configuration. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.download_config_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) + """ - @validate_arguments - def get_request_options(self, **kwargs) -> object: # noqa: E501 - """Get Request Options # noqa: E501 + _params = locals() + + _all_params = [ + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method download_config" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/text']) # noqa: E501 + + # authentication setting + _auth_settings = ['oAuth2'] # noqa: E501 + + _response_types_map = { + '200': "str", + } + + return self.api_client.call_api( + '/api/config/download', 'GET', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + + @validate_arguments + def get_request_options(self, **kwargs) -> object: # noqa: E501 + """Get Request Options # noqa: E501 Returns a list BaseRequestOptions attributes. # noqa: E501 This method makes a synchronous HTTP request by default. To make an @@ -61,16 +195,15 @@ def get_request_options(self, **kwargs) -> object: # noqa: E501 returns the request thread. :rtype: object """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the get_request_options_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.get_request_options_with_http_info(**kwargs) # noqa: E501 + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the get_request_options_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.get_request_options_with_http_info(**kwargs) # noqa: E501 - @validate_arguments - def get_request_options_with_http_info( - self, **kwargs) -> ApiResponse: # noqa: E501 - """Get Request Options # noqa: E501 + @validate_arguments + def get_request_options_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """Get Request Options # noqa: E501 Returns a list BaseRequestOptions attributes. # noqa: E501 This method makes a synchronous HTTP request by default. To make an @@ -104,70 +237,77 @@ def get_request_options_with_http_info( :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ - _params = locals() - - _all_params = [] - _all_params.extend([ - 'async_req', '_return_http_data_only', '_preload_content', - '_request_timeout', '_request_auth', '_content_type', '_headers' - ]) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_request_options" % _key) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['oAuth2'] # noqa: E501 - - _response_types_map = { - '200': "object", - } - - return self.api_client.call_api( - '/api/config/request_options', - 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get( - '_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def get_version(self, **kwargs) -> object: # noqa: E501 - """Get Version # noqa: E501 + _params = locals() + + _all_params = [ + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method get_request_options" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # authentication setting + _auth_settings = ['oAuth2'] # noqa: E501 + + _response_types_map = { + '200': "object", + } + + return self.api_client.call_api( + '/api/config/request_options', 'GET', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + + @validate_arguments + def get_version(self, **kwargs) -> object: # noqa: E501 + """Get Version # noqa: E501 Returns the Turbinia version. # noqa: E501 This method makes a synchronous HTTP request by default. To make an @@ -187,15 +327,15 @@ def get_version(self, **kwargs) -> object: # noqa: E501 returns the request thread. :rtype: object """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the get_version_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.get_version_with_http_info(**kwargs) # noqa: E501 + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the get_version_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.get_version_with_http_info(**kwargs) # noqa: E501 - @validate_arguments - def get_version_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 - """Get Version # noqa: E501 + @validate_arguments + def get_version_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """Get Version # noqa: E501 Returns the Turbinia version. # noqa: E501 This method makes a synchronous HTTP request by default. To make an @@ -229,70 +369,77 @@ def get_version_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ - _params = locals() - - _all_params = [] - _all_params.extend([ - 'async_req', '_return_http_data_only', '_preload_content', - '_request_timeout', '_request_auth', '_content_type', '_headers' - ]) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_version" % _key) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['oAuth2'] # noqa: E501 - - _response_types_map = { - '200': "object", - } - - return self.api_client.call_api( - '/api/config/version', - 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get( - '_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_arguments - def read_config(self, **kwargs) -> object: # noqa: E501 - """Read Config # noqa: E501 + _params = locals() + + _all_params = [ + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method get_version" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # authentication setting + _auth_settings = ['oAuth2'] # noqa: E501 + + _response_types_map = { + '200': "object", + } + + return self.api_client.call_api( + '/api/config/version', 'GET', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + + @validate_arguments + def read_config(self, **kwargs) -> object: # noqa: E501 + """Read Config # noqa: E501 Retrieve turbinia config. # noqa: E501 This method makes a synchronous HTTP request by default. To make an @@ -312,15 +459,15 @@ def read_config(self, **kwargs) -> object: # noqa: E501 returns the request thread. :rtype: object """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the read_config_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.read_config_with_http_info(**kwargs) # noqa: E501 + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the read_config_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.read_config_with_http_info(**kwargs) # noqa: E501 - @validate_arguments - def read_config_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 - """Read Config # noqa: E501 + @validate_arguments + def read_config_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """Read Config # noqa: E501 Retrieve turbinia config. # noqa: E501 This method makes a synchronous HTTP request by default. To make an @@ -354,63 +501,70 @@ def read_config_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ - _params = locals() - - _all_params = [] - _all_params.extend([ - 'async_req', '_return_http_data_only', '_preload_content', - '_request_timeout', '_request_auth', '_content_type', '_headers' - ]) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method read_config" % _key) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['oAuth2'] # noqa: E501 - - _response_types_map = { - '200': "object", - } - - return self.api_client.call_api( - '/api/config/', - 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get( - '_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _params = locals() + + _all_params = [ + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method read_config" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # authentication setting + _auth_settings = ['oAuth2'] # noqa: E501 + + _response_types_map = { + '200': "object", + } + + return self.api_client.call_api( + '/api/config/', 'GET', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) diff --git a/turbinia/api/client/turbinia_api_lib/api/turbinia_jobs_api.py b/turbinia/api/client/turbinia_api_lib/api/turbinia_jobs_api.py index 58078351b..0d205f640 100644 --- a/turbinia/api/client/turbinia_api_lib/api/turbinia_jobs_api.py +++ b/turbinia/api/client/turbinia_api_lib/api/turbinia_jobs_api.py @@ -11,6 +11,7 @@ Do not edit the class manually. """ # noqa: E501 + import re # noqa: F401 import io import warnings @@ -19,6 +20,7 @@ from typing import Any + from turbinia_api_lib.api_client import ApiClient from turbinia_api_lib.api_response import ApiResponse from turbinia_api_lib.exceptions import ( # noqa: F401 @@ -28,20 +30,20 @@ class TurbiniaJobsApi: - """NOTE: This class is auto generated by OpenAPI Generator + """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ - def __init__(self, api_client=None) -> None: - if api_client is None: - api_client = ApiClient.get_default() - self.api_client = api_client + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client - @validate_arguments - def read_jobs(self, **kwargs) -> object: # noqa: E501 - """Read Jobs # noqa: E501 + @validate_arguments + def read_jobs(self, **kwargs) -> object: # noqa: E501 + """Read Jobs # noqa: E501 Return enabled jobs from the current Turbinia config. # noqa: E501 This method makes a synchronous HTTP request by default. To make an @@ -61,15 +63,15 @@ def read_jobs(self, **kwargs) -> object: # noqa: E501 returns the request thread. :rtype: object """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the read_jobs_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.read_jobs_with_http_info(**kwargs) # noqa: E501 + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the read_jobs_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.read_jobs_with_http_info(**kwargs) # noqa: E501 - @validate_arguments - def read_jobs_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 - """Read Jobs # noqa: E501 + @validate_arguments + def read_jobs_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """Read Jobs # noqa: E501 Return enabled jobs from the current Turbinia config. # noqa: E501 This method makes a synchronous HTTP request by default. To make an @@ -103,63 +105,70 @@ def read_jobs_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ - _params = locals() - - _all_params = [] - _all_params.extend([ - 'async_req', '_return_http_data_only', '_preload_content', - '_request_timeout', '_request_auth', '_content_type', '_headers' - ]) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method read_jobs" % _key) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats = {} - - # process the path parameters - _path_params = {} - - # process the query parameters - _query_params = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params = [] - _files = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings = ['oAuth2'] # noqa: E501 - - _response_types_map = { - '200': "object", - } - - return self.api_client.call_api( - '/api/jobs/', - 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, - response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get( - '_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _params = locals() + + _all_params = [ + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method read_jobs" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # authentication setting + _auth_settings = ['oAuth2'] # noqa: E501 + + _response_types_map = { + '200': "object", + } + + return self.api_client.call_api( + '/api/jobs/', 'GET', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) diff --git a/turbinia/api/client/turbinia_api_lib/api/turbinia_requests_api.py b/turbinia/api/client/turbinia_api_lib/api/turbinia_requests_api.py index a53f9bdb0..217abcbb2 100644 --- a/turbinia/api/client/turbinia_api_lib/api/turbinia_requests_api.py +++ b/turbinia/api/client/turbinia_api_lib/api/turbinia_requests_api.py @@ -192,6 +192,146 @@ def create_request_with_http_info(self, request : Request, **kwargs) -> ApiRespo collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + @validate_arguments + def get_request_report(self, request_id : StrictStr, **kwargs) -> str: # noqa: E501 + """Get Request Markdown Report # noqa: E501 + + Retrieves the markdown report for a Turbinia Request. Args: request (Request): FastAPI request object. request_id (str): A Turbinia request identifier. Raises: HTTPException: if another exception is caught. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.get_request_report(request_id, async_req=True) + >>> result = thread.get() + + :param request_id: (required) + :type request_id: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: str + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the get_request_report_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.get_request_report_with_http_info(request_id, **kwargs) # noqa: E501 + + @validate_arguments + def get_request_report_with_http_info(self, request_id : StrictStr, **kwargs) -> ApiResponse: # noqa: E501 + """Get Request Markdown Report # noqa: E501 + + Retrieves the markdown report for a Turbinia Request. Args: request (Request): FastAPI request object. request_id (str): A Turbinia request identifier. Raises: HTTPException: if another exception is caught. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.get_request_report_with_http_info(request_id, async_req=True) + >>> result = thread.get() + + :param request_id: (required) + :type request_id: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + 'request_id' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method get_request_report" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + if _params['request_id'] is not None: + _path_params['request_id'] = _params['request_id'] + + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/text']) # noqa: E501 + + # authentication setting + _auth_settings = ['oAuth2'] # noqa: E501 + + _response_types_map = { + '200': "str", + } + + return self.api_client.call_api( + '/api/request/report/{request_id}', 'GET', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + @validate_arguments def get_request_status(self, request_id : StrictStr, **kwargs) -> object: # noqa: E501 """Get Request Status # noqa: E501 diff --git a/turbinia/api/client/turbinia_api_lib/api/turbinia_tasks_api.py b/turbinia/api/client/turbinia_api_lib/api/turbinia_tasks_api.py index e2a1eebd6..56bda6256 100644 --- a/turbinia/api/client/turbinia_api_lib/api/turbinia_tasks_api.py +++ b/turbinia/api/client/turbinia_api_lib/api/turbinia_tasks_api.py @@ -44,6 +44,147 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_arguments + def get_task_report(self, task_id : StrictStr, **kwargs) -> object: # noqa: E501 + """Get Task Report # noqa: E501 + + Retrieves the MarkDown report of a Turbinia task. Raises: HTTPException: if another exception is caught. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.get_task_report(task_id, async_req=True) + >>> result = thread.get() + + :param task_id: (required) + :type task_id: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: object + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the get_task_report_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.get_task_report_with_http_info(task_id, **kwargs) # noqa: E501 + + @validate_arguments + def get_task_report_with_http_info(self, task_id : StrictStr, **kwargs) -> ApiResponse: # noqa: E501 + """Get Task Report # noqa: E501 + + Retrieves the MarkDown report of a Turbinia task. Raises: HTTPException: if another exception is caught. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.get_task_report_with_http_info(task_id, async_req=True) + >>> result = thread.get() + + :param task_id: (required) + :type task_id: str + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + 'task_id' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method get_task_report" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + if _params['task_id'] is not None: + _path_params['task_id'] = _params['task_id'] + + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # authentication setting + _auth_settings = ['oAuth2'] # noqa: E501 + + _response_types_map = { + '200': "object", + '422': "HTTPValidationError", + } + + return self.api_client.call_api( + '/api/task/report/{task_id}', 'GET', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + @validate_arguments def get_task_statistics(self, days : Optional[StrictInt] = None, task_id : Optional[StrictStr] = None, request_id : Optional[StrictStr] = None, user : Optional[StrictStr] = None, **kwargs) -> CompleteTurbiniaStats: # noqa: E501 """Get Task Statistics # noqa: E501 diff --git a/turbinia/api/client/turbinia_api_lib/api_client.py b/turbinia/api/client/turbinia_api_lib/api_client.py index c68d7a48c..14a0f5d93 100644 --- a/turbinia/api/client/turbinia_api_lib/api_client.py +++ b/turbinia/api/client/turbinia_api_lib/api_client.py @@ -11,6 +11,7 @@ Do not edit the class manually. """ # noqa: E501 + import atexit import datetime from dateutil.parser import parse @@ -31,7 +32,7 @@ class ApiClient: - """Generic API client for OpenAPI client library builds. + """Generic API client for OpenAPI client library builds. OpenAPI generic API client. This client handles the client- server communication, and is invariant across implementations. Specifics of @@ -48,78 +49,78 @@ class ApiClient: to the API. More threads means more concurrent API requests. """ - PRIMITIVE_TYPES = (float, bool, bytes, str, int) - NATIVE_TYPES_MAPPING = { - 'int': int, - 'long': int, # TODO remove as only py3 is supported? - 'float': float, - 'str': str, - 'bool': bool, - 'date': datetime.date, - 'datetime': datetime.datetime, - 'object': object, - } - _pool = None - - def __init__( - self, configuration=None, header_name=None, header_value=None, - cookie=None, pool_threads=1) -> None: - # use default configuration if none is provided - if configuration is None: - configuration = Configuration.get_default() - self.configuration = configuration - self.pool_threads = pool_threads - - self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.cookie = cookie - # Set default User-Agent. - self.user_agent = 'OpenAPI-Generator/1.0.0/python' - self.client_side_validation = configuration.client_side_validation - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self.close() - - def close(self): - if self._pool: - self._pool.close() - self._pool.join() - self._pool = None - if hasattr(atexit, 'unregister'): - atexit.unregister(self.close) - - @property - def pool(self): - """Create thread pool on first request + PRIMITIVE_TYPES = (float, bool, bytes, str, int) + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int, # TODO remove as only py3 is supported? + 'float': float, + 'str': str, + 'bool': bool, + 'date': datetime.date, + 'datetime': datetime.datetime, + 'object': object, + } + _pool = None + + def __init__(self, configuration=None, header_name=None, header_value=None, + cookie=None, pool_threads=1) -> None: + # use default configuration if none is provided + if configuration is None: + configuration = Configuration.get_default() + self.configuration = configuration + self.pool_threads = pool_threads + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'OpenAPI-Generator/1.0.0/python' + self.client_side_validation = configuration.client_side_validation + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + def close(self): + if self._pool: + self._pool.close() + self._pool.join() + self._pool = None + if hasattr(atexit, 'unregister'): + atexit.unregister(self.close) + + @property + def pool(self): + """Create thread pool on first request avoids instantiating unused threadpool for blocking clients. """ - if self._pool is None: - atexit.register(self.close) - self._pool = ThreadPool(self.pool_threads) - return self._pool + if self._pool is None: + atexit.register(self.close) + self._pool = ThreadPool(self.pool_threads) + return self._pool + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers['User-Agent'] - @property - def user_agent(self): - """User agent for this API client""" - return self.default_headers['User-Agent'] + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value - @user_agent.setter - def user_agent(self, value): - self.default_headers['User-Agent'] = value + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - _default = None + _default = None - @classmethod - def get_default(cls): - """Return new instance of ApiClient. + @classmethod + def get_default(cls): + """Return new instance of ApiClient. This method returns newly created, based on default constructor, object of ApiClient class or returns a copy of default @@ -127,127 +128,136 @@ def get_default(cls): :return: The ApiClient object. """ - if cls._default is None: - cls._default = ApiClient() - return cls._default + if cls._default is None: + cls._default = ApiClient() + return cls._default - @classmethod - def set_default(cls, default): - """Set default instance of ApiClient. + @classmethod + def set_default(cls, default): + """Set default instance of ApiClient. It stores default ApiClient. :param default: object of ApiClient. """ - cls._default = default - - def __call_api( - self, resource_path, method, path_params=None, query_params=None, - header_params=None, body=None, post_params=None, files=None, - response_types_map=None, auth_settings=None, _return_http_data_only=None, - collection_formats=None, _preload_content=True, _request_timeout=None, - _host=None, _request_auth=None): - - config = self.configuration - - # header parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params['Cookie'] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - header_params = dict( - self.parameters_to_tuples(header_params, collection_formats)) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, collection_formats) - for k, v in path_params: - # specified safe chars, encode everything - resource_path = resource_path.replace( - '{%s}' % k, quote(str(v), safe=config.safe_chars_for_path_param)) - - # post parameters - if post_params or files: - post_params = post_params if post_params else [] - post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, collection_formats) - post_params.extend(self.files_parameters(files)) - - # auth setting - self.update_params_for_auth( - header_params, query_params, auth_settings, resource_path, method, body, - request_auth=_request_auth) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # request url - if _host is None: - url = self.configuration.host + resource_path - else: - # use server/host defined in path or operation instead - url = _host + resource_path - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - url_query = self.parameters_to_url_query(query_params, collection_formats) - url += "?" + url_query - - try: - # perform request and return response - response_data = self.request( - method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body, _preload_content=_preload_content, - _request_timeout=_request_timeout) - except ApiException as e: - if e.body: - e.body = e.body.decode('utf-8') - raise e - - self.last_response = response_data - - return_data = None # assuming deserialization is not needed - # data needs deserialization or returns HTTP data (deserialized) only - if _preload_content or _return_http_data_only: - response_type = response_types_map.get(str(response_data.status), None) - if not response_type and isinstance( - response_data.status, int) and 100 <= response_data.status <= 599: - # if not found, look for '1XX', '2XX', etc. - response_type = response_types_map.get( - str(response_data.status)[0] + "XX", None) - - if response_type == "bytearray": - response_data.data = response_data.data - else: - match = None - content_type = response_data.getheader('content-type') - if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) - encoding = match.group(1) if match else "utf-8" - response_data.data = response_data.data.decode(encoding) - - # deserialize response data - if response_type == "bytearray": - return_data = response_data.data - elif response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - - if _return_http_data_only: - return return_data - else: - return ApiResponse( - status_code=response_data.status, data=return_data, - headers=response_data.getheaders(), raw_data=response_data.data) - - def sanitize_for_serialization(self, obj): - """Builds a JSON POST object. + cls._default = default + + def __call_api( + self, resource_path, method, path_params=None, + query_params=None, header_params=None, body=None, post_params=None, + files=None, response_types_map=None, auth_settings=None, + _return_http_data_only=None, collection_formats=None, + _preload_content=True, _request_timeout=None, _host=None, + _request_auth=None): + + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict(self.parameters_to_tuples(header_params, + collection_formats)) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples(path_params, + collection_formats) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples(post_params, + collection_formats) + post_params.extend(self.files_parameters(files)) + + # auth setting + self.update_params_for_auth( + header_params, query_params, auth_settings, + resource_path, method, body, + request_auth=_request_auth) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # request url + if _host is None: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + url_query = self.parameters_to_url_query(query_params, + collection_formats) + url += "?" + url_query + + try: + # perform request and return response + response_data = self.request( + method, url, + query_params=query_params, + headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) + except ApiException as e: + if e.body: + e.body = e.body.decode('utf-8') + raise e + + self.last_response = response_data + + return_data = None # assuming deserialization is not needed + # data needs deserialization or returns HTTP data (deserialized) only + if _preload_content or _return_http_data_only: + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) + + if response_type == "bytearray": + response_data.data = response_data.data + else: + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_data.data = response_data.data.decode(encoding) + + # deserialize response data + if response_type == "bytearray": + return_data = response_data.data + elif response_type: + return_data = self.deserialize(response_data, response_type) + else: + return_data = None + + if _return_http_data_only: + return return_data + else: + return ApiResponse(status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data) + + def sanitize_for_serialization(self, obj): + """Builds a JSON POST object. If obj is None, return None. If obj is str, int, long, float, bool, return directly. @@ -260,34 +270,34 @@ def sanitize_for_serialization(self, obj): :param obj: The data to serialize. :return: The serialized form of data. """ - if obj is None: - return None - elif isinstance(obj, self.PRIMITIVE_TYPES): - return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] - elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) - elif isinstance(obj, (datetime.datetime, datetime.date)): - return obj.isoformat() - - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `openapi_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = obj.to_dict() - - return { - key: self.sanitize_for_serialization(val) - for key, val in obj_dict.items() - } + if obj is None: + return None + elif isinstance(obj, self.PRIMITIVE_TYPES): + return obj + elif isinstance(obj, list): + return [self.sanitize_for_serialization(sub_obj) + for sub_obj in obj] + elif isinstance(obj, tuple): + return tuple(self.sanitize_for_serialization(sub_obj) + for sub_obj in obj) + elif isinstance(obj, (datetime.datetime, datetime.date)): + return obj.isoformat() + + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `openapi_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = obj.to_dict() - def deserialize(self, response, response_type): - """Deserializes response into an object. + return {key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items()} + + def deserialize(self, response, response_type): + """Deserializes response into an object. :param response: RESTResponse object to be deserialized. :param response_type: class literal for @@ -295,64 +305,66 @@ def deserialize(self, response, response_type): :return: deserialized object. """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) + # handle file downloading + # save response body into a tmp file and return the instance + if response_type == "file": + return self.__deserialize_file(response) - # fetch data from response object - try: - data = json.loads(response.data) - except ValueError: - data = response.data + # fetch data from response object + try: + data = json.loads(response.data) + except ValueError: + data = response.data - return self.__deserialize(data, response_type) + return self.__deserialize(data, response_type) - def __deserialize(self, data, klass): - """Deserializes dict, list, str into an object. + def __deserialize(self, data, klass): + """Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. :return: object. """ - if data is None: - return None - - if isinstance(klass, str): - if klass.startswith('List['): - sub_kls = re.match(r'List\[(.*)]', klass).group(1) - return [self.__deserialize(sub_data, sub_kls) for sub_data in data] - - if klass.startswith('Dict['): - sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) - return {k: self.__deserialize(v, sub_kls) for k, v in data.items()} - - # convert str to class - if klass in self.NATIVE_TYPES_MAPPING: - klass = self.NATIVE_TYPES_MAPPING[klass] - else: - klass = getattr(turbinia_api_lib.models, klass) - - if klass in self.PRIMITIVE_TYPES: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object(data) - elif klass == datetime.date: - return self.__deserialize_date(data) - elif klass == datetime.datetime: - return self.__deserialize_datetime(data) - else: - return self.__deserialize_model(data, klass) - - def call_api( - self, resource_path, method, path_params=None, query_params=None, - header_params=None, body=None, post_params=None, files=None, - response_types_map=None, auth_settings=None, async_req=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None, _host=None, - _request_auth=None): - """Makes the HTTP request (synchronous) and returns deserialized data. + if data is None: + return None + + if isinstance(klass, str): + if klass.startswith('List['): + sub_kls = re.match(r'List\[(.*)]', klass).group(1) + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] + + if klass.startswith('Dict['): + sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) + return {k: self.__deserialize(v, sub_kls) + for k, v in data.items()} + + # convert str to class + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] + else: + klass = getattr(turbinia_api_lib.models, klass) + + if klass in self.PRIMITIVE_TYPES: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object(data) + elif klass == datetime.date: + return self.__deserialize_date(data) + elif klass == datetime.datetime: + return self.__deserialize_datetime(data) + else: + return self.__deserialize_model(data, klass) + + def call_api(self, resource_path, method, + path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, + response_types_map=None, auth_settings=None, + async_req=None, _return_http_data_only=None, + collection_formats=None, _preload_content=True, + _request_timeout=None, _host=None, _request_auth=None): + """Makes the HTTP request (synchronous) and returns deserialized data. To make an async_req request, set the async_req parameter. @@ -393,196 +405,214 @@ def call_api( If parameter async_req is False or missing, then the method will return the response directly. """ - args = ( - resource_path, - method, - path_params, - query_params, - header_params, - body, - post_params, - files, - response_types_map, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - _host, - _request_auth, - ) - if not async_req: - return self.__call_api(*args) - - return self.pool.apply_async(self.__call_api, args) - - def request( - self, method, url, query_params=None, headers=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.get_request( - url, query_params=query_params, _preload_content=_preload_content, - _request_timeout=_request_timeout, headers=headers) - elif method == "HEAD": - return self.rest_client.head_request( - url, query_params=query_params, _preload_content=_preload_content, - _request_timeout=_request_timeout, headers=headers) - elif method == "OPTIONS": - return self.rest_client.options_request( - url, query_params=query_params, headers=headers, - _preload_content=_preload_content, _request_timeout=_request_timeout) - elif method == "POST": - return self.rest_client.post_request( - url, query_params=query_params, headers=headers, - post_params=post_params, _preload_content=_preload_content, - _request_timeout=_request_timeout, body=body) - elif method == "PUT": - return self.rest_client.put_request( - url, query_params=query_params, headers=headers, - post_params=post_params, _preload_content=_preload_content, - _request_timeout=_request_timeout, body=body) - elif method == "PATCH": - return self.rest_client.patch_request( - url, query_params=query_params, headers=headers, - post_params=post_params, _preload_content=_preload_content, - _request_timeout=_request_timeout, body=body) - elif method == "DELETE": - return self.rest_client.delete_request( - url, query_params=query_params, headers=headers, - _preload_content=_preload_content, _request_timeout=_request_timeout, - body=body) - else: - raise ApiValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`.") - - def parameters_to_tuples(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. + args = ( + resource_path, + method, + path_params, + query_params, + header_params, + body, + post_params, + files, + response_types_map, + auth_settings, + _return_http_data_only, + collection_formats, + _preload_content, + _request_timeout, + _host, + _request_auth, + ) + if not async_req: + return self.__call_api(*args) + + return self.pool.apply_async(self.__call_api, args) + + def request(self, method, url, query_params=None, headers=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + """Makes the HTTP request using RESTClient.""" + if method == "GET": + return self.rest_client.get_request(url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers) + elif method == "HEAD": + return self.rest_client.head_request(url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers) + elif method == "OPTIONS": + return self.rest_client.options_request(url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout) + elif method == "POST": + return self.rest_client.post_request(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "PUT": + return self.rest_client.put_request(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "PATCH": + return self.rest_client.patch_request(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "DELETE": + return self.rest_client.delete_request(url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + else: + raise ApiValueError( + "http method must be `GET`, `HEAD`, `OPTIONS`," + " `POST`, `PATCH`, `PUT` or `DELETE`." + ) + + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collections formatted """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in params.items() if isinstance(params, - dict) else params: # noqa: E501 - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == 'multi': - new_params.extend((k, value) for value in v) - else: - if collection_format == 'ssv': - delimiter = ' ' - elif collection_format == 'tsv': - delimiter = '\t' - elif collection_format == 'pipes': - delimiter = '|' - else: # csv is the default - delimiter = ',' - new_params.append((k, delimiter.join(str(value) for value in v))) - else: - new_params.append((k, v)) - return new_params - - def parameters_to_url_query(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + + def parameters_to_url_query(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats :return: URL query string (e.g. a=Hello%20World&b=123) """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in params.items() if isinstance(params, - dict) else params: # noqa: E501 - if isinstance(v, bool): - v = str(v).lower() - if isinstance(v, (int, float)): - v = str(v) - if isinstance(v, dict): - v = json.dumps(v) - - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == 'multi': - new_params.extend((k, str(value)) for value in v) - else: - if collection_format == 'ssv': - delimiter = ' ' - elif collection_format == 'tsv': - delimiter = '\t' - elif collection_format == 'pipes': - delimiter = '|' - else: # csv is the default - delimiter = ',' - new_params.append( - (k, delimiter.join(quote(str(value)) for value in v))) - else: - new_params.append((k, quote(str(v)))) - - return "&".join(["=".join(map(str, item)) for item in new_params]) - - def files_parameters(self, files=None): - """Builds form parameters. + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + if isinstance(v, bool): + v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) + if isinstance(v, dict): + v = json.dumps(v) + + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, str(value)) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(quote(str(value)) for value in v))) + else: + new_params.append((k, quote(str(v)))) + + return "&".join(["=".join(map(str, item)) for item in new_params]) + + def files_parameters(self, files=None): + """Builds form parameters. :param files: File parameters. :return: Form parameters with files. """ - params = [] - - if files: - for k, v in files.items(): - if not v: - continue - file_names = v if type(v) is list else [v] - for n in file_names: - with open(n, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = ( - mimetypes.guess_type(filename)[0] or 'application/octet-stream') - params.append(tuple([k, tuple([filename, filedata, mimetype])])) - - return params - - def select_header_accept(self, accepts): - """Returns `Accept` based on an array of accepts provided. + params = [] + + if files: + for k, v in files.items(): + if not v: + continue + file_names = v if type(v) is list else [v] + for n in file_names: + with open(n, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = (mimetypes.guess_type(filename)[0] or + 'application/octet-stream') + params.append( + tuple([k, tuple([filename, filedata, mimetype])])) + + return params + + def select_header_accept(self, accepts): + """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). """ - if not accepts: - return + if not accepts: + return - for accept in accepts: - if re.search('json', accept, re.IGNORECASE): - return accept + for accept in accepts: + if re.search('json', accept, re.IGNORECASE): + return accept - return accepts[0] + return accepts[0] - def select_header_content_type(self, content_types): - """Returns `Content-Type` based on an array of content_types provided. + def select_header_content_type(self, content_types): + """Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. :return: Content-Type (e.g. application/json). """ - if not content_types: - return None + if not content_types: + return None - for content_type in content_types: - if re.search('json', content_type, re.IGNORECASE): - return content_type + for content_type in content_types: + if re.search('json', content_type, re.IGNORECASE): + return content_type - return content_types[0] + return content_types[0] - def update_params_for_auth( - self, headers, queries, auth_settings, resource_path, method, body, - request_auth=None): - """Updates header and query params based on authentication setting. + def update_params_for_auth(self, headers, queries, auth_settings, + resource_path, method, body, + request_auth=None): + """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. :param queries: Query parameters tuple list to be updated. @@ -594,23 +624,26 @@ def update_params_for_auth( :param request_auth: if set, the provided settings will override the token in the configuration. """ - if not auth_settings: - return - - if request_auth: - self._apply_auth_params( - headers, queries, resource_path, method, body, request_auth) - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - self._apply_auth_params( - headers, queries, resource_path, method, body, auth_setting) - - def _apply_auth_params( - self, headers, queries, resource_path, method, body, auth_setting): - """Updates the request parameters based on a single auth_setting + if not auth_settings: + return + + if request_auth: + self._apply_auth_params(headers, queries, + resource_path, method, body, + request_auth) + return + + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params(headers, queries, + resource_path, method, body, + auth_setting) + + def _apply_auth_params(self, headers, queries, + resource_path, method, body, + auth_setting): + """Updates the request parameters based on a single auth_setting :param headers: Header parameters dict to be updated. :param queries: Query parameters tuple list to be updated. @@ -620,18 +653,20 @@ def _apply_auth_params( The object type is the return value of sanitize_for_serialization(). :param auth_setting: auth settings for the endpoint """ - if auth_setting['in'] == 'cookie': - headers['Cookie'] = auth_setting['value'] - elif auth_setting['in'] == 'header': - if auth_setting['type'] != 'http-signature': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - queries.append((auth_setting['key'], auth_setting['value'])) - else: - raise ApiValueError('Authentication token must be in `query` or `header`') - - def __deserialize_file(self, response): - """Deserializes body to file + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + queries.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) + + def __deserialize_file(self, response): + """Deserializes body to file Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. @@ -639,81 +674,86 @@ def __deserialize_file(self, response): :param response: RESTResponse. :return: file path. """ - fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) - os.close(fd) - os.remove(path) + fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + os.close(fd) + os.remove(path) - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search( - r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition).group(1) + path = os.path.join(os.path.dirname(path), filename) - with open(path, "wb") as f: - f.write(response.data) + with open(path, "wb") as f: + f.write(response.data) - return path + return path - def __deserialize_primitive(self, data, klass): - """Deserializes string to primitive type. + def __deserialize_primitive(self, data, klass): + """Deserializes string to primitive type. :param data: str. :param klass: class literal. :return: int, long, float, str, bool. """ - try: - return klass(data) - except UnicodeEncodeError: - return str(data) - except TypeError: - return data + try: + return klass(data) + except UnicodeEncodeError: + return str(data) + except TypeError: + return data - def __deserialize_object(self, value): - """Return an original value. + def __deserialize_object(self, value): + """Return an original value. :return: object. """ - return value + return value - def __deserialize_date(self, string): - """Deserializes string to date. + def __deserialize_date(self, string): + """Deserializes string to date. :param string: str. :return: date. """ - try: - return parse(string).date() - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason="Failed to parse `{0}` as date object".format(string)) - - def __deserialize_datetime(self, string): - """Deserializes string to datetime. + try: + return parse(string).date() + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason="Failed to parse `{0}` as date object".format(string) + ) + + def __deserialize_datetime(self, string): + """Deserializes string to datetime. The string should be in iso8601 datetime format. :param string: str. :return: datetime. """ - try: - return parse(string) - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason=("Failed to parse `{0}` as datetime object".format(string))) - - def __deserialize_model(self, data, klass): - """Deserializes list or dict to model. + try: + return parse(string) + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as datetime object" + .format(string) + ) + ) + + def __deserialize_model(self, data, klass): + """Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object. """ - return klass.from_dict(data) + return klass.from_dict(data) diff --git a/turbinia/api/client/turbinia_api_lib/models/validation_error.py b/turbinia/api/client/turbinia_api_lib/models/validation_error.py index f7cf8158c..9c513201e 100644 --- a/turbinia/api/client/turbinia_api_lib/models/validation_error.py +++ b/turbinia/api/client/turbinia_api_lib/models/validation_error.py @@ -11,70 +11,73 @@ Do not edit the class manually. """ # noqa: E501 + from __future__ import annotations import pprint import re # noqa: F401 import json + from typing import List from pydantic import BaseModel, Field, StrictStr, conlist from turbinia_api_lib.models.location_inner import LocationInner - class ValidationError(BaseModel): - """ + """ ValidationError """ - loc: conlist(LocationInner) = Field(...) - msg: StrictStr = Field(...) - type: StrictStr = Field(...) - __properties = ["loc", "msg", "type"] - - class Config: - """Pydantic configuration""" - allow_population_by_field_name = True - validate_assignment = True - - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.dict(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> ValidationError: - """Create an instance of ValidationError from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self): - """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) - # override the default output from pydantic by calling `to_dict()` of each item in loc (list) - _items = [] - if self.loc: - for _item in self.loc: - if _item: - _items.append(_item.to_dict()) - _dict['loc'] = _items - return _dict - - @classmethod - def from_dict(cls, obj: dict) -> ValidationError: - """Create an instance of ValidationError from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return ValidationError.parse_obj(obj) - - _obj = ValidationError.parse_obj({ - "loc": [LocationInner.from_dict(_item) for _item in obj.get("loc")] - if obj.get("loc") is not None else None, - "msg": - obj.get("msg"), - "type": - obj.get("type") - }) - return _obj + loc: conlist(LocationInner) = Field(...) + msg: StrictStr = Field(...) + type: StrictStr = Field(...) + __properties = ["loc", "msg", "type"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> ValidationError: + """Create an instance of ValidationError from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + # override the default output from pydantic by calling `to_dict()` of each item in loc (list) + _items = [] + if self.loc: + for _item in self.loc: + if _item: + _items.append(_item.to_dict()) + _dict['loc'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> ValidationError: + """Create an instance of ValidationError from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return ValidationError.parse_obj(obj) + + _obj = ValidationError.parse_obj({ + "loc": [LocationInner.from_dict(_item) for _item in obj.get("loc")] if obj.get("loc") is not None else None, + "msg": obj.get("msg"), + "type": obj.get("type") + }) + return _obj + + diff --git a/turbinia/api/utils.py b/turbinia/api/utils.py index f3f4bea53..a90ce4199 100644 --- a/turbinia/api/utils.py +++ b/turbinia/api/utils.py @@ -156,13 +156,13 @@ async def create_tarball(output_path: str) -> AsyncGenerator[bytes, Any]: file_path = os.path.join(root, filename) # skip empty files if os.stat(file_path).st_size > 0: - log.info(f'Adding {file_path} to tarball.') file_paths.append(file_path) with ByteStream() as stream: with tarfile.TarFile.open(fileobj=stream, mode='w:gz', compresslevel=1) as tar: for file_path in file_paths: + log.info(f'Adding {file_path} to tarball.') tar_info = tar.gettarinfo(name=file_path) tar.addfile(tar_info) # Yield the header for the tarinfo file.