diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/CHANGELOG.md b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/CHANGELOG.md index d06a69ac2708..6f110d53dc87 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/CHANGELOG.md +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/CHANGELOG.md @@ -1,5 +1,166 @@ # Release History +## 2.0.0b3 (2025-05-13) + +### Features Added + + - Client `AlertsManagementClient` added method `preview_alert_rule` + - Client `AlertsManagementClient` added operation group `alert_rule_recommendations` + - Client `AlertsManagementClient` added operation group `issue` + - Enum `AlertState` added member `FIRED` + - Enum `AlertState` added member `FIRING` + - Enum `AlertState` added member `NO_ALERT` + - Enum `AlertState` added member `RESOLVED` + - Enum `AlertState` added member `RESOLVING` + - Model `Essentials` added property `has_enrichments` + - Model `Essentials` added property `is_stateful_alert` + - Model `Essentials` added property `correlation_details` + - Enum `MonitorService` added member `RESOURCE_HEALTH` + - Model `Resource` added property `system_data` + - Added model `AbnormalEventAnomalyInsight` + - Added model `AbnormalEventData` + - Added model `AbnormalEventDetails` + - Added enum `AbnormalEventType` + - Added enum `AddedByType` + - Added enum `AggregationType` + - Added model `AlertEnrichmentItem` + - Added model `AlertEnrichmentProperties` + - Added model `AlertEnrichmentResponse` + - Added model `AlertEnrichmentsList` + - Added model `AlertRuleRecommendationResource` + - Added model `AlertRuleRecommendationsListResponse` + - Added enum `AlertSeverity` + - Added enum `AnomalyDirection` + - Added model `AnomalyRange` + - Added enum `AvailabilityState` + - Added model `AzureMetricAnomalyInsight` + - Added model `AzureMetricData` + - Added model `AzureMetricDetails` + - Added model `BaselineRange` + - Added enum `CategoryType` + - Added enum `ConditionOperator` + - Added model `CorrelationDetails` + - Added enum `CriterionType` + - Added model `DetailsBase` + - Added enum `DetailsType` + - Added model `DiagnosticsInsight` + - Added model `DiagnosticsSolutionDetails` + - Added model `DimensionNameAndValue` + - Added enum `DimensionOperator` + - Added model `ErrorDetailAutoGenerated` + - Added model `ErrorDetailAutoGenerated2` + - Added model `ErrorResponseAutoGenerated4` + - Added model `ErrorResponseAutoGenerated5` + - Added model `EvaluatedPeriod` + - Added model `Evaluation` + - Added model `ExceptionPatternAnomaly` + - Added model `FetchInvestigationResultParameters` + - Added enum `HealthState` + - Added model `InvestigationDetails` + - Added model `InvestigationEntity` + - Added enum `InvestigationEntityType` + - Added model `InvestigationExecution` + - Added enum `InvestigationExecutionRunState` + - Added model `InvestigationMetadata` + - Added model `InvestigationResult` + - Added model `InvestigationScope` + - Added model `IssueProperties` + - Added model `IssuePropertiesUpdate` + - Added model `IssueResource` + - Added model `IssueResourceListResult` + - Added model `IssueResourceUpdate` + - Added enum `Kind` + - Added model `ListParameter` + - Added model `LogAlertRuleCondition` + - Added model `LogAlertRuleConditionFailingPeriods` + - Added model `LogAlertRuleCriteria` + - Added model `LogAlertRuleDimension` + - Added model `LogAlertRuleResolveConfiguration` + - Added model `LogAlertRuleResource` + - Added model `LogAlertRuleUserIdentityProperties` + - Added enum `MetricAlertsDisplayUnit` + - Added model `Origin` + - Added model `PagedRelatedAlert` + - Added model `PagedRelatedResource` + - Added model `PreviewAlertRuleRequest` + - Added model `PreviewAlertRuleRequestProperties` + - Added model `PreviewAlertRuleResponse` + - Added model `PrometheusEnrichmentItem` + - Added model `PrometheusInstantQuery` + - Added model `PrometheusRangeQuery` + - Added model `PrometheusRuleGroupResourcePatchParameters` + - Added model `ProxyResource` + - Added model `ProxyResourceAutoGenerated` + - Added model `RelatedAlert` + - Added model `RelatedAlertAnomalyInsight` + - Added model `RelatedAlertData` + - Added model `RelatedAlertDetails` + - Added model `RelatedAlerts` + - Added model `RelatedResource` + - Added model `RelatedResources` + - Added enum `Relevance` + - Added model `ResourceAutoGenerated2` + - Added model `ResourceAutoGenerated3` + - Added model `ResourceHealthDetails` + - Added model `ResourceHealthInsight` + - Added enum `ResourceProvisioningState` + - Added model `RuleArmTemplate` + - Added model `RulePreviewResult` + - Added model `RunParameters` + - Added model `StartInvestigationParameters` + - Added enum `Status` + - Added model `Summary` + - Added enum `TimeAggregation` + - Added model `TracePatternAnomaly` + - Added model `TransactionEdge` + - Added model `TransactionNode` + - Added model `TransactionPatternAnomaly` + - Added enum `Type` + - Model `AlertsOperations` added method `get_enrichments` + - Model `AlertsOperations` added method `list_enrichments` + - Added model `AlertRuleRecommendationsOperations` + - Added model `AlertsManagementClientOperationsMixin` + - Added model `IssueOperations` + - Method `AlertsManagementClient.preview_alert_rule` has a new overload `def preview_alert_rule(self: None, parameters: PreviewAlertRuleRequest, content_type: str)` + - Method `AlertsManagementClient.preview_alert_rule` has a new overload `def preview_alert_rule(self: None, parameters: IO[bytes], content_type: str)` + - Method `AlertProcessingRulesOperations.create_or_update` has a new overload `def create_or_update(self: None, resource_group_name: str, alert_processing_rule_name: str, alert_processing_rule: IO[bytes], content_type: str)` + - Method `AlertProcessingRulesOperations.update` has a new overload `def update(self: None, resource_group_name: str, alert_processing_rule_name: str, alert_processing_rule_patch: IO[bytes], content_type: str)` + - Method `AlertsOperations.change_state` has a new overload `def change_state(self: None, scope: str, alert_id: str, new_state: Union[str, AlertState], comment: Optional[Comments], content_type: str)` + - Method `AlertsOperations.change_state` has a new overload `def change_state(self: None, scope: str, alert_id: str, new_state: Union[str, AlertState], comment: Optional[IO[bytes]], content_type: str)` + - Method `PrometheusRuleGroupsOperations.create_or_update` has a new overload `def create_or_update(self: None, resource_group_name: str, rule_group_name: str, parameters: IO[bytes], content_type: str)` + - Method `PrometheusRuleGroupsOperations.update` has a new overload `def update(self: None, resource_group_name: str, rule_group_name: str, parameters: PrometheusRuleGroupResourcePatchParameters, content_type: str)` + - Method `PrometheusRuleGroupsOperations.update` has a new overload `def update(self: None, resource_group_name: str, rule_group_name: str, parameters: IO[bytes], content_type: str)` + - Method `AlertsManagementClientOperationsMixin.preview_alert_rule` has a new overload `def preview_alert_rule(self: None, parameters: PreviewAlertRuleRequest, content_type: str)` + - Method `AlertsManagementClientOperationsMixin.preview_alert_rule` has a new overload `def preview_alert_rule(self: None, parameters: IO[bytes], content_type: str)` + - Method `IssueOperations.add_or_update_alerts` has a new overload `def add_or_update_alerts(self: None, resource_uri: str, body: RelatedAlerts, content_type: str)` + - Method `IssueOperations.add_or_update_alerts` has a new overload `def add_or_update_alerts(self: None, resource_uri: str, body: IO[bytes], content_type: str)` + - Method `IssueOperations.add_or_update_resources` has a new overload `def add_or_update_resources(self: None, resource_uri: str, body: RelatedResources, content_type: str)` + - Method `IssueOperations.add_or_update_resources` has a new overload `def add_or_update_resources(self: None, resource_uri: str, body: IO[bytes], content_type: str)` + - Method `IssueOperations.create` has a new overload `def create(self: None, resource_uri: str, resource: IssueResource, content_type: str)` + - Method `IssueOperations.create` has a new overload `def create(self: None, resource_uri: str, resource: IO[bytes], content_type: str)` + - Method `IssueOperations.fetch_investigation_result` has a new overload `def fetch_investigation_result(self: None, resource_uri: str, body: FetchInvestigationResultParameters, content_type: str)` + - Method `IssueOperations.fetch_investigation_result` has a new overload `def fetch_investigation_result(self: None, resource_uri: str, body: IO[bytes], content_type: str)` + - Method `IssueOperations.list_alerts` has a new overload `def list_alerts(self: None, resource_uri: str, body: ListParameter, content_type: str)` + - Method `IssueOperations.list_alerts` has a new overload `def list_alerts(self: None, resource_uri: str, body: IO[bytes], content_type: str)` + - Method `IssueOperations.list_resources` has a new overload `def list_resources(self: None, resource_uri: str, body: ListParameter, content_type: str)` + - Method `IssueOperations.list_resources` has a new overload `def list_resources(self: None, resource_uri: str, body: IO[bytes], content_type: str)` + - Method `IssueOperations.start_investigation` has a new overload `def start_investigation(self: None, resource_uri: str, body: StartInvestigationParameters, content_type: str)` + - Method `IssueOperations.start_investigation` has a new overload `def start_investigation(self: None, resource_uri: str, body: IO[bytes], content_type: str)` + - Method `IssueOperations.update` has a new overload `def update(self: None, resource_uri: str, properties: IssueResourceUpdate, content_type: str)` + - Method `IssueOperations.update` has a new overload `def update(self: None, resource_uri: str, properties: IO[bytes], content_type: str)` + +### Breaking Changes + + - Method `AlertsManagementClient.__init__` inserted a `positional_or_keyword` parameter `issue_name` + - Model `ResourceAutoGenerated` deleted or renamed its instance variable `system_data` + - Deleted or renamed model `PrometheusRuleGroupResourcePatch` + - Deleted or renamed model `PrometheusRuleGroupResourcePatchProperties` + - Method `AlertsOperations.change_state` inserted a `positional_or_keyword` parameter `scope` + - Method `AlertsOperations.get_all` inserted a `positional_or_keyword` parameter `scope` + - Method `AlertsOperations.get_by_id` inserted a `positional_or_keyword` parameter `scope` + - Method `AlertsOperations.get_history` inserted a `positional_or_keyword` parameter `scope` + - Method `AlertsOperations.get_summary` inserted a `positional_or_keyword` parameter `scope` + ## 2.0.0b2 (2022-12-26) ### Features Added diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/README.md b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/README.md index 5f79292ae927..740042022ba7 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/README.md +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/README.md @@ -1,28 +1,61 @@ # Microsoft Azure SDK for Python This is the Microsoft Azure Alerts Management Client Library. -This package has been tested with Python 3.7+. +This package has been tested with Python 3.9+. For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all). ## _Disclaimer_ _Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_ -# Usage +## Getting started +### Prerequisites -To learn how to use this package, see the [quickstart guide](https://aka.ms/azsdk/python/mgmt) - -For docs and references, see [Python SDK References](https://docs.microsoft.com/python/api/overview/azure/) -Code samples for this package can be found at [Alerts Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com. -Additional code samples for different Azure services are available at [Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) +- Python 3.9+ is required to use this package. +- [Azure subscription](https://azure.microsoft.com/free/) +### Install the package -# Provide Feedback +```bash +pip install azure-mgmt-alertsmanagement +pip install azure-identity +``` -If you encounter any bugs or have suggestions, please file an issue in the -[Issues](https://github.com/Azure/azure-sdk-for-python/issues) -section of the project. +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configuration of the following environment variables. + +- `AZURE_CLIENT_ID` for Azure client ID. +- `AZURE_TENANT_ID` for Azure tenant ID. +- `AZURE_CLIENT_SECRET` for Azure client secret. + +In addition, Azure subscription ID can be configured via environment variable `AZURE_SUBSCRIPTION_ID`. + +With above configuration, client can be authenticated by following code: + +```python +from azure.identity import DefaultAzureCredential +from azure.mgmt.alertsmanagement import AlertsManagementClient +import os +sub_id = os.getenv("AZURE_SUBSCRIPTION_ID") +client = AlertsManagementClient(credential=DefaultAzureCredential(), subscription_id=sub_id) +``` +## Examples +Code samples for this package can be found at: +- [Search Alerts Management](https://docs.microsoft.com/samples/browse/?languages=python&term=Getting%20started%20-%20Managing&terms=Getting%20started%20-%20Managing) on docs.microsoft.com +- [Azure Python Mgmt SDK Samples Repo](https://aka.ms/azsdk/python/mgmt/samples) + + +## Troubleshooting + +## Next steps + +## Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/_meta.json b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/_meta.json index 4acb590471e5..16224a878194 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/_meta.json +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/_meta.json @@ -1,11 +1,11 @@ { - "commit": "e37a57df67daaa82f9c3758fc450bc8655812a08", + "commit": "6b632b979e210aad99b0050050d63f1539b50ad3", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest": "3.9.2", + "autorest": "3.10.2", "use": [ - "@autorest/python@6.2.7", - "@autorest/modelerfour@4.24.3" + "@autorest/python@6.34.1", + "@autorest/modelerfour@4.27.0" ], - "autorest_command": "autorest specification/alertsmanagement/resource-manager/readme.md --generate-sample=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/home/vsts/work/1/azure-sdk-for-python/sdk --use=@autorest/python@6.2.7 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", + "autorest_command": "autorest specification/alertsmanagement/resource-manager/readme.md --generate-sample=True --generate-test=True --include-x-ms-examples-original-file=True --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.34.1 --use=@autorest/modelerfour@4.27.0 --version=3.10.2 --version-tolerant=False", "readme": "specification/alertsmanagement/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/__init__.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/__init__.py index 8f236949edfc..e73c34c5a526 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/__init__.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/__init__.py @@ -5,15 +5,21 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._alerts_management_client import AlertsManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._alerts_management_client import AlertsManagementClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk @@ -21,6 +27,6 @@ __all__ = [ "AlertsManagementClient", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_alerts_management_client.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_alerts_management_client.py index e896dc0a388c..f3b30a1942b3 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_alerts_management_client.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_alerts_management_client.py @@ -7,33 +7,39 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, TYPE_CHECKING +from typing import Any, Optional, TYPE_CHECKING, cast +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse +from azure.core.settings import settings from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints from . import models as _models from ._configuration import AlertsManagementClientConfiguration -from ._serialization import Deserializer, Serializer +from ._utils.serialization import Deserializer, Serializer from .operations import ( AlertProcessingRulesOperations, + AlertRuleRecommendationsOperations, + AlertsManagementClientOperationsMixin, AlertsOperations, + IssueOperations, Operations, PrometheusRuleGroupsOperations, SmartGroupsOperations, ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class AlertsManagementClient: # pylint: disable=client-accepts-api-version-keyword +class AlertsManagementClient( + AlertsManagementClientOperationsMixin +): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """AlertsManagement Client. - :ivar alert_processing_rules: AlertProcessingRulesOperations operations - :vartype alert_processing_rules: - azure.mgmt.alertsmanagement.operations.AlertProcessingRulesOperations :ivar prometheus_rule_groups: PrometheusRuleGroupsOperations operations :vartype prometheus_rule_groups: azure.mgmt.alertsmanagement.operations.PrometheusRuleGroupsOperations @@ -43,41 +49,84 @@ class AlertsManagementClient: # pylint: disable=client-accepts-api-version-keyw :vartype alerts: azure.mgmt.alertsmanagement.operations.AlertsOperations :ivar smart_groups: SmartGroupsOperations operations :vartype smart_groups: azure.mgmt.alertsmanagement.operations.SmartGroupsOperations + :ivar alert_rule_recommendations: AlertRuleRecommendationsOperations operations + :vartype alert_rule_recommendations: + azure.mgmt.alertsmanagement.operations.AlertRuleRecommendationsOperations + :ivar alert_processing_rules: AlertProcessingRulesOperations operations + :vartype alert_processing_rules: + azure.mgmt.alertsmanagement.operations.AlertProcessingRulesOperations + :ivar issue: IssueOperations operations + :vartype issue: azure.mgmt.alertsmanagement.operations.IssueOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential + :param issue_name: The name of the IssueResource. Required. + :type issue_name: str :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param base_url: Service URL. Default value is "https://management.azure.com". + :param base_url: Service URL. Default value is None. :type base_url: str """ def __init__( self, credential: "TokenCredential", + issue_name: str, subscription_id: str, - base_url: str = "https://management.azure.com", + base_url: Optional[str] = None, **kwargs: Any ) -> None: + _cloud = kwargs.pop("cloud_setting", None) or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) self._config = AlertsManagementClientConfiguration( - credential=credential, subscription_id=subscription_id, **kwargs + credential=credential, + issue_name=issue_name, + subscription_id=subscription_id, + credential_scopes=credential_scopes, + **kwargs ) - self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + ARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: ARMPipelineClient = ARMPipelineClient(base_url=cast(str, base_url), policies=_policies, **kwargs) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False - self.alert_processing_rules = AlertProcessingRulesOperations( - self._client, self._config, self._serialize, self._deserialize - ) self.prometheus_rule_groups = PrometheusRuleGroupsOperations( self._client, self._config, self._serialize, self._deserialize ) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.alerts = AlertsOperations(self._client, self._config, self._serialize, self._deserialize) self.smart_groups = SmartGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.alert_rule_recommendations = AlertRuleRecommendationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.alert_processing_rules = AlertProcessingRulesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.issue = IssueOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -97,14 +146,14 @@ def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore def close(self) -> None: self._client.close() - def __enter__(self) -> "AlertsManagementClient": + def __enter__(self) -> Self: self._client.__enter__() return self - def __exit__(self, *exc_details) -> None: + def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_configuration.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_configuration.py index c5cebde237ea..8357401611a2 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_configuration.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential -class AlertsManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class AlertsManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for AlertsManagementClient. Note that all parameters used to create this instance are saved as instance @@ -27,21 +25,26 @@ class AlertsManagementClientConfiguration(Configuration): # pylint: disable=too :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential + :param issue_name: The name of the IssueResource. Required. + :type issue_name: str :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str """ - def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(AlertsManagementClientConfiguration, self).__init__(**kwargs) + def __init__(self, credential: "TokenCredential", issue_name: str, subscription_id: str, **kwargs: Any) -> None: if credential is None: raise ValueError("Parameter 'credential' must not be None.") + if issue_name is None: + raise ValueError("Parameter 'issue_name' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential + self.issue_name = issue_name self.subscription_id = subscription_id self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-alertsmanagement/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -50,9 +53,9 @@ def _configure(self, **kwargs: Any) -> None: self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = ARMChallengeAuthenticationPolicy( diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_utils/__init__.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_utils/__init__.py new file mode 100644 index 000000000000..0af9b28f6607 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_serialization.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_utils/serialization.py similarity index 77% rename from sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_serialization.py rename to sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_utils/serialization.py index 2c170e28dbca..f5187701d7be 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_serialization.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_utils/serialization.py @@ -1,30 +1,12 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# pylint: skip-file # pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode @@ -38,7 +20,19 @@ import re import sys import codecs -from typing import Optional, Union, AnyStr, IO, Mapping +from typing import ( + Dict, + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, + List, +) try: from urllib import quote # type: ignore @@ -47,13 +41,15 @@ import xml.etree.ElementTree as ET import isodate # type: ignore +from typing_extensions import Self -from typing import Dict, Any, cast - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") +JSON = MutableMapping[str, Any] + class RawDeserializer: @@ -74,6 +70,8 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: :param data: Input, could be bytes or stream (will be decoded with UTF8) or text :type data: str or bytes or IO :param str content_type: The content type. + :return: The deserialized data. + :rtype: object """ if hasattr(data, "read"): # Assume a stream @@ -95,7 +93,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: try: return json.loads(data_as_str) except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) + raise DeserializationError("JSON is invalid: {}".format(err), err) from err elif "xml" in (content_type or []): try: @@ -107,7 +105,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: pass return ET.fromstring(data_as_str) # nosec - except ET.ParseError: + except ET.ParseError as err: # It might be because the server has an issue, and returned JSON with # content-type XML.... # So let's try a JSON load, and if it's still broken @@ -126,7 +124,9 @@ def _json_attemp(data): # The function hack is because Py2.7 messes up with exception # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod @@ -136,6 +136,11 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], Use bytes and headers to NOT use any requests/aiohttp or whatever specific implementation. Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object """ # Try to use content-type from headers if available content_type = None @@ -153,13 +158,6 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str - unicode_str = str - _LOGGER = logging.getLogger(__name__) try: @@ -167,80 +165,31 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], except NameError: _long_type = int - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -try: - from datetime import timezone as _FixedOffset # type: ignore -except ImportError: # Python 2.7 - - class _FixedOffset(datetime.tzinfo): # type: ignore - """Fixed offset in minutes east from UTC. - Copy/pasted from Python doc - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc -except ImportError: - TZ_UTC = UTC() # type: ignore +TZ_UTC = datetime.timezone.utc _FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[Dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items if k not in self._attribute_map: _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) elif k in self._validation and self._validation[k].get("readonly", False): @@ -287,25 +243,35 @@ def __init__(self, **kwargs): else: setattr(self, k, kwargs[k]) - def __eq__(self, other): - """Compare objects by comparing all attributes.""" + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False - def __ne__(self, other): - """Compare objects by comparing all attributes.""" + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ return not self.__eq__(other) - def __str__(self): + def __str__(self) -> str: return str(self.__dict__) @classmethod - def enable_additional_properties_sending(cls): + def enable_additional_properties_sending(cls) -> None: cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} @classmethod - def is_xml_model(cls): + def is_xml_model(cls) -> bool: try: cls._xml_map # type: ignore except AttributeError: @@ -314,7 +280,11 @@ def is_xml_model(cls): @classmethod def _create_xml_node(cls): - """Create XML node.""" + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ try: xml_map = cls._xml_map # type: ignore except AttributeError: @@ -322,8 +292,8 @@ def _create_xml_node(cls): return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - def serialize(self, keep_readonly=False, **kwargs): - """Return the JSON that would be sent to azure from this model. + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. @@ -334,10 +304,17 @@ def serialize(self, keep_readonly=False, **kwargs): :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) - def as_dict(self, keep_readonly=True, key_transformer=attribute_transformer, **kwargs): - """Return a dict that can be JSONify using json.dump. + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. Advanced usage might optionally use a callback as parameter: @@ -363,12 +340,15 @@ def my_key_transformer(key, attr_desc, value): If you want XML serialization, you can pass the kwargs is_xml=True. + :param bool keep_readonly: If you want to serialize the readonly attributes :param function key_transformer: A key transformer function. :returns: A dict JSON compatible object :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) @classmethod def _infer_class_models(cls): @@ -378,25 +358,31 @@ def _infer_class_models(cls): client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} if cls.__name__ not in client_models: raise ValueError("Not Autorest generated code") - except Exception: + except Exception: # pylint: disable=broad-exception-caught # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. client_models = {cls.__name__: cls} return client_models @classmethod - def deserialize(cls, data, content_type=None): + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod - def from_dict(cls, data, key_extractors=None, content_type=None): + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: """Parse a dict using given key extractor return a model. By default consider key @@ -404,13 +390,15 @@ def from_dict(cls, data, key_extractors=None, content_type=None): and last_rest_key_case_insensitive_extractor) :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( - [ + deserializer.key_extractors = ( # type: ignore + [ # type: ignore attribute_key_case_insensitive_extractor, rest_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, @@ -418,7 +406,7 @@ def from_dict(cls, data, key_extractors=None, content_type=None): if key_extractors is None else key_extractors ) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def _flatten_subtype(cls, key, objects): @@ -426,21 +414,25 @@ def _flatten_subtype(cls, key, objects): return {} result = dict(cls._subtype_map[key]) for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) + result.update(objects[valuetype]._flatten_subtype(key, objects)) # pylint: disable=protected-access return result @classmethod def _classify(cls, response, objects): """Check the class _subtype_map for any child classes. We want to ignore any inherited _subtype_maps. - Remove the polymorphic key from the initial data. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class """ for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): subtype_value = None if not isinstance(response, ET.Element): rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) else: subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) if subtype_value: @@ -479,11 +471,13 @@ def _decode_attribute_map_key(key): inside the received data. :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str """ return key.replace("\\.", ".") -class Serializer(object): +class Serializer: # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -518,7 +512,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -534,17 +528,20 @@ def __init__(self, classes=None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_transformer = full_restapi_key_transformer self.client_side_validation = True - def _serialize(self, target_obj, data_type=None, **kwargs): + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): """Serialize data into a string according to type. - :param target_obj: The data to be serialized. + :param object target_obj: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str, dict - :raises: SerializationError if serialization fails. + :raises SerializationError: if serialization fails. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -570,12 +567,14 @@ def _serialize(self, target_obj, data_type=None, **kwargs): serialized = {} if is_xml_model_serialization: - serialized = target_obj._create_xml_node() + serialized = target_obj._create_xml_node() # pylint: disable=protected-access try: - attributes = target_obj._attribute_map + attributes = target_obj._attribute_map # pylint: disable=protected-access for attr, attr_desc in attributes.items(): attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): continue if attr_name == "additional_properties" and attr_desc["key"] == "": @@ -602,7 +601,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if xml_desc.get("attr", False): if xml_ns: ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) serialized.set(xml_name, new_attr) # type: ignore continue if xml_desc.get("text", False): @@ -611,7 +610,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if isinstance(new_attr, list): serialized.extend(new_attr) # type: ignore elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. if "name" not in getattr(orig_attr, "_xml_map", {}): splitted_tag = new_attr.tag.split("}") if len(splitted_tag) == 2: # Namespace @@ -622,12 +622,11 @@ def _serialize(self, target_obj, data_type=None, **kwargs): else: # That's a basic type # Integrate namespace if necessary local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) + local_node.text = str(new_attr) serialized.append(local_node) # type: ignore else: # JSON for k in reversed(keys): # type: ignore - unflattened = {k: new_attr} - new_attr = unflattened + new_attr = {k: new_attr} _new_attr = new_attr _serialized = serialized @@ -636,28 +635,29 @@ def _serialize(self, target_obj, data_type=None, **kwargs): _serialized.update(_new_attr) # type: ignore _new_attr = _new_attr[k] # type: ignore _serialized = _serialized[k] - except ValueError: - continue + except ValueError as err: + if isinstance(err, SerializationError): + raise except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized + raise SerializationError(msg) from err + return serialized def body(self, data, data_type, **kwargs): """Serialize data intended for a request body. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body """ # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) try: is_xml_model_serialization = kwargs["is_xml"] except KeyError: @@ -681,20 +681,22 @@ def body(self, data, data_type, **kwargs): attribute_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, ] - data = deserializer._deserialize(data_type, data) + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + raise SerializationError("Unable to build a model: " + str(err)) from err return self._serialize(data, data_type, **kwargs) def url(self, name, data, data_type, **kwargs): """Serialize data intended for a URL path. - :param data: The data to be serialized. + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None """ try: output = self.serialize_data(data, data_type, **kwargs) @@ -703,30 +705,30 @@ def url(self, name, data, data_type, **kwargs): if kwargs.get("skip_quote") is True: output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output def query(self, name, data, data_type, **kwargs): """Serialize data intended for a URL query. - :param data: The data to be serialized. + :param str name: The name of the query parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter """ try: # Treat the list aside, since we don't want to encode the div separator if data_type.startswith("["): internal_data_type = data_type[1:-1] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) # Not a list, regular serialization output = self.serialize_data(data, data_type, **kwargs) @@ -736,19 +738,20 @@ def query(self, name, data, data_type, **kwargs): output = str(output) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def header(self, name, data, data_type, **kwargs): """Serialize data intended for a request header. - :param data: The data to be serialized. + :param str name: The name of the header. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -757,30 +760,31 @@ def header(self, name, data, data_type, **kwargs): output = self.serialize_data(data, data_type, **kwargs) if data_type == "bool": output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def serialize_data(self, data, data_type, **kwargs): """Serialize generic data according to supplied data type. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list """ if data is None: raise ValueError("No value for given attribute") try: + if data is CoreNull: + return None if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) - elif data_type in self.serialize_type: + if data_type in self.serialize_type: return self.serialize_type[data_type](data, **kwargs) # If dependencies is empty, try with current data class @@ -795,12 +799,11 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) if custom_serializer: return custom_serializer @@ -816,23 +819,26 @@ def serialize_basic(cls, data, data_type, **kwargs): - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - is_xml bool : If set, use xml_basic_types_serializers - :param data: Object to be serialized. + :param obj data: Object to be serialized. :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec + return eval(data_type)(data) # nosec # pylint: disable=eval-used @classmethod def serialize_unicode(cls, data): """Special handling for serializing unicode strings in Py2. Encode to UTF-8 if unicode, otherwise handle as a str. - :param data: Object to be serialized. + :param str data: Object to be serialized. :rtype: str + :return: serialized object """ try: # If I received an enum, return its value return data.value @@ -846,8 +852,7 @@ def serialize_unicode(cls, data): return data except NameError: return str(data) - else: - return str(data) + return str(data) def serialize_iter(self, data, iter_type, div=None, **kwargs): """Serialize iterable. @@ -857,13 +862,13 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): serialization_ctxt['type'] should be same as data_type. - is_xml bool : If set, serialize as XML - :param list attr: Object to be serialized. + :param list data: Object to be serialized. :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. :param str div: If set, this str will be used to combine the elements in the iterable into a combined string. Default is 'None'. + Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -875,9 +880,14 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): for d in data: try: serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized.append(None) + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + if div: serialized = ["" if s is None else str(s) for s in serialized] serialized = div.join(serialized) @@ -913,16 +923,17 @@ def serialize_dict(self, attr, dict_type, **kwargs): :param dict attr: Object to be serialized. :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. :rtype: dict + :return: serialized dictionary """ serialization_ctxt = kwargs.get("serialization_ctxt", {}) serialized = {} for key, value in attr.items(): try: serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized[self.serialize_unicode(key)] = None if "xml" in serialization_ctxt: @@ -937,7 +948,7 @@ def serialize_dict(self, attr, dict_type, **kwargs): return serialized - def serialize_object(self, attr, **kwargs): + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Serialize a generic object. This will be handled as a dictionary. If object passed in is not a basic type (str, int, float, dict, list) it will simply be @@ -945,6 +956,7 @@ def serialize_object(self, attr, **kwargs): :param dict attr: Object to be serialized. :rtype: dict or str + :return: serialized object """ if attr is None: return None @@ -955,7 +967,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) if obj_type is _long_type: return self.serialize_long(attr) - if obj_type is unicode_str: + if obj_type is str: return self.serialize_unicode(attr) if obj_type is datetime.datetime: return self.serialize_iso(attr) @@ -969,7 +981,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_decimal(attr) # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): + if obj_type in self.dependencies.values() or isinstance(attr, Model): return self._serialize(attr) if obj_type == dict: @@ -1000,56 +1012,61 @@ def serialize_enum(attr, enum_obj=None): try: enum_obj(result) # type: ignore return result - except ValueError: + except ValueError as exc: for enum_value in enum_obj: # type: ignore if enum_value.value.lower() == str(attr).lower(): return enum_value.value error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) + raise SerializationError(error.format(attr, enum_obj)) from exc @staticmethod - def serialize_bytearray(attr, **kwargs): + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument """Serialize bytearray into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ return b64encode(attr).decode() @staticmethod - def serialize_base64(attr, **kwargs): + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument """Serialize str into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ encoded = b64encode(attr).decode("ascii") return encoded.strip("=").replace("+", "-").replace("/", "_") @staticmethod - def serialize_decimal(attr, **kwargs): + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument """Serialize Decimal object to float. - :param attr: Object to be serialized. + :param decimal attr: Object to be serialized. :rtype: float + :return: serialized decimal """ return float(attr) @staticmethod - def serialize_long(attr, **kwargs): + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument """Serialize long (Py2) or int (Py3). - :param attr: Object to be serialized. + :param int attr: Object to be serialized. :rtype: int/long + :return: serialized long """ return _long_type(attr) @staticmethod - def serialize_date(attr, **kwargs): + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument """Serialize Date object into ISO-8601 formatted string. :param Date attr: Object to be serialized. :rtype: str + :return: serialized date """ if isinstance(attr, str): attr = isodate.parse_date(attr) @@ -1057,11 +1074,12 @@ def serialize_date(attr, **kwargs): return t @staticmethod - def serialize_time(attr, **kwargs): + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument """Serialize Time object into ISO-8601 formatted string. :param datetime.time attr: Object to be serialized. :rtype: str + :return: serialized time """ if isinstance(attr, str): attr = isodate.parse_time(attr) @@ -1071,30 +1089,32 @@ def serialize_time(attr, **kwargs): return t @staticmethod - def serialize_duration(attr, **kwargs): + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument """Serialize TimeDelta object into ISO-8601 formatted string. :param TimeDelta attr: Object to be serialized. :rtype: str + :return: serialized duration """ if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) @staticmethod - def serialize_rfc(attr, **kwargs): + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: TypeError if format invalid. + :raises TypeError: if format invalid. + :return: serialized rfc """ try: if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( Serializer.days[utc.tm_wday], @@ -1107,12 +1127,13 @@ def serialize_rfc(attr, **kwargs): ) @staticmethod - def serialize_iso(attr, **kwargs): + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into ISO-8601 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: SerializationError if format invalid. + :raises SerializationError: if format invalid. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1132,19 +1153,20 @@ def serialize_iso(attr, **kwargs): return date + microseconds + "Z" except (ValueError, OverflowError) as err: msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err except AttributeError as err: msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) + raise TypeError(msg) from err @staticmethod - def serialize_unix(attr, **kwargs): + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into IntTime format. This is represented as seconds. :param Datetime attr: Object to be serialized. :rtype: int - :raises: SerializationError if format invalid + :raises SerializationError: if format invalid + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1152,16 +1174,17 @@ def serialize_unix(attr, **kwargs): if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc -def rest_key_extractor(attr, attr_desc, data): +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument key = attr_desc["key"] working_data = data while "." in key: - dict_keys = _FLATTEN.split(key) + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(List[str], _FLATTEN.split(key)) if len(dict_keys) == 1: key = _decode_attribute_map_key(dict_keys[0]) break @@ -1170,14 +1193,15 @@ def rest_key_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) return working_data.get(key) -def rest_key_case_insensitive_extractor(attr, attr_desc, data): +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): key = attr_desc["key"] working_data = data @@ -1191,7 +1215,6 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1199,17 +1222,29 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): return attribute_key_case_insensitive_extractor(key, None, working_data) -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) return attribute_key_extractor(dict_keys[-1], None, data) -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument """Extract the attribute in "data" based on the last part of the JSON path key. This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) @@ -1242,11 +1277,11 @@ def _extract_name_from_internal_type(internal_type): xml_name = internal_type_xml_map.get("name", internal_type.__name__) xml_ns = internal_type_xml_map.get("ns", None) if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) return xml_name -def xml_key_extractor(attr, attr_desc, data): +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements if isinstance(data, dict): return None @@ -1266,7 +1301,7 @@ def xml_key_extractor(attr, attr_desc, data): # Integrate namespace if necessary xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) # If it's an attribute, that's simple if xml_desc.get("attr", False): @@ -1298,22 +1333,21 @@ def xml_key_extractor(attr, attr_desc, data): if is_iter_type: if is_wrapped: return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list + return [] # not wrapped, assume empty list return None # Assume it's not there, maybe an optional node. # If is_iter_type and not wrapped, return all found children if is_iter_type: if not is_wrapped: return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name ) - return list(children[0]) # Might be empty list and that's ok. + ) + return list(children[0]) # Might be empty list and that's ok. # Here it's not a itertype, we should have found one element only or empty if len(children) > 1: @@ -1321,7 +1355,7 @@ def xml_key_extractor(attr, attr_desc, data): return children[0] -class Deserializer(object): +class Deserializer: """Response object model deserializer. :param dict classes: Class type dictionary for deserializing complex types. @@ -1330,9 +1364,9 @@ class Deserializer(object): basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1352,7 +1386,7 @@ def __init__(self, classes=None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_extractors = [rest_key_extractor, xml_key_extractor] # Additional properties only works if the "rest_key_extractor" is used to # extract the keys. Making it to work whatever the key extractor is too much @@ -1368,27 +1402,29 @@ def __call__(self, target_obj, response_data, content_type=None): :param str target_obj: Target data type to deserialize to. :param requests.Response response_data: REST response object. :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) - def _deserialize(self, target_obj, data): + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements """Call the deserializer on a model. Data needs to be already deserialized as JSON or XML ElementTree :param str target_obj: Target data type to deserialize to. :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ # This is already a model, go recursive just in case if hasattr(data, "_attribute_map"): constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] try: - for attr, mapconfig in data._attribute_map.items(): + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access if attr in constants: continue value = getattr(data, attr) @@ -1405,15 +1441,15 @@ def _deserialize(self, target_obj, data): response, class_name = self._classify_target(target_obj, data) - if isinstance(response, basestring): + if isinstance(response, str): return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): + if isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) - if data is None: + if data is None or data is CoreNull: return data try: - attributes = response._attribute_map # type: ignore + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access d_attrs = {} for attr, attr_desc in attributes.items(): # Check empty string. If it's not empty, someone has a real "additionalProperties"... @@ -1442,10 +1478,9 @@ def _deserialize(self, target_obj, data): d_attrs[attr] = value except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) def _build_additional_properties(self, attribute_map, data): if not self.additional_properties_detection: @@ -1471,22 +1506,24 @@ def _classify_target(self, target, data): Once classification has been determined, initialize object. :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple """ if target is None: return None, None - if isinstance(target, basestring): + if isinstance(target, str): try: target = self.dependencies[target] except KeyError: return target, target try: - target = target._classify(data, self.dependencies) + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access except AttributeError: pass # Target is not a Model, no classify - return target, target.__class__.__name__ + return target, target.__class__.__name__ # type: ignore def failsafe_deserialize(self, target_obj, data, content_type=None): """Ignores any errors encountered in deserialization, @@ -1496,12 +1533,14 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): a deserialization error. :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object """ try: return self(target_obj, data, content_type=content_type) - except: + except: # pylint: disable=bare-except _LOGGER.debug( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) @@ -1519,10 +1558,12 @@ def _unpack_content(raw_data, content_type=None): If raw_data is something else, bypass all logic and return it directly. - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. :raises JSONDecodeError: If JSON is requested and parsing is impossible. :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. """ # Assume this is enough to detect a Pipeline Response without importing it context = getattr(raw_data, "context", {}) @@ -1539,31 +1580,42 @@ def _unpack_content(raw_data, content_type=None): if hasattr(raw_data, "_content_consumed"): return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore return raw_data def _instantiate_model(self, response, attrs, additional_properties=None): """Instantiate a response model passing in deserialized args. - :param response: The response model class. - :param d_attrs: The deserialized response attributes. + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. """ if callable(response): subtype = getattr(response, "_subtype_map", {}) try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} response_obj = response(**kwargs) for attr in readonly: setattr(response_obj, attr, attrs.get(attr)) if additional_properties: - response_obj.additional_properties = additional_properties + response_obj.additional_properties = additional_properties # type: ignore return response_obj except TypeError as err: msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1572,15 +1624,16 @@ def _instantiate_model(self, response, attrs, additional_properties=None): except Exception as exp: msg = "Unable to populate response model. " msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) + raise DeserializationError(msg) from exp - def deserialize_data(self, data, data_type): + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements """Process data for deserialization according to data type. :param str data: The response string to be deserialized. :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1594,7 +1647,11 @@ def deserialize_data(self, data, data_type): if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): return data - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: return None data_val = self.deserialize_type[data_type](data) @@ -1613,15 +1670,15 @@ def deserialize_data(self, data, data_type): except (ValueError, TypeError, AttributeError) as err: msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) def deserialize_iter(self, attr, iter_type): """Deserialize an iterable. :param list attr: Iterable to be deserialized. :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. :rtype: list """ if attr is None: @@ -1638,6 +1695,7 @@ def deserialize_dict(self, attr, dict_type): :param dict/list attr: Dictionary to be deserialized. Also accepts a list of key, value pairs. :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. :rtype: dict """ if isinstance(attr, list): @@ -1648,20 +1706,21 @@ def deserialize_dict(self, attr, dict_type): attr = {el.tag: el.text for el in attr} return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - def deserialize_object(self, attr, **kwargs): + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Deserialize a generic object. This will be handled as a dictionary. :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. :rtype: dict - :raises: TypeError if non-builtin datatype encountered. + :raises TypeError: if non-builtin datatype encountered. """ if attr is None: return None if isinstance(attr, ET.Element): # Do no recurse on XML, just return the tree as-is return attr - if isinstance(attr, basestring): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1687,11 +1746,10 @@ def deserialize_object(self, attr, **kwargs): pass return deserialized - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) - def deserialize_basic(self, attr, data_type): + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements """Deserialize basic builtin data type from string. Will attempt to convert to str, int, float and bool. This function will also accept '1', '0', 'true' and 'false' as @@ -1699,8 +1757,9 @@ def deserialize_basic(self, attr, data_type): :param str attr: response string to be deserialized. :param str data_type: deserialization data type. + :return: Deserialized basic type. :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. + :raises TypeError: if string format is not valid. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1710,24 +1769,23 @@ def deserialize_basic(self, attr, data_type): if data_type == "str": # None or '', node is empty string. return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, basestring): + if isinstance(attr, str): if attr.lower() in ["true", "1"]: return True - elif attr.lower() in ["false", "0"]: + if attr.lower() in ["false", "0"]: return False raise TypeError("Invalid boolean value: {}".format(attr)) if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec + return eval(data_type)(attr) # nosec # pylint: disable=eval-used @staticmethod def deserialize_unicode(data): @@ -1735,6 +1793,7 @@ def deserialize_unicode(data): as a string. :param str data: response string to be deserialized. + :return: Deserialized string. :rtype: str or unicode """ # We might be here because we have an enum modeled as string, @@ -1748,8 +1807,7 @@ def deserialize_unicode(data): return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1761,6 +1819,7 @@ def deserialize_enum(data, enum_obj): :param str data: Response string to be deserialized. If this value is None or invalid it will be returned as-is. :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. :rtype: Enum """ if isinstance(data, enum_obj) or data is None: @@ -1769,12 +1828,11 @@ def deserialize_enum(data, enum_obj): data = data.value if isinstance(data, int): # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 try: return list(enum_obj.__members__.values())[data] - except IndexError: + except IndexError as exc: error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) + raise DeserializationError(error.format(data, enum_obj)) from exc try: return enum_obj(str(data)) except ValueError: @@ -1790,8 +1848,9 @@ def deserialize_bytearray(attr): """Deserialize string into bytearray. :param str attr: response string to be deserialized. + :return: Deserialized bytearray :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1802,8 +1861,9 @@ def deserialize_base64(attr): """Deserialize base64 encoded string into string. :param str attr: response string to be deserialized. + :return: Deserialized base64 string :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1817,24 +1877,26 @@ def deserialize_decimal(attr): """Deserialize string into Decimal object. :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text try: - return decimal.Decimal(attr) # type: ignore + return decimal.Decimal(str(attr)) # type: ignore except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err @staticmethod def deserialize_long(attr): """Deserialize string into long (Py2) or int (Py3). :param str attr: response string to be deserialized. + :return: Deserialized int :rtype: long or int - :raises: ValueError if string format invalid. + :raises ValueError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1845,8 +1907,9 @@ def deserialize_duration(attr): """Deserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. + :return: Deserialized duration :rtype: TimeDelta - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1854,32 +1917,33 @@ def deserialize_duration(attr): duration = isodate.parse_duration(attr) except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration + raise DeserializationError(msg) from err + return duration @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. :param str attr: response string to be deserialized. + :return: Deserialized date :rtype: Date - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore raise DeserializationError("Date must have only digits and -. Received: %s" % attr) # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) @staticmethod def deserialize_time(attr): """Deserialize ISO-8601 formatted string into time object. :param str attr: response string to be deserialized. + :return: Deserialized time :rtype: datetime.time - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1892,31 +1956,32 @@ def deserialize_rfc(attr): """Deserialize RFC-1123 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text try: parsed_date = email.utils.parsedate_tz(attr) # type: ignore date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) ) if not date_obj.tzinfo: date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + return date_obj @staticmethod def deserialize_iso(attr): """Deserialize ISO-8601 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1943,9 +2008,8 @@ def deserialize_iso(attr): raise OverflowError("Hit max or min date") except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + return date_obj @staticmethod def deserialize_unix(attr): @@ -1953,15 +2017,16 @@ def deserialize_unix(attr): This is represented as seconds. :param int attr: Object to be serialized. + :return: Deserialized datetime :rtype: Datetime - :raises: DeserializationError if format invalid + :raises DeserializationError: if format invalid """ if isinstance(attr, ET.Element): attr = int(attr.text) # type: ignore try: + attr = int(attr) date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) except ValueError as err: msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_utils/utils.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_utils/utils.py new file mode 100644 index 000000000000..39b612f39a9b --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_utils/utils.py @@ -0,0 +1,25 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from abc import ABC +from typing import Generic, TYPE_CHECKING, TypeVar + +if TYPE_CHECKING: + from .serialization import Deserializer, Serializer + + +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") + + +class ClientMixinABC(ABC, Generic[TClient, TConfig]): + """DO NOT use this class. It is for internal typing use only.""" + + _client: TClient + _config: TConfig + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_vendor.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_vendor.py deleted file mode 100644 index 9aad73fc743e..000000000000 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_vendor.py +++ /dev/null @@ -1,27 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.pipeline.transport import HttpRequest - - -def _convert_request(request, files=None): - data = request.content if not files else None - request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) - if files: - request.set_formdata_body(files) - return request - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_version.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_version.py index 2eda20789583..be0a9764bc6d 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_version.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "2.0.0b2" +VERSION = "2.0.0b3" diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/__init__.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/__init__.py index 42051a8571a2..ed872336d0d8 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/__init__.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/__init__.py @@ -5,12 +5,18 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._alerts_management_client import AlertsManagementClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._alerts_management_client import AlertsManagementClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk @@ -18,6 +24,6 @@ __all__ = [ "AlertsManagementClient", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/_alerts_management_client.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/_alerts_management_client.py index 3848d1701f82..739835d4e8c2 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/_alerts_management_client.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/_alerts_management_client.py @@ -7,33 +7,39 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING +from typing import Any, Awaitable, Optional, TYPE_CHECKING, cast +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.settings import settings from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy +from azure.mgmt.core.tools import get_arm_endpoints from .. import models as _models -from .._serialization import Deserializer, Serializer +from .._utils.serialization import Deserializer, Serializer from ._configuration import AlertsManagementClientConfiguration from .operations import ( AlertProcessingRulesOperations, + AlertRuleRecommendationsOperations, + AlertsManagementClientOperationsMixin, AlertsOperations, + IssueOperations, Operations, PrometheusRuleGroupsOperations, SmartGroupsOperations, ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class AlertsManagementClient: # pylint: disable=client-accepts-api-version-keyword +class AlertsManagementClient( + AlertsManagementClientOperationsMixin +): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """AlertsManagement Client. - :ivar alert_processing_rules: AlertProcessingRulesOperations operations - :vartype alert_processing_rules: - azure.mgmt.alertsmanagement.aio.operations.AlertProcessingRulesOperations :ivar prometheus_rule_groups: PrometheusRuleGroupsOperations operations :vartype prometheus_rule_groups: azure.mgmt.alertsmanagement.aio.operations.PrometheusRuleGroupsOperations @@ -43,41 +49,88 @@ class AlertsManagementClient: # pylint: disable=client-accepts-api-version-keyw :vartype alerts: azure.mgmt.alertsmanagement.aio.operations.AlertsOperations :ivar smart_groups: SmartGroupsOperations operations :vartype smart_groups: azure.mgmt.alertsmanagement.aio.operations.SmartGroupsOperations + :ivar alert_rule_recommendations: AlertRuleRecommendationsOperations operations + :vartype alert_rule_recommendations: + azure.mgmt.alertsmanagement.aio.operations.AlertRuleRecommendationsOperations + :ivar alert_processing_rules: AlertProcessingRulesOperations operations + :vartype alert_processing_rules: + azure.mgmt.alertsmanagement.aio.operations.AlertProcessingRulesOperations + :ivar issue: IssueOperations operations + :vartype issue: azure.mgmt.alertsmanagement.aio.operations.IssueOperations :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param issue_name: The name of the IssueResource. Required. + :type issue_name: str :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str - :param base_url: Service URL. Default value is "https://management.azure.com". + :param base_url: Service URL. Default value is None. :type base_url: str """ def __init__( self, credential: "AsyncTokenCredential", + issue_name: str, subscription_id: str, - base_url: str = "https://management.azure.com", + base_url: Optional[str] = None, **kwargs: Any ) -> None: + _cloud = kwargs.pop("cloud_setting", None) or settings.current.azure_cloud # type: ignore + _endpoints = get_arm_endpoints(_cloud) + if not base_url: + base_url = _endpoints["resource_manager"] + credential_scopes = kwargs.pop("credential_scopes", _endpoints["credential_scopes"]) self._config = AlertsManagementClientConfiguration( - credential=credential, subscription_id=subscription_id, **kwargs + credential=credential, + issue_name=issue_name, + subscription_id=subscription_id, + credential_scopes=credential_scopes, + **kwargs + ) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + AsyncARMAutoResourceProviderRegistrationPolicy(), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncARMPipelineClient = AsyncARMPipelineClient( + base_url=cast(str, base_url), policies=_policies, **kwargs ) - self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False - self.alert_processing_rules = AlertProcessingRulesOperations( - self._client, self._config, self._serialize, self._deserialize - ) self.prometheus_rule_groups = PrometheusRuleGroupsOperations( self._client, self._config, self._serialize, self._deserialize ) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.alerts = AlertsOperations(self._client, self._config, self._serialize, self._deserialize) self.smart_groups = SmartGroupsOperations(self._client, self._config, self._serialize, self._deserialize) + self.alert_rule_recommendations = AlertRuleRecommendationsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.alert_processing_rules = AlertProcessingRulesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.issue = IssueOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + def _send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -97,14 +150,14 @@ def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncH request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "AlertsManagementClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self - async def __aexit__(self, *exc_details) -> None: + async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/_configuration.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/_configuration.py index 4295ad594068..da736e45eac7 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/_configuration.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/_configuration.py @@ -8,18 +8,16 @@ from typing import Any, TYPE_CHECKING -from azure.core.configuration import Configuration from azure.core.pipeline import policies from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -class AlertsManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class AlertsManagementClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for AlertsManagementClient. Note that all parameters used to create this instance are saved as instance @@ -27,21 +25,28 @@ class AlertsManagementClientConfiguration(Configuration): # pylint: disable=too :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param issue_name: The name of the IssueResource. Required. + :type issue_name: str :param subscription_id: The ID of the target subscription. Required. :type subscription_id: str """ - def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(AlertsManagementClientConfiguration, self).__init__(**kwargs) + def __init__( + self, credential: "AsyncTokenCredential", issue_name: str, subscription_id: str, **kwargs: Any + ) -> None: if credential is None: raise ValueError("Parameter 'credential' must not be None.") + if issue_name is None: + raise ValueError("Parameter 'issue_name' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") self.credential = credential + self.issue_name = issue_name self.subscription_id = subscription_id self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "mgmt-alertsmanagement/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -50,9 +55,9 @@ def _configure(self, **kwargs: Any) -> None: self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/__init__.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/__init__.py index c8dd1e48dcf0..19989121f059 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/__init__.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/__init__.py @@ -5,23 +5,35 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._alert_processing_rules_operations import AlertProcessingRulesOperations -from ._prometheus_rule_groups_operations import PrometheusRuleGroupsOperations -from ._operations import Operations -from ._alerts_operations import AlertsOperations -from ._smart_groups_operations import SmartGroupsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._prometheus_rule_groups_operations import PrometheusRuleGroupsOperations # type: ignore +from ._operations import Operations # type: ignore +from ._alerts_operations import AlertsOperations # type: ignore +from ._smart_groups_operations import SmartGroupsOperations # type: ignore +from ._alert_rule_recommendations_operations import AlertRuleRecommendationsOperations # type: ignore +from ._alert_processing_rules_operations import AlertProcessingRulesOperations # type: ignore +from ._issue_operations import IssueOperations # type: ignore +from ._alerts_management_client_operations import AlertsManagementClientOperationsMixin # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AlertProcessingRulesOperations", "PrometheusRuleGroupsOperations", "Operations", "AlertsOperations", "SmartGroupsOperations", + "AlertRuleRecommendationsOperations", + "AlertProcessingRulesOperations", + "IssueOperations", + "AlertsManagementClientOperationsMixin", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alert_processing_rules_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alert_processing_rules_operations.py index 4ffa545dcedd..d48aaea7ad50 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alert_processing_rules_operations.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alert_processing_rules_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from collections.abc import MutableMapping +from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -19,15 +20,14 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._alert_processing_rules_operations import ( build_create_or_update_request, build_delete_request, @@ -36,11 +36,8 @@ build_list_by_subscription_request, build_update_request, ) +from .._configuration import AlertsManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,16 +56,15 @@ class AlertProcessingRulesOperations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AlertsManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AlertProcessingRule"]: """List all alert processing rules in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AlertProcessingRule or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.AlertProcessingRule] @@ -77,10 +73,10 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AlertPro _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) cls: ClsType[_models.AlertProcessingRulesList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -91,22 +87,19 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.AlertPro def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AlertProcessingRulesList", pipeline_response) @@ -116,26 +109,23 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated4, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/actionRules" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -144,7 +134,6 @@ def list_by_resource_group( :param resource_group_name: Resource group name where the resource is created. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AlertProcessingRule or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.AlertProcessingRule] @@ -153,10 +142,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) cls: ClsType[_models.AlertProcessingRulesList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -167,23 +156,20 @@ def list_by_resource_group( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_group_request( + _request = build_list_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AlertProcessingRulesList", pipeline_response) @@ -193,26 +179,23 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated4, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules" - } - @distributed_trace_async async def get_by_name( self, resource_group_name: str, alert_processing_rule_name: str, **kwargs: Any @@ -224,12 +207,11 @@ async def get_by_name( :param alert_processing_rule_name: The name of the alert processing rule that needs to be fetched. Required. :type alert_processing_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertProcessingRule or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -240,45 +222,40 @@ async def get_by_name( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) cls: ClsType[_models.AlertProcessingRule] = kwargs.pop("cls", None) - request = build_get_by_name_request( + _request = build_get_by_name_request( resource_group_name=resource_group_name, alert_processing_rule_name=alert_processing_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_by_name.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated4, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - deserialized = self._deserialize("AlertProcessingRule", pipeline_response) + deserialized = self._deserialize("AlertProcessingRule", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized + return cls(pipeline_response, deserialized, response_headers) # type: ignore - get_by_name.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{alertProcessingRuleName}" - } + return deserialized # type: ignore @overload async def create_or_update( @@ -302,7 +279,6 @@ async def create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertProcessingRule or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule :raises ~azure.core.exceptions.HttpResponseError: @@ -313,7 +289,7 @@ async def create_or_update( self, resource_group_name: str, alert_processing_rule_name: str, - alert_processing_rule: IO, + alert_processing_rule: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -326,11 +302,10 @@ async def create_or_update( created/updated. Required. :type alert_processing_rule_name: str :param alert_processing_rule: Alert processing rule to be created/updated. Required. - :type alert_processing_rule: IO + :type alert_processing_rule: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertProcessingRule or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule :raises ~azure.core.exceptions.HttpResponseError: @@ -341,7 +316,7 @@ async def create_or_update( self, resource_group_name: str, alert_processing_rule_name: str, - alert_processing_rule: Union[_models.AlertProcessingRule, IO], + alert_processing_rule: Union[_models.AlertProcessingRule, IO[bytes]], **kwargs: Any ) -> _models.AlertProcessingRule: """Create or update an alert processing rule. @@ -351,18 +326,15 @@ async def create_or_update( :param alert_processing_rule_name: The name of the alert processing rule that needs to be created/updated. Required. :type alert_processing_rule_name: str - :param alert_processing_rule: Alert processing rule to be created/updated. Is either a model - type or a IO type. Required. - :type alert_processing_rule: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param alert_processing_rule: Alert processing rule to be created/updated. Is either a + AlertProcessingRule type or a IO[bytes] type. Required. + :type alert_processing_rule: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule or + IO[bytes] :return: AlertProcessingRule or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -373,19 +345,19 @@ async def create_or_update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AlertProcessingRule] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(alert_processing_rule, (IO, bytes)): + if isinstance(alert_processing_rule, (IOBase, bytes)): _content = alert_processing_rule else: _json = self._serialize.body(alert_processing_rule, "AlertProcessingRule") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, alert_processing_rule_name=alert_processing_rule_name, subscription_id=self._config.subscription_id, @@ -393,48 +365,35 @@ async def create_or_update( content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated4, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} - if response.status_code == 200: - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - - deserialized = self._deserialize("AlertProcessingRule", pipeline_response) - - if response.status_code == 201: - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - deserialized = self._deserialize("AlertProcessingRule", pipeline_response) + deserialized = self._deserialize("AlertProcessingRule", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{alertProcessingRuleName}" - } - @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, alert_processing_rule_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, alert_processing_rule_name: str, **kwargs: Any) -> None: """Delete an alert processing rule. :param resource_group_name: Resource group name where the resource is created. Required. @@ -442,12 +401,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :param alert_processing_rule_name: The name of the alert processing rule that needs to be deleted. Required. :type alert_processing_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -458,45 +416,36 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, alert_processing_rule_name=alert_processing_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated4, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} - if response.status_code == 200: - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - - if response.status_code == 204: - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) if cls: - return cls(pipeline_response, None, response_headers) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{alertProcessingRuleName}" - } + return cls(pipeline_response, None, response_headers) # type: ignore @overload async def update( @@ -519,7 +468,6 @@ async def update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertProcessingRule or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule :raises ~azure.core.exceptions.HttpResponseError: @@ -530,7 +478,7 @@ async def update( self, resource_group_name: str, alert_processing_rule_name: str, - alert_processing_rule_patch: IO, + alert_processing_rule_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -542,11 +490,10 @@ async def update( :param alert_processing_rule_name: The name that needs to be updated. Required. :type alert_processing_rule_name: str :param alert_processing_rule_patch: Parameters supplied to the operation. Required. - :type alert_processing_rule_patch: IO + :type alert_processing_rule_patch: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertProcessingRule or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule :raises ~azure.core.exceptions.HttpResponseError: @@ -557,7 +504,7 @@ async def update( self, resource_group_name: str, alert_processing_rule_name: str, - alert_processing_rule_patch: Union[_models.PatchObject, IO], + alert_processing_rule_patch: Union[_models.PatchObject, IO[bytes]], **kwargs: Any ) -> _models.AlertProcessingRule: """Enable, disable, or update tags for an alert processing rule. @@ -566,18 +513,14 @@ async def update( :type resource_group_name: str :param alert_processing_rule_name: The name that needs to be updated. Required. :type alert_processing_rule_name: str - :param alert_processing_rule_patch: Parameters supplied to the operation. Is either a model - type or a IO type. Required. - :type alert_processing_rule_patch: ~azure.mgmt.alertsmanagement.models.PatchObject or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param alert_processing_rule_patch: Parameters supplied to the operation. Is either a + PatchObject type or a IO[bytes] type. Required. + :type alert_processing_rule_patch: ~azure.mgmt.alertsmanagement.models.PatchObject or IO[bytes] :return: AlertProcessingRule or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -588,19 +531,19 @@ async def update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AlertProcessingRule] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(alert_processing_rule_patch, (IO, bytes)): + if isinstance(alert_processing_rule_patch, (IOBase, bytes)): _content = alert_processing_rule_patch else: _json = self._serialize.body(alert_processing_rule_patch, "PatchObject") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, alert_processing_rule_name=alert_processing_rule_name, subscription_id=self._config.subscription_id, @@ -608,34 +551,29 @@ async def update( content_type=content_type, json=_json, content=_content, - template_url=self.update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated4, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - deserialized = self._deserialize("AlertProcessingRule", pipeline_response) + deserialized = self._deserialize("AlertProcessingRule", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized + return cls(pipeline_response, deserialized, response_headers) # type: ignore - update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{alertProcessingRuleName}" - } + return deserialized # type: ignore diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alert_rule_recommendations_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alert_rule_recommendations_operations.py new file mode 100644 index 000000000000..a08abb7549ed --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alert_rule_recommendations_operations.py @@ -0,0 +1,197 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar + +from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._alert_rule_recommendations_operations import ( + build_list_by_resource_request, + build_list_by_target_type_request, +) +from .._configuration import AlertsManagementClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AlertRuleRecommendationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.alertsmanagement.aio.AlertsManagementClient`'s + :attr:`alert_rule_recommendations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AlertsManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_resource( + self, resource_uri: str, **kwargs: Any + ) -> AsyncIterable["_models.AlertRuleRecommendationResource"]: + """Retrieve alert rule recommendations for a resource. + + :param resource_uri: The identifier of the resource. Required. + :type resource_uri: str + :return: An iterator like instance of either AlertRuleRecommendationResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.AlertRuleRecommendationResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-08-01-preview")) + cls: ClsType[_models.AlertRuleRecommendationsListResponse] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_resource_request( + resource_uri=resource_uri, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AlertRuleRecommendationsListResponse", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_target_type( + self, target_type: str, **kwargs: Any + ) -> AsyncIterable["_models.AlertRuleRecommendationResource"]: + """Retrieve alert rule recommendations for a target type. + + :param target_type: The recommendations target type. Required. + :type target_type: str + :return: An iterator like instance of either AlertRuleRecommendationResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.AlertRuleRecommendationResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-08-01-preview")) + cls: ClsType[_models.AlertRuleRecommendationsListResponse] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_target_type_request( + subscription_id=self._config.subscription_id, + target_type=target_type, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AlertRuleRecommendationsListResponse", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alerts_management_client_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alerts_management_client_operations.py new file mode 100644 index 000000000000..aa14441bacfd --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alerts_management_client_operations.py @@ -0,0 +1,135 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._utils.utils import ClientMixinABC +from ...operations._alerts_management_client_operations import build_preview_alert_rule_request +from .._configuration import AlertsManagementClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class AlertsManagementClientOperationsMixin(ClientMixinABC[AsyncPipelineClient, AlertsManagementClientConfiguration]): + + @overload + async def preview_alert_rule( + self, parameters: _models.PreviewAlertRuleRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PreviewAlertRuleResponse: + """Retrieves the results of a simulated historical execution of an alert rule. + + :param parameters: The alert rule to preview. Required. + :type parameters: ~azure.mgmt.alertsmanagement.models.PreviewAlertRuleRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PreviewAlertRuleResponse or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.PreviewAlertRuleResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def preview_alert_rule( + self, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PreviewAlertRuleResponse: + """Retrieves the results of a simulated historical execution of an alert rule. + + :param parameters: The alert rule to preview. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PreviewAlertRuleResponse or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.PreviewAlertRuleResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def preview_alert_rule( + self, parameters: Union[_models.PreviewAlertRuleRequest, IO[bytes]], **kwargs: Any + ) -> _models.PreviewAlertRuleResponse: + """Retrieves the results of a simulated historical execution of an alert rule. + + :param parameters: The alert rule to preview. Is either a PreviewAlertRuleRequest type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.alertsmanagement.models.PreviewAlertRuleRequest or IO[bytes] + :return: PreviewAlertRuleResponse or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.PreviewAlertRuleResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PreviewAlertRuleResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PreviewAlertRuleRequest") + + _request = build_preview_alert_rule_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PreviewAlertRuleResponse", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alerts_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alerts_operations.py index 4e3955d1a17e..108d159369ec 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alerts_operations.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alerts_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from collections.abc import MutableMapping +from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -19,28 +20,26 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._alerts_operations import ( build_change_state_request, build_get_all_request, build_get_by_id_request, + build_get_enrichments_request, build_get_history_request, build_get_summary_request, + build_list_enrichments_request, build_meta_data_request, ) +from .._configuration import AlertsManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,10 +58,10 @@ class AlertsOperations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AlertsManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async async def meta_data(self, identifier: Union[str, _models.Identifier], **kwargs: Any) -> _models.AlertsMetaData: @@ -71,12 +70,11 @@ async def meta_data(self, identifier: Union[str, _models.Identifier], **kwargs: :param identifier: Identification of the information to be retrieved by API call. "MonitorServiceList" Required. :type identifier: str or ~azure.mgmt.alertsmanagement.models.Identifier - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertsMetaData or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertsMetaData :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -87,44 +85,40 @@ async def meta_data(self, identifier: Union[str, _models.Identifier], **kwargs: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) cls: ClsType[_models.AlertsMetaData] = kwargs.pop("cls", None) - request = build_meta_data_request( + _request = build_meta_data_request( identifier=identifier, api_version=api_version, - template_url=self.meta_data.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertsMetaData", pipeline_response) + deserialized = self._deserialize("AlertsMetaData", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - meta_data.metadata = {"url": "/providers/Microsoft.AlertsManagement/alertsMetaData"} + return deserialized # type: ignore @distributed_trace def get_all( self, + scope: str, target_resource: Optional[str] = None, target_resource_type: Optional[str] = None, target_resource_group: Optional[str] = None, @@ -148,6 +142,8 @@ def get_all( (e.g. time range). The results can then be sorted on the basis specific fields, with the default being lastModifiedDateTime. + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str :param target_resource: Filter by target resource( which is full ARM ID) Default value is select all. Default value is None. :type target_resource: str @@ -161,7 +157,7 @@ def get_all( value is select all. Known values are: "Application Insights", "ActivityLog Administrative", "ActivityLog Security", "ActivityLog Recommendation", "ActivityLog Policy", "ActivityLog Autoscale", "Log Analytics", "Nagios", "Platform", "SCOM", "ServiceHealth", "SmartDetector", - "VM Insights", and "Zabbix". Default value is None. + "VM Insights", "Zabbix", and "Resource Health". Default value is None. :type monitor_service: str or ~azure.mgmt.alertsmanagement.models.MonitorService :param monitor_condition: Filter by monitor condition which is either 'Fired' or 'Resolved'. Default value is to select all. Known values are: "Fired" and "Resolved". Default value is @@ -171,7 +167,8 @@ def get_all( "Sev1", "Sev2", "Sev3", and "Sev4". Default value is None. :type severity: str or ~azure.mgmt.alertsmanagement.models.Severity :param alert_state: Filter by state of the alert instance. Default value is to select all. - Known values are: "New", "Acknowledged", and "Closed". Default value is None. + Known values are: "New", "Acknowledged", "Closed", "NoAlert", "Fired", "Firing", "Resolving", + and "Resolved". Default value is None. :type alert_state: str or ~azure.mgmt.alertsmanagement.models.AlertState :param alert_rule: Filter by specific alert rule. Default value is to select all. Default value is None. @@ -206,12 +203,11 @@ def get_all( :param time_range: Filter by time range by below listed values. Default value is 1 day. Known values are: "1h", "1d", "7d", and "30d". Default value is None. :type time_range: str or ~azure.mgmt.alertsmanagement.models.TimeRange - :param custom_time_range: Filter by custom time range in the format - :code:``/:code:`` where time is in (ISO-8601 format)'. Permissible - values is within 30 days from query time. Either timeRange or customTimeRange could be used - but not both. Default is none. Default value is None. + :param custom_time_range: Filter by custom time range in the format :code:``/\\ + :code:`` where time is in (ISO-8601 format)'. Permissible values is within 30 days + from query time. Either timeRange or customTimeRange could be used but not both. Default is + none. Default value is None. :type custom_time_range: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Alert or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.Alert] :raises ~azure.core.exceptions.HttpResponseError: @@ -219,12 +215,10 @@ def get_all( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) cls: ClsType[_models.AlertsList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -235,8 +229,8 @@ def get_all( def prepare_request(next_link=None): if not next_link: - request = build_get_all_request( - subscription_id=self._config.subscription_id, + _request = build_get_all_request( + scope=scope, target_resource=target_resource, target_resource_type=target_resource_type, target_resource_group=target_resource_group, @@ -255,19 +249,16 @@ def prepare_request(next_link=None): time_range=time_range, custom_time_range=custom_time_range, api_version=api_version, - template_url=self.get_all.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("AlertsList", pipeline_response) @@ -277,38 +268,38 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - get_all.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts"} - @distributed_trace_async - async def get_by_id(self, alert_id: str, **kwargs: Any) -> _models.Alert: + async def get_by_id(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: """Get a specific alert. Get information related to a specific alert. + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str :param alert_id: Unique ID of an alert instance. Required. :type alert_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -319,47 +310,41 @@ async def get_by_id(self, alert_id: str, **kwargs: Any) -> _models.Alert: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) cls: ClsType[_models.Alert] = kwargs.pop("cls", None) - request = build_get_by_id_request( + _request = build_get_by_id_request( + scope=scope, alert_id=alert_id, - subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_by_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Alert", pipeline_response) + deserialized = self._deserialize("Alert", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_by_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}" - } + return deserialized # type: ignore @overload async def change_state( self, + scope: str, alert_id: str, new_state: Union[str, _models.AlertState], comment: Optional[_models.Comments] = None, @@ -369,17 +354,18 @@ async def change_state( ) -> _models.Alert: """Change the state of an alert. + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str :param alert_id: Unique ID of an alert instance. Required. :type alert_id: str - :param new_state: New state of the alert. Known values are: "New", "Acknowledged", and - "Closed". Required. + :param new_state: New state of the alert. Known values are: "New", "Acknowledged", "Closed", + "NoAlert", "Fired", "Firing", "Resolving", and "Resolved". Required. :type new_state: str or ~azure.mgmt.alertsmanagement.models.AlertState :param comment: reason of change alert state. Default value is None. :type comment: ~azure.mgmt.alertsmanagement.models.Comments :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: @@ -388,26 +374,28 @@ async def change_state( @overload async def change_state( self, + scope: str, alert_id: str, new_state: Union[str, _models.AlertState], - comment: Optional[IO] = None, + comment: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Alert: """Change the state of an alert. + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str :param alert_id: Unique ID of an alert instance. Required. :type alert_id: str - :param new_state: New state of the alert. Known values are: "New", "Acknowledged", and - "Closed". Required. + :param new_state: New state of the alert. Known values are: "New", "Acknowledged", "Closed", + "NoAlert", "Fired", "Firing", "Resolving", and "Resolved". Required. :type new_state: str or ~azure.mgmt.alertsmanagement.models.AlertState :param comment: reason of change alert state. Default value is None. - :type comment: IO + :type comment: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: @@ -416,30 +404,29 @@ async def change_state( @distributed_trace_async async def change_state( self, + scope: str, alert_id: str, new_state: Union[str, _models.AlertState], - comment: Optional[Union[_models.Comments, IO]] = None, + comment: Optional[Union[_models.Comments, IO[bytes]]] = None, **kwargs: Any ) -> _models.Alert: """Change the state of an alert. + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str :param alert_id: Unique ID of an alert instance. Required. :type alert_id: str - :param new_state: New state of the alert. Known values are: "New", "Acknowledged", and - "Closed". Required. + :param new_state: New state of the alert. Known values are: "New", "Acknowledged", "Closed", + "NoAlert", "Fired", "Firing", "Resolving", and "Resolved". Required. :type new_state: str or ~azure.mgmt.alertsmanagement.models.AlertState - :param comment: reason of change alert state. Is either a model type or a IO type. Default - value is None. - :type comment: ~azure.mgmt.alertsmanagement.models.Comments or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param comment: reason of change alert state. Is either a Comments type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type comment: ~azure.mgmt.alertsmanagement.models.Comments or IO[bytes] :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -450,16 +437,14 @@ async def change_state( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Alert] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(comment, (IO, bytes)): + if isinstance(comment, (IOBase, bytes)): _content = comment else: if comment is not None: @@ -467,56 +452,52 @@ async def change_state( else: _json = None - request = build_change_state_request( + _request = build_change_state_request( + scope=scope, alert_id=alert_id, - subscription_id=self._config.subscription_id, new_state=new_state, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.change_state.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Alert", pipeline_response) + deserialized = self._deserialize("Alert", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - change_state.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}/changestate" - } + return deserialized # type: ignore @distributed_trace_async - async def get_history(self, alert_id: str, **kwargs: Any) -> _models.AlertModification: + async def get_history(self, scope: str, alert_id: str, **kwargs: Any) -> _models.AlertModification: """Get the history of an alert, which captures any monitor condition changes (Fired/Resolved) and alert state changes (New/Acknowledged/Closed). + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str :param alert_id: Unique ID of an alert instance. Required. :type alert_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertModification or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertModification :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -527,47 +508,41 @@ async def get_history(self, alert_id: str, **kwargs: Any) -> _models.AlertModifi _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) cls: ClsType[_models.AlertModification] = kwargs.pop("cls", None) - request = build_get_history_request( + _request = build_get_history_request( + scope=scope, alert_id=alert_id, - subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_history.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertModification", pipeline_response) + deserialized = self._deserialize("AlertModification", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_history.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}/history" - } + return deserialized # type: ignore @distributed_trace_async async def get_summary( self, + scope: str, groupby: Union[str, _models.AlertsSummaryGroupByFields], include_smart_groups_count: Optional[bool] = None, target_resource: Optional[str] = None, @@ -585,6 +560,8 @@ async def get_summary( """Get a summarized count of your alerts grouped by various parameters (e.g. grouping by 'Severity' returns the count of alerts for each severity). + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str :param groupby: This parameter allows the result set to be grouped by input fields (Maximum 2 comma separated fields supported). For example, groupby=severity or groupby=severity,alertstate. Known values are: "severity", "alertState", "monitorCondition", @@ -606,7 +583,7 @@ async def get_summary( value is select all. Known values are: "Application Insights", "ActivityLog Administrative", "ActivityLog Security", "ActivityLog Recommendation", "ActivityLog Policy", "ActivityLog Autoscale", "Log Analytics", "Nagios", "Platform", "SCOM", "ServiceHealth", "SmartDetector", - "VM Insights", and "Zabbix". Default value is None. + "VM Insights", "Zabbix", and "Resource Health". Default value is None. :type monitor_service: str or ~azure.mgmt.alertsmanagement.models.MonitorService :param monitor_condition: Filter by monitor condition which is either 'Fired' or 'Resolved'. Default value is to select all. Known values are: "Fired" and "Resolved". Default value is @@ -616,7 +593,8 @@ async def get_summary( "Sev1", "Sev2", "Sev3", and "Sev4". Default value is None. :type severity: str or ~azure.mgmt.alertsmanagement.models.Severity :param alert_state: Filter by state of the alert instance. Default value is to select all. - Known values are: "New", "Acknowledged", and "Closed". Default value is None. + Known values are: "New", "Acknowledged", "Closed", "NoAlert", "Fired", "Firing", "Resolving", + and "Resolved". Default value is None. :type alert_state: str or ~azure.mgmt.alertsmanagement.models.AlertState :param alert_rule: Filter by specific alert rule. Default value is to select all. Default value is None. @@ -624,17 +602,16 @@ async def get_summary( :param time_range: Filter by time range by below listed values. Default value is 1 day. Known values are: "1h", "1d", "7d", and "30d". Default value is None. :type time_range: str or ~azure.mgmt.alertsmanagement.models.TimeRange - :param custom_time_range: Filter by custom time range in the format - :code:``/:code:`` where time is in (ISO-8601 format)'. Permissible - values is within 30 days from query time. Either timeRange or customTimeRange could be used - but not both. Default is none. Default value is None. + :param custom_time_range: Filter by custom time range in the format :code:``/\\ + :code:`` where time is in (ISO-8601 format)'. Permissible values is within 30 days + from query time. Either timeRange or customTimeRange could be used but not both. Default is + none. Default value is None. :type custom_time_range: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertsSummary or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertsSummary :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -645,13 +622,11 @@ async def get_summary( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) cls: ClsType[_models.AlertsSummary] = kwargs.pop("cls", None) - request = build_get_summary_request( - subscription_id=self._config.subscription_id, + _request = build_get_summary_request( + scope=scope, groupby=groupby, include_smart_groups_count=include_smart_groups_count, target_resource=target_resource, @@ -665,29 +640,153 @@ async def get_summary( time_range=time_range, custom_time_range=custom_time_range, api_version=api_version, - template_url=self.get_summary.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertsSummary", pipeline_response) + deserialized = self._deserialize("AlertsSummary", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_enrichments( + self, scope: str, alert_id: str, **kwargs: Any + ) -> AsyncIterable["_models.AlertEnrichmentResponse"]: + """List the enrichments of an alert. It returns a collection of one object named default. + + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str + :param alert_id: Unique ID of an alert instance. Required. + :type alert_id: str + :return: An iterator like instance of either AlertEnrichmentResponse or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.AlertEnrichmentResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) + cls: ClsType[_models.AlertEnrichmentsList] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_enrichments_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("AlertEnrichmentsList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) - return deserialized + @distributed_trace_async + async def get_enrichments(self, scope: str, alert_id: str, **kwargs: Any) -> _models.AlertEnrichmentResponse: + """Get the enrichments of an alert. + + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str + :param alert_id: Unique ID of an alert instance. Required. + :type alert_id: str + :return: AlertEnrichmentResponse or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.AlertEnrichmentResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) + cls: ClsType[_models.AlertEnrichmentResponse] = kwargs.pop("cls", None) + + _request = build_get_enrichments_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AlertEnrichmentResponse", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - get_summary.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alertsSummary"} + return deserialized # type: ignore diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_issue_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_issue_operations.py new file mode 100644 index 000000000000..e1af6b8b319b --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_issue_operations.py @@ -0,0 +1,1161 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.async_paging import AsyncItemPaged, AsyncList +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from ... import models as _models +from ..._utils.serialization import Deserializer, Serializer +from ...operations._issue_operations import ( + build_add_or_update_alerts_request, + build_add_or_update_resources_request, + build_create_request, + build_delete_request, + build_fetch_investigation_result_request, + build_get_request, + build_list_alerts_request, + build_list_request, + build_list_resources_request, + build_start_investigation_request, + build_update_request, +) +from .._configuration import AlertsManagementClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class IssueOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.alertsmanagement.aio.AlertsManagementClient`'s + :attr:`issue` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AlertsManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, resource_uri: str, **kwargs: Any) -> AsyncIterable["_models.IssueResource"]: + """List all issues under the parent. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :return: An iterator like instance of either IssueResource or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.IssueResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + cls: ClsType[_models.IssueResourceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + resource_uri=resource_uri, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("IssueResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def get(self, resource_uri: str, **kwargs: Any) -> _models.IssueResource: + """Get issue properties. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :return: IssueResource or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.IssueResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + cls: ClsType[_models.IssueResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("IssueResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, + resource_uri: str, + resource: _models.IssueResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.IssueResource: + """Create a new issue or updates an existing one. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.mgmt.alertsmanagement.models.IssueResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: IssueResource or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.IssueResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, resource_uri: str, resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.IssueResource: + """Create a new issue or updates an existing one. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: IssueResource or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.IssueResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, resource_uri: str, resource: Union[_models.IssueResource, IO[bytes]], **kwargs: Any + ) -> _models.IssueResource: + """Create a new issue or updates an existing one. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param resource: Resource create parameters. Is either a IssueResource type or a IO[bytes] + type. Required. + :type resource: ~azure.mgmt.alertsmanagement.models.IssueResource or IO[bytes] + :return: IssueResource or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.IssueResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.IssueResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _json = self._serialize.body(resource, "IssueResource") + + _request = build_create_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("IssueResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + resource_uri: str, + properties: _models.IssueResourceUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.IssueResource: + """Update an issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param properties: The resource properties to be updated. Required. + :type properties: ~azure.mgmt.alertsmanagement.models.IssueResourceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: IssueResource or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.IssueResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, resource_uri: str, properties: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.IssueResource: + """Update an issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param properties: The resource properties to be updated. Required. + :type properties: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: IssueResource or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.IssueResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, resource_uri: str, properties: Union[_models.IssueResourceUpdate, IO[bytes]], **kwargs: Any + ) -> _models.IssueResource: + """Update an issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param properties: The resource properties to be updated. Is either a IssueResourceUpdate type + or a IO[bytes] type. Required. + :type properties: ~azure.mgmt.alertsmanagement.models.IssueResourceUpdate or IO[bytes] + :return: IssueResource or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.IssueResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.IssueResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IOBase, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "IssueResourceUpdate") + + _request = build_update_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("IssueResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, resource_uri: str, **kwargs: Any) -> None: + """Delete an issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def add_or_update_alerts( + self, resource_uri: str, body: _models.RelatedAlerts, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RelatedAlerts: + """Add or update alerts in the issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: ~azure.mgmt.alertsmanagement.models.RelatedAlerts + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RelatedAlerts or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.RelatedAlerts + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def add_or_update_alerts( + self, resource_uri: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RelatedAlerts: + """Add or update alerts in the issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RelatedAlerts or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.RelatedAlerts + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def add_or_update_alerts( + self, resource_uri: str, body: Union[_models.RelatedAlerts, IO[bytes]], **kwargs: Any + ) -> _models.RelatedAlerts: + """Add or update alerts in the issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Is either a RelatedAlerts type or a IO[bytes] + type. Required. + :type body: ~azure.mgmt.alertsmanagement.models.RelatedAlerts or IO[bytes] + :return: RelatedAlerts or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.RelatedAlerts + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RelatedAlerts] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "RelatedAlerts") + + _request = build_add_or_update_alerts_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RelatedAlerts", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def add_or_update_resources( + self, + resource_uri: str, + body: _models.RelatedResources, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RelatedResources: + """Add or update resources in the issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: ~azure.mgmt.alertsmanagement.models.RelatedResources + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RelatedResources or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.RelatedResources + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def add_or_update_resources( + self, resource_uri: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RelatedResources: + """Add or update resources in the issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RelatedResources or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.RelatedResources + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def add_or_update_resources( + self, resource_uri: str, body: Union[_models.RelatedResources, IO[bytes]], **kwargs: Any + ) -> _models.RelatedResources: + """Add or update resources in the issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Is either a RelatedResources type or a + IO[bytes] type. Required. + :type body: ~azure.mgmt.alertsmanagement.models.RelatedResources or IO[bytes] + :return: RelatedResources or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.RelatedResources + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RelatedResources] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "RelatedResources") + + _request = build_add_or_update_resources_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RelatedResources", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def fetch_investigation_result( + self, + resource_uri: str, + body: _models.FetchInvestigationResultParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.InvestigationResult: + """Fetch investigation results. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: ~azure.mgmt.alertsmanagement.models.FetchInvestigationResultParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: InvestigationResult or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.InvestigationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def fetch_investigation_result( + self, resource_uri: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.InvestigationResult: + """Fetch investigation results. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: InvestigationResult or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.InvestigationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def fetch_investigation_result( + self, resource_uri: str, body: Union[_models.FetchInvestigationResultParameters, IO[bytes]], **kwargs: Any + ) -> _models.InvestigationResult: + """Fetch investigation results. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Is either a FetchInvestigationResultParameters + type or a IO[bytes] type. Required. + :type body: ~azure.mgmt.alertsmanagement.models.FetchInvestigationResultParameters or IO[bytes] + :return: InvestigationResult or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.InvestigationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.InvestigationResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "FetchInvestigationResultParameters") + + _request = build_fetch_investigation_result_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("InvestigationResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def list_alerts( + self, resource_uri: str, body: _models.ListParameter, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncIterable["_models.RelatedAlert"]: + """List all alerts in the issue - this method uses pagination to return all alerts. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: ~azure.mgmt.alertsmanagement.models.ListParameter + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An iterator like instance of either RelatedAlert or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.RelatedAlert] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def list_alerts( + self, resource_uri: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncIterable["_models.RelatedAlert"]: + """List all alerts in the issue - this method uses pagination to return all alerts. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An iterator like instance of either RelatedAlert or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.RelatedAlert] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def list_alerts( + self, resource_uri: str, body: Union[_models.ListParameter, IO[bytes]], **kwargs: Any + ) -> AsyncIterable["_models.RelatedAlert"]: + """List all alerts in the issue - this method uses pagination to return all alerts. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Is either a ListParameter type or a IO[bytes] + type. Required. + :type body: ~azure.mgmt.alertsmanagement.models.ListParameter or IO[bytes] + :return: An iterator like instance of either RelatedAlert or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.RelatedAlert] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PagedRelatedAlert] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ListParameter") + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_alerts_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PagedRelatedAlert", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + def list_resources( + self, resource_uri: str, body: _models.ListParameter, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncIterable["_models.RelatedResource"]: + """List all resources in the issue - this method uses pagination to return all resources. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: ~azure.mgmt.alertsmanagement.models.ListParameter + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An iterator like instance of either RelatedResource or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.RelatedResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def list_resources( + self, resource_uri: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncIterable["_models.RelatedResource"]: + """List all resources in the issue - this method uses pagination to return all resources. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An iterator like instance of either RelatedResource or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.RelatedResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def list_resources( + self, resource_uri: str, body: Union[_models.ListParameter, IO[bytes]], **kwargs: Any + ) -> AsyncIterable["_models.RelatedResource"]: + """List all resources in the issue - this method uses pagination to return all resources. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Is either a ListParameter type or a IO[bytes] + type. Required. + :type body: ~azure.mgmt.alertsmanagement.models.ListParameter or IO[bytes] + :return: An iterator like instance of either RelatedResource or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.RelatedResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PagedRelatedResource] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ListParameter") + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_resources_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("PagedRelatedResource", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def start_investigation( + self, + resource_uri: str, + body: _models.StartInvestigationParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.InvestigationMetadata: + """Start a new investigation. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: ~azure.mgmt.alertsmanagement.models.StartInvestigationParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: InvestigationMetadata or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.InvestigationMetadata + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def start_investigation( + self, resource_uri: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.InvestigationMetadata: + """Start a new investigation. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: InvestigationMetadata or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.InvestigationMetadata + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def start_investigation( + self, resource_uri: str, body: Union[_models.StartInvestigationParameters, IO[bytes]], **kwargs: Any + ) -> _models.InvestigationMetadata: + """Start a new investigation. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Is either a StartInvestigationParameters type + or a IO[bytes] type. Required. + :type body: ~azure.mgmt.alertsmanagement.models.StartInvestigationParameters or IO[bytes] + :return: InvestigationMetadata or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.InvestigationMetadata + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.InvestigationMetadata] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "StartInvestigationParameters") + + _request = build_start_investigation_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("InvestigationMetadata", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_operations.py index 16de0c077489..05436b319712 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_operations.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from collections.abc import MutableMapping from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -19,20 +19,16 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._operations import build_list_request +from .._configuration import AlertsManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -51,16 +47,15 @@ class Operations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AlertsManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: """List all operations available through Azure Alerts Management Resource Provider. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: @@ -68,12 +63,10 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) cls: ClsType[_models.OperationsList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -84,21 +77,18 @@ def list(self, **kwargs: Any) -> AsyncIterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("OperationsList", pipeline_response) @@ -108,20 +98,19 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.AlertsManagement/operations"} diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_prometheus_rule_groups_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_prometheus_rule_groups_operations.py index a63d6eb5c371..ac96e810ea21 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_prometheus_rule_groups_operations.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_prometheus_rule_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from collections.abc import MutableMapping +from io import IOBase from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -19,15 +20,14 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._prometheus_rule_groups_operations import ( build_create_or_update_request, build_delete_request, @@ -36,11 +36,8 @@ build_list_by_subscription_request, build_update_request, ) +from .._configuration import AlertsManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -59,16 +56,15 @@ class PrometheusRuleGroupsOperations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AlertsManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.PrometheusRuleGroupResource"]: - """Retrieve Prometheus rule group definitions in a subscription. + """Retrieve Prometheus all rule group definitions in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrometheusRuleGroupResource or the result of cls(response) :rtype: @@ -78,12 +74,10 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Promethe _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) cls: ClsType[_models.PrometheusRuleGroupResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -94,22 +88,19 @@ def list_by_subscription(self, **kwargs: Any) -> AsyncIterable["_models.Promethe def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("PrometheusRuleGroupResourceCollection", pipeline_response) @@ -119,26 +110,23 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/prometheusRuleGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -148,7 +136,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrometheusRuleGroupResource or the result of cls(response) :rtype: @@ -158,12 +145,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) cls: ClsType[_models.PrometheusRuleGroupResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -174,23 +159,20 @@ def list_by_resource_group( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_group_request( + _request = build_list_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("PrometheusRuleGroupResourceCollection", pipeline_response) @@ -200,26 +182,23 @@ async def extract_data(pipeline_response): return None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups" - } - @distributed_trace_async async def get( self, resource_group_name: str, rule_group_name: str, **kwargs: Any @@ -231,12 +210,11 @@ async def get( :type resource_group_name: str :param rule_group_name: The name of the rule group. Required. :type rule_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrometheusRuleGroupResource or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -247,44 +225,37 @@ async def get( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) cls: ClsType[_models.PrometheusRuleGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_group_name=rule_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrometheusRuleGroupResource", pipeline_response) + deserialized = self._deserialize("PrometheusRuleGroupResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}" - } + return deserialized # type: ignore @overload async def create_or_update( @@ -308,7 +279,6 @@ async def create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrometheusRuleGroupResource or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -319,7 +289,7 @@ async def create_or_update( self, resource_group_name: str, rule_group_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -332,11 +302,10 @@ async def create_or_update( :param rule_group_name: The name of the rule group. Required. :type rule_group_name: str :param parameters: The parameters of the rule group to create or update. Required. - :type parameters: IO + :type parameters: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrometheusRuleGroupResource or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -347,7 +316,7 @@ async def create_or_update( self, resource_group_name: str, rule_group_name: str, - parameters: Union[_models.PrometheusRuleGroupResource, IO], + parameters: Union[_models.PrometheusRuleGroupResource, IO[bytes]], **kwargs: Any ) -> _models.PrometheusRuleGroupResource: """Create or update a Prometheus rule group definition. @@ -357,18 +326,14 @@ async def create_or_update( :type resource_group_name: str :param rule_group_name: The name of the rule group. Required. :type rule_group_name: str - :param parameters: The parameters of the rule group to create or update. Is either a model type - or a IO type. Required. - :type parameters: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param parameters: The parameters of the rule group to create or update. Is either a + PrometheusRuleGroupResource type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource or IO[bytes] :return: PrometheusRuleGroupResource or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -379,21 +344,19 @@ async def create_or_update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.PrometheusRuleGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "PrometheusRuleGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, rule_group_name=rule_group_name, subscription_id=self._config.subscription_id, @@ -401,45 +364,36 @@ async def create_or_update( content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("PrometheusRuleGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("PrometheusRuleGroupResource", pipeline_response) + deserialized = self._deserialize("PrometheusRuleGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}" - } - @overload async def update( self, resource_group_name: str, rule_group_name: str, - parameters: _models.PrometheusRuleGroupResourcePatch, + parameters: _models.PrometheusRuleGroupResourcePatchParameters, *, content_type: str = "application/json", **kwargs: Any @@ -452,11 +406,11 @@ async def update( :param rule_group_name: The name of the rule group. Required. :type rule_group_name: str :param parameters: The parameters of the rule group to update. Required. - :type parameters: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResourcePatch + :type parameters: + ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResourcePatchParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrometheusRuleGroupResource or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -467,7 +421,7 @@ async def update( self, resource_group_name: str, rule_group_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -480,11 +434,10 @@ async def update( :param rule_group_name: The name of the rule group. Required. :type rule_group_name: str :param parameters: The parameters of the rule group to update. Required. - :type parameters: IO + :type parameters: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrometheusRuleGroupResource or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -495,7 +448,7 @@ async def update( self, resource_group_name: str, rule_group_name: str, - parameters: Union[_models.PrometheusRuleGroupResourcePatch, IO], + parameters: Union[_models.PrometheusRuleGroupResourcePatchParameters, IO[bytes]], **kwargs: Any ) -> _models.PrometheusRuleGroupResource: """Update an Prometheus rule group definition. @@ -505,18 +458,15 @@ async def update( :type resource_group_name: str :param rule_group_name: The name of the rule group. Required. :type rule_group_name: str - :param parameters: The parameters of the rule group to update. Is either a model type or a IO - type. Required. - :type parameters: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResourcePatch or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param parameters: The parameters of the rule group to update. Is either a + PrometheusRuleGroupResourcePatchParameters type or a IO[bytes] type. Required. + :type parameters: + ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResourcePatchParameters or IO[bytes] :return: PrometheusRuleGroupResource or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -527,21 +477,19 @@ async def update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.PrometheusRuleGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "PrometheusRuleGroupResourcePatch") + _json = self._serialize.body(parameters, "PrometheusRuleGroupResourcePatchParameters") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, rule_group_name=rule_group_name, subscription_id=self._config.subscription_id, @@ -549,39 +497,32 @@ async def update( content_type=content_type, json=_json, content=_content, - template_url=self.update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrometheusRuleGroupResource", pipeline_response) + deserialized = self._deserialize("PrometheusRuleGroupResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}" - } + return deserialized # type: ignore @distributed_trace_async - async def delete( # pylint: disable=inconsistent-return-statements - self, resource_group_name: str, rule_group_name: str, **kwargs: Any - ) -> None: + async def delete(self, resource_group_name: str, rule_group_name: str, **kwargs: Any) -> None: """Delete a Prometheus rule group definition. :param resource_group_name: The name of the resource group. The name is case insensitive. @@ -589,12 +530,11 @@ async def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param rule_group_name: The name of the rule group. Required. :type rule_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -605,37 +545,30 @@ async def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, rule_group_name=rule_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_smart_groups_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_smart_groups_operations.py index e1efa4572337..065c9224dac7 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_smart_groups_operations.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_smart_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from collections.abc import MutableMapping from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +from azure.core import AsyncPipelineClient from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -19,26 +19,22 @@ map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models -from ..._vendor import _convert_request +from ..._utils.serialization import Deserializer, Serializer from ...operations._smart_groups_operations import ( build_change_state_request, build_get_all_request, build_get_by_id_request, build_get_history_request, ) +from .._configuration import AlertsManagementClientConfiguration -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -57,10 +53,10 @@ class SmartGroupsOperations: def __init__(self, *args, **kwargs) -> None: input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AlertsManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get_all( @@ -95,7 +91,7 @@ def get_all( value is select all. Known values are: "Application Insights", "ActivityLog Administrative", "ActivityLog Security", "ActivityLog Recommendation", "ActivityLog Policy", "ActivityLog Autoscale", "Log Analytics", "Nagios", "Platform", "SCOM", "ServiceHealth", "SmartDetector", - "VM Insights", and "Zabbix". Default value is None. + "VM Insights", "Zabbix", and "Resource Health". Default value is None. :type monitor_service: str or ~azure.mgmt.alertsmanagement.models.MonitorService :param monitor_condition: Filter by monitor condition which is either 'Fired' or 'Resolved'. Default value is to select all. Known values are: "Fired" and "Resolved". Default value is @@ -105,7 +101,8 @@ def get_all( "Sev1", "Sev2", "Sev3", and "Sev4". Default value is None. :type severity: str or ~azure.mgmt.alertsmanagement.models.Severity :param smart_group_state: Filter by state of the smart group. Default value is to select all. - Known values are: "New", "Acknowledged", and "Closed". Default value is None. + Known values are: "New", "Acknowledged", "Closed", "NoAlert", "Fired", "Firing", "Resolving", + and "Resolved". Default value is None. :type smart_group_state: str or ~azure.mgmt.alertsmanagement.models.AlertState :param time_range: Filter by time range by below listed values. Default value is 1 day. Known values are: "1h", "1d", "7d", and "30d". Default value is None. @@ -122,7 +119,6 @@ def get_all( value is 'desc' for time fields and 'asc' for others. Known values are: "asc" and "desc". Default value is None. :type sort_order: str or ~azure.mgmt.alertsmanagement.models.SortOrder - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SmartGroup or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.SmartGroup] :raises ~azure.core.exceptions.HttpResponseError: @@ -130,12 +126,10 @@ def get_all( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-05-05-preview")) cls: ClsType[_models.SmartGroupsList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -146,7 +140,7 @@ def get_all( def prepare_request(next_link=None): if not next_link: - request = build_get_all_request( + _request = build_get_all_request( subscription_id=self._config.subscription_id, target_resource=target_resource, target_resource_group=target_resource_group, @@ -160,19 +154,16 @@ def prepare_request(next_link=None): sort_by=sort_by, sort_order=sort_order, api_version=api_version, - template_url=self.get_all.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request async def extract_data(pipeline_response): deserialized = self._deserialize("SmartGroupsList", pipeline_response) @@ -182,10 +173,11 @@ async def extract_data(pipeline_response): return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -198,8 +190,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - get_all.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups"} - @distributed_trace_async async def get_by_id(self, smart_group_id: str, **kwargs: Any) -> _models.SmartGroup: """Get information related to a specific Smart Group. @@ -208,12 +198,11 @@ async def get_by_id(self, smart_group_id: str, **kwargs: Any) -> _models.SmartGr :param smart_group_id: Smart group unique id. Required. :type smart_group_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: SmartGroup or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.SmartGroup :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -224,24 +213,21 @@ async def get_by_id(self, smart_group_id: str, **kwargs: Any) -> _models.SmartGr _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-05-05-preview")) cls: ClsType[_models.SmartGroup] = kwargs.pop("cls", None) - request = build_get_by_id_request( + _request = build_get_by_id_request( smart_group_id=smart_group_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_by_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -254,16 +240,12 @@ async def get_by_id(self, smart_group_id: str, **kwargs: Any) -> _models.SmartGr response_headers = {} response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - deserialized = self._deserialize("SmartGroup", pipeline_response) + deserialized = self._deserialize("SmartGroup", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized + return cls(pipeline_response, deserialized, response_headers) # type: ignore - get_by_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}" - } + return deserialized # type: ignore @distributed_trace_async async def change_state( @@ -273,15 +255,14 @@ async def change_state( :param smart_group_id: Smart group unique id. Required. :type smart_group_id: str - :param new_state: New state of the alert. Known values are: "New", "Acknowledged", and - "Closed". Required. + :param new_state: New state of the alert. Known values are: "New", "Acknowledged", "Closed", + "NoAlert", "Fired", "Firing", "Resolving", and "Resolved". Required. :type new_state: str or ~azure.mgmt.alertsmanagement.models.AlertState - :keyword callable cls: A custom type or function that will be passed the direct response :return: SmartGroup or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.SmartGroup :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -292,25 +273,22 @@ async def change_state( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-05-05-preview")) cls: ClsType[_models.SmartGroup] = kwargs.pop("cls", None) - request = build_change_state_request( + _request = build_change_state_request( smart_group_id=smart_group_id, subscription_id=self._config.subscription_id, new_state=new_state, api_version=api_version, - template_url=self.change_state.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -323,16 +301,12 @@ async def change_state( response_headers = {} response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - deserialized = self._deserialize("SmartGroup", pipeline_response) + deserialized = self._deserialize("SmartGroup", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized + return cls(pipeline_response, deserialized, response_headers) # type: ignore - change_state.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}/changeState" - } + return deserialized # type: ignore @distributed_trace_async async def get_history(self, smart_group_id: str, **kwargs: Any) -> _models.SmartGroupModification: @@ -341,12 +315,11 @@ async def get_history(self, smart_group_id: str, **kwargs: Any) -> _models.Smart :param smart_group_id: Smart group unique id. Required. :type smart_group_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: SmartGroupModification or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.SmartGroupModification :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -357,24 +330,21 @@ async def get_history(self, smart_group_id: str, **kwargs: Any) -> _models.Smart _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-05-05-preview")) cls: ClsType[_models.SmartGroupModification] = kwargs.pop("cls", None) - request = build_get_history_request( + _request = build_get_history_request( smart_group_id=smart_group_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_history.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -384,13 +354,9 @@ async def get_history(self, smart_group_id: str, **kwargs: Any) -> _models.Smart error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated3, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SmartGroupModification", pipeline_response) + deserialized = self._deserialize("SmartGroupModification", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_history.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}/history" - } + return deserialized # type: ignore diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/models/__init__.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/models/__init__.py index 1bea22079797..b8678c5bd7ac 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/models/__init__.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/models/__init__.py @@ -5,97 +5,212 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._models_py3 import Action -from ._models_py3 import ActionStatus -from ._models_py3 import AddActionGroups -from ._models_py3 import Alert -from ._models_py3 import AlertModification -from ._models_py3 import AlertModificationItem -from ._models_py3 import AlertModificationProperties -from ._models_py3 import AlertProcessingRule -from ._models_py3 import AlertProcessingRuleProperties -from ._models_py3 import AlertProcessingRulesList -from ._models_py3 import AlertProperties -from ._models_py3 import AlertsList -from ._models_py3 import AlertsMetaData -from ._models_py3 import AlertsMetaDataProperties -from ._models_py3 import AlertsSummary -from ._models_py3 import AlertsSummaryGroup -from ._models_py3 import AlertsSummaryGroupItem -from ._models_py3 import Comments -from ._models_py3 import Condition -from ._models_py3 import DailyRecurrence -from ._models_py3 import ErrorAdditionalInfo -from ._models_py3 import ErrorDetail -from ._models_py3 import ErrorResponse -from ._models_py3 import ErrorResponseAutoGenerated -from ._models_py3 import ErrorResponseAutoGenerated2 -from ._models_py3 import ErrorResponseAutoGenerated3 -from ._models_py3 import ErrorResponseBody -from ._models_py3 import ErrorResponseBodyAutoGenerated -from ._models_py3 import ErrorResponseBodyAutoGenerated2 -from ._models_py3 import Essentials -from ._models_py3 import ManagedResource -from ._models_py3 import MonitorServiceDetails -from ._models_py3 import MonitorServiceList -from ._models_py3 import MonthlyRecurrence -from ._models_py3 import Operation -from ._models_py3 import OperationDisplay -from ._models_py3 import OperationsList -from ._models_py3 import PatchObject -from ._models_py3 import PrometheusRule -from ._models_py3 import PrometheusRuleGroupAction -from ._models_py3 import PrometheusRuleGroupResource -from ._models_py3 import PrometheusRuleGroupResourceCollection -from ._models_py3 import PrometheusRuleGroupResourcePatch -from ._models_py3 import PrometheusRuleGroupResourcePatchProperties -from ._models_py3 import PrometheusRuleResolveConfiguration -from ._models_py3 import Recurrence -from ._models_py3 import RemoveAllActionGroups -from ._models_py3 import Resource -from ._models_py3 import ResourceAutoGenerated -from ._models_py3 import Schedule -from ._models_py3 import SmartGroup -from ._models_py3 import SmartGroupAggregatedProperty -from ._models_py3 import SmartGroupModification -from ._models_py3 import SmartGroupModificationItem -from ._models_py3 import SmartGroupModificationProperties -from ._models_py3 import SmartGroupsList -from ._models_py3 import SystemData -from ._models_py3 import TrackedResource -from ._models_py3 import WeeklyRecurrence +from typing import TYPE_CHECKING -from ._alerts_management_client_enums import ActionType -from ._alerts_management_client_enums import AlertModificationEvent -from ._alerts_management_client_enums import AlertState -from ._alerts_management_client_enums import AlertsSortByFields -from ._alerts_management_client_enums import AlertsSummaryGroupByFields -from ._alerts_management_client_enums import CreatedByType -from ._alerts_management_client_enums import DaysOfWeek -from ._alerts_management_client_enums import Field -from ._alerts_management_client_enums import Identifier -from ._alerts_management_client_enums import MetadataIdentifier -from ._alerts_management_client_enums import MonitorCondition -from ._alerts_management_client_enums import MonitorService -from ._alerts_management_client_enums import Operator -from ._alerts_management_client_enums import RecurrenceType -from ._alerts_management_client_enums import Severity -from ._alerts_management_client_enums import SignalType -from ._alerts_management_client_enums import SmartGroupModificationEvent -from ._alerts_management_client_enums import SmartGroupsSortByFields -from ._alerts_management_client_enums import SortOrder -from ._alerts_management_client_enums import State -from ._alerts_management_client_enums import TimeRange +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models_py3 import ( # type: ignore + AbnormalEventAnomalyInsight, + AbnormalEventData, + AbnormalEventDetails, + Action, + ActionStatus, + AddActionGroups, + Alert, + AlertEnrichmentItem, + AlertEnrichmentProperties, + AlertEnrichmentResponse, + AlertEnrichmentsList, + AlertModification, + AlertModificationItem, + AlertModificationProperties, + AlertProcessingRule, + AlertProcessingRuleProperties, + AlertProcessingRulesList, + AlertProperties, + AlertRuleRecommendationResource, + AlertRuleRecommendationsListResponse, + AlertsList, + AlertsMetaData, + AlertsMetaDataProperties, + AlertsSummary, + AlertsSummaryGroup, + AlertsSummaryGroupItem, + AnomalyRange, + AzureMetricAnomalyInsight, + AzureMetricData, + AzureMetricDetails, + BaselineRange, + Comments, + Condition, + CorrelationDetails, + DailyRecurrence, + DetailsBase, + DiagnosticsInsight, + DiagnosticsSolutionDetails, + DimensionNameAndValue, + ErrorAdditionalInfo, + ErrorDetail, + ErrorDetailAutoGenerated, + ErrorDetailAutoGenerated2, + ErrorResponse, + ErrorResponseAutoGenerated, + ErrorResponseAutoGenerated2, + ErrorResponseAutoGenerated3, + ErrorResponseAutoGenerated4, + ErrorResponseAutoGenerated5, + ErrorResponseBody, + ErrorResponseBodyAutoGenerated, + ErrorResponseBodyAutoGenerated2, + Essentials, + EvaluatedPeriod, + Evaluation, + ExceptionPatternAnomaly, + FetchInvestigationResultParameters, + InvestigationDetails, + InvestigationEntity, + InvestigationExecution, + InvestigationMetadata, + InvestigationResult, + InvestigationScope, + IssueProperties, + IssuePropertiesUpdate, + IssueResource, + IssueResourceListResult, + IssueResourceUpdate, + ListParameter, + LogAlertRuleCondition, + LogAlertRuleConditionFailingPeriods, + LogAlertRuleCriteria, + LogAlertRuleDimension, + LogAlertRuleResolveConfiguration, + LogAlertRuleResource, + LogAlertRuleUserIdentityProperties, + ManagedResource, + MonitorServiceDetails, + MonitorServiceList, + MonthlyRecurrence, + Operation, + OperationDisplay, + OperationsList, + Origin, + PagedRelatedAlert, + PagedRelatedResource, + PatchObject, + PreviewAlertRuleRequest, + PreviewAlertRuleRequestProperties, + PreviewAlertRuleResponse, + PrometheusEnrichmentItem, + PrometheusInstantQuery, + PrometheusRangeQuery, + PrometheusRule, + PrometheusRuleGroupAction, + PrometheusRuleGroupResource, + PrometheusRuleGroupResourceCollection, + PrometheusRuleGroupResourcePatchParameters, + PrometheusRuleResolveConfiguration, + ProxyResource, + ProxyResourceAutoGenerated, + Recurrence, + RelatedAlert, + RelatedAlertAnomalyInsight, + RelatedAlertData, + RelatedAlertDetails, + RelatedAlerts, + RelatedResource, + RelatedResources, + RemoveAllActionGroups, + Resource, + ResourceAutoGenerated, + ResourceAutoGenerated2, + ResourceAutoGenerated3, + ResourceHealthDetails, + ResourceHealthInsight, + RuleArmTemplate, + RulePreviewResult, + RunParameters, + Schedule, + SmartGroup, + SmartGroupAggregatedProperty, + SmartGroupModification, + SmartGroupModificationItem, + SmartGroupModificationProperties, + SmartGroupsList, + StartInvestigationParameters, + Summary, + SystemData, + TracePatternAnomaly, + TrackedResource, + TransactionEdge, + TransactionNode, + TransactionPatternAnomaly, + WeeklyRecurrence, +) + +from ._alerts_management_client_enums import ( # type: ignore + AbnormalEventType, + ActionType, + AddedByType, + AggregationType, + AlertModificationEvent, + AlertSeverity, + AlertState, + AlertsSortByFields, + AlertsSummaryGroupByFields, + AnomalyDirection, + AvailabilityState, + CategoryType, + ConditionOperator, + CreatedByType, + CriterionType, + DaysOfWeek, + DetailsType, + DimensionOperator, + Field, + HealthState, + Identifier, + InvestigationEntityType, + InvestigationExecutionRunState, + Kind, + MetadataIdentifier, + MetricAlertsDisplayUnit, + MonitorCondition, + MonitorService, + Operator, + RecurrenceType, + Relevance, + ResourceProvisioningState, + Severity, + SignalType, + SmartGroupModificationEvent, + SmartGroupsSortByFields, + SortOrder, + State, + Status, + TimeAggregation, + TimeRange, + Type, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ + "AbnormalEventAnomalyInsight", + "AbnormalEventData", + "AbnormalEventDetails", "Action", "ActionStatus", "AddActionGroups", "Alert", + "AlertEnrichmentItem", + "AlertEnrichmentProperties", + "AlertEnrichmentResponse", + "AlertEnrichmentsList", "AlertModification", "AlertModificationItem", "AlertModificationProperties", @@ -103,25 +218,64 @@ "AlertProcessingRuleProperties", "AlertProcessingRulesList", "AlertProperties", + "AlertRuleRecommendationResource", + "AlertRuleRecommendationsListResponse", "AlertsList", "AlertsMetaData", "AlertsMetaDataProperties", "AlertsSummary", "AlertsSummaryGroup", "AlertsSummaryGroupItem", + "AnomalyRange", + "AzureMetricAnomalyInsight", + "AzureMetricData", + "AzureMetricDetails", + "BaselineRange", "Comments", "Condition", + "CorrelationDetails", "DailyRecurrence", + "DetailsBase", + "DiagnosticsInsight", + "DiagnosticsSolutionDetails", + "DimensionNameAndValue", "ErrorAdditionalInfo", "ErrorDetail", + "ErrorDetailAutoGenerated", + "ErrorDetailAutoGenerated2", "ErrorResponse", "ErrorResponseAutoGenerated", "ErrorResponseAutoGenerated2", "ErrorResponseAutoGenerated3", + "ErrorResponseAutoGenerated4", + "ErrorResponseAutoGenerated5", "ErrorResponseBody", "ErrorResponseBodyAutoGenerated", "ErrorResponseBodyAutoGenerated2", "Essentials", + "EvaluatedPeriod", + "Evaluation", + "ExceptionPatternAnomaly", + "FetchInvestigationResultParameters", + "InvestigationDetails", + "InvestigationEntity", + "InvestigationExecution", + "InvestigationMetadata", + "InvestigationResult", + "InvestigationScope", + "IssueProperties", + "IssuePropertiesUpdate", + "IssueResource", + "IssueResourceListResult", + "IssueResourceUpdate", + "ListParameter", + "LogAlertRuleCondition", + "LogAlertRuleConditionFailingPeriods", + "LogAlertRuleCriteria", + "LogAlertRuleDimension", + "LogAlertRuleResolveConfiguration", + "LogAlertRuleResource", + "LogAlertRuleUserIdentityProperties", "ManagedResource", "MonitorServiceDetails", "MonitorServiceList", @@ -129,18 +283,42 @@ "Operation", "OperationDisplay", "OperationsList", + "Origin", + "PagedRelatedAlert", + "PagedRelatedResource", "PatchObject", + "PreviewAlertRuleRequest", + "PreviewAlertRuleRequestProperties", + "PreviewAlertRuleResponse", + "PrometheusEnrichmentItem", + "PrometheusInstantQuery", + "PrometheusRangeQuery", "PrometheusRule", "PrometheusRuleGroupAction", "PrometheusRuleGroupResource", "PrometheusRuleGroupResourceCollection", - "PrometheusRuleGroupResourcePatch", - "PrometheusRuleGroupResourcePatchProperties", + "PrometheusRuleGroupResourcePatchParameters", "PrometheusRuleResolveConfiguration", + "ProxyResource", + "ProxyResourceAutoGenerated", "Recurrence", + "RelatedAlert", + "RelatedAlertAnomalyInsight", + "RelatedAlertData", + "RelatedAlertDetails", + "RelatedAlerts", + "RelatedResource", + "RelatedResources", "RemoveAllActionGroups", "Resource", "ResourceAutoGenerated", + "ResourceAutoGenerated2", + "ResourceAutoGenerated3", + "ResourceHealthDetails", + "ResourceHealthInsight", + "RuleArmTemplate", + "RulePreviewResult", + "RunParameters", "Schedule", "SmartGroup", "SmartGroupAggregatedProperty", @@ -148,30 +326,57 @@ "SmartGroupModificationItem", "SmartGroupModificationProperties", "SmartGroupsList", + "StartInvestigationParameters", + "Summary", "SystemData", + "TracePatternAnomaly", "TrackedResource", + "TransactionEdge", + "TransactionNode", + "TransactionPatternAnomaly", "WeeklyRecurrence", + "AbnormalEventType", "ActionType", + "AddedByType", + "AggregationType", "AlertModificationEvent", + "AlertSeverity", "AlertState", "AlertsSortByFields", "AlertsSummaryGroupByFields", + "AnomalyDirection", + "AvailabilityState", + "CategoryType", + "ConditionOperator", "CreatedByType", + "CriterionType", "DaysOfWeek", + "DetailsType", + "DimensionOperator", "Field", + "HealthState", "Identifier", + "InvestigationEntityType", + "InvestigationExecutionRunState", + "Kind", "MetadataIdentifier", + "MetricAlertsDisplayUnit", "MonitorCondition", "MonitorService", "Operator", "RecurrenceType", + "Relevance", + "ResourceProvisioningState", "Severity", "SignalType", "SmartGroupModificationEvent", "SmartGroupsSortByFields", "SortOrder", "State", + "Status", + "TimeAggregation", "TimeRange", + "Type", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/models/_alerts_management_client_enums.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/models/_alerts_management_client_enums.py index 845acc76887f..082d6832ea60 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/models/_alerts_management_client_enums.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/models/_alerts_management_client_enums.py @@ -10,6 +10,17 @@ from azure.core import CaseInsensitiveEnumMeta +class AbnormalEventType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the abnormal event.""" + + DEPENDENCY = "Dependency" + """The abnormal event type is a dependency""" + REQUEST = "Request" + """The abnormal event type is a request""" + EXCEPTION = "Exception" + """The abnormal event type is an exception""" + + class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Action that should be applied.""" @@ -17,6 +28,34 @@ class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): REMOVE_ALL_ACTION_GROUPS = "RemoveAllActionGroups" +class AddedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of entity that added data to the issue.""" + + MANUAL = "Manual" + """The data was added manually by a user""" + AUTOMATIC = "Automatic" + """The data was added automatically""" + + +class AggregationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The aggregation type of the metric.""" + + AVERAGE = "Average" + """The metric aggregation type is average""" + MINIMUM = "Minimum" + """The metric aggregation type is minimum""" + MAXIMUM = "Maximum" + """The metric aggregation type is maximum""" + TOTAL = "Total" + """The metric aggregation type is total""" + COUNT = "Count" + """The metric aggregation type is count""" + UNIQUE = "Unique" + """The metric aggregation type is unique, used for logs""" + NONE = "None" + """There is no aggregation type""" + + class AlertModificationEvent(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Reason for the modification.""" @@ -31,6 +70,18 @@ class AlertModificationEvent(str, Enum, metaclass=CaseInsensitiveEnumMeta): ACTIONS_FAILED = "ActionsFailed" +class AlertSeverity(int, Enum, metaclass=CaseInsensitiveEnumMeta): + """Severity of the alert. Should be an integer between [0-4]. Value of 0 is severest. Relevant and + required only for rules of the kind LogAlert. + """ + + ZERO = 0 + ONE = 1 + TWO = 2 + THREE = 3 + FOUR = 4 + + class AlertsSortByFields(str, Enum, metaclass=CaseInsensitiveEnumMeta): """AlertsSortByFields.""" @@ -63,6 +114,65 @@ class AlertState(str, Enum, metaclass=CaseInsensitiveEnumMeta): NEW = "New" ACKNOWLEDGED = "Acknowledged" CLOSED = "Closed" + NO_ALERT = "NoAlert" + FIRED = "Fired" + FIRING = "Firing" + RESOLVING = "Resolving" + RESOLVED = "Resolved" + + +class AnomalyDirection(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The direction of the anomaly.""" + + INCREASE = "Increase" + """The anomaly direction is increasing""" + DECREASE = "Decrease" + """The anomaly direction is decreasing""" + INCREASE_AND_DECREASE = "IncreaseAndDecrease" + """The anomaly direction is both increasing and decreasing""" + + +class AvailabilityState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Represents the health state of a resource.""" + + AVAILABLE = "Available" + """The resource is available""" + DEGRADED = "Degraded" + """The resource is degraded""" + UNAVAILABLE = "Unavailable" + """The resource is unavailable""" + UNKNOWN = "Unknown" + """The availability state of the resource is unknown""" + USER_INITIATED = "UserInitiated" + """The user initiated this state change""" + + +class CategoryType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The category type.""" + + INVESTIGATION = "Investigation" + """The category is for an investigation""" + METRIC = "Metric" + """The category is for a metric""" + LOG = "Log" + """The category is for a log""" + ALERT = "Alert" + """The category is for an alert""" + RESOURCE_HEALTH = "ResourceHealth" + """The category is for resource health""" + DIAGNOSTICS = "Diagnostics" + """The category is for diagnostics""" + + +class ConditionOperator(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The criteria operator. Relevant and required only for rules of the kind LogAlert.""" + + EQUALS = "Equals" + GREATER_THAN = "GreaterThan" + GREATER_THAN_OR_EQUAL = "GreaterThanOrEqual" + LESS_THAN = "LessThan" + LESS_THAN_OR_EQUAL = "LessThanOrEqual" + GREATER_OR_LESS_THAN = "GreaterOrLessThan" class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -74,6 +184,13 @@ class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): KEY = "Key" +class CriterionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the type of threshold criteria.""" + + STATIC_THRESHOLD_CRITERION = "StaticThresholdCriterion" + DYNAMIC_THRESHOLD_CRITERION = "DynamicThresholdCriterion" + + class DaysOfWeek(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Days of week.""" @@ -86,6 +203,32 @@ class DaysOfWeek(str, Enum, metaclass=CaseInsensitiveEnumMeta): SATURDAY = "Saturday" +class DetailsType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The details type.""" + + INVESTIGATION = "Investigation" + """The details is for an investigation""" + FINDING = "Finding" + """The details is for a finding""" + AZURE_METRIC = "AzureMetric" + """The details is for an azure metric""" + ABNORMAL_EVENT = "AbnormalEvent" + """The details is for a abnormal event""" + RELATED_ALERT = "RelatedAlert" + """The details is for a related alert""" + RESOURCE_HEALTH = "ResourceHealth" + """The details is for resource health""" + DIAGNOSTICS = "Diagnostics" + """The details for diagnostics""" + + +class DimensionOperator(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Operator for dimension values.""" + + INCLUDE = "Include" + EXCLUDE = "Exclude" + + class Field(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Field for a given condition.""" @@ -102,18 +245,104 @@ class Field(str, Enum, metaclass=CaseInsensitiveEnumMeta): ALERT_CONTEXT = "AlertContext" +class HealthState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The health state of the investigation result.""" + + UNKNOWN = "Unknown" + """The health state of the result is unknown""" + HEALTHY = "Healthy" + """The result is healthy""" + UNHEALTHY = "Unhealthy" + """The result is unhealthy""" + + class Identifier(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Identifier.""" MONITOR_SERVICE_LIST = "MonitorServiceList" +class InvestigationEntityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the investigation entity.""" + + INVESTIGATION = "Investigation" + """Investigation entity""" + FINDING = "Finding" + """Finding entity""" + EVIDENCE = "Evidence" + """Evidence entity""" + + +class InvestigationExecutionRunState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The execution state of the investigation.""" + + NONE = "None" + """The investigation execution didn't start""" + IN_PROGRESS = "InProgress" + """The investigation execution is in progress""" + SUCCEEDED = "Succeeded" + """The investigation execution completed successfully""" + FAILED = "Failed" + """The investigation execution failed""" + CANCELED = "Canceled" + """The investigation execution was canceled""" + + +class Kind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates the type of scheduled query rule. The default is LogAlert.""" + + LOG_ALERT = "LogAlert" + EVENT_LOG_ALERT = "EventLogAlert" + LOG_TO_METRIC = "LogToMetric" + + class MetadataIdentifier(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Identification of the information to be retrieved by API call.""" MONITOR_SERVICE_LIST = "MonitorServiceList" +class MetricAlertsDisplayUnit(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The unit to display for a metric alert rule.""" + + NONE = "None" + PERCENTAGE = "Percentage" + BYTES = "Bytes" + KILOBYTES = "Kilobytes" + MEGABYTES = "Megabytes" + GIGABYTES = "Gigabytes" + TERABYTES = "Terabytes" + PETABYTES = "Petabytes" + BYTES_PER_DAY = "BytesPerDay" + BYTES_PER_HOUR = "BytesPerHour" + BYTES_PER_MINUTE = "BytesPerMinute" + BYTES_PER_SECOND = "BytesPerSecond" + KILOBYTES_PER_SECOND = "KilobytesPerSecond" + MEGABYTES_PER_SECOND = "MegabytesPerSecond" + GIGABYTES_PER_SECOND = "GigabytesPerSecond" + TERABYTES_PER_SECOND = "TerabytesPerSecond" + PETABYTES_PER_SECOND = "PetabytesPerSecond" + COUNT = "Count" + THOUSAND = "Thousand" + MILLION = "Million" + BILLION = "Billion" + TRILLION = "Trillion" + MICRO_SECONDS = "MicroSeconds" + MILLI_SECONDS = "MilliSeconds" + SECONDS = "Seconds" + MINUTES = "Minutes" + HOURS = "Hours" + DAYS = "Days" + COUNT_PER_DAY = "CountPerDay" + COUNT_PER_HOUR = "CountPerHour" + COUNT_PER_MINUTE = "CountPerMinute" + COUNT_PER_SECOND = "CountPerSecond" + THOUSAND_PER_SECOND = "ThousandPerSecond" + MILLION_PER_SECOND = "MillionPerSecond" + BILLION_PER_SECOND = "BillionPerSecond" + TRILLION_PER_SECOND = "TrillionPerSecond" + + class MonitorCondition(str, Enum, metaclass=CaseInsensitiveEnumMeta): """MonitorCondition.""" @@ -138,6 +367,7 @@ class MonitorService(str, Enum, metaclass=CaseInsensitiveEnumMeta): SMART_DETECTOR = "SmartDetector" VM_INSIGHTS = "VM Insights" ZABBIX = "Zabbix" + RESOURCE_HEALTH = "Resource Health" class Operator(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -157,6 +387,28 @@ class RecurrenceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): MONTHLY = "Monthly" +class Relevance(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The relevance status of the resource.""" + + NONE = "None" + """No relevance status for the resource""" + RELEVANT = "Relevant" + """The resource is relevant to the issue""" + IRRELEVANT = "Irrelevant" + """The resource is irrelevant to the issue""" + + +class ResourceProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The provisioning state of a resource type.""" + + SUCCEEDED = "Succeeded" + """Resource has been created.""" + FAILED = "Failed" + """Resource creation failed.""" + CANCELED = "Canceled" + """Resource creation was canceled.""" + + class Severity(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Severity.""" @@ -209,6 +461,28 @@ class State(str, Enum, metaclass=CaseInsensitiveEnumMeta): CLOSED = "Closed" +class Status(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the evaluation of the enrichment.""" + + SUCCEEDED = "Succeeded" + FAILED = "Failed" + NEW = "New" + IN_PROGRESS = "InProgress" + MITIGATED = "Mitigated" + CLOSED = "Closed" + CANCELED = "Canceled" + + +class TimeAggregation(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Aggregation type. Relevant and required only for rules of the kind LogAlert.""" + + COUNT = "Count" + AVERAGE = "Average" + MINIMUM = "Minimum" + MAXIMUM = "Maximum" + TOTAL = "Total" + + class TimeRange(str, Enum, metaclass=CaseInsensitiveEnumMeta): """TimeRange.""" @@ -216,3 +490,10 @@ class TimeRange(str, Enum, metaclass=CaseInsensitiveEnumMeta): ONE_D = "1d" SEVEN_D = "7d" THIRTY_D = "30d" + + +class Type(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The enrichment type.""" + + PROMETHEUS_INSTANT_QUERY = "PrometheusInstantQuery" + PROMETHEUS_RANGE_QUERY = "PrometheusRangeQuery" diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/models/_models_py3.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/models/_models_py3.py index de87aaa590fe..4ea2142b64d8 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/models/_models_py3.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/models/_models_py3.py @@ -1,5 +1,5 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 -# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -7,14 +7,291 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping import datetime -from typing import Dict, List, Optional, TYPE_CHECKING, Union +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union -from .. import _serialization +from .._utils import serialization as _serialization if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models +JSON = MutableMapping[str, Any] + + +class AbnormalEventAnomalyInsight(_serialization.Model): + """The insight for an abnormal event. + + All required parameters must be populated in order to send to server. + + :ivar cloud_role_name: The cloud role name for which the log was made. Required. + :vartype cloud_role_name: str + :ivar analysis_start_time: The start time of the analysis (in UTC). Required. + :vartype analysis_start_time: ~datetime.datetime + :ivar analysis_end_time: The end time of the analysis (in UTC). Required. + :vartype analysis_end_time: ~datetime.datetime + :ivar target: The source of the detected anomaly, for example: target URI of a dependency, name + of a failed operation, or type of an exception. Required. + :vartype target: str + :ivar description: The description of the abnormal event. + :vartype description: str + :ivar examples: Examples of the abnormal event. Required. + :vartype examples: list[str] + :ivar total_count: The total count of log entries analyzed. + :vartype total_count: int + :ivar failed_count: The count of failed log entries. + :vartype failed_count: int + :ivar abnormal_event_type: The type of abnormal event. Required. Known values are: + "Dependency", "Request", and "Exception". + :vartype abnormal_event_type: str or ~azure.mgmt.alertsmanagement.models.AbnormalEventType + :ivar anomaly_time: The time when the anomaly was detected (in UTC). Required. + :vartype anomaly_time: ~datetime.datetime + :ivar transaction_pattern_anomalies: The transaction pattern anomalies. Required. + :vartype transaction_pattern_anomalies: + list[~azure.mgmt.alertsmanagement.models.TransactionPatternAnomaly] + :ivar trace_pattern_anomalies: The trace pattern anomalies. Required. + :vartype trace_pattern_anomalies: list[~azure.mgmt.alertsmanagement.models.TracePatternAnomaly] + :ivar exception_pattern_anomalies: The exception pattern anomalies. Required. + :vartype exception_pattern_anomalies: + list[~azure.mgmt.alertsmanagement.models.ExceptionPatternAnomaly] + """ + + _validation = { + "cloud_role_name": {"required": True}, + "analysis_start_time": {"required": True}, + "analysis_end_time": {"required": True}, + "target": {"required": True}, + "examples": {"required": True}, + "abnormal_event_type": {"required": True}, + "anomaly_time": {"required": True}, + "transaction_pattern_anomalies": {"required": True}, + "trace_pattern_anomalies": {"required": True}, + "exception_pattern_anomalies": {"required": True}, + } + + _attribute_map = { + "cloud_role_name": {"key": "cloudRoleName", "type": "str"}, + "analysis_start_time": {"key": "analysisStartTime", "type": "iso-8601"}, + "analysis_end_time": {"key": "analysisEndTime", "type": "iso-8601"}, + "target": {"key": "target", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "examples": {"key": "examples", "type": "[str]"}, + "total_count": {"key": "totalCount", "type": "int"}, + "failed_count": {"key": "failedCount", "type": "int"}, + "abnormal_event_type": {"key": "abnormalEventType", "type": "str"}, + "anomaly_time": {"key": "anomalyTime", "type": "iso-8601"}, + "transaction_pattern_anomalies": {"key": "transactionPatternAnomalies", "type": "[TransactionPatternAnomaly]"}, + "trace_pattern_anomalies": {"key": "tracePatternAnomalies", "type": "[TracePatternAnomaly]"}, + "exception_pattern_anomalies": {"key": "exceptionPatternAnomalies", "type": "[ExceptionPatternAnomaly]"}, + } + + def __init__( + self, + *, + cloud_role_name: str, + analysis_start_time: datetime.datetime, + analysis_end_time: datetime.datetime, + target: str, + examples: List[str], + abnormal_event_type: Union[str, "_models.AbnormalEventType"], + anomaly_time: datetime.datetime, + transaction_pattern_anomalies: List["_models.TransactionPatternAnomaly"], + trace_pattern_anomalies: List["_models.TracePatternAnomaly"], + exception_pattern_anomalies: List["_models.ExceptionPatternAnomaly"], + description: Optional[str] = None, + total_count: Optional[int] = None, + failed_count: Optional[int] = None, + **kwargs: Any + ) -> None: + """ + :keyword cloud_role_name: The cloud role name for which the log was made. Required. + :paramtype cloud_role_name: str + :keyword analysis_start_time: The start time of the analysis (in UTC). Required. + :paramtype analysis_start_time: ~datetime.datetime + :keyword analysis_end_time: The end time of the analysis (in UTC). Required. + :paramtype analysis_end_time: ~datetime.datetime + :keyword target: The source of the detected anomaly, for example: target URI of a dependency, + name of a failed operation, or type of an exception. Required. + :paramtype target: str + :keyword description: The description of the abnormal event. + :paramtype description: str + :keyword examples: Examples of the abnormal event. Required. + :paramtype examples: list[str] + :keyword total_count: The total count of log entries analyzed. + :paramtype total_count: int + :keyword failed_count: The count of failed log entries. + :paramtype failed_count: int + :keyword abnormal_event_type: The type of abnormal event. Required. Known values are: + "Dependency", "Request", and "Exception". + :paramtype abnormal_event_type: str or ~azure.mgmt.alertsmanagement.models.AbnormalEventType + :keyword anomaly_time: The time when the anomaly was detected (in UTC). Required. + :paramtype anomaly_time: ~datetime.datetime + :keyword transaction_pattern_anomalies: The transaction pattern anomalies. Required. + :paramtype transaction_pattern_anomalies: + list[~azure.mgmt.alertsmanagement.models.TransactionPatternAnomaly] + :keyword trace_pattern_anomalies: The trace pattern anomalies. Required. + :paramtype trace_pattern_anomalies: + list[~azure.mgmt.alertsmanagement.models.TracePatternAnomaly] + :keyword exception_pattern_anomalies: The exception pattern anomalies. Required. + :paramtype exception_pattern_anomalies: + list[~azure.mgmt.alertsmanagement.models.ExceptionPatternAnomaly] + """ + super().__init__(**kwargs) + self.cloud_role_name = cloud_role_name + self.analysis_start_time = analysis_start_time + self.analysis_end_time = analysis_end_time + self.target = target + self.description = description + self.examples = examples + self.total_count = total_count + self.failed_count = failed_count + self.abnormal_event_type = abnormal_event_type + self.anomaly_time = anomaly_time + self.transaction_pattern_anomalies = transaction_pattern_anomalies + self.trace_pattern_anomalies = trace_pattern_anomalies + self.exception_pattern_anomalies = exception_pattern_anomalies + + +class AbnormalEventData(_serialization.Model): + """The data details for logs. + + All required parameters must be populated in order to send to server. + + :ivar kql_filter: The kql filter to display. Required. + :vartype kql_filter: str + """ + + _validation = { + "kql_filter": {"required": True}, + } + + _attribute_map = { + "kql_filter": {"key": "kqlFilter", "type": "str"}, + } + + def __init__(self, *, kql_filter: str, **kwargs: Any) -> None: + """ + :keyword kql_filter: The kql filter to display. Required. + :paramtype kql_filter: str + """ + super().__init__(**kwargs) + self.kql_filter = kql_filter + + +class DetailsBase(_serialization.Model): + """The details base type. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AbnormalEventDetails, AzureMetricDetails, DiagnosticsSolutionDetails, InvestigationDetails, + RelatedAlertDetails, ResourceHealthDetails + + All required parameters must be populated in order to send to server. + + :ivar details_type: The type of details. Required. Known values are: "Investigation", + "Finding", "AzureMetric", "AbnormalEvent", "RelatedAlert", "ResourceHealth", and "Diagnostics". + :vartype details_type: str or ~azure.mgmt.alertsmanagement.models.DetailsType + :ivar category: The details category. Required. Known values are: "Investigation", "Metric", + "Log", "Alert", "ResourceHealth", and "Diagnostics". + :vartype category: str or ~azure.mgmt.alertsmanagement.models.CategoryType + :ivar resource_ids: The resource ids related to the anomaly. + :vartype resource_ids: list[str] + """ + + _validation = { + "details_type": {"required": True}, + "category": {"required": True}, + } + + _attribute_map = { + "details_type": {"key": "detailsType", "type": "str"}, + "category": {"key": "category", "type": "str"}, + "resource_ids": {"key": "resourceIds", "type": "[str]"}, + } + + _subtype_map = { + "details_type": { + "AbnormalEvent": "AbnormalEventDetails", + "AzureMetric": "AzureMetricDetails", + "Diagnostics": "DiagnosticsSolutionDetails", + "Investigation": "InvestigationDetails", + "RelatedAlert": "RelatedAlertDetails", + "ResourceHealth": "ResourceHealthDetails", + } + } + + def __init__( + self, *, category: Union[str, "_models.CategoryType"], resource_ids: Optional[List[str]] = None, **kwargs: Any + ) -> None: + """ + :keyword category: The details category. Required. Known values are: "Investigation", "Metric", + "Log", "Alert", "ResourceHealth", and "Diagnostics". + :paramtype category: str or ~azure.mgmt.alertsmanagement.models.CategoryType + :keyword resource_ids: The resource ids related to the anomaly. + :paramtype resource_ids: list[str] + """ + super().__init__(**kwargs) + self.details_type: Optional[str] = None + self.category = category + self.resource_ids = resource_ids + + +class AbnormalEventDetails(DetailsBase): + """An abnormal event details. + + All required parameters must be populated in order to send to server. + + :ivar details_type: The type of details. Required. Known values are: "Investigation", + "Finding", "AzureMetric", "AbnormalEvent", "RelatedAlert", "ResourceHealth", and "Diagnostics". + :vartype details_type: str or ~azure.mgmt.alertsmanagement.models.DetailsType + :ivar category: The details category. Required. Known values are: "Investigation", "Metric", + "Log", "Alert", "ResourceHealth", and "Diagnostics". + :vartype category: str or ~azure.mgmt.alertsmanagement.models.CategoryType + :ivar resource_ids: The resource ids related to the anomaly. + :vartype resource_ids: list[str] + :ivar data: The details data, which could be user generated or system generated. Required. + :vartype data: ~azure.mgmt.alertsmanagement.models.AbnormalEventData + :ivar insight: Insight about the anomaly, this is system generated. Required. + :vartype insight: ~azure.mgmt.alertsmanagement.models.AbnormalEventAnomalyInsight + """ + + _validation = { + "details_type": {"required": True}, + "category": {"required": True}, + "data": {"required": True}, + "insight": {"required": True}, + } + + _attribute_map = { + "details_type": {"key": "detailsType", "type": "str"}, + "category": {"key": "category", "type": "str"}, + "resource_ids": {"key": "resourceIds", "type": "[str]"}, + "data": {"key": "data", "type": "AbnormalEventData"}, + "insight": {"key": "insight", "type": "AbnormalEventAnomalyInsight"}, + } + + def __init__( + self, + *, + category: Union[str, "_models.CategoryType"], + data: "_models.AbnormalEventData", + insight: "_models.AbnormalEventAnomalyInsight", + resource_ids: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword category: The details category. Required. Known values are: "Investigation", "Metric", + "Log", "Alert", "ResourceHealth", and "Diagnostics". + :paramtype category: str or ~azure.mgmt.alertsmanagement.models.CategoryType + :keyword resource_ids: The resource ids related to the anomaly. + :paramtype resource_ids: list[str] + :keyword data: The details data, which could be user generated or system generated. Required. + :paramtype data: ~azure.mgmt.alertsmanagement.models.AbnormalEventData + :keyword insight: Insight about the anomaly, this is system generated. Required. + :paramtype insight: ~azure.mgmt.alertsmanagement.models.AbnormalEventAnomalyInsight + """ + super().__init__(category=category, resource_ids=resource_ids, **kwargs) + self.details_type: str = "AbnormalEvent" + self.data = data + self.insight = insight class Action(_serialization.Model): @@ -23,7 +300,7 @@ class Action(_serialization.Model): You probably want to use the sub-classes and not this class directly. Known sub-classes are: AddActionGroups, RemoveAllActionGroups - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar action_type: Action that should be applied. Required. Known values are: "AddActionGroups" and "RemoveAllActionGroups". @@ -42,7 +319,7 @@ class Action(_serialization.Model): "action_type": {"AddActionGroups": "AddActionGroups", "RemoveAllActionGroups": "RemoveAllActionGroups"} } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.action_type: Optional[str] = None @@ -59,7 +336,7 @@ class ActionStatus(_serialization.Model): "is_suppressed": {"key": "isSuppressed", "type": "bool"}, } - def __init__(self, *, is_suppressed: Optional[bool] = None, **kwargs): + def __init__(self, *, is_suppressed: Optional[bool] = None, **kwargs: Any) -> None: """ :keyword is_suppressed: Value indicating whether alert is suppressed. :paramtype is_suppressed: bool @@ -71,7 +348,7 @@ def __init__(self, *, is_suppressed: Optional[bool] = None, **kwargs): class AddActionGroups(Action): """Add action groups to alert processing rule. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar action_type: Action that should be applied. Required. Known values are: "AddActionGroups" and "RemoveAllActionGroups". @@ -90,7 +367,7 @@ class AddActionGroups(Action): "action_group_ids": {"key": "actionGroupIds", "type": "[str]"}, } - def __init__(self, *, action_group_ids: List[str], **kwargs): + def __init__(self, *, action_group_ids: List[str], **kwargs: Any) -> None: """ :keyword action_group_ids: List of action group Ids to add to alert processing rule. Required. :paramtype action_group_ids: list[str] @@ -100,7 +377,7 @@ def __init__(self, *, action_group_ids: List[str], **kwargs): self.action_group_ids = action_group_ids -class Resource(_serialization.Model): +class ResourceAutoGenerated(_serialization.Model): """An azure resource object. Variables are only populated by the server, and will be ignored when sending a request. @@ -125,15 +402,15 @@ class Resource(_serialization.Model): "name": {"key": "name", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.id = None - self.type = None - self.name = None + self.id: Optional[str] = None + self.type: Optional[str] = None + self.name: Optional[str] = None -class Alert(Resource): +class Alert(ResourceAutoGenerated): """An alert created in alert management service. Variables are only populated by the server, and will be ignored when sending a request. @@ -161,7 +438,7 @@ class Alert(Resource): "properties": {"key": "properties", "type": "AlertProperties"}, } - def __init__(self, *, properties: Optional["_models.AlertProperties"] = None, **kwargs): + def __init__(self, *, properties: Optional["_models.AlertProperties"] = None, **kwargs: Any) -> None: """ :keyword properties: Alert property bag. :paramtype properties: ~azure.mgmt.alertsmanagement.models.AlertProperties @@ -170,7 +447,221 @@ def __init__(self, *, properties: Optional["_models.AlertProperties"] = None, ** self.properties = properties -class AlertModification(Resource): +class AlertEnrichmentItem(_serialization.Model): + """Alert enrichment item. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + PrometheusEnrichmentItem + + All required parameters must be populated in order to send to server. + + :ivar title: The enrichment title. Required. + :vartype title: str + :ivar description: The enrichment description. Required. + :vartype description: str + :ivar status: The status of the evaluation of the enrichment. Required. Known values are: + "Succeeded", "Failed", "New", "InProgress", "Mitigated", "Closed", and "Canceled". + :vartype status: str or ~azure.mgmt.alertsmanagement.models.Status + :ivar error_message: The error message. Will be present only if the status is 'Failed'. + :vartype error_message: str + :ivar type: The enrichment type. Required. Known values are: "PrometheusInstantQuery" and + "PrometheusRangeQuery". + :vartype type: str or ~azure.mgmt.alertsmanagement.models.Type + """ + + _validation = { + "title": {"required": True}, + "description": {"required": True}, + "status": {"required": True}, + "type": {"required": True}, + } + + _attribute_map = { + "title": {"key": "title", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "error_message": {"key": "errorMessage", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + _subtype_map = {"type": {"PrometheusEnrichmentItem": "PrometheusEnrichmentItem"}} + + def __init__( + self, + *, + title: str, + description: str, + status: Union[str, "_models.Status"], + error_message: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword title: The enrichment title. Required. + :paramtype title: str + :keyword description: The enrichment description. Required. + :paramtype description: str + :keyword status: The status of the evaluation of the enrichment. Required. Known values are: + "Succeeded", "Failed", "New", "InProgress", "Mitigated", "Closed", and "Canceled". + :paramtype status: str or ~azure.mgmt.alertsmanagement.models.Status + :keyword error_message: The error message. Will be present only if the status is 'Failed'. + :paramtype error_message: str + """ + super().__init__(**kwargs) + self.title = title + self.description = description + self.status = status + self.error_message = error_message + self.type: Optional[str] = None + + +class AlertEnrichmentProperties(_serialization.Model): + """Properties of the alert enrichment item. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar alert_id: Unique Id (GUID) of the alert for which the enrichments are being retrieved. + :vartype alert_id: str + :ivar enrichments: Enrichment details. + :vartype enrichments: list[~azure.mgmt.alertsmanagement.models.AlertEnrichmentItem] + """ + + _validation = { + "alert_id": {"readonly": True}, + } + + _attribute_map = { + "alert_id": {"key": "alertId", "type": "str"}, + "enrichments": {"key": "enrichments", "type": "[AlertEnrichmentItem]"}, + } + + def __init__(self, *, enrichments: Optional[List["_models.AlertEnrichmentItem"]] = None, **kwargs: Any) -> None: + """ + :keyword enrichments: Enrichment details. + :paramtype enrichments: list[~azure.mgmt.alertsmanagement.models.AlertEnrichmentItem] + """ + super().__init__(**kwargs) + self.alert_id: Optional[str] = None + self.enrichments = enrichments + + +class ResourceAutoGenerated2(_serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.alertsmanagement.models.SystemData + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None + + +class AlertEnrichmentResponse(ResourceAutoGenerated2): + """The alert's enrichments. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.alertsmanagement.models.SystemData + :ivar properties: Properties of the alert enrichment item. + :vartype properties: ~azure.mgmt.alertsmanagement.models.AlertEnrichmentProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "properties": {"key": "properties", "type": "AlertEnrichmentProperties"}, + } + + def __init__(self, *, properties: Optional["_models.AlertEnrichmentProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: Properties of the alert enrichment item. + :paramtype properties: ~azure.mgmt.alertsmanagement.models.AlertEnrichmentProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class AlertEnrichmentsList(_serialization.Model): + """List the alert's enrichments. + + :ivar value: List the alert's enrichments. + :vartype value: list[~azure.mgmt.alertsmanagement.models.AlertEnrichmentResponse] + :ivar next_link: Request URL that can be used to query next page. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[AlertEnrichmentResponse]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, + *, + value: Optional[List["_models.AlertEnrichmentResponse"]] = None, + next_link: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword value: List the alert's enrichments. + :paramtype value: list[~azure.mgmt.alertsmanagement.models.AlertEnrichmentResponse] + :keyword next_link: Request URL that can be used to query next page. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AlertModification(ResourceAutoGenerated): """Alert Modification details. Variables are only populated by the server, and will be ignored when sending a request. @@ -198,7 +689,7 @@ class AlertModification(Resource): "properties": {"key": "properties", "type": "AlertModificationProperties"}, } - def __init__(self, *, properties: Optional["_models.AlertModificationProperties"] = None, **kwargs): + def __init__(self, *, properties: Optional["_models.AlertModificationProperties"] = None, **kwargs: Any) -> None: """ :keyword properties: Properties of the alert modification item. :paramtype properties: ~azure.mgmt.alertsmanagement.models.AlertModificationProperties @@ -248,8 +739,8 @@ def __init__( modified_by: Optional[str] = None, comments: Optional[str] = None, description: Optional[str] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword modification_event: Reason for the modification. Known values are: "AlertCreated", "StateChange", "MonitorConditionChange", "SeverityChange", "ActionRuleTriggered", @@ -299,22 +790,22 @@ class AlertModificationProperties(_serialization.Model): "modifications": {"key": "modifications", "type": "[AlertModificationItem]"}, } - def __init__(self, *, modifications: Optional[List["_models.AlertModificationItem"]] = None, **kwargs): + def __init__(self, *, modifications: Optional[List["_models.AlertModificationItem"]] = None, **kwargs: Any) -> None: """ :keyword modifications: Modification details. :paramtype modifications: list[~azure.mgmt.alertsmanagement.models.AlertModificationItem] """ super().__init__(**kwargs) - self.alert_id = None + self.alert_id: Optional[str] = None self.modifications = modifications -class ManagedResource(Resource): +class ManagedResource(ResourceAutoGenerated): """An azure managed resource object. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: Azure resource Id. :vartype id: str @@ -343,7 +834,7 @@ class ManagedResource(Resource): "tags": {"key": "tags", "type": "{str}"}, } - def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs): + def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: """ :keyword location: Resource location. Required. :paramtype location: str @@ -360,7 +851,7 @@ class AlertProcessingRule(ManagedResource): Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: Azure resource Id. :vartype id: str @@ -402,8 +893,8 @@ def __init__( location: str, tags: Optional[Dict[str, str]] = None, properties: Optional["_models.AlertProcessingRuleProperties"] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword location: Resource location. Required. :paramtype location: str @@ -414,13 +905,14 @@ def __init__( """ super().__init__(location=location, tags=tags, **kwargs) self.properties = properties - self.system_data = None + self.system_data: Optional["_models.SystemData"] = None class AlertProcessingRuleProperties(_serialization.Model): - """Alert processing rule properties defining scopes, conditions and scheduling logic for alert processing rule. + """Alert processing rule properties defining scopes, conditions and scheduling logic for alert + processing rule. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar scopes: Scopes on which alert processing rule will apply. Required. :vartype scopes: list[str] @@ -459,8 +951,8 @@ def __init__( schedule: Optional["_models.Schedule"] = None, description: Optional[str] = None, enabled: bool = True, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword scopes: Scopes on which alert processing rule will apply. Required. :paramtype scopes: list[str] @@ -499,8 +991,12 @@ class AlertProcessingRulesList(_serialization.Model): } def __init__( - self, *, next_link: Optional[str] = None, value: Optional[List["_models.AlertProcessingRule"]] = None, **kwargs - ): + self, + *, + next_link: Optional[str] = None, + value: Optional[List["_models.AlertProcessingRule"]] = None, + **kwargs: Any + ) -> None: """ :keyword next_link: URL to fetch the next set of alert processing rules. :paramtype next_link: str @@ -537,41 +1033,215 @@ class AlertProperties(_serialization.Model): "egress_config": {"key": "egressConfig", "type": "object"}, } - def __init__(self, *, essentials: Optional["_models.Essentials"] = None, **kwargs): + def __init__(self, *, essentials: Optional["_models.Essentials"] = None, **kwargs: Any) -> None: """ :keyword essentials: This object contains consistent fields across different monitor services. :paramtype essentials: ~azure.mgmt.alertsmanagement.models.Essentials """ super().__init__(**kwargs) self.essentials = essentials - self.context = None - self.egress_config = None + self.context: Optional[JSON] = None + self.egress_config: Optional[JSON] = None -class AlertsList(_serialization.Model): - """List the alerts. +class Resource(_serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. - :ivar next_link: URL to fetch the next set of alerts. - :vartype next_link: str - :ivar value: List of alerts. - :vartype value: list[~azure.mgmt.alertsmanagement.models.Alert] + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.alertsmanagement.models.SystemData """ + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + _attribute_map = { - "next_link": {"key": "nextLink", "type": "str"}, - "value": {"key": "value", "type": "[Alert]"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, } - def __init__(self, *, next_link: Optional[str] = None, value: Optional[List["_models.Alert"]] = None, **kwargs): - """ - :keyword next_link: URL to fetch the next set of alerts. - :paramtype next_link: str - :keyword value: List of alerts. - :paramtype value: list[~azure.mgmt.alertsmanagement.models.Alert] - """ + def __init__(self, **kwargs: Any) -> None: + """ """ super().__init__(**kwargs) - self.next_link = next_link - self.value = value + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None + + +class ProxyResource(Resource): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have + tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.alertsmanagement.models.SystemData + """ + + +class AlertRuleRecommendationResource(ProxyResource): + """A single alert rule recommendation resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.alertsmanagement.models.SystemData + :ivar alert_rule_type: The recommendation alert rule type. Required. + :vartype alert_rule_type: str + :ivar category: The recommendation alert rule category. + :vartype category: str + :ivar display_information: A dictionary that provides the display information for an alert rule + recommendation. Required. + :vartype display_information: dict[str, str] + :ivar rule_arm_template: A complete ARM template to deploy the alert rules. Required. + :vartype rule_arm_template: ~azure.mgmt.alertsmanagement.models.RuleArmTemplate + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "alert_rule_type": {"required": True}, + "display_information": {"required": True}, + "rule_arm_template": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "alert_rule_type": {"key": "properties.alertRuleType", "type": "str"}, + "category": {"key": "properties.category", "type": "str"}, + "display_information": {"key": "properties.displayInformation", "type": "{str}"}, + "rule_arm_template": {"key": "properties.ruleArmTemplate", "type": "RuleArmTemplate"}, + } + + def __init__( + self, + *, + alert_rule_type: str, + display_information: Dict[str, str], + rule_arm_template: "_models.RuleArmTemplate", + category: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword alert_rule_type: The recommendation alert rule type. Required. + :paramtype alert_rule_type: str + :keyword category: The recommendation alert rule category. + :paramtype category: str + :keyword display_information: A dictionary that provides the display information for an alert + rule recommendation. Required. + :paramtype display_information: dict[str, str] + :keyword rule_arm_template: A complete ARM template to deploy the alert rules. Required. + :paramtype rule_arm_template: ~azure.mgmt.alertsmanagement.models.RuleArmTemplate + """ + super().__init__(**kwargs) + self.alert_rule_type = alert_rule_type + self.category = category + self.display_information = display_information + self.rule_arm_template = rule_arm_template + + +class AlertRuleRecommendationsListResponse(_serialization.Model): + """List of alert rule recommendations. + + All required parameters must be populated in order to send to server. + + :ivar value: the values for the alert rule recommendations. Required. + :vartype value: list[~azure.mgmt.alertsmanagement.models.AlertRuleRecommendationResource] + :ivar next_link: URL to fetch the next set of recommendations. + :vartype next_link: str + """ + + _validation = { + "value": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[AlertRuleRecommendationResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: List["_models.AlertRuleRecommendationResource"], next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: the values for the alert rule recommendations. Required. + :paramtype value: list[~azure.mgmt.alertsmanagement.models.AlertRuleRecommendationResource] + :keyword next_link: URL to fetch the next set of recommendations. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class AlertsList(_serialization.Model): + """List the alerts. + + :ivar next_link: URL to fetch the next set of alerts. + :vartype next_link: str + :ivar value: List of alerts. + :vartype value: list[~azure.mgmt.alertsmanagement.models.Alert] + """ + + _attribute_map = { + "next_link": {"key": "nextLink", "type": "str"}, + "value": {"key": "value", "type": "[Alert]"}, + } + + def __init__( + self, *, next_link: Optional[str] = None, value: Optional[List["_models.Alert"]] = None, **kwargs: Any + ) -> None: + """ + :keyword next_link: URL to fetch the next set of alerts. + :paramtype next_link: str + :keyword value: List of alerts. + :paramtype value: list[~azure.mgmt.alertsmanagement.models.Alert] + """ + super().__init__(**kwargs) + self.next_link = next_link + self.value = value class AlertsMetaData(_serialization.Model): @@ -585,7 +1255,7 @@ class AlertsMetaData(_serialization.Model): "properties": {"key": "properties", "type": "AlertsMetaDataProperties"}, } - def __init__(self, *, properties: Optional["_models.AlertsMetaDataProperties"] = None, **kwargs): + def __init__(self, *, properties: Optional["_models.AlertsMetaDataProperties"] = None, **kwargs: Any) -> None: """ :keyword properties: alert meta data property bag. :paramtype properties: ~azure.mgmt.alertsmanagement.models.AlertsMetaDataProperties @@ -600,7 +1270,7 @@ class AlertsMetaDataProperties(_serialization.Model): You probably want to use the sub-classes and not this class directly. Known sub-classes are: MonitorServiceList - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar metadata_identifier: Identification of the information to be retrieved by API call. Required. "MonitorServiceList" @@ -617,13 +1287,13 @@ class AlertsMetaDataProperties(_serialization.Model): _subtype_map = {"metadata_identifier": {"MonitorServiceList": "MonitorServiceList"}} - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.metadata_identifier: Optional[str] = None -class AlertsSummary(Resource): +class AlertsSummary(ResourceAutoGenerated): """Summary of alerts based on the input filters and 'groupby' parameters. Variables are only populated by the server, and will be ignored when sending a request. @@ -651,7 +1321,7 @@ class AlertsSummary(Resource): "properties": {"key": "properties", "type": "AlertsSummaryGroup"}, } - def __init__(self, *, properties: Optional["_models.AlertsSummaryGroup"] = None, **kwargs): + def __init__(self, *, properties: Optional["_models.AlertsSummaryGroup"] = None, **kwargs: Any) -> None: """ :keyword properties: Group the result set. :paramtype properties: ~azure.mgmt.alertsmanagement.models.AlertsSummaryGroup @@ -687,8 +1357,8 @@ def __init__( smart_groups_count: Optional[int] = None, groupedby: Optional[str] = None, values: Optional[List["_models.AlertsSummaryGroupItem"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword total: Total count of the result set. :paramtype total: int @@ -733,8 +1403,8 @@ def __init__( count: Optional[int] = None, groupedby: Optional[str] = None, values: Optional[List["_models.AlertsSummaryGroupItem"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword name: Value of the aggregated field. :paramtype name: str @@ -752,6 +1422,262 @@ def __init__( self.values = values +class AnomalyRange(_serialization.Model): + """The range for anomaly scanning. + + All required parameters must be populated in order to send to server. + + :ivar start: The start time of the range (in UTC). Required. + :vartype start: ~datetime.datetime + :ivar end: The end time of the range (in UTC). Required. + :vartype end: ~datetime.datetime + """ + + _validation = { + "start": {"required": True}, + "end": {"required": True}, + } + + _attribute_map = { + "start": {"key": "start", "type": "iso-8601"}, + "end": {"key": "end", "type": "iso-8601"}, + } + + def __init__(self, *, start: datetime.datetime, end: datetime.datetime, **kwargs: Any) -> None: + """ + :keyword start: The start time of the range (in UTC). Required. + :paramtype start: ~datetime.datetime + :keyword end: The end time of the range (in UTC). Required. + :paramtype end: ~datetime.datetime + """ + super().__init__(**kwargs) + self.start = start + self.end = end + + +class AzureMetricAnomalyInsight(_serialization.Model): + """The insight for a metric anomaly. + + All required parameters must be populated in order to send to server. + + :ivar anomaly_scan_range: The range of that was scanned for anomalies. Required. + :vartype anomaly_scan_range: ~azure.mgmt.alertsmanagement.models.AnomalyRange + :ivar thresholds: The baseline range for the metric. Required. + :vartype thresholds: ~azure.mgmt.alertsmanagement.models.BaselineRange + :ivar anomaly_direction: The direction of the anomaly. Required. Known values are: "Increase", + "Decrease", and "IncreaseAndDecrease". + :vartype anomaly_direction: str or ~azure.mgmt.alertsmanagement.models.AnomalyDirection + :ivar anomaly_time: The time of the anomaly (in UTC). Required. + :vartype anomaly_time: ~datetime.datetime + """ + + _validation = { + "anomaly_scan_range": {"required": True}, + "thresholds": {"required": True}, + "anomaly_direction": {"required": True}, + "anomaly_time": {"required": True}, + } + + _attribute_map = { + "anomaly_scan_range": {"key": "anomalyScanRange", "type": "AnomalyRange"}, + "thresholds": {"key": "thresholds", "type": "BaselineRange"}, + "anomaly_direction": {"key": "anomalyDirection", "type": "str"}, + "anomaly_time": {"key": "anomalyTime", "type": "iso-8601"}, + } + + def __init__( + self, + *, + anomaly_scan_range: "_models.AnomalyRange", + thresholds: "_models.BaselineRange", + anomaly_direction: Union[str, "_models.AnomalyDirection"], + anomaly_time: datetime.datetime, + **kwargs: Any + ) -> None: + """ + :keyword anomaly_scan_range: The range of that was scanned for anomalies. Required. + :paramtype anomaly_scan_range: ~azure.mgmt.alertsmanagement.models.AnomalyRange + :keyword thresholds: The baseline range for the metric. Required. + :paramtype thresholds: ~azure.mgmt.alertsmanagement.models.BaselineRange + :keyword anomaly_direction: The direction of the anomaly. Required. Known values are: + "Increase", "Decrease", and "IncreaseAndDecrease". + :paramtype anomaly_direction: str or ~azure.mgmt.alertsmanagement.models.AnomalyDirection + :keyword anomaly_time: The time of the anomaly (in UTC). Required. + :paramtype anomaly_time: ~datetime.datetime + """ + super().__init__(**kwargs) + self.anomaly_scan_range = anomaly_scan_range + self.thresholds = thresholds + self.anomaly_direction = anomaly_direction + self.anomaly_time = anomaly_time + + +class AzureMetricData(_serialization.Model): + """The data details for azure metrics. + + All required parameters must be populated in order to send to server. + + :ivar metric_name: The name of the metric. Required. + :vartype metric_name: str + :ivar metric_namespace: The namespace of the metric. Required. + :vartype metric_namespace: str + :ivar metric_interval: The interval at which the metric is collected. Required. + :vartype metric_interval: ~datetime.timedelta + :ivar metric_aggregation: The aggregation type of the metric. Required. Known values are: + "Average", "Minimum", "Maximum", "Total", "Count", "Unique", and "None". + :vartype metric_aggregation: str or ~azure.mgmt.alertsmanagement.models.AggregationType + :ivar scan_range: The range for anomaly scanning. Required. + :vartype scan_range: ~azure.mgmt.alertsmanagement.models.AnomalyRange + :ivar dimensions: The dimensions of the metric. Required. + :vartype dimensions: dict[str, list[str]] + """ + + _validation = { + "metric_name": {"required": True}, + "metric_namespace": {"required": True}, + "metric_interval": {"required": True}, + "metric_aggregation": {"required": True}, + "scan_range": {"required": True}, + "dimensions": {"required": True}, + } + + _attribute_map = { + "metric_name": {"key": "metricName", "type": "str"}, + "metric_namespace": {"key": "metricNamespace", "type": "str"}, + "metric_interval": {"key": "metricInterval", "type": "duration"}, + "metric_aggregation": {"key": "metricAggregation", "type": "str"}, + "scan_range": {"key": "scanRange", "type": "AnomalyRange"}, + "dimensions": {"key": "dimensions", "type": "{[str]}"}, + } + + def __init__( + self, + *, + metric_name: str, + metric_namespace: str, + metric_interval: datetime.timedelta, + metric_aggregation: Union[str, "_models.AggregationType"], + scan_range: "_models.AnomalyRange", + dimensions: Dict[str, List[str]], + **kwargs: Any + ) -> None: + """ + :keyword metric_name: The name of the metric. Required. + :paramtype metric_name: str + :keyword metric_namespace: The namespace of the metric. Required. + :paramtype metric_namespace: str + :keyword metric_interval: The interval at which the metric is collected. Required. + :paramtype metric_interval: ~datetime.timedelta + :keyword metric_aggregation: The aggregation type of the metric. Required. Known values are: + "Average", "Minimum", "Maximum", "Total", "Count", "Unique", and "None". + :paramtype metric_aggregation: str or ~azure.mgmt.alertsmanagement.models.AggregationType + :keyword scan_range: The range for anomaly scanning. Required. + :paramtype scan_range: ~azure.mgmt.alertsmanagement.models.AnomalyRange + :keyword dimensions: The dimensions of the metric. Required. + :paramtype dimensions: dict[str, list[str]] + """ + super().__init__(**kwargs) + self.metric_name = metric_name + self.metric_namespace = metric_namespace + self.metric_interval = metric_interval + self.metric_aggregation = metric_aggregation + self.scan_range = scan_range + self.dimensions = dimensions + + +class AzureMetricDetails(DetailsBase): + """An azure metric details. + + All required parameters must be populated in order to send to server. + + :ivar details_type: The type of details. Required. Known values are: "Investigation", + "Finding", "AzureMetric", "AbnormalEvent", "RelatedAlert", "ResourceHealth", and "Diagnostics". + :vartype details_type: str or ~azure.mgmt.alertsmanagement.models.DetailsType + :ivar category: The details category. Required. Known values are: "Investigation", "Metric", + "Log", "Alert", "ResourceHealth", and "Diagnostics". + :vartype category: str or ~azure.mgmt.alertsmanagement.models.CategoryType + :ivar resource_ids: The resource ids related to the anomaly. + :vartype resource_ids: list[str] + :ivar data: The details data, which could be user generated or system generated. Required. + :vartype data: ~azure.mgmt.alertsmanagement.models.AzureMetricData + :ivar insight: Insight about the anomaly, which is system generated. Required. + :vartype insight: ~azure.mgmt.alertsmanagement.models.AzureMetricAnomalyInsight + """ + + _validation = { + "details_type": {"required": True}, + "category": {"required": True}, + "data": {"required": True}, + "insight": {"required": True}, + } + + _attribute_map = { + "details_type": {"key": "detailsType", "type": "str"}, + "category": {"key": "category", "type": "str"}, + "resource_ids": {"key": "resourceIds", "type": "[str]"}, + "data": {"key": "data", "type": "AzureMetricData"}, + "insight": {"key": "insight", "type": "AzureMetricAnomalyInsight"}, + } + + def __init__( + self, + *, + category: Union[str, "_models.CategoryType"], + data: "_models.AzureMetricData", + insight: "_models.AzureMetricAnomalyInsight", + resource_ids: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword category: The details category. Required. Known values are: "Investigation", "Metric", + "Log", "Alert", "ResourceHealth", and "Diagnostics". + :paramtype category: str or ~azure.mgmt.alertsmanagement.models.CategoryType + :keyword resource_ids: The resource ids related to the anomaly. + :paramtype resource_ids: list[str] + :keyword data: The details data, which could be user generated or system generated. Required. + :paramtype data: ~azure.mgmt.alertsmanagement.models.AzureMetricData + :keyword insight: Insight about the anomaly, which is system generated. Required. + :paramtype insight: ~azure.mgmt.alertsmanagement.models.AzureMetricAnomalyInsight + """ + super().__init__(category=category, resource_ids=resource_ids, **kwargs) + self.details_type: str = "AzureMetric" + self.data = data + self.insight = insight + + +class BaselineRange(_serialization.Model): + """The range for the baseline for an anomaly. + + All required parameters must be populated in order to send to server. + + :ivar high: The highest value of the range. Required. + :vartype high: float + :ivar low: The lowest value of the range. Required. + :vartype low: float + """ + + _validation = { + "high": {"required": True}, + "low": {"required": True}, + } + + _attribute_map = { + "high": {"key": "high", "type": "float"}, + "low": {"key": "low", "type": "float"}, + } + + def __init__(self, *, high: float, low: float, **kwargs: Any) -> None: + """ + :keyword high: The highest value of the range. Required. + :paramtype high: float + :keyword low: The lowest value of the range. Required. + :paramtype low: float + """ + super().__init__(**kwargs) + self.high = high + self.low = low + + class Comments(_serialization.Model): """Change alert state reason. @@ -763,7 +1689,7 @@ class Comments(_serialization.Model): "comments": {"key": "comments", "type": "str"}, } - def __init__(self, *, comments: Optional[str] = None, **kwargs): + def __init__(self, *, comments: Optional[str] = None, **kwargs: Any) -> None: """ :keyword comments: :paramtype comments: str @@ -798,8 +1724,8 @@ def __init__( field: Optional[Union[str, "_models.Field"]] = None, operator: Optional[Union[str, "_models.Operator"]] = None, values: Optional[List[str]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword field: Field for a given condition. Known values are: "Severity", "MonitorService", "MonitorCondition", "SignalType", "TargetResourceType", "TargetResource", @@ -817,13 +1743,47 @@ def __init__( self.values = values +class CorrelationDetails(_serialization.Model): + """Correlation details. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar parent_alert_id: Unique Id (GUID) of the alert that this alert was correlated to. + :vartype parent_alert_id: str + :ivar correlation_date_time: The alert's correlation date time in ISO-8601 format. + :vartype correlation_date_time: ~datetime.datetime + :ivar alert_processing_rule: The alert processing rule that was used to correlate this alert. + This is an optional field, it will be presented only for a parent alert. + :vartype alert_processing_rule: str + """ + + _validation = { + "parent_alert_id": {"readonly": True}, + "correlation_date_time": {"readonly": True}, + "alert_processing_rule": {"readonly": True}, + } + + _attribute_map = { + "parent_alert_id": {"key": "parentAlertId", "type": "str"}, + "correlation_date_time": {"key": "correlationDateTime", "type": "iso-8601"}, + "alert_processing_rule": {"key": "alertProcessingRule", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.parent_alert_id: Optional[str] = None + self.correlation_date_time: Optional[datetime.datetime] = None + self.alert_processing_rule: Optional[str] = None + + class Recurrence(_serialization.Model): """Recurrence object. You probably want to use the sub-classes and not this class directly. Known sub-classes are: DailyRecurrence, MonthlyRecurrence, WeeklyRecurrence - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar recurrence_type: Specifies when the recurrence should be applied. Required. Known values are: "Daily", "Weekly", and "Monthly". @@ -848,7 +1808,7 @@ class Recurrence(_serialization.Model): "recurrence_type": {"Daily": "DailyRecurrence", "Monthly": "MonthlyRecurrence", "Weekly": "WeeklyRecurrence"} } - def __init__(self, *, start_time: Optional[str] = None, end_time: Optional[str] = None, **kwargs): + def __init__(self, *, start_time: Optional[str] = None, end_time: Optional[str] = None, **kwargs: Any) -> None: """ :keyword start_time: Start time for recurrence. :paramtype start_time: str @@ -864,7 +1824,7 @@ def __init__(self, *, start_time: Optional[str] = None, end_time: Optional[str] class DailyRecurrence(Recurrence): """Daily recurrence object. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar recurrence_type: Specifies when the recurrence should be applied. Required. Known values are: "Daily", "Weekly", and "Monthly". @@ -885,7 +1845,7 @@ class DailyRecurrence(Recurrence): "end_time": {"key": "endTime", "type": "str"}, } - def __init__(self, *, start_time: Optional[str] = None, end_time: Optional[str] = None, **kwargs): + def __init__(self, *, start_time: Optional[str] = None, end_time: Optional[str] = None, **kwargs: Any) -> None: """ :keyword start_time: Start time for recurrence. :paramtype start_time: str @@ -896,6 +1856,124 @@ def __init__(self, *, start_time: Optional[str] = None, end_time: Optional[str] self.recurrence_type: str = "Daily" +class DiagnosticsInsight(_serialization.Model): + """The insight for diagnostics. + + All required parameters must be populated in order to send to server. + + :ivar content: The diagnostics HTML content. Required. + :vartype content: str + :ivar solution_id: The diagnostics solution Id. Required. + :vartype solution_id: str + """ + + _validation = { + "content": {"required": True}, + "solution_id": {"required": True}, + } + + _attribute_map = { + "content": {"key": "content", "type": "str"}, + "solution_id": {"key": "solutionId", "type": "str"}, + } + + def __init__(self, *, content: str, solution_id: str, **kwargs: Any) -> None: + """ + :keyword content: The diagnostics HTML content. Required. + :paramtype content: str + :keyword solution_id: The diagnostics solution Id. Required. + :paramtype solution_id: str + """ + super().__init__(**kwargs) + self.content = content + self.solution_id = solution_id + + +class DiagnosticsSolutionDetails(DetailsBase): + """An diagnostics details. + + All required parameters must be populated in order to send to server. + + :ivar details_type: The type of details. Required. Known values are: "Investigation", + "Finding", "AzureMetric", "AbnormalEvent", "RelatedAlert", "ResourceHealth", and "Diagnostics". + :vartype details_type: str or ~azure.mgmt.alertsmanagement.models.DetailsType + :ivar category: The details category. Required. Known values are: "Investigation", "Metric", + "Log", "Alert", "ResourceHealth", and "Diagnostics". + :vartype category: str or ~azure.mgmt.alertsmanagement.models.CategoryType + :ivar resource_ids: The resource ids related to the anomaly. + :vartype resource_ids: list[str] + :ivar insight: Insight about the anomaly, this is system generated. Required. + :vartype insight: ~azure.mgmt.alertsmanagement.models.DiagnosticsInsight + """ + + _validation = { + "details_type": {"required": True}, + "category": {"required": True}, + "insight": {"required": True}, + } + + _attribute_map = { + "details_type": {"key": "detailsType", "type": "str"}, + "category": {"key": "category", "type": "str"}, + "resource_ids": {"key": "resourceIds", "type": "[str]"}, + "insight": {"key": "insight", "type": "DiagnosticsInsight"}, + } + + def __init__( + self, + *, + category: Union[str, "_models.CategoryType"], + insight: "_models.DiagnosticsInsight", + resource_ids: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword category: The details category. Required. Known values are: "Investigation", "Metric", + "Log", "Alert", "ResourceHealth", and "Diagnostics". + :paramtype category: str or ~azure.mgmt.alertsmanagement.models.CategoryType + :keyword resource_ids: The resource ids related to the anomaly. + :paramtype resource_ids: list[str] + :keyword insight: Insight about the anomaly, this is system generated. Required. + :paramtype insight: ~azure.mgmt.alertsmanagement.models.DiagnosticsInsight + """ + super().__init__(category=category, resource_ids=resource_ids, **kwargs) + self.details_type: str = "Diagnostics" + self.insight = insight + + +class DimensionNameAndValue(_serialization.Model): + """Dimension name and value. + + All required parameters must be populated in order to send to server. + + :ivar name: Name of the dimension. Required. + :vartype name: str + :ivar value: Value of the dimension. Required. + :vartype value: str + """ + + _validation = { + "name": {"required": True}, + "value": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "value": {"key": "value", "type": "str"}, + } + + def __init__(self, *, name: str, value: str, **kwargs: Any) -> None: + """ + :keyword name: Name of the dimension. Required. + :paramtype name: str + :keyword value: Value of the dimension. Required. + :paramtype value: str + """ + super().__init__(**kwargs) + self.name = name + self.value = value + + class ErrorAdditionalInfo(_serialization.Model): """The resource management error additional info. @@ -917,11 +1995,11 @@ class ErrorAdditionalInfo(_serialization.Model): "info": {"key": "info", "type": "object"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.type = None - self.info = None + self.type: Optional[str] = None + self.info: Optional[JSON] = None class ErrorDetail(_serialization.Model): @@ -957,28 +2035,135 @@ class ErrorDetail(_serialization.Model): "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None + self.code: Optional[str] = None + self.message: Optional[str] = None + self.target: Optional[str] = None + self.details: Optional[List["_models.ErrorDetail"]] = None + self.additional_info: Optional[List["_models.ErrorAdditionalInfo"]] = None -class ErrorResponse(_serialization.Model): - """An error response from the service. +class ErrorDetailAutoGenerated(_serialization.Model): + """The error detail. - :ivar error: Details of error response. - :vartype error: ~azure.mgmt.alertsmanagement.models.ErrorResponseBody - """ + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.alertsmanagement.models.ErrorDetailAutoGenerated] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.alertsmanagement.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetailAutoGenerated]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code: Optional[str] = None + self.message: Optional[str] = None + self.target: Optional[str] = None + self.details: Optional[List["_models.ErrorDetailAutoGenerated"]] = None + self.additional_info: Optional[List["_models.ErrorAdditionalInfo"]] = None + + +class ErrorDetailAutoGenerated2(_serialization.Model): + """The error detail. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar code: The error code. + :vartype code: str + :ivar message: The error message. + :vartype message: str + :ivar target: The error target. + :vartype target: str + :ivar details: The error details. + :vartype details: list[~azure.mgmt.alertsmanagement.models.ErrorDetailAutoGenerated2] + :ivar additional_info: The error additional info. + :vartype additional_info: list[~azure.mgmt.alertsmanagement.models.ErrorAdditionalInfo] + """ + + _validation = { + "code": {"readonly": True}, + "message": {"readonly": True}, + "target": {"readonly": True}, + "details": {"readonly": True}, + "additional_info": {"readonly": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDetailAutoGenerated2]"}, + "additional_info": {"key": "additionalInfo", "type": "[ErrorAdditionalInfo]"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.code: Optional[str] = None + self.message: Optional[str] = None + self.target: Optional[str] = None + self.details: Optional[List["_models.ErrorDetailAutoGenerated2"]] = None + self.additional_info: Optional[List["_models.ErrorAdditionalInfo"]] = None + + +class ErrorResponse(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.mgmt.alertsmanagement.models.ErrorDetail + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetail"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.alertsmanagement.models.ErrorDetail + """ + super().__init__(**kwargs) + self.error = error + + +class ErrorResponseAutoGenerated(_serialization.Model): + """An error response from the service. + + :ivar error: Details of error response. + :vartype error: ~azure.mgmt.alertsmanagement.models.ErrorResponseBody + """ _attribute_map = { "error": {"key": "error", "type": "ErrorResponseBody"}, } - def __init__(self, *, error: Optional["_models.ErrorResponseBody"] = None, **kwargs): + def __init__(self, *, error: Optional["_models.ErrorResponseBody"] = None, **kwargs: Any) -> None: """ :keyword error: Details of error response. :paramtype error: ~azure.mgmt.alertsmanagement.models.ErrorResponseBody @@ -987,27 +2172,28 @@ def __init__(self, *, error: Optional["_models.ErrorResponseBody"] = None, **kwa self.error = error -class ErrorResponseAutoGenerated(_serialization.Model): - """Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). +class ErrorResponseAutoGenerated2(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). :ivar error: The error object. - :vartype error: ~azure.mgmt.alertsmanagement.models.ErrorDetail + :vartype error: ~azure.mgmt.alertsmanagement.models.ErrorDetailAutoGenerated """ _attribute_map = { - "error": {"key": "error", "type": "ErrorDetail"}, + "error": {"key": "error", "type": "ErrorDetailAutoGenerated"}, } - def __init__(self, *, error: Optional["_models.ErrorDetail"] = None, **kwargs): + def __init__(self, *, error: Optional["_models.ErrorDetailAutoGenerated"] = None, **kwargs: Any) -> None: """ :keyword error: The error object. - :paramtype error: ~azure.mgmt.alertsmanagement.models.ErrorDetail + :paramtype error: ~azure.mgmt.alertsmanagement.models.ErrorDetailAutoGenerated """ super().__init__(**kwargs) self.error = error -class ErrorResponseAutoGenerated2(_serialization.Model): +class ErrorResponseAutoGenerated3(_serialization.Model): """An error response from the service. :ivar error: Details of error response. @@ -1018,7 +2204,7 @@ class ErrorResponseAutoGenerated2(_serialization.Model): "error": {"key": "error", "type": "ErrorResponseBodyAutoGenerated"}, } - def __init__(self, *, error: Optional["_models.ErrorResponseBodyAutoGenerated"] = None, **kwargs): + def __init__(self, *, error: Optional["_models.ErrorResponseBodyAutoGenerated"] = None, **kwargs: Any) -> None: """ :keyword error: Details of error response. :paramtype error: ~azure.mgmt.alertsmanagement.models.ErrorResponseBodyAutoGenerated @@ -1027,7 +2213,7 @@ def __init__(self, *, error: Optional["_models.ErrorResponseBodyAutoGenerated"] self.error = error -class ErrorResponseAutoGenerated3(_serialization.Model): +class ErrorResponseAutoGenerated4(_serialization.Model): """An error response from the service. :ivar error: Details of error response. @@ -1038,7 +2224,7 @@ class ErrorResponseAutoGenerated3(_serialization.Model): "error": {"key": "error", "type": "ErrorResponseBodyAutoGenerated2"}, } - def __init__(self, *, error: Optional["_models.ErrorResponseBodyAutoGenerated2"] = None, **kwargs): + def __init__(self, *, error: Optional["_models.ErrorResponseBodyAutoGenerated2"] = None, **kwargs: Any) -> None: """ :keyword error: Details of error response. :paramtype error: ~azure.mgmt.alertsmanagement.models.ErrorResponseBodyAutoGenerated2 @@ -1047,6 +2233,27 @@ def __init__(self, *, error: Optional["_models.ErrorResponseBodyAutoGenerated2"] self.error = error +class ErrorResponseAutoGenerated5(_serialization.Model): + """Common error response for all Azure Resource Manager APIs to return error details for failed + operations. (This also follows the OData error response format.). + + :ivar error: The error object. + :vartype error: ~azure.mgmt.alertsmanagement.models.ErrorDetailAutoGenerated2 + """ + + _attribute_map = { + "error": {"key": "error", "type": "ErrorDetailAutoGenerated2"}, + } + + def __init__(self, *, error: Optional["_models.ErrorDetailAutoGenerated2"] = None, **kwargs: Any) -> None: + """ + :keyword error: The error object. + :paramtype error: ~azure.mgmt.alertsmanagement.models.ErrorDetailAutoGenerated2 + """ + super().__init__(**kwargs) + self.error = error + + class ErrorResponseBody(_serialization.Model): """Details of error response. @@ -1074,8 +2281,8 @@ def __init__( message: Optional[str] = None, target: Optional[str] = None, details: Optional[List["_models.ErrorResponseBody"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword code: Error code, intended to be consumed programmatically. :paramtype code: str @@ -1120,8 +2327,8 @@ def __init__( message: Optional[str] = None, target: Optional[str] = None, details: Optional[List["_models.ErrorResponseBodyAutoGenerated"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword code: Error code, intended to be consumed programmatically. :paramtype code: str @@ -1166,8 +2373,8 @@ def __init__( message: Optional[str] = None, target: Optional[str] = None, details: Optional[List["_models.ErrorResponseBodyAutoGenerated2"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword code: Error code, intended to be consumed programmatically. :paramtype code: str @@ -1185,7 +2392,7 @@ def __init__( self.details = details -class Essentials(_serialization.Model): # pylint: disable=too-many-instance-attributes +class Essentials(_serialization.Model): """This object contains consistent fields across different monitor services. Variables are only populated by the server, and will be ignored when sending a request. @@ -1197,7 +2404,7 @@ class Essentials(_serialization.Model): # pylint: disable=too-many-instance-att activity logs. Known values are: "Metric", "Log", and "Unknown". :vartype signal_type: str or ~azure.mgmt.alertsmanagement.models.SignalType :ivar alert_state: Alert object state, which can be modified by the user. Known values are: - "New", "Acknowledged", and "Closed". + "New", "Acknowledged", "Closed", "NoAlert", "Fired", "Firing", "Resolving", and "Resolved". :vartype alert_state: str or ~azure.mgmt.alertsmanagement.models.AlertState :ivar monitor_condition: Condition of the rule at the monitor service. It represents whether the underlying conditions have crossed the defined alert rule thresholds. Known values are: @@ -1214,7 +2421,8 @@ class Essentials(_serialization.Model): # pylint: disable=too-many-instance-att :ivar monitor_service: Monitor service on which the rule(monitor) is set. Known values are: "Application Insights", "ActivityLog Administrative", "ActivityLog Security", "ActivityLog Recommendation", "ActivityLog Policy", "ActivityLog Autoscale", "Log Analytics", "Nagios", - "Platform", "SCOM", "ServiceHealth", "SmartDetector", "VM Insights", and "Zabbix". + "Platform", "SCOM", "ServiceHealth", "SmartDetector", "VM Insights", "Zabbix", and "Resource + Health". :vartype monitor_service: str or ~azure.mgmt.alertsmanagement.models.MonitorService :ivar alert_rule: Rule(monitor) which fired alert instance. Depending on the monitor service, this would be ARM id or name of the rule. @@ -1242,6 +2450,12 @@ class Essentials(_serialization.Model): # pylint: disable=too-many-instance-att :vartype action_status: ~azure.mgmt.alertsmanagement.models.ActionStatus :ivar description: Alert description. :vartype description: str + :ivar has_enrichments: Will be presented with the value true only if there are enrichments. + :vartype has_enrichments: bool + :ivar is_stateful_alert: True if the alert is stateful, and false if it isn't. + :vartype is_stateful_alert: bool + :ivar correlation_details: Correlation details. + :vartype correlation_details: ~azure.mgmt.alertsmanagement.models.CorrelationDetails """ _validation = { @@ -1258,6 +2472,8 @@ class Essentials(_serialization.Model): # pylint: disable=too-many-instance-att "last_modified_date_time": {"readonly": True}, "monitor_condition_resolved_date_time": {"readonly": True}, "last_modified_user_name": {"readonly": True}, + "has_enrichments": {"readonly": True}, + "is_stateful_alert": {"readonly": True}, } _attribute_map = { @@ -1280,6 +2496,9 @@ class Essentials(_serialization.Model): # pylint: disable=too-many-instance-att "last_modified_user_name": {"key": "lastModifiedUserName", "type": "str"}, "action_status": {"key": "actionStatus", "type": "ActionStatus"}, "description": {"key": "description", "type": "str"}, + "has_enrichments": {"key": "hasEnrichments", "type": "bool"}, + "is_stateful_alert": {"key": "isStatefulAlert", "type": "bool"}, + "correlation_details": {"key": "correlationDetails", "type": "CorrelationDetails"}, } def __init__( @@ -1291,8 +2510,9 @@ def __init__( target_resource_type: Optional[str] = None, action_status: Optional["_models.ActionStatus"] = None, description: Optional[str] = None, - **kwargs - ): + correlation_details: Optional["_models.CorrelationDetails"] = None, + **kwargs: Any + ) -> None: """ :keyword target_resource: Target ARM resource, on which alert got created. :paramtype target_resource: str @@ -1309,208 +2529,1650 @@ def __init__( :paramtype action_status: ~azure.mgmt.alertsmanagement.models.ActionStatus :keyword description: Alert description. :paramtype description: str + :keyword correlation_details: Correlation details. + :paramtype correlation_details: ~azure.mgmt.alertsmanagement.models.CorrelationDetails """ super().__init__(**kwargs) - self.severity = None - self.signal_type = None - self.alert_state = None - self.monitor_condition = None + self.severity: Optional[Union[str, "_models.Severity"]] = None + self.signal_type: Optional[Union[str, "_models.SignalType"]] = None + self.alert_state: Optional[Union[str, "_models.AlertState"]] = None + self.monitor_condition: Optional[Union[str, "_models.MonitorCondition"]] = None self.target_resource = target_resource self.target_resource_name = target_resource_name self.target_resource_group = target_resource_group self.target_resource_type = target_resource_type - self.monitor_service = None - self.alert_rule = None - self.source_created_id = None - self.smart_group_id = None - self.smart_grouping_reason = None - self.start_date_time = None - self.last_modified_date_time = None - self.monitor_condition_resolved_date_time = None - self.last_modified_user_name = None + self.monitor_service: Optional[Union[str, "_models.MonitorService"]] = None + self.alert_rule: Optional[str] = None + self.source_created_id: Optional[str] = None + self.smart_group_id: Optional[str] = None + self.smart_grouping_reason: Optional[str] = None + self.start_date_time: Optional[datetime.datetime] = None + self.last_modified_date_time: Optional[datetime.datetime] = None + self.monitor_condition_resolved_date_time: Optional[datetime.datetime] = None + self.last_modified_user_name: Optional[str] = None self.action_status = action_status self.description = description + self.has_enrichments: Optional[bool] = None + self.is_stateful_alert: Optional[bool] = None + self.correlation_details = correlation_details + + +class EvaluatedPeriod(_serialization.Model): + """Details of the evaluated period. + + :ivar timestamp: The timestamp of the evaluated period. + :vartype timestamp: ~datetime.datetime + :ivar high_threshold: The high threshold value for the evaluation period. + :vartype high_threshold: float + :ivar low_threshold: The low threshold value for the evaluation period. + :vartype low_threshold: float + :ivar metric_value: The metric value for the evaluation period. + :vartype metric_value: float + :ivar threshold_met: Indicates whether the threshold was met during the evaluation period. + :vartype threshold_met: bool + """ + _attribute_map = { + "timestamp": {"key": "timestamp", "type": "iso-8601"}, + "high_threshold": {"key": "highThreshold", "type": "float"}, + "low_threshold": {"key": "lowThreshold", "type": "float"}, + "metric_value": {"key": "metricValue", "type": "float"}, + "threshold_met": {"key": "thresholdMet", "type": "bool"}, + } -class MonitorServiceDetails(_serialization.Model): - """Details of a monitor service. + def __init__( + self, + *, + timestamp: Optional[datetime.datetime] = None, + high_threshold: Optional[float] = None, + low_threshold: Optional[float] = None, + metric_value: Optional[float] = None, + threshold_met: Optional[bool] = None, + **kwargs: Any + ) -> None: + """ + :keyword timestamp: The timestamp of the evaluated period. + :paramtype timestamp: ~datetime.datetime + :keyword high_threshold: The high threshold value for the evaluation period. + :paramtype high_threshold: float + :keyword low_threshold: The low threshold value for the evaluation period. + :paramtype low_threshold: float + :keyword metric_value: The metric value for the evaluation period. + :paramtype metric_value: float + :keyword threshold_met: Indicates whether the threshold was met during the evaluation period. + :paramtype threshold_met: bool + """ + super().__init__(**kwargs) + self.timestamp = timestamp + self.high_threshold = high_threshold + self.low_threshold = low_threshold + self.metric_value = metric_value + self.threshold_met = threshold_met - :ivar name: Monitor service name. - :vartype name: str - :ivar display_name: Monitor service display name. - :vartype display_name: str + +class Evaluation(_serialization.Model): + """An evaluation of the alert rule. + + :ivar evaluation_time: The time when the evaluation was performed. + :vartype evaluation_time: ~datetime.datetime + :ivar alert_state: The state of the alert after the evaluation. Known values are: "New", + "Acknowledged", "Closed", "NoAlert", "Fired", "Firing", "Resolving", and "Resolved". + :vartype alert_state: str or ~azure.mgmt.alertsmanagement.models.AlertState + :ivar evaluated_periods: An array of evaluated periods. + :vartype evaluated_periods: list[~azure.mgmt.alertsmanagement.models.EvaluatedPeriod] + :ivar threshold_met: Indicates whether the threshold was met for this evaluation. + :vartype threshold_met: bool """ _attribute_map = { - "name": {"key": "name", "type": "str"}, - "display_name": {"key": "displayName", "type": "str"}, + "evaluation_time": {"key": "evaluationTime", "type": "iso-8601"}, + "alert_state": {"key": "alertState", "type": "str"}, + "evaluated_periods": {"key": "evaluatedPeriods", "type": "[EvaluatedPeriod]"}, + "threshold_met": {"key": "thresholdMet", "type": "bool"}, } - def __init__(self, *, name: Optional[str] = None, display_name: Optional[str] = None, **kwargs): + def __init__( + self, + *, + evaluation_time: Optional[datetime.datetime] = None, + alert_state: Optional[Union[str, "_models.AlertState"]] = None, + evaluated_periods: Optional[List["_models.EvaluatedPeriod"]] = None, + threshold_met: Optional[bool] = None, + **kwargs: Any + ) -> None: """ - :keyword name: Monitor service name. - :paramtype name: str - :keyword display_name: Monitor service display name. - :paramtype display_name: str + :keyword evaluation_time: The time when the evaluation was performed. + :paramtype evaluation_time: ~datetime.datetime + :keyword alert_state: The state of the alert after the evaluation. Known values are: "New", + "Acknowledged", "Closed", "NoAlert", "Fired", "Firing", "Resolving", and "Resolved". + :paramtype alert_state: str or ~azure.mgmt.alertsmanagement.models.AlertState + :keyword evaluated_periods: An array of evaluated periods. + :paramtype evaluated_periods: list[~azure.mgmt.alertsmanagement.models.EvaluatedPeriod] + :keyword threshold_met: Indicates whether the threshold was met for this evaluation. + :paramtype threshold_met: bool """ super().__init__(**kwargs) - self.name = name - self.display_name = display_name + self.evaluation_time = evaluation_time + self.alert_state = alert_state + self.evaluated_periods = evaluated_periods + self.threshold_met = threshold_met -class MonitorServiceList(AlertsMetaDataProperties): - """Monitor service details. +class ExceptionPatternAnomaly(_serialization.Model): + """The exception pattern anomaly. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar metadata_identifier: Identification of the information to be retrieved by API call. - Required. "MonitorServiceList" - :vartype metadata_identifier: str or ~azure.mgmt.alertsmanagement.models.MetadataIdentifier - :ivar data: Array of operations. Required. - :vartype data: list[~azure.mgmt.alertsmanagement.models.MonitorServiceDetails] + :ivar problem_id: The problem ID of the exception, from the Application Insights telemetry data + model. Required. + :vartype problem_id: str + :ivar count: The count of the exception occurrences. Required. + :vartype count: int + :ivar item_id: The exception's item ID, from the Application Insights telemetry data model. + Required. + :vartype item_id: str + :ivar generated_message: The generated message for the exception. Required. + :vartype generated_message: str """ _validation = { - "metadata_identifier": {"required": True}, - "data": {"required": True}, + "problem_id": {"required": True}, + "count": {"required": True}, + "item_id": {"required": True}, + "generated_message": {"required": True}, } _attribute_map = { - "metadata_identifier": {"key": "metadataIdentifier", "type": "str"}, - "data": {"key": "data", "type": "[MonitorServiceDetails]"}, + "problem_id": {"key": "problemId", "type": "str"}, + "count": {"key": "count", "type": "int"}, + "item_id": {"key": "itemId", "type": "str"}, + "generated_message": {"key": "generatedMessage", "type": "str"}, } - def __init__(self, *, data: List["_models.MonitorServiceDetails"], **kwargs): + def __init__(self, *, problem_id: str, count: int, item_id: str, generated_message: str, **kwargs: Any) -> None: """ - :keyword data: Array of operations. Required. - :paramtype data: list[~azure.mgmt.alertsmanagement.models.MonitorServiceDetails] + :keyword problem_id: The problem ID of the exception, from the Application Insights telemetry + data model. Required. + :paramtype problem_id: str + :keyword count: The count of the exception occurrences. Required. + :paramtype count: int + :keyword item_id: The exception's item ID, from the Application Insights telemetry data model. + Required. + :paramtype item_id: str + :keyword generated_message: The generated message for the exception. Required. + :paramtype generated_message: str """ super().__init__(**kwargs) - self.metadata_identifier: str = "MonitorServiceList" - self.data = data + self.problem_id = problem_id + self.count = count + self.item_id = item_id + self.generated_message = generated_message -class MonthlyRecurrence(Recurrence): - """Monthly recurrence object. +class FetchInvestigationResultParameters(_serialization.Model): + """Parameters provided to get the investigation result. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar recurrence_type: Specifies when the recurrence should be applied. Required. Known values - are: "Daily", "Weekly", and "Monthly". - :vartype recurrence_type: str or ~azure.mgmt.alertsmanagement.models.RecurrenceType - :ivar start_time: Start time for recurrence. - :vartype start_time: str - :ivar end_time: End time for recurrence. - :vartype end_time: str - :ivar days_of_month: Specifies the values for monthly recurrence pattern. Required. - :vartype days_of_month: list[int] + :ivar investigation_id: The unique identifier of the investigation. Required. + :vartype investigation_id: str """ _validation = { - "recurrence_type": {"required": True}, - "days_of_month": {"required": True}, + "investigation_id": {"required": True}, } _attribute_map = { - "recurrence_type": {"key": "recurrenceType", "type": "str"}, - "start_time": {"key": "startTime", "type": "str"}, - "end_time": {"key": "endTime", "type": "str"}, - "days_of_month": {"key": "daysOfMonth", "type": "[int]"}, + "investigation_id": {"key": "investigationId", "type": "str"}, } - def __init__( - self, *, days_of_month: List[int], start_time: Optional[str] = None, end_time: Optional[str] = None, **kwargs - ): + def __init__(self, *, investigation_id: str, **kwargs: Any) -> None: """ - :keyword start_time: Start time for recurrence. - :paramtype start_time: str - :keyword end_time: End time for recurrence. - :paramtype end_time: str - :keyword days_of_month: Specifies the values for monthly recurrence pattern. Required. - :paramtype days_of_month: list[int] + :keyword investigation_id: The unique identifier of the investigation. Required. + :paramtype investigation_id: str """ - super().__init__(start_time=start_time, end_time=end_time, **kwargs) - self.recurrence_type: str = "Monthly" - self.days_of_month = days_of_month + super().__init__(**kwargs) + self.investigation_id = investigation_id -class Operation(_serialization.Model): - """Operation provided by provider. +class InvestigationDetails(DetailsBase): + """An investigation details. - :ivar name: Name of the operation. - :vartype name: str - :ivar display: Properties of the operation. - :vartype display: ~azure.mgmt.alertsmanagement.models.OperationDisplay - :ivar origin: Origin of the operation. - :vartype origin: str + All required parameters must be populated in order to send to server. + + :ivar details_type: The type of details. Required. Known values are: "Investigation", + "Finding", "AzureMetric", "AbnormalEvent", "RelatedAlert", "ResourceHealth", and "Diagnostics". + :vartype details_type: str or ~azure.mgmt.alertsmanagement.models.DetailsType + :ivar category: The details category. Required. Known values are: "Investigation", "Metric", + "Log", "Alert", "ResourceHealth", and "Diagnostics". + :vartype category: str or ~azure.mgmt.alertsmanagement.models.CategoryType + :ivar resource_ids: The resource ids related to the anomaly. + :vartype resource_ids: list[str] + :ivar data: The parameters used for this investigation execution. Required. + :vartype data: ~azure.mgmt.alertsmanagement.models.StartInvestigationParameters """ + _validation = { + "details_type": {"required": True}, + "category": {"required": True}, + "data": {"required": True}, + } + _attribute_map = { - "name": {"key": "name", "type": "str"}, - "display": {"key": "display", "type": "OperationDisplay"}, - "origin": {"key": "origin", "type": "str"}, + "details_type": {"key": "detailsType", "type": "str"}, + "category": {"key": "category", "type": "str"}, + "resource_ids": {"key": "resourceIds", "type": "[str]"}, + "data": {"key": "data", "type": "StartInvestigationParameters"}, } def __init__( self, *, - name: Optional[str] = None, - display: Optional["_models.OperationDisplay"] = None, - origin: Optional[str] = None, - **kwargs - ): + category: Union[str, "_models.CategoryType"], + data: "_models.StartInvestigationParameters", + resource_ids: Optional[List[str]] = None, + **kwargs: Any + ) -> None: """ - :keyword name: Name of the operation. - :paramtype name: str - :keyword display: Properties of the operation. - :paramtype display: ~azure.mgmt.alertsmanagement.models.OperationDisplay - :keyword origin: Origin of the operation. - :paramtype origin: str + :keyword category: The details category. Required. Known values are: "Investigation", "Metric", + "Log", "Alert", "ResourceHealth", and "Diagnostics". + :paramtype category: str or ~azure.mgmt.alertsmanagement.models.CategoryType + :keyword resource_ids: The resource ids related to the anomaly. + :paramtype resource_ids: list[str] + :keyword data: The parameters used for this investigation execution. Required. + :paramtype data: ~azure.mgmt.alertsmanagement.models.StartInvestigationParameters """ - super().__init__(**kwargs) - self.name = name - self.display = display - self.origin = origin + super().__init__(category=category, resource_ids=resource_ids, **kwargs) + self.details_type: str = "Investigation" + self.data = data -class OperationDisplay(_serialization.Model): - """Properties of the operation. +class InvestigationEntity(_serialization.Model): + """Details about the investigation entity. - :ivar provider: Provider name. - :vartype provider: str - :ivar resource: Resource name. - :vartype resource: str - :ivar operation: Operation name. - :vartype operation: str - :ivar description: Description of the operation. - :vartype description: str + All required parameters must be populated in order to send to server. + + :ivar id: The identifier of the entity. Required. + :vartype id: str + :ivar entity_type: The type of the entity. Required. Known values are: "Investigation", + "Finding", and "Evidence". + :vartype entity_type: str or ~azure.mgmt.alertsmanagement.models.InvestigationEntityType + :ivar relevance: The relevance of the entity. Known values are: "None", "Relevant", and + "Irrelevant". + :vartype relevance: str or ~azure.mgmt.alertsmanagement.models.Relevance + :ivar health_state: The health state of the entity. Required. Known values are: "Unknown", + "Healthy", and "Unhealthy". + :vartype health_state: str or ~azure.mgmt.alertsmanagement.models.HealthState + :ivar origin: The origin of the entity. Required. + :vartype origin: ~azure.mgmt.alertsmanagement.models.Origin + :ivar created_at: The creation time of the entity (in UTC). Required. + :vartype created_at: ~datetime.datetime + :ivar last_modified_at: The last update time of the entity (in UTC). Required. + :vartype last_modified_at: ~datetime.datetime + :ivar execution: The execution details of the entity. Required. + :vartype execution: ~azure.mgmt.alertsmanagement.models.InvestigationExecution + :ivar summary: The summary of the entity. + :vartype summary: ~azure.mgmt.alertsmanagement.models.Summary + :ivar details: The details of the entity. + :vartype details: ~azure.mgmt.alertsmanagement.models.DetailsBase + :ivar children: The children of this investigation entity. + :vartype children: list[~azure.mgmt.alertsmanagement.models.InvestigationEntity] """ + _validation = { + "id": {"required": True}, + "entity_type": {"required": True}, + "health_state": {"required": True}, + "origin": {"required": True}, + "created_at": {"required": True}, + "last_modified_at": {"required": True}, + "execution": {"required": True}, + } + _attribute_map = { - "provider": {"key": "provider", "type": "str"}, - "resource": {"key": "resource", "type": "str"}, - "operation": {"key": "operation", "type": "str"}, - "description": {"key": "description", "type": "str"}, + "id": {"key": "id", "type": "str"}, + "entity_type": {"key": "entityType", "type": "str"}, + "relevance": {"key": "relevance", "type": "str"}, + "health_state": {"key": "healthState", "type": "str"}, + "origin": {"key": "origin", "type": "Origin"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, + "execution": {"key": "execution", "type": "InvestigationExecution"}, + "summary": {"key": "summary", "type": "Summary"}, + "details": {"key": "details", "type": "DetailsBase"}, + "children": {"key": "children", "type": "[InvestigationEntity]"}, } def __init__( self, *, - provider: Optional[str] = None, - resource: Optional[str] = None, - operation: Optional[str] = None, - description: Optional[str] = None, - **kwargs - ): + id: str, # pylint: disable=redefined-builtin + entity_type: Union[str, "_models.InvestigationEntityType"], + health_state: Union[str, "_models.HealthState"], + origin: "_models.Origin", + created_at: datetime.datetime, + last_modified_at: datetime.datetime, + execution: "_models.InvestigationExecution", + relevance: Optional[Union[str, "_models.Relevance"]] = None, + summary: Optional["_models.Summary"] = None, + details: Optional["_models.DetailsBase"] = None, + children: Optional[List["_models.InvestigationEntity"]] = None, + **kwargs: Any + ) -> None: """ - :keyword provider: Provider name. - :paramtype provider: str - :keyword resource: Resource name. - :paramtype resource: str - :keyword operation: Operation name. - :paramtype operation: str - :keyword description: Description of the operation. - :paramtype description: str + :keyword id: The identifier of the entity. Required. + :paramtype id: str + :keyword entity_type: The type of the entity. Required. Known values are: "Investigation", + "Finding", and "Evidence". + :paramtype entity_type: str or ~azure.mgmt.alertsmanagement.models.InvestigationEntityType + :keyword relevance: The relevance of the entity. Known values are: "None", "Relevant", and + "Irrelevant". + :paramtype relevance: str or ~azure.mgmt.alertsmanagement.models.Relevance + :keyword health_state: The health state of the entity. Required. Known values are: "Unknown", + "Healthy", and "Unhealthy". + :paramtype health_state: str or ~azure.mgmt.alertsmanagement.models.HealthState + :keyword origin: The origin of the entity. Required. + :paramtype origin: ~azure.mgmt.alertsmanagement.models.Origin + :keyword created_at: The creation time of the entity (in UTC). Required. + :paramtype created_at: ~datetime.datetime + :keyword last_modified_at: The last update time of the entity (in UTC). Required. + :paramtype last_modified_at: ~datetime.datetime + :keyword execution: The execution details of the entity. Required. + :paramtype execution: ~azure.mgmt.alertsmanagement.models.InvestigationExecution + :keyword summary: The summary of the entity. + :paramtype summary: ~azure.mgmt.alertsmanagement.models.Summary + :keyword details: The details of the entity. + :paramtype details: ~azure.mgmt.alertsmanagement.models.DetailsBase + :keyword children: The children of this investigation entity. + :paramtype children: list[~azure.mgmt.alertsmanagement.models.InvestigationEntity] + """ + super().__init__(**kwargs) + self.id = id + self.entity_type = entity_type + self.relevance = relevance + self.health_state = health_state + self.origin = origin + self.created_at = created_at + self.last_modified_at = last_modified_at + self.execution = execution + self.summary = summary + self.details = details + self.children = children + + +class InvestigationExecution(_serialization.Model): + """Details about the execution of the investigation. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar run_state: The state of the investigation execution. Required. Known values are: "None", + "InProgress", "Succeeded", "Failed", and "Canceled". + :vartype run_state: str or ~azure.mgmt.alertsmanagement.models.InvestigationExecutionRunState + :ivar completed_at: The time at which the investigation execution completed (in UTC). Required. + :vartype completed_at: ~datetime.datetime + """ + + _validation = { + "run_state": {"required": True, "readonly": True}, + "completed_at": {"required": True}, + } + + _attribute_map = { + "run_state": {"key": "runState", "type": "str"}, + "completed_at": {"key": "completedAt", "type": "iso-8601"}, + } + + def __init__(self, *, completed_at: datetime.datetime, **kwargs: Any) -> None: + """ + :keyword completed_at: The time at which the investigation execution completed (in UTC). + Required. + :paramtype completed_at: ~datetime.datetime + """ + super().__init__(**kwargs) + self.run_state: Optional[Union[str, "_models.InvestigationExecutionRunState"]] = None + self.completed_at = completed_at + + +class InvestigationMetadata(_serialization.Model): + """Properties of the current investigation. + + All required parameters must be populated in order to send to server. + + :ivar id: The unique identifier of the investigation. Required. + :vartype id: str + :ivar execution: The execution details of the investigation. Required. + :vartype execution: ~azure.mgmt.alertsmanagement.models.InvestigationExecution + :ivar created_at: The creation time of the investigation (in UTC). Required. + :vartype created_at: ~datetime.datetime + :ivar run_parameters: The parameters that were used to start the investigation. Required. + :vartype run_parameters: ~azure.mgmt.alertsmanagement.models.RunParameters + """ + + _validation = { + "id": {"required": True}, + "execution": {"required": True}, + "created_at": {"required": True}, + "run_parameters": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "execution": {"key": "execution", "type": "InvestigationExecution"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "run_parameters": {"key": "runParameters", "type": "RunParameters"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + execution: "_models.InvestigationExecution", + created_at: datetime.datetime, + run_parameters: "_models.RunParameters", + **kwargs: Any + ) -> None: + """ + :keyword id: The unique identifier of the investigation. Required. + :paramtype id: str + :keyword execution: The execution details of the investigation. Required. + :paramtype execution: ~azure.mgmt.alertsmanagement.models.InvestigationExecution + :keyword created_at: The creation time of the investigation (in UTC). Required. + :paramtype created_at: ~datetime.datetime + :keyword run_parameters: The parameters that were used to start the investigation. Required. + :paramtype run_parameters: ~azure.mgmt.alertsmanagement.models.RunParameters + """ + super().__init__(**kwargs) + self.id = id + self.execution = execution + self.created_at = created_at + self.run_parameters = run_parameters + + +class InvestigationResult(_serialization.Model): + """Details about the investigation result. + + All required parameters must be populated in order to send to server. + + :ivar id: The identifier of the investigation. Required. + :vartype id: str + :ivar entity_type: The type of the investigation. Required. Known values are: "Investigation", + "Finding", and "Evidence". + :vartype entity_type: str or ~azure.mgmt.alertsmanagement.models.InvestigationEntityType + :ivar origin: The origin of the investigation. Required. + :vartype origin: ~azure.mgmt.alertsmanagement.models.Origin + :ivar created_at: The creation time of the investigation (in UTC). Required. + :vartype created_at: ~datetime.datetime + :ivar last_modified_at: The last update time of the investigation (in UTC). Required. + :vartype last_modified_at: ~datetime.datetime + :ivar execution: The execution details of the investigation. Required. + :vartype execution: ~azure.mgmt.alertsmanagement.models.InvestigationExecution + :ivar run_parameters: The parameters used to run the investigation. Required. + :vartype run_parameters: ~azure.mgmt.alertsmanagement.models.RunParameters + :ivar children: The children of this investigation, findings and evidences. Required. + :vartype children: list[~azure.mgmt.alertsmanagement.models.InvestigationEntity] + """ + + _validation = { + "id": {"required": True}, + "entity_type": {"required": True}, + "origin": {"required": True}, + "created_at": {"required": True}, + "last_modified_at": {"required": True}, + "execution": {"required": True}, + "run_parameters": {"required": True}, + "children": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "entity_type": {"key": "entityType", "type": "str"}, + "origin": {"key": "origin", "type": "Origin"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, + "execution": {"key": "execution", "type": "InvestigationExecution"}, + "run_parameters": {"key": "runParameters", "type": "RunParameters"}, + "children": {"key": "children", "type": "[InvestigationEntity]"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + entity_type: Union[str, "_models.InvestigationEntityType"], + origin: "_models.Origin", + created_at: datetime.datetime, + last_modified_at: datetime.datetime, + execution: "_models.InvestigationExecution", + run_parameters: "_models.RunParameters", + children: List["_models.InvestigationEntity"], + **kwargs: Any + ) -> None: + """ + :keyword id: The identifier of the investigation. Required. + :paramtype id: str + :keyword entity_type: The type of the investigation. Required. Known values are: + "Investigation", "Finding", and "Evidence". + :paramtype entity_type: str or ~azure.mgmt.alertsmanagement.models.InvestigationEntityType + :keyword origin: The origin of the investigation. Required. + :paramtype origin: ~azure.mgmt.alertsmanagement.models.Origin + :keyword created_at: The creation time of the investigation (in UTC). Required. + :paramtype created_at: ~datetime.datetime + :keyword last_modified_at: The last update time of the investigation (in UTC). Required. + :paramtype last_modified_at: ~datetime.datetime + :keyword execution: The execution details of the investigation. Required. + :paramtype execution: ~azure.mgmt.alertsmanagement.models.InvestigationExecution + :keyword run_parameters: The parameters used to run the investigation. Required. + :paramtype run_parameters: ~azure.mgmt.alertsmanagement.models.RunParameters + :keyword children: The children of this investigation, findings and evidences. Required. + :paramtype children: list[~azure.mgmt.alertsmanagement.models.InvestigationEntity] + """ + super().__init__(**kwargs) + self.id = id + self.entity_type = entity_type + self.origin = origin + self.created_at = created_at + self.last_modified_at = last_modified_at + self.execution = execution + self.run_parameters = run_parameters + self.children = children + + +class InvestigationScope(_serialization.Model): + """A single scope of the investigation. + + All required parameters must be populated in order to send to server. + + :ivar id: The ID of the scope of the investigation - either an Azure alert ID or an Azure + resource ID. Required. + :vartype id: str + :ivar origin: The origin of the scope. Required. + :vartype origin: ~azure.mgmt.alertsmanagement.models.Origin + :ivar relevance: The relevance of the scope. Known values are: "None", "Relevant", and + "Irrelevant". + :vartype relevance: str or ~azure.mgmt.alertsmanagement.models.Relevance + """ + + _validation = { + "id": {"required": True}, + "origin": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "origin": {"key": "origin", "type": "Origin"}, + "relevance": {"key": "relevance", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + origin: "_models.Origin", + relevance: Optional[Union[str, "_models.Relevance"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: The ID of the scope of the investigation - either an Azure alert ID or an Azure + resource ID. Required. + :paramtype id: str + :keyword origin: The origin of the scope. Required. + :paramtype origin: ~azure.mgmt.alertsmanagement.models.Origin + :keyword relevance: The relevance of the scope. Known values are: "None", "Relevant", and + "Irrelevant". + :paramtype relevance: str or ~azure.mgmt.alertsmanagement.models.Relevance + """ + super().__init__(**kwargs) + self.id = id + self.origin = origin + self.relevance = relevance + + +class IssueProperties(_serialization.Model): + """The issue properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar title: The issue title. Required. + :vartype title: str + :ivar status: The issue status. Required. Known values are: "Succeeded", "Failed", "New", + "InProgress", "Mitigated", "Closed", and "Canceled". + :vartype status: str or ~azure.mgmt.alertsmanagement.models.Status + :ivar severity: The issue severity. Required. + :vartype severity: str + :ivar investigations: The list of investigations in the issue. Required. + :vartype investigations: list[~azure.mgmt.alertsmanagement.models.InvestigationMetadata] + :ivar impact_time: The issue impact time (in UTC). Required. + :vartype impact_time: ~datetime.datetime + :ivar investigations_count: The number of investigations in the issue. Required. + :vartype investigations_count: int + :ivar provisioning_state: The provisioning state of the resource. Known values are: + "Succeeded", "Failed", and "Canceled". + :vartype provisioning_state: str or + ~azure.mgmt.alertsmanagement.models.ResourceProvisioningState + """ + + _validation = { + "title": {"required": True}, + "status": {"required": True}, + "severity": {"required": True}, + "investigations": {"required": True, "readonly": True}, + "impact_time": {"required": True}, + "investigations_count": {"required": True, "readonly": True}, + "provisioning_state": {"readonly": True}, + } + + _attribute_map = { + "title": {"key": "title", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "severity": {"key": "severity", "type": "str"}, + "investigations": {"key": "investigations", "type": "[InvestigationMetadata]"}, + "impact_time": {"key": "impactTime", "type": "iso-8601"}, + "investigations_count": {"key": "investigationsCount", "type": "int"}, + "provisioning_state": {"key": "provisioningState", "type": "str"}, + } + + def __init__( + self, + *, + title: str, + status: Union[str, "_models.Status"], + severity: str, + impact_time: datetime.datetime, + **kwargs: Any + ) -> None: + """ + :keyword title: The issue title. Required. + :paramtype title: str + :keyword status: The issue status. Required. Known values are: "Succeeded", "Failed", "New", + "InProgress", "Mitigated", "Closed", and "Canceled". + :paramtype status: str or ~azure.mgmt.alertsmanagement.models.Status + :keyword severity: The issue severity. Required. + :paramtype severity: str + :keyword impact_time: The issue impact time (in UTC). Required. + :paramtype impact_time: ~datetime.datetime + """ + super().__init__(**kwargs) + self.title = title + self.status = status + self.severity = severity + self.investigations: Optional[List["_models.InvestigationMetadata"]] = None + self.impact_time = impact_time + self.investigations_count: Optional[int] = None + self.provisioning_state: Optional[Union[str, "_models.ResourceProvisioningState"]] = None + + +class IssuePropertiesUpdate(_serialization.Model): + """The issue properties. + + :ivar title: The issue title. + :vartype title: str + :ivar status: The issue status. Known values are: "Succeeded", "Failed", "New", "InProgress", + "Mitigated", "Closed", and "Canceled". + :vartype status: str or ~azure.mgmt.alertsmanagement.models.Status + :ivar severity: The issue severity. + :vartype severity: str + :ivar impact_time: The issue impact time (in UTC). + :vartype impact_time: ~datetime.datetime + """ + + _attribute_map = { + "title": {"key": "title", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "severity": {"key": "severity", "type": "str"}, + "impact_time": {"key": "impactTime", "type": "iso-8601"}, + } + + def __init__( + self, + *, + title: Optional[str] = None, + status: Optional[Union[str, "_models.Status"]] = None, + severity: Optional[str] = None, + impact_time: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword title: The issue title. + :paramtype title: str + :keyword status: The issue status. Known values are: "Succeeded", "Failed", "New", + "InProgress", "Mitigated", "Closed", and "Canceled". + :paramtype status: str or ~azure.mgmt.alertsmanagement.models.Status + :keyword severity: The issue severity. + :paramtype severity: str + :keyword impact_time: The issue impact time (in UTC). + :paramtype impact_time: ~datetime.datetime + """ + super().__init__(**kwargs) + self.title = title + self.status = status + self.severity = severity + self.impact_time = impact_time + + +class ResourceAutoGenerated3(_serialization.Model): + """Common fields that are returned in the response for all Azure Resource Manager resources. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.alertsmanagement.models.SystemData + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None + + +class ProxyResourceAutoGenerated(ResourceAutoGenerated3): + """The resource model definition for a Azure Resource Manager proxy resource. It will not have + tags and a location. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.alertsmanagement.models.SystemData + """ + + +class IssueResource(ProxyResourceAutoGenerated): + """The Issue resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.alertsmanagement.models.SystemData + :ivar properties: The resource-specific properties for this resource. + :vartype properties: ~azure.mgmt.alertsmanagement.models.IssueProperties + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "properties": {"key": "properties", "type": "IssueProperties"}, + } + + def __init__(self, *, properties: Optional["_models.IssueProperties"] = None, **kwargs: Any) -> None: + """ + :keyword properties: The resource-specific properties for this resource. + :paramtype properties: ~azure.mgmt.alertsmanagement.models.IssueProperties + """ + super().__init__(**kwargs) + self.properties = properties + + +class IssueResourceListResult(_serialization.Model): + """The response of a IssueResource list operation. + + All required parameters must be populated in order to send to server. + + :ivar value: The IssueResource items on this page. Required. + :vartype value: list[~azure.mgmt.alertsmanagement.models.IssueResource] + :ivar next_link: The link to the next page of items. + :vartype next_link: str + """ + + _validation = { + "value": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[IssueResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: List["_models.IssueResource"], next_link: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword value: The IssueResource items on this page. Required. + :paramtype value: list[~azure.mgmt.alertsmanagement.models.IssueResource] + :keyword next_link: The link to the next page of items. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class IssueResourceUpdate(ProxyResourceAutoGenerated): + """The Issue resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar id: Fully qualified resource ID for the resource. E.g. + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}". + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy + information. + :vartype system_data: ~azure.mgmt.alertsmanagement.models.SystemData + :ivar properties: The resource-specific properties for this resource. + :vartype properties: ~azure.mgmt.alertsmanagement.models.IssuePropertiesUpdate + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "properties": {"key": "properties", "type": "IssuePropertiesUpdate"}, + } + + def __init__(self, *, properties: Optional["_models.IssuePropertiesUpdate"] = None, **kwargs: Any) -> None: + """ + :keyword properties: The resource-specific properties for this resource. + :paramtype properties: ~azure.mgmt.alertsmanagement.models.IssuePropertiesUpdate + """ + super().__init__(**kwargs) + self.properties = properties + + +class ListParameter(_serialization.Model): + """Parameters for listing related entities. + + :ivar filter: The filter to apply on the operation. For example, to filter by relevance, use + "$filter=relevance eq 'Relevant'". + :vartype filter: str + """ + + _attribute_map = { + "filter": {"key": "filter", "type": "str"}, + } + + def __init__(self, *, filter: Optional[str] = None, **kwargs: Any) -> None: # pylint: disable=redefined-builtin + """ + :keyword filter: The filter to apply on the operation. For example, to filter by relevance, use + "$filter=relevance eq 'Relevant'". + :paramtype filter: str + """ + super().__init__(**kwargs) + self.filter = filter + + +class LogAlertRuleCondition(_serialization.Model): + """A condition of the scheduled query rule. + + :ivar criterion_type: Specifies the type of threshold criteria. Known values are: + "StaticThresholdCriterion" and "DynamicThresholdCriterion". + :vartype criterion_type: str or ~azure.mgmt.alertsmanagement.models.CriterionType + :ivar query: Log query alert. + :vartype query: str + :ivar time_aggregation: Aggregation type. Relevant and required only for rules of the kind + LogAlert. Known values are: "Count", "Average", "Minimum", "Maximum", and "Total". + :vartype time_aggregation: str or ~azure.mgmt.alertsmanagement.models.TimeAggregation + :ivar metric_measure_column: The column containing the metric measure number. Relevant only for + rules of the kind LogAlert. + :vartype metric_measure_column: str + :ivar resource_id_column: The column containing the resource id. The content of the column must + be a uri formatted as resource id. Relevant only for rules of the kind LogAlert. + :vartype resource_id_column: str + :ivar dimensions: List of Dimensions conditions. + :vartype dimensions: list[~azure.mgmt.alertsmanagement.models.LogAlertRuleDimension] + :ivar operator: The criteria operator. Relevant and required only for rules of the kind + LogAlert. Known values are: "Equals", "GreaterThan", "GreaterThanOrEqual", "LessThan", + "LessThanOrEqual", and "GreaterOrLessThan". + :vartype operator: str or ~azure.mgmt.alertsmanagement.models.ConditionOperator + :ivar threshold: the criteria threshold value that activates the alert. Relevant and required + only for static threshold rules of the kind LogAlert. + :vartype threshold: float + :ivar alert_sensitivity: The extent of deviation required to trigger an alert. Allowed values + are 'Low', 'Medium' and 'High'. This will affect how tight the threshold is to the metric + series pattern. Relevant and required only for dynamic threshold rules of the kind LogAlert. + :vartype alert_sensitivity: str + :ivar ignore_data_before: Use this option to set the date from which to start learning the + metric historical data and calculate the dynamic thresholds (in ISO8601 format). Relevant only + for dynamic threshold rules of the kind LogAlert. + :vartype ignore_data_before: ~datetime.datetime + :ivar failing_periods: The minimum number of violations required within the selected lookback + time window required to raise an alert. Relevant only for rules of the kind LogAlert. + :vartype failing_periods: + ~azure.mgmt.alertsmanagement.models.LogAlertRuleConditionFailingPeriods + :ivar metric_name: The name of the metric to be sent. Relevant and required only for rules of + the kind LogToMetric. + :vartype metric_name: str + """ + + _attribute_map = { + "criterion_type": {"key": "criterionType", "type": "str"}, + "query": {"key": "query", "type": "str"}, + "time_aggregation": {"key": "timeAggregation", "type": "str"}, + "metric_measure_column": {"key": "metricMeasureColumn", "type": "str"}, + "resource_id_column": {"key": "resourceIdColumn", "type": "str"}, + "dimensions": {"key": "dimensions", "type": "[LogAlertRuleDimension]"}, + "operator": {"key": "operator", "type": "str"}, + "threshold": {"key": "threshold", "type": "float"}, + "alert_sensitivity": {"key": "alertSensitivity", "type": "str"}, + "ignore_data_before": {"key": "ignoreDataBefore", "type": "iso-8601"}, + "failing_periods": {"key": "failingPeriods", "type": "LogAlertRuleConditionFailingPeriods"}, + "metric_name": {"key": "metricName", "type": "str"}, + } + + def __init__( + self, + *, + criterion_type: Optional[Union[str, "_models.CriterionType"]] = None, + query: Optional[str] = None, + time_aggregation: Optional[Union[str, "_models.TimeAggregation"]] = None, + metric_measure_column: Optional[str] = None, + resource_id_column: Optional[str] = None, + dimensions: Optional[List["_models.LogAlertRuleDimension"]] = None, + operator: Optional[Union[str, "_models.ConditionOperator"]] = None, + threshold: Optional[float] = None, + alert_sensitivity: Optional[str] = None, + ignore_data_before: Optional[datetime.datetime] = None, + failing_periods: Optional["_models.LogAlertRuleConditionFailingPeriods"] = None, + metric_name: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword criterion_type: Specifies the type of threshold criteria. Known values are: + "StaticThresholdCriterion" and "DynamicThresholdCriterion". + :paramtype criterion_type: str or ~azure.mgmt.alertsmanagement.models.CriterionType + :keyword query: Log query alert. + :paramtype query: str + :keyword time_aggregation: Aggregation type. Relevant and required only for rules of the kind + LogAlert. Known values are: "Count", "Average", "Minimum", "Maximum", and "Total". + :paramtype time_aggregation: str or ~azure.mgmt.alertsmanagement.models.TimeAggregation + :keyword metric_measure_column: The column containing the metric measure number. Relevant only + for rules of the kind LogAlert. + :paramtype metric_measure_column: str + :keyword resource_id_column: The column containing the resource id. The content of the column + must be a uri formatted as resource id. Relevant only for rules of the kind LogAlert. + :paramtype resource_id_column: str + :keyword dimensions: List of Dimensions conditions. + :paramtype dimensions: list[~azure.mgmt.alertsmanagement.models.LogAlertRuleDimension] + :keyword operator: The criteria operator. Relevant and required only for rules of the kind + LogAlert. Known values are: "Equals", "GreaterThan", "GreaterThanOrEqual", "LessThan", + "LessThanOrEqual", and "GreaterOrLessThan". + :paramtype operator: str or ~azure.mgmt.alertsmanagement.models.ConditionOperator + :keyword threshold: the criteria threshold value that activates the alert. Relevant and + required only for static threshold rules of the kind LogAlert. + :paramtype threshold: float + :keyword alert_sensitivity: The extent of deviation required to trigger an alert. Allowed + values are 'Low', 'Medium' and 'High'. This will affect how tight the threshold is to the + metric series pattern. Relevant and required only for dynamic threshold rules of the kind + LogAlert. + :paramtype alert_sensitivity: str + :keyword ignore_data_before: Use this option to set the date from which to start learning the + metric historical data and calculate the dynamic thresholds (in ISO8601 format). Relevant only + for dynamic threshold rules of the kind LogAlert. + :paramtype ignore_data_before: ~datetime.datetime + :keyword failing_periods: The minimum number of violations required within the selected + lookback time window required to raise an alert. Relevant only for rules of the kind LogAlert. + :paramtype failing_periods: + ~azure.mgmt.alertsmanagement.models.LogAlertRuleConditionFailingPeriods + :keyword metric_name: The name of the metric to be sent. Relevant and required only for rules + of the kind LogToMetric. + :paramtype metric_name: str + """ + super().__init__(**kwargs) + self.criterion_type = criterion_type + self.query = query + self.time_aggregation = time_aggregation + self.metric_measure_column = metric_measure_column + self.resource_id_column = resource_id_column + self.dimensions = dimensions + self.operator = operator + self.threshold = threshold + self.alert_sensitivity = alert_sensitivity + self.ignore_data_before = ignore_data_before + self.failing_periods = failing_periods + self.metric_name = metric_name + + +class LogAlertRuleConditionFailingPeriods(_serialization.Model): + """The minimum number of violations required within the selected lookback time window required to + raise an alert. Relevant only for rules of the kind LogAlert. + + :ivar number_of_evaluation_periods: The number of aggregated lookback points. The lookback time + window is calculated based on the aggregation granularity (windowSize) and the selected number + of aggregated points. Default value is 1. + :vartype number_of_evaluation_periods: int + :ivar min_failing_periods_to_alert: The number of violations to trigger an alert. Should be + smaller or equal to numberOfEvaluationPeriods. Default value is 1. + :vartype min_failing_periods_to_alert: int + """ + + _attribute_map = { + "number_of_evaluation_periods": {"key": "numberOfEvaluationPeriods", "type": "int"}, + "min_failing_periods_to_alert": {"key": "minFailingPeriodsToAlert", "type": "int"}, + } + + def __init__( + self, *, number_of_evaluation_periods: int = 1, min_failing_periods_to_alert: int = 1, **kwargs: Any + ) -> None: + """ + :keyword number_of_evaluation_periods: The number of aggregated lookback points. The lookback + time window is calculated based on the aggregation granularity (windowSize) and the selected + number of aggregated points. Default value is 1. + :paramtype number_of_evaluation_periods: int + :keyword min_failing_periods_to_alert: The number of violations to trigger an alert. Should be + smaller or equal to numberOfEvaluationPeriods. Default value is 1. + :paramtype min_failing_periods_to_alert: int + """ + super().__init__(**kwargs) + self.number_of_evaluation_periods = number_of_evaluation_periods + self.min_failing_periods_to_alert = min_failing_periods_to_alert + + +class LogAlertRuleCriteria(_serialization.Model): + """The rule criteria that defines the conditions of the scheduled query rule. + + :ivar all_of: A list of conditions to evaluate against the specified scopes. + :vartype all_of: list[~azure.mgmt.alertsmanagement.models.LogAlertRuleCondition] + """ + + _attribute_map = { + "all_of": {"key": "allOf", "type": "[LogAlertRuleCondition]"}, + } + + def __init__(self, *, all_of: Optional[List["_models.LogAlertRuleCondition"]] = None, **kwargs: Any) -> None: + """ + :keyword all_of: A list of conditions to evaluate against the specified scopes. + :paramtype all_of: list[~azure.mgmt.alertsmanagement.models.LogAlertRuleCondition] + """ + super().__init__(**kwargs) + self.all_of = all_of + + +class LogAlertRuleDimension(_serialization.Model): + """Dimension splitting and filtering definition. + + All required parameters must be populated in order to send to server. + + :ivar name: Name of the dimension. Required. + :vartype name: str + :ivar operator: Operator for dimension values. Required. Known values are: "Include" and + "Exclude". + :vartype operator: str or ~azure.mgmt.alertsmanagement.models.DimensionOperator + :ivar values: List of dimension values. Required. + :vartype values: list[str] + """ + + _validation = { + "name": {"required": True}, + "operator": {"required": True}, + "values": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "operator": {"key": "operator", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, + } + + def __init__( + self, *, name: str, operator: Union[str, "_models.DimensionOperator"], values: List[str], **kwargs: Any + ) -> None: + """ + :keyword name: Name of the dimension. Required. + :paramtype name: str + :keyword operator: Operator for dimension values. Required. Known values are: "Include" and + "Exclude". + :paramtype operator: str or ~azure.mgmt.alertsmanagement.models.DimensionOperator + :keyword values: List of dimension values. Required. + :paramtype values: list[str] + """ + super().__init__(**kwargs) + self.name = name + self.operator = operator + self.values = values + + +class LogAlertRuleResolveConfiguration(_serialization.Model): + """TBD. Relevant only for rules of the kind LogAlert. + + :ivar auto_resolved: The flag that indicates whether or not to auto resolve a fired alert. + :vartype auto_resolved: bool + :ivar time_to_resolve: The duration a rule must evaluate as healthy before the fired alert is + automatically resolved represented in ISO 8601 duration format. + :vartype time_to_resolve: ~datetime.timedelta + """ + + _attribute_map = { + "auto_resolved": {"key": "autoResolved", "type": "bool"}, + "time_to_resolve": {"key": "timeToResolve", "type": "duration"}, + } + + def __init__( + self, + *, + auto_resolved: Optional[bool] = None, + time_to_resolve: Optional[datetime.timedelta] = None, + **kwargs: Any + ) -> None: + """ + :keyword auto_resolved: The flag that indicates whether or not to auto resolve a fired alert. + :paramtype auto_resolved: bool + :keyword time_to_resolve: The duration a rule must evaluate as healthy before the fired alert + is automatically resolved represented in ISO 8601 duration format. + :paramtype time_to_resolve: ~datetime.timedelta + """ + super().__init__(**kwargs) + self.auto_resolved = auto_resolved + self.time_to_resolve = time_to_resolve + + +class LogAlertRuleResource(_serialization.Model): + """The scheduled query rule resource. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: Fully qualified resource ID for the resource. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. + :vartype id: str + :ivar name: The name of the resource. + :vartype name: str + :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or + "Microsoft.Storage/storageAccounts". + :vartype type: str + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str + :ivar kind: Indicates the type of scheduled query rule. The default is LogAlert. Known values + are: "LogAlert", "EventLogAlert", and "LogToMetric". + :vartype kind: str or ~azure.mgmt.alertsmanagement.models.Kind + :ivar etag: The etag field is *not* required. If it is provided in the response body, it must + also be provided as a header per the normal etag convention. Entity tags are used for + comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in + the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range + (section 14.27) header fields. + :vartype etag: str + :ivar system_data: SystemData of ScheduledQueryRule. + :vartype system_data: ~azure.mgmt.alertsmanagement.models.SystemData + :ivar created_with_api_version: The api-version used when creating this alert rule. + :vartype created_with_api_version: str + :ivar is_legacy_log_analytics_rule: True if alert rule is legacy Log Analytic rule. + :vartype is_legacy_log_analytics_rule: bool + :ivar description: The description of the scheduled query rule. + :vartype description: str + :ivar display_name: The display name of the alert rule. + :vartype display_name: str + :ivar severity: Severity of the alert. Should be an integer between [0-4]. Value of 0 is + severest. Relevant and required only for rules of the kind LogAlert. Known values are: 0, 1, 2, + 3, and 4. + :vartype severity: int or ~azure.mgmt.alertsmanagement.models.AlertSeverity + :ivar enabled: The flag which indicates whether this scheduled query rule is enabled. Value + should be true or false. + :vartype enabled: bool + :ivar scopes: The list of resource id's that this scheduled query rule is scoped to. + :vartype scopes: list[str] + :ivar evaluation_frequency: How often the scheduled query rule is evaluated represented in ISO + 8601 duration format. Relevant and required only for rules of the kind LogAlert. + :vartype evaluation_frequency: ~datetime.timedelta + :ivar window_size: The period of time (in ISO 8601 duration format) on which the Alert query + will be executed (bin size). Relevant and required only for rules of the kind LogAlert. + :vartype window_size: ~datetime.timedelta + :ivar override_query_time_range: If specified then overrides the query time range (default is + WindowSize*NumberOfEvaluationPeriods). Relevant only for rules of the kind LogAlert. + :vartype override_query_time_range: ~datetime.timedelta + :ivar target_resource_types: List of resource type of the target resource(s) on which the alert + is created/updated. For example if the scope is a resource group and targetResourceTypes is + Microsoft.Compute/virtualMachines, then a different alert will be fired for each virtual + machine in the resource group which meet the alert criteria. Relevant only for rules of the + kind LogAlert. + :vartype target_resource_types: list[str] + :ivar criteria: The rule criteria that defines the conditions of the scheduled query rule. + :vartype criteria: ~azure.mgmt.alertsmanagement.models.LogAlertRuleCriteria + :ivar mute_actions_duration: Mute actions for the chosen period of time (in ISO 8601 duration + format) after the alert is fired. Relevant only for rules of the kind LogAlert. + :vartype mute_actions_duration: ~datetime.timedelta + :ivar is_workspace_alerts_storage_configured: The flag which indicates whether this scheduled + query rule has been configured to be stored in the customer's storage. The default is false. + :vartype is_workspace_alerts_storage_configured: bool + :ivar check_workspace_alerts_storage_configured: The flag which indicates whether this + scheduled query rule should be stored in the customer's storage. The default is false. Relevant + only for rules of the kind LogAlert. + :vartype check_workspace_alerts_storage_configured: bool + :ivar skip_query_validation: The flag which indicates whether the provided query should be + validated or not. The default is false. Relevant only for rules of the kind LogAlert. + :vartype skip_query_validation: bool + :ivar auto_mitigate: The flag that indicates whether the alert should be automatically resolved + or not. The default is true. Relevant only for rules of the kind LogAlert. + :vartype auto_mitigate: bool + :ivar resolve_configuration: Defines the configuration for resolving fired alerts. Relevant + only for rules of the kind LogAlert. + :vartype resolve_configuration: + ~azure.mgmt.alertsmanagement.models.LogAlertRuleResolveConfiguration + """ + + _validation = { + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "location": {"required": True}, + "etag": {"readonly": True}, + "system_data": {"readonly": True}, + "created_with_api_version": {"readonly": True}, + "is_legacy_log_analytics_rule": {"readonly": True}, + "is_workspace_alerts_storage_configured": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, + "kind": {"key": "kind", "type": "str"}, + "etag": {"key": "etag", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "created_with_api_version": {"key": "properties.createdWithApiVersion", "type": "str"}, + "is_legacy_log_analytics_rule": {"key": "properties.isLegacyLogAnalyticsRule", "type": "bool"}, + "description": {"key": "properties.description", "type": "str"}, + "display_name": {"key": "properties.displayName", "type": "str"}, + "severity": {"key": "properties.severity", "type": "int"}, + "enabled": {"key": "properties.enabled", "type": "bool"}, + "scopes": {"key": "properties.scopes", "type": "[str]"}, + "evaluation_frequency": {"key": "properties.evaluationFrequency", "type": "duration"}, + "window_size": {"key": "properties.windowSize", "type": "duration"}, + "override_query_time_range": {"key": "properties.overrideQueryTimeRange", "type": "duration"}, + "target_resource_types": {"key": "properties.targetResourceTypes", "type": "[str]"}, + "criteria": {"key": "properties.criteria", "type": "LogAlertRuleCriteria"}, + "mute_actions_duration": {"key": "properties.muteActionsDuration", "type": "duration"}, + "is_workspace_alerts_storage_configured": { + "key": "properties.isWorkspaceAlertsStorageConfigured", + "type": "bool", + }, + "check_workspace_alerts_storage_configured": { + "key": "properties.checkWorkspaceAlertsStorageConfigured", + "type": "bool", + }, + "skip_query_validation": {"key": "properties.skipQueryValidation", "type": "bool"}, + "auto_mitigate": {"key": "properties.autoMitigate", "type": "bool"}, + "resolve_configuration": {"key": "properties.resolveConfiguration", "type": "LogAlertRuleResolveConfiguration"}, + } + + def __init__( # pylint: disable=too-many-locals + self, + *, + location: str, + tags: Optional[Dict[str, str]] = None, + kind: Optional[Union[str, "_models.Kind"]] = None, + description: Optional[str] = None, + display_name: Optional[str] = None, + severity: Optional[Union[int, "_models.AlertSeverity"]] = None, + enabled: Optional[bool] = None, + scopes: Optional[List[str]] = None, + evaluation_frequency: Optional[datetime.timedelta] = None, + window_size: Optional[datetime.timedelta] = None, + override_query_time_range: Optional[datetime.timedelta] = None, + target_resource_types: Optional[List[str]] = None, + criteria: Optional["_models.LogAlertRuleCriteria"] = None, + mute_actions_duration: Optional[datetime.timedelta] = None, + check_workspace_alerts_storage_configured: Optional[bool] = None, + skip_query_validation: Optional[bool] = None, + auto_mitigate: Optional[bool] = None, + resolve_configuration: Optional["_models.LogAlertRuleResolveConfiguration"] = None, + **kwargs: Any + ) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword location: The geo-location where the resource lives. Required. + :paramtype location: str + :keyword kind: Indicates the type of scheduled query rule. The default is LogAlert. Known + values are: "LogAlert", "EventLogAlert", and "LogToMetric". + :paramtype kind: str or ~azure.mgmt.alertsmanagement.models.Kind + :keyword description: The description of the scheduled query rule. + :paramtype description: str + :keyword display_name: The display name of the alert rule. + :paramtype display_name: str + :keyword severity: Severity of the alert. Should be an integer between [0-4]. Value of 0 is + severest. Relevant and required only for rules of the kind LogAlert. Known values are: 0, 1, 2, + 3, and 4. + :paramtype severity: int or ~azure.mgmt.alertsmanagement.models.AlertSeverity + :keyword enabled: The flag which indicates whether this scheduled query rule is enabled. Value + should be true or false. + :paramtype enabled: bool + :keyword scopes: The list of resource id's that this scheduled query rule is scoped to. + :paramtype scopes: list[str] + :keyword evaluation_frequency: How often the scheduled query rule is evaluated represented in + ISO 8601 duration format. Relevant and required only for rules of the kind LogAlert. + :paramtype evaluation_frequency: ~datetime.timedelta + :keyword window_size: The period of time (in ISO 8601 duration format) on which the Alert query + will be executed (bin size). Relevant and required only for rules of the kind LogAlert. + :paramtype window_size: ~datetime.timedelta + :keyword override_query_time_range: If specified then overrides the query time range (default + is WindowSize*NumberOfEvaluationPeriods). Relevant only for rules of the kind LogAlert. + :paramtype override_query_time_range: ~datetime.timedelta + :keyword target_resource_types: List of resource type of the target resource(s) on which the + alert is created/updated. For example if the scope is a resource group and targetResourceTypes + is Microsoft.Compute/virtualMachines, then a different alert will be fired for each virtual + machine in the resource group which meet the alert criteria. Relevant only for rules of the + kind LogAlert. + :paramtype target_resource_types: list[str] + :keyword criteria: The rule criteria that defines the conditions of the scheduled query rule. + :paramtype criteria: ~azure.mgmt.alertsmanagement.models.LogAlertRuleCriteria + :keyword mute_actions_duration: Mute actions for the chosen period of time (in ISO 8601 + duration format) after the alert is fired. Relevant only for rules of the kind LogAlert. + :paramtype mute_actions_duration: ~datetime.timedelta + :keyword check_workspace_alerts_storage_configured: The flag which indicates whether this + scheduled query rule should be stored in the customer's storage. The default is false. Relevant + only for rules of the kind LogAlert. + :paramtype check_workspace_alerts_storage_configured: bool + :keyword skip_query_validation: The flag which indicates whether the provided query should be + validated or not. The default is false. Relevant only for rules of the kind LogAlert. + :paramtype skip_query_validation: bool + :keyword auto_mitigate: The flag that indicates whether the alert should be automatically + resolved or not. The default is true. Relevant only for rules of the kind LogAlert. + :paramtype auto_mitigate: bool + :keyword resolve_configuration: Defines the configuration for resolving fired alerts. Relevant + only for rules of the kind LogAlert. + :paramtype resolve_configuration: + ~azure.mgmt.alertsmanagement.models.LogAlertRuleResolveConfiguration + """ + super().__init__(**kwargs) + self.id: Optional[str] = None + self.name: Optional[str] = None + self.type: Optional[str] = None + self.tags = tags + self.location = location + self.kind = kind + self.etag: Optional[str] = None + self.system_data: Optional["_models.SystemData"] = None + self.created_with_api_version: Optional[str] = None + self.is_legacy_log_analytics_rule: Optional[bool] = None + self.description = description + self.display_name = display_name + self.severity = severity + self.enabled = enabled + self.scopes = scopes + self.evaluation_frequency = evaluation_frequency + self.window_size = window_size + self.override_query_time_range = override_query_time_range + self.target_resource_types = target_resource_types + self.criteria = criteria + self.mute_actions_duration = mute_actions_duration + self.is_workspace_alerts_storage_configured: Optional[bool] = None + self.check_workspace_alerts_storage_configured = check_workspace_alerts_storage_configured + self.skip_query_validation = skip_query_validation + self.auto_mitigate = auto_mitigate + self.resolve_configuration = resolve_configuration + + +class LogAlertRuleUserIdentityProperties(_serialization.Model): + """User assigned identity properties. + + Variables are only populated by the server, and will be ignored when sending a request. + + :ivar principal_id: The principal id of user assigned identity. + :vartype principal_id: str + :ivar client_id: The client id of user assigned identity. + :vartype client_id: str + """ + + _validation = { + "principal_id": {"readonly": True}, + "client_id": {"readonly": True}, + } + + _attribute_map = { + "principal_id": {"key": "principalId", "type": "str"}, + "client_id": {"key": "clientId", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.principal_id: Optional[str] = None + self.client_id: Optional[str] = None + + +class MonitorServiceDetails(_serialization.Model): + """Details of a monitor service. + + :ivar name: Monitor service name. + :vartype name: str + :ivar display_name: Monitor service display name. + :vartype display_name: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display_name": {"key": "displayName", "type": "str"}, + } + + def __init__(self, *, name: Optional[str] = None, display_name: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword name: Monitor service name. + :paramtype name: str + :keyword display_name: Monitor service display name. + :paramtype display_name: str + """ + super().__init__(**kwargs) + self.name = name + self.display_name = display_name + + +class MonitorServiceList(AlertsMetaDataProperties): + """Monitor service details. + + All required parameters must be populated in order to send to server. + + :ivar metadata_identifier: Identification of the information to be retrieved by API call. + Required. "MonitorServiceList" + :vartype metadata_identifier: str or ~azure.mgmt.alertsmanagement.models.MetadataIdentifier + :ivar data: Array of operations. Required. + :vartype data: list[~azure.mgmt.alertsmanagement.models.MonitorServiceDetails] + """ + + _validation = { + "metadata_identifier": {"required": True}, + "data": {"required": True}, + } + + _attribute_map = { + "metadata_identifier": {"key": "metadataIdentifier", "type": "str"}, + "data": {"key": "data", "type": "[MonitorServiceDetails]"}, + } + + def __init__(self, *, data: List["_models.MonitorServiceDetails"], **kwargs: Any) -> None: + """ + :keyword data: Array of operations. Required. + :paramtype data: list[~azure.mgmt.alertsmanagement.models.MonitorServiceDetails] + """ + super().__init__(**kwargs) + self.metadata_identifier: str = "MonitorServiceList" + self.data = data + + +class MonthlyRecurrence(Recurrence): + """Monthly recurrence object. + + All required parameters must be populated in order to send to server. + + :ivar recurrence_type: Specifies when the recurrence should be applied. Required. Known values + are: "Daily", "Weekly", and "Monthly". + :vartype recurrence_type: str or ~azure.mgmt.alertsmanagement.models.RecurrenceType + :ivar start_time: Start time for recurrence. + :vartype start_time: str + :ivar end_time: End time for recurrence. + :vartype end_time: str + :ivar days_of_month: Specifies the values for monthly recurrence pattern. Required. + :vartype days_of_month: list[int] + """ + + _validation = { + "recurrence_type": {"required": True}, + "days_of_month": {"required": True}, + } + + _attribute_map = { + "recurrence_type": {"key": "recurrenceType", "type": "str"}, + "start_time": {"key": "startTime", "type": "str"}, + "end_time": {"key": "endTime", "type": "str"}, + "days_of_month": {"key": "daysOfMonth", "type": "[int]"}, + } + + def __init__( + self, + *, + days_of_month: List[int], + start_time: Optional[str] = None, + end_time: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword start_time: Start time for recurrence. + :paramtype start_time: str + :keyword end_time: End time for recurrence. + :paramtype end_time: str + :keyword days_of_month: Specifies the values for monthly recurrence pattern. Required. + :paramtype days_of_month: list[int] + """ + super().__init__(start_time=start_time, end_time=end_time, **kwargs) + self.recurrence_type: str = "Monthly" + self.days_of_month = days_of_month + + +class Operation(_serialization.Model): + """Operation provided by provider. + + :ivar name: Name of the operation. + :vartype name: str + :ivar display: Properties of the operation. + :vartype display: ~azure.mgmt.alertsmanagement.models.OperationDisplay + :ivar origin: Origin of the operation. + :vartype origin: str + """ + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + "origin": {"key": "origin", "type": "str"}, + } + + def __init__( + self, + *, + name: Optional[str] = None, + display: Optional["_models.OperationDisplay"] = None, + origin: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword name: Name of the operation. + :paramtype name: str + :keyword display: Properties of the operation. + :paramtype display: ~azure.mgmt.alertsmanagement.models.OperationDisplay + :keyword origin: Origin of the operation. + :paramtype origin: str + """ + super().__init__(**kwargs) + self.name = name + self.display = display + self.origin = origin + + +class OperationDisplay(_serialization.Model): + """Properties of the operation. + + :ivar provider: Provider name. + :vartype provider: str + :ivar resource: Resource name. + :vartype resource: str + :ivar operation: Operation name. + :vartype operation: str + :ivar description: Description of the operation. + :vartype description: str + """ + + _attribute_map = { + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, + } + + def __init__( + self, + *, + provider: Optional[str] = None, + resource: Optional[str] = None, + operation: Optional[str] = None, + description: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword provider: Provider name. + :paramtype provider: str + :keyword resource: Resource name. + :paramtype resource: str + :keyword operation: Operation name. + :paramtype operation: str + :keyword description: Description of the operation. + :paramtype description: str """ super().__init__(**kwargs) self.provider = provider @@ -1522,7 +4184,7 @@ def __init__( class OperationsList(_serialization.Model): """Lists the operations available in the AlertsManagement RP. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar next_link: URL to fetch the next set of alerts. :vartype next_link: str @@ -1539,7 +4201,7 @@ class OperationsList(_serialization.Model): "value": {"key": "value", "type": "[Operation]"}, } - def __init__(self, *, value: List["_models.Operation"], next_link: Optional[str] = None, **kwargs): + def __init__(self, *, value: List["_models.Operation"], next_link: Optional[str] = None, **kwargs: Any) -> None: """ :keyword next_link: URL to fetch the next set of alerts. :paramtype next_link: str @@ -1551,6 +4213,109 @@ def __init__(self, *, value: List["_models.Operation"], next_link: Optional[str] self.value = value +class Origin(_serialization.Model): + """Details about the origin of the entity - the source that added it to the issue. + + All required parameters must be populated in order to send to server. + + :ivar added_by: The ID of the origin - for example, in case of 'Manual', the object ID of the + identity, and in case of 'Automatic', the name of the automatic system. Required. + :vartype added_by: str + :ivar added_by_type: The source of the origin - Manual or Automatic. Required. Known values + are: "Manual" and "Automatic". + :vartype added_by_type: str or ~azure.mgmt.alertsmanagement.models.AddedByType + """ + + _validation = { + "added_by": {"required": True}, + "added_by_type": {"required": True}, + } + + _attribute_map = { + "added_by": {"key": "addedBy", "type": "str"}, + "added_by_type": {"key": "addedByType", "type": "str"}, + } + + def __init__(self, *, added_by: str, added_by_type: Union[str, "_models.AddedByType"], **kwargs: Any) -> None: + """ + :keyword added_by: The ID of the origin - for example, in case of 'Manual', the object ID of + the identity, and in case of 'Automatic', the name of the automatic system. Required. + :paramtype added_by: str + :keyword added_by_type: The source of the origin - Manual or Automatic. Required. Known values + are: "Manual" and "Automatic". + :paramtype added_by_type: str or ~azure.mgmt.alertsmanagement.models.AddedByType + """ + super().__init__(**kwargs) + self.added_by = added_by + self.added_by_type = added_by_type + + +class PagedRelatedAlert(_serialization.Model): + """Paged collection of RelatedAlert items. + + All required parameters must be populated in order to send to server. + + :ivar value: The RelatedAlert items on this page. Required. + :vartype value: list[~azure.mgmt.alertsmanagement.models.RelatedAlert] + :ivar next_link: The link to the next page of items. + :vartype next_link: str + """ + + _validation = { + "value": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RelatedAlert]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: List["_models.RelatedAlert"], next_link: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword value: The RelatedAlert items on this page. Required. + :paramtype value: list[~azure.mgmt.alertsmanagement.models.RelatedAlert] + :keyword next_link: The link to the next page of items. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class PagedRelatedResource(_serialization.Model): + """Paged collection of RelatedResource items. + + All required parameters must be populated in order to send to server. + + :ivar value: The RelatedResource items on this page. Required. + :vartype value: list[~azure.mgmt.alertsmanagement.models.RelatedResource] + :ivar next_link: The link to the next page of items. + :vartype next_link: str + """ + + _validation = { + "value": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RelatedResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: List["_models.RelatedResource"], next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: The RelatedResource items on this page. Required. + :paramtype value: list[~azure.mgmt.alertsmanagement.models.RelatedResource] + :keyword next_link: The link to the next page of items. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + class PatchObject(_serialization.Model): """Data contract for patch. @@ -1561,48 +4326,477 @@ class PatchObject(_serialization.Model): """ _attribute_map = { - "tags": {"key": "tags", "type": "{str}"}, - "enabled": {"key": "properties.enabled", "type": "bool"}, + "tags": {"key": "tags", "type": "{str}"}, + "enabled": {"key": "properties.enabled", "type": "bool"}, + } + + def __init__(self, *, tags: Optional[Dict[str, str]] = None, enabled: Optional[bool] = None, **kwargs: Any) -> None: + """ + :keyword tags: Tags to be updated. + :paramtype tags: dict[str, str] + :keyword enabled: Indicates if the given alert processing rule is enabled or disabled. + :paramtype enabled: bool + """ + super().__init__(**kwargs) + self.tags = tags + self.enabled = enabled + + +class PreviewAlertRuleRequest(_serialization.Model): + """PreviewAlertRuleRequest. + + All required parameters must be populated in order to send to server. + + :ivar location: The location of the rule resource. Required. + :vartype location: str + :ivar properties: Required. + :vartype properties: ~azure.mgmt.alertsmanagement.models.PreviewAlertRuleRequestProperties + """ + + _validation = { + "location": {"required": True}, + "properties": {"required": True}, + } + + _attribute_map = { + "location": {"key": "location", "type": "str"}, + "properties": {"key": "properties", "type": "PreviewAlertRuleRequestProperties"}, + } + + def __init__( + self, *, location: str, properties: "_models.PreviewAlertRuleRequestProperties", **kwargs: Any + ) -> None: + """ + :keyword location: The location of the rule resource. Required. + :paramtype location: str + :keyword properties: Required. + :paramtype properties: ~azure.mgmt.alertsmanagement.models.PreviewAlertRuleRequestProperties + """ + super().__init__(**kwargs) + self.location = location + self.properties = properties + + +class PreviewAlertRuleRequestProperties(_serialization.Model): + """PreviewAlertRuleRequestProperties. + + All required parameters must be populated in order to send to server. + + :ivar lookback_period: Specifies the lookback of the preview. Required. + :vartype lookback_period: str + :ivar alert_rule_type: The type of the alert rule to be previewed. Required. + :vartype alert_rule_type: str + :ivar alert_rule_properties: The properties of the alert rule to preview. Required. + :vartype alert_rule_properties: ~azure.mgmt.alertsmanagement.models.LogAlertRuleResource + """ + + _validation = { + "lookback_period": {"required": True}, + "alert_rule_type": {"required": True}, + "alert_rule_properties": {"required": True}, + } + + _attribute_map = { + "lookback_period": {"key": "lookbackPeriod", "type": "str"}, + "alert_rule_type": {"key": "alertRuleType", "type": "str"}, + "alert_rule_properties": {"key": "alertRuleProperties", "type": "LogAlertRuleResource"}, + } + + def __init__( + self, + *, + lookback_period: str, + alert_rule_type: str, + alert_rule_properties: "_models.LogAlertRuleResource", + **kwargs: Any + ) -> None: + """ + :keyword lookback_period: Specifies the lookback of the preview. Required. + :paramtype lookback_period: str + :keyword alert_rule_type: The type of the alert rule to be previewed. Required. + :paramtype alert_rule_type: str + :keyword alert_rule_properties: The properties of the alert rule to preview. Required. + :paramtype alert_rule_properties: ~azure.mgmt.alertsmanagement.models.LogAlertRuleResource + """ + super().__init__(**kwargs) + self.lookback_period = lookback_period + self.alert_rule_type = alert_rule_type + self.alert_rule_properties = alert_rule_properties + + +class PreviewAlertRuleResponse(_serialization.Model): + """PreviewAlertRuleResponse. + + :ivar rule_preview_results: An array of rule preview results. + :vartype rule_preview_results: list[~azure.mgmt.alertsmanagement.models.RulePreviewResult] + """ + + _attribute_map = { + "rule_preview_results": {"key": "rulePreviewResults", "type": "[RulePreviewResult]"}, + } + + def __init__( + self, *, rule_preview_results: Optional[List["_models.RulePreviewResult"]] = None, **kwargs: Any + ) -> None: + """ + :keyword rule_preview_results: An array of rule preview results. + :paramtype rule_preview_results: list[~azure.mgmt.alertsmanagement.models.RulePreviewResult] + """ + super().__init__(**kwargs) + self.rule_preview_results = rule_preview_results + + +class PrometheusEnrichmentItem(AlertEnrichmentItem): + """Prometheus enrichment object. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + PrometheusInstantQuery, PrometheusRangeQuery + + All required parameters must be populated in order to send to server. + + :ivar title: The enrichment title. Required. + :vartype title: str + :ivar description: The enrichment description. Required. + :vartype description: str + :ivar status: The status of the evaluation of the enrichment. Required. Known values are: + "Succeeded", "Failed", "New", "InProgress", "Mitigated", "Closed", and "Canceled". + :vartype status: str or ~azure.mgmt.alertsmanagement.models.Status + :ivar error_message: The error message. Will be present only if the status is 'Failed'. + :vartype error_message: str + :ivar type: The enrichment type. Required. Known values are: "PrometheusInstantQuery" and + "PrometheusRangeQuery". + :vartype type: str or ~azure.mgmt.alertsmanagement.models.Type + :ivar link_to_api: Link to Prometheus query API (Url format). Required. + :vartype link_to_api: str + :ivar datasources: An array of the azure monitor workspace resource ids. Required. + :vartype datasources: list[str] + :ivar grafana_explore_path: Partial link to the Grafana explore API. Required. + :vartype grafana_explore_path: str + :ivar query: The Prometheus expression query. Required. + :vartype query: str + """ + + _validation = { + "title": {"required": True}, + "description": {"required": True}, + "status": {"required": True}, + "type": {"required": True}, + "link_to_api": {"required": True}, + "datasources": {"required": True}, + "grafana_explore_path": {"required": True}, + "query": {"required": True}, + } + + _attribute_map = { + "title": {"key": "title", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "error_message": {"key": "errorMessage", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "link_to_api": {"key": "linkToApi", "type": "str"}, + "datasources": {"key": "datasources", "type": "[str]"}, + "grafana_explore_path": {"key": "grafanaExplorePath", "type": "str"}, + "query": {"key": "query", "type": "str"}, + } + + _subtype_map = { + "type": {"PrometheusInstantQuery": "PrometheusInstantQuery", "PrometheusRangeQuery": "PrometheusRangeQuery"} + } + + def __init__( + self, + *, + title: str, + description: str, + status: Union[str, "_models.Status"], + link_to_api: str, + datasources: List[str], + grafana_explore_path: str, + query: str, + error_message: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword title: The enrichment title. Required. + :paramtype title: str + :keyword description: The enrichment description. Required. + :paramtype description: str + :keyword status: The status of the evaluation of the enrichment. Required. Known values are: + "Succeeded", "Failed", "New", "InProgress", "Mitigated", "Closed", and "Canceled". + :paramtype status: str or ~azure.mgmt.alertsmanagement.models.Status + :keyword error_message: The error message. Will be present only if the status is 'Failed'. + :paramtype error_message: str + :keyword link_to_api: Link to Prometheus query API (Url format). Required. + :paramtype link_to_api: str + :keyword datasources: An array of the azure monitor workspace resource ids. Required. + :paramtype datasources: list[str] + :keyword grafana_explore_path: Partial link to the Grafana explore API. Required. + :paramtype grafana_explore_path: str + :keyword query: The Prometheus expression query. Required. + :paramtype query: str + """ + super().__init__(title=title, description=description, status=status, error_message=error_message, **kwargs) + self.type: str = "PrometheusEnrichmentItem" + self.link_to_api = link_to_api + self.datasources = datasources + self.grafana_explore_path = grafana_explore_path + self.query = query + + +class PrometheusInstantQuery(PrometheusEnrichmentItem): + """Prometheus instant query enrichment object. + + All required parameters must be populated in order to send to server. + + :ivar title: The enrichment title. Required. + :vartype title: str + :ivar description: The enrichment description. Required. + :vartype description: str + :ivar status: The status of the evaluation of the enrichment. Required. Known values are: + "Succeeded", "Failed", "New", "InProgress", "Mitigated", "Closed", and "Canceled". + :vartype status: str or ~azure.mgmt.alertsmanagement.models.Status + :ivar error_message: The error message. Will be present only if the status is 'Failed'. + :vartype error_message: str + :ivar type: The enrichment type. Required. Known values are: "PrometheusInstantQuery" and + "PrometheusRangeQuery". + :vartype type: str or ~azure.mgmt.alertsmanagement.models.Type + :ivar link_to_api: Link to Prometheus query API (Url format). Required. + :vartype link_to_api: str + :ivar datasources: An array of the azure monitor workspace resource ids. Required. + :vartype datasources: list[str] + :ivar grafana_explore_path: Partial link to the Grafana explore API. Required. + :vartype grafana_explore_path: str + :ivar query: The Prometheus expression query. Required. + :vartype query: str + :ivar time: The date and the time of the evaluation. Required. + :vartype time: str + """ + + _validation = { + "title": {"required": True}, + "description": {"required": True}, + "status": {"required": True}, + "type": {"required": True}, + "link_to_api": {"required": True}, + "datasources": {"required": True}, + "grafana_explore_path": {"required": True}, + "query": {"required": True}, + "time": {"required": True}, + } + + _attribute_map = { + "title": {"key": "title", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "error_message": {"key": "errorMessage", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "link_to_api": {"key": "linkToApi", "type": "str"}, + "datasources": {"key": "datasources", "type": "[str]"}, + "grafana_explore_path": {"key": "grafanaExplorePath", "type": "str"}, + "query": {"key": "query", "type": "str"}, + "time": {"key": "time", "type": "str"}, + } + + def __init__( + self, + *, + title: str, + description: str, + status: Union[str, "_models.Status"], + link_to_api: str, + datasources: List[str], + grafana_explore_path: str, + query: str, + time: str, + error_message: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword title: The enrichment title. Required. + :paramtype title: str + :keyword description: The enrichment description. Required. + :paramtype description: str + :keyword status: The status of the evaluation of the enrichment. Required. Known values are: + "Succeeded", "Failed", "New", "InProgress", "Mitigated", "Closed", and "Canceled". + :paramtype status: str or ~azure.mgmt.alertsmanagement.models.Status + :keyword error_message: The error message. Will be present only if the status is 'Failed'. + :paramtype error_message: str + :keyword link_to_api: Link to Prometheus query API (Url format). Required. + :paramtype link_to_api: str + :keyword datasources: An array of the azure monitor workspace resource ids. Required. + :paramtype datasources: list[str] + :keyword grafana_explore_path: Partial link to the Grafana explore API. Required. + :paramtype grafana_explore_path: str + :keyword query: The Prometheus expression query. Required. + :paramtype query: str + :keyword time: The date and the time of the evaluation. Required. + :paramtype time: str + """ + super().__init__( + title=title, + description=description, + status=status, + error_message=error_message, + link_to_api=link_to_api, + datasources=datasources, + grafana_explore_path=grafana_explore_path, + query=query, + **kwargs + ) + self.type: str = "PrometheusInstantQuery" + self.time = time + + +class PrometheusRangeQuery(PrometheusEnrichmentItem): + """Prometheus instant query enrichment object. + + All required parameters must be populated in order to send to server. + + :ivar title: The enrichment title. Required. + :vartype title: str + :ivar description: The enrichment description. Required. + :vartype description: str + :ivar status: The status of the evaluation of the enrichment. Required. Known values are: + "Succeeded", "Failed", "New", "InProgress", "Mitigated", "Closed", and "Canceled". + :vartype status: str or ~azure.mgmt.alertsmanagement.models.Status + :ivar error_message: The error message. Will be present only if the status is 'Failed'. + :vartype error_message: str + :ivar type: The enrichment type. Required. Known values are: "PrometheusInstantQuery" and + "PrometheusRangeQuery". + :vartype type: str or ~azure.mgmt.alertsmanagement.models.Type + :ivar link_to_api: Link to Prometheus query API (Url format). Required. + :vartype link_to_api: str + :ivar datasources: An array of the azure monitor workspace resource ids. Required. + :vartype datasources: list[str] + :ivar grafana_explore_path: Partial link to the Grafana explore API. Required. + :vartype grafana_explore_path: str + :ivar query: The Prometheus expression query. Required. + :vartype query: str + :ivar start: The start evaluation date and time in ISO8601 format. Required. + :vartype start: ~datetime.datetime + :ivar end: The end evaluation date and time in ISO8601 format. Required. + :vartype end: ~datetime.datetime + :ivar step: Query resolution step width in ISO8601 format. Required. + :vartype step: str + """ + + _validation = { + "title": {"required": True}, + "description": {"required": True}, + "status": {"required": True}, + "type": {"required": True}, + "link_to_api": {"required": True}, + "datasources": {"required": True}, + "grafana_explore_path": {"required": True}, + "query": {"required": True}, + "start": {"required": True}, + "end": {"required": True}, + "step": {"required": True}, + } + + _attribute_map = { + "title": {"key": "title", "type": "str"}, + "description": {"key": "description", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "error_message": {"key": "errorMessage", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "link_to_api": {"key": "linkToApi", "type": "str"}, + "datasources": {"key": "datasources", "type": "[str]"}, + "grafana_explore_path": {"key": "grafanaExplorePath", "type": "str"}, + "query": {"key": "query", "type": "str"}, + "start": {"key": "start", "type": "iso-8601"}, + "end": {"key": "end", "type": "iso-8601"}, + "step": {"key": "step", "type": "str"}, } - def __init__(self, *, tags: Optional[Dict[str, str]] = None, enabled: Optional[bool] = None, **kwargs): + def __init__( + self, + *, + title: str, + description: str, + status: Union[str, "_models.Status"], + link_to_api: str, + datasources: List[str], + grafana_explore_path: str, + query: str, + start: datetime.datetime, + end: datetime.datetime, + step: str, + error_message: Optional[str] = None, + **kwargs: Any + ) -> None: """ - :keyword tags: Tags to be updated. - :paramtype tags: dict[str, str] - :keyword enabled: Indicates if the given alert processing rule is enabled or disabled. - :paramtype enabled: bool + :keyword title: The enrichment title. Required. + :paramtype title: str + :keyword description: The enrichment description. Required. + :paramtype description: str + :keyword status: The status of the evaluation of the enrichment. Required. Known values are: + "Succeeded", "Failed", "New", "InProgress", "Mitigated", "Closed", and "Canceled". + :paramtype status: str or ~azure.mgmt.alertsmanagement.models.Status + :keyword error_message: The error message. Will be present only if the status is 'Failed'. + :paramtype error_message: str + :keyword link_to_api: Link to Prometheus query API (Url format). Required. + :paramtype link_to_api: str + :keyword datasources: An array of the azure monitor workspace resource ids. Required. + :paramtype datasources: list[str] + :keyword grafana_explore_path: Partial link to the Grafana explore API. Required. + :paramtype grafana_explore_path: str + :keyword query: The Prometheus expression query. Required. + :paramtype query: str + :keyword start: The start evaluation date and time in ISO8601 format. Required. + :paramtype start: ~datetime.datetime + :keyword end: The end evaluation date and time in ISO8601 format. Required. + :paramtype end: ~datetime.datetime + :keyword step: Query resolution step width in ISO8601 format. Required. + :paramtype step: str """ - super().__init__(**kwargs) - self.tags = tags - self.enabled = enabled + super().__init__( + title=title, + description=description, + status=status, + error_message=error_message, + link_to_api=link_to_api, + datasources=datasources, + grafana_explore_path=grafana_explore_path, + query=query, + **kwargs + ) + self.type: str = "PrometheusRangeQuery" + self.start = start + self.end = end + self.step = step class PrometheusRule(_serialization.Model): - """PrometheusRule. + """An Azure Prometheus alerting or recording rule. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar record: the name of the recording rule. + :ivar record: Recorded metrics name. :vartype record: str - :ivar alert: the name of the alert rule. + :ivar alert: Alert rule name. :vartype alert: str - :ivar enabled: the flag that indicates whether the Prometheus rule is enabled. + :ivar enabled: Enable/disable rule. :vartype enabled: bool - :ivar expression: the expression to run for the rule. Required. + :ivar expression: The PromQL expression to evaluate. + https://prometheus.io/docs/prometheus/latest/querying/basics/. Evaluated periodically as given + by 'interval', and the result recorded as a new set of time series with the metric name as + given by 'record'. Required. :vartype expression: str - :ivar severity: the severity of the alerts fired by the rule. Only relevant for alerts. - :vartype severity: int - :ivar for_property: the amount of time alert must be active before firing. Only relevant for - alerts. - :vartype for_property: str - :ivar labels: labels for rule group. Only relevant for alerts. + :ivar labels: Labels to add or overwrite before storing the result. :vartype labels: dict[str, str] - :ivar annotations: annotations for rule group. Only relevant for alerts. + :ivar severity: The severity of the alerts fired by the rule. Must be between 0 and 4. + :vartype severity: int + :ivar for_property: The amount of time alert must be active before firing. + :vartype for_property: ~datetime.timedelta + :ivar annotations: The annotations clause specifies a set of informational labels that can be + used to store longer additional information such as alert descriptions or runbook links. The + annotation values can be templated. :vartype annotations: dict[str, str] - :ivar actions: The array of actions that are performed when the alert rule becomes active, and - when an alert condition is resolved. Only relevant for alerts. + :ivar actions: Actions that are performed when the alert rule becomes active, and when an alert + condition is resolved. :vartype actions: list[~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupAction] - :ivar resolve_configuration: defines the configuration for resolving fired alerts. Only + :ivar resolve_configuration: Defines the configuration for resolving fired alerts. Only relevant for alerts. :vartype resolve_configuration: ~azure.mgmt.alertsmanagement.models.PrometheusRuleResolveConfiguration @@ -1617,9 +4811,9 @@ class PrometheusRule(_serialization.Model): "alert": {"key": "alert", "type": "str"}, "enabled": {"key": "enabled", "type": "bool"}, "expression": {"key": "expression", "type": "str"}, - "severity": {"key": "severity", "type": "int"}, - "for_property": {"key": "for", "type": "str"}, "labels": {"key": "labels", "type": "{str}"}, + "severity": {"key": "severity", "type": "int"}, + "for_property": {"key": "for", "type": "duration"}, "annotations": {"key": "annotations", "type": "{str}"}, "actions": {"key": "actions", "type": "[PrometheusRuleGroupAction]"}, "resolve_configuration": {"key": "resolveConfiguration", "type": "PrometheusRuleResolveConfiguration"}, @@ -1632,36 +4826,40 @@ def __init__( record: Optional[str] = None, alert: Optional[str] = None, enabled: Optional[bool] = None, - severity: Optional[int] = None, - for_property: Optional[str] = None, labels: Optional[Dict[str, str]] = None, + severity: Optional[int] = None, + for_property: Optional[datetime.timedelta] = None, annotations: Optional[Dict[str, str]] = None, actions: Optional[List["_models.PrometheusRuleGroupAction"]] = None, resolve_configuration: Optional["_models.PrometheusRuleResolveConfiguration"] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ - :keyword record: the name of the recording rule. + :keyword record: Recorded metrics name. :paramtype record: str - :keyword alert: the name of the alert rule. + :keyword alert: Alert rule name. :paramtype alert: str - :keyword enabled: the flag that indicates whether the Prometheus rule is enabled. + :keyword enabled: Enable/disable rule. :paramtype enabled: bool - :keyword expression: the expression to run for the rule. Required. + :keyword expression: The PromQL expression to evaluate. + https://prometheus.io/docs/prometheus/latest/querying/basics/. Evaluated periodically as given + by 'interval', and the result recorded as a new set of time series with the metric name as + given by 'record'. Required. :paramtype expression: str - :keyword severity: the severity of the alerts fired by the rule. Only relevant for alerts. - :paramtype severity: int - :keyword for_property: the amount of time alert must be active before firing. Only relevant for - alerts. - :paramtype for_property: str - :keyword labels: labels for rule group. Only relevant for alerts. + :keyword labels: Labels to add or overwrite before storing the result. :paramtype labels: dict[str, str] - :keyword annotations: annotations for rule group. Only relevant for alerts. + :keyword severity: The severity of the alerts fired by the rule. Must be between 0 and 4. + :paramtype severity: int + :keyword for_property: The amount of time alert must be active before firing. + :paramtype for_property: ~datetime.timedelta + :keyword annotations: The annotations clause specifies a set of informational labels that can + be used to store longer additional information such as alert descriptions or runbook links. The + annotation values can be templated. :paramtype annotations: dict[str, str] - :keyword actions: The array of actions that are performed when the alert rule becomes active, - and when an alert condition is resolved. Only relevant for alerts. + :keyword actions: Actions that are performed when the alert rule becomes active, and when an + alert condition is resolved. :paramtype actions: list[~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupAction] - :keyword resolve_configuration: defines the configuration for resolving fired alerts. Only + :keyword resolve_configuration: Defines the configuration for resolving fired alerts. Only relevant for alerts. :paramtype resolve_configuration: ~azure.mgmt.alertsmanagement.models.PrometheusRuleResolveConfiguration @@ -1671,9 +4869,9 @@ def __init__( self.alert = alert self.enabled = enabled self.expression = expression + self.labels = labels self.severity = severity self.for_property = for_property - self.labels = labels self.annotations = annotations self.actions = actions self.resolve_configuration = resolve_configuration @@ -1694,8 +4892,12 @@ class PrometheusRuleGroupAction(_serialization.Model): } def __init__( - self, *, action_group_id: Optional[str] = None, action_properties: Optional[Dict[str, str]] = None, **kwargs - ): + self, + *, + action_group_id: Optional[str] = None, + action_properties: Optional[Dict[str, str]] = None, + **kwargs: Any + ) -> None: """ :keyword action_group_id: The resource id of the action group to use. :paramtype action_group_id: str @@ -1707,11 +4909,14 @@ def __init__( self.action_properties = action_properties -class ResourceAutoGenerated(_serialization.Model): - """Common fields that are returned in the response for all Azure Resource Manager resources. +class TrackedResource(Resource): + """The resource model definition for an Azure Resource Manager tracked top level resource which + has 'tags' and a 'location'. Variables are only populated by the server, and will be ignored when sending a request. + All required parameters must be populated in order to send to server. + :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str @@ -1723,6 +4928,10 @@ class ResourceAutoGenerated(_serialization.Model): :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. :vartype system_data: ~azure.mgmt.alertsmanagement.models.SystemData + :ivar tags: Resource tags. + :vartype tags: dict[str, str] + :ivar location: The geo-location where the resource lives. Required. + :vartype location: str """ _validation = { @@ -1730,6 +4939,7 @@ class ResourceAutoGenerated(_serialization.Model): "name": {"readonly": True}, "type": {"readonly": True}, "system_data": {"readonly": True}, + "location": {"required": True}, } _attribute_map = { @@ -1737,23 +4947,28 @@ class ResourceAutoGenerated(_serialization.Model): "name": {"key": "name", "type": "str"}, "type": {"key": "type", "type": "str"}, "system_data": {"key": "systemData", "type": "SystemData"}, + "tags": {"key": "tags", "type": "{str}"}, + "location": {"key": "location", "type": "str"}, } - def __init__(self, **kwargs): - """ """ + def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs: Any) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword location: The geo-location where the resource lives. Required. + :paramtype location: str + """ super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.system_data = None + self.tags = tags + self.location = location -class TrackedResource(ResourceAutoGenerated): - """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. +class PrometheusRuleGroupResource(TrackedResource): + """The Prometheus rule group resource. Variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. @@ -1770,6 +4985,20 @@ class TrackedResource(ResourceAutoGenerated): :vartype tags: dict[str, str] :ivar location: The geo-location where the resource lives. Required. :vartype location: str + :ivar description: Rule group description. + :vartype description: str + :ivar enabled: Enable/disable rule group. + :vartype enabled: bool + :ivar cluster_name: Apply rule to data from a specific cluster. + :vartype cluster_name: str + :ivar scopes: Target Azure Monitor workspaces resource ids. This api-version is currently + limited to creating with one scope. This may change in future. Required. + :vartype scopes: list[str] + :ivar interval: The interval in which to run the Prometheus rule group represented in ISO 8601 + duration format. Should be between 1 and 15 minutes. + :vartype interval: ~datetime.timedelta + :ivar rules: Defines the rules in the Prometheus rule group. Required. + :vartype rules: list[~azure.mgmt.alertsmanagement.models.PrometheusRule] """ _validation = { @@ -1778,6 +5007,8 @@ class TrackedResource(ResourceAutoGenerated): "type": {"readonly": True}, "system_data": {"readonly": True}, "location": {"required": True}, + "scopes": {"required": True}, + "rules": {"required": True}, } _attribute_map = { @@ -1787,251 +5018,690 @@ class TrackedResource(ResourceAutoGenerated): "system_data": {"key": "systemData", "type": "SystemData"}, "tags": {"key": "tags", "type": "{str}"}, "location": {"key": "location", "type": "str"}, + "description": {"key": "properties.description", "type": "str"}, + "enabled": {"key": "properties.enabled", "type": "bool"}, + "cluster_name": {"key": "properties.clusterName", "type": "str"}, + "scopes": {"key": "properties.scopes", "type": "[str]"}, + "interval": {"key": "properties.interval", "type": "duration"}, + "rules": {"key": "properties.rules", "type": "[PrometheusRule]"}, } - def __init__(self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs): + def __init__( + self, + *, + location: str, + scopes: List[str], + rules: List["_models.PrometheusRule"], + tags: Optional[Dict[str, str]] = None, + description: Optional[str] = None, + enabled: Optional[bool] = None, + cluster_name: Optional[str] = None, + interval: Optional[datetime.timedelta] = None, + **kwargs: Any + ) -> None: """ :keyword tags: Resource tags. :paramtype tags: dict[str, str] :keyword location: The geo-location where the resource lives. Required. :paramtype location: str + :keyword description: Rule group description. + :paramtype description: str + :keyword enabled: Enable/disable rule group. + :paramtype enabled: bool + :keyword cluster_name: Apply rule to data from a specific cluster. + :paramtype cluster_name: str + :keyword scopes: Target Azure Monitor workspaces resource ids. This api-version is currently + limited to creating with one scope. This may change in future. Required. + :paramtype scopes: list[str] + :keyword interval: The interval in which to run the Prometheus rule group represented in ISO + 8601 duration format. Should be between 1 and 15 minutes. + :paramtype interval: ~datetime.timedelta + :keyword rules: Defines the rules in the Prometheus rule group. Required. + :paramtype rules: list[~azure.mgmt.alertsmanagement.models.PrometheusRule] """ - super().__init__(**kwargs) - self.tags = tags - self.location = location + super().__init__(tags=tags, location=location, **kwargs) + self.description = description + self.enabled = enabled + self.cluster_name = cluster_name + self.scopes = scopes + self.interval = interval + self.rules = rules -class PrometheusRuleGroupResource(TrackedResource): # pylint: disable=too-many-instance-attributes - """The Prometheus rule group resource. +class PrometheusRuleGroupResourceCollection(_serialization.Model): + """Represents a collection of alert rule resources. - Variables are only populated by the server, and will be ignored when sending a request. + :ivar value: the values for the alert rule resources. + :vartype value: list[~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource] + """ - All required parameters must be populated in order to send to Azure. + _attribute_map = { + "value": {"key": "value", "type": "[PrometheusRuleGroupResource]"}, + } + + def __init__(self, *, value: Optional[List["_models.PrometheusRuleGroupResource"]] = None, **kwargs: Any) -> None: + """ + :keyword value: the values for the alert rule resources. + :paramtype value: list[~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource] + """ + super().__init__(**kwargs) + self.value = value + + +class PrometheusRuleGroupResourcePatchParameters(_serialization.Model): # pylint: disable=name-too-long + """The Prometheus rule group resource for patch operations. - :ivar id: Fully qualified resource ID for the resource. Ex - - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. - :vartype id: str - :ivar name: The name of the resource. - :vartype name: str - :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or - "Microsoft.Storage/storageAccounts". - :vartype type: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.alertsmanagement.models.SystemData :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar location: The geo-location where the resource lives. Required. - :vartype location: str - :ivar description: the description of the Prometheus rule group that will be included in the - alert email. - :vartype description: str :ivar enabled: the flag that indicates whether the Prometheus rule group is enabled. :vartype enabled: bool - :ivar cluster_name: the cluster name of the rule group evaluation. - :vartype cluster_name: str - :ivar scopes: the list of resource id's that this rule group is scoped to. Required. - :vartype scopes: list[str] - :ivar interval: the interval in which to run the Prometheus rule group represented in ISO 8601 - duration format. Should be between 1 and 15 minutes. - :vartype interval: str - :ivar rules: defines the rules in the Prometheus rule group. Required. - :vartype rules: list[~azure.mgmt.alertsmanagement.models.PrometheusRule] + """ + + _attribute_map = { + "tags": {"key": "tags", "type": "{str}"}, + "enabled": {"key": "properties.enabled", "type": "bool"}, + } + + def __init__(self, *, tags: Optional[Dict[str, str]] = None, enabled: Optional[bool] = None, **kwargs: Any) -> None: + """ + :keyword tags: Resource tags. + :paramtype tags: dict[str, str] + :keyword enabled: the flag that indicates whether the Prometheus rule group is enabled. + :paramtype enabled: bool + """ + super().__init__(**kwargs) + self.tags = tags + self.enabled = enabled + + +class PrometheusRuleResolveConfiguration(_serialization.Model): + """Specifies the Prometheus alert rule configuration. + + :ivar auto_resolved: Enable alert auto-resolution. + :vartype auto_resolved: bool + :ivar time_to_resolve: Alert auto-resolution timeout. + :vartype time_to_resolve: ~datetime.timedelta + """ + + _attribute_map = { + "auto_resolved": {"key": "autoResolved", "type": "bool"}, + "time_to_resolve": {"key": "timeToResolve", "type": "duration"}, + } + + def __init__( + self, + *, + auto_resolved: Optional[bool] = None, + time_to_resolve: Optional[datetime.timedelta] = None, + **kwargs: Any + ) -> None: + """ + :keyword auto_resolved: Enable alert auto-resolution. + :paramtype auto_resolved: bool + :keyword time_to_resolve: Alert auto-resolution timeout. + :paramtype time_to_resolve: ~datetime.timedelta + """ + super().__init__(**kwargs) + self.auto_resolved = auto_resolved + self.time_to_resolve = time_to_resolve + + +class RelatedAlert(_serialization.Model): + """Properties of an alert which is related to the issue. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The alert ID. Required. + :vartype id: str + :ivar relevance: The alerts's relevance status. Required. Known values are: "None", "Relevant", + and "Irrelevant". + :vartype relevance: str or ~azure.mgmt.alertsmanagement.models.Relevance + :ivar origin: The source that related the alert to the issue. Required. + :vartype origin: ~azure.mgmt.alertsmanagement.models.Origin + :ivar added_at: The time this relation was added to the issue (in UTC). Required. + :vartype added_at: ~datetime.datetime + :ivar last_modified_at: The last update time of this relation (in UTC). Required. + :vartype last_modified_at: ~datetime.datetime + """ + + _validation = { + "id": {"required": True}, + "relevance": {"required": True}, + "origin": {"required": True, "readonly": True}, + "added_at": {"required": True, "readonly": True}, + "last_modified_at": {"required": True, "readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "relevance": {"key": "relevance", "type": "str"}, + "origin": {"key": "origin", "type": "Origin"}, + "added_at": {"key": "addedAt", "type": "iso-8601"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, + } + + def __init__( + self, *, id: str, relevance: Union[str, "_models.Relevance"], **kwargs: Any # pylint: disable=redefined-builtin + ) -> None: + """ + :keyword id: The alert ID. Required. + :paramtype id: str + :keyword relevance: The alerts's relevance status. Required. Known values are: "None", + "Relevant", and "Irrelevant". + :paramtype relevance: str or ~azure.mgmt.alertsmanagement.models.Relevance + """ + super().__init__(**kwargs) + self.id = id + self.relevance = relevance + self.origin: Optional["_models.Origin"] = None + self.added_at: Optional[datetime.datetime] = None + self.last_modified_at: Optional[datetime.datetime] = None + + +class RelatedAlertAnomalyInsight(_serialization.Model): + """The insight for a related alert. + + All required parameters must be populated in order to send to server. + + :ivar fired_time: The time when the alert was fired (in UTC). Required. + :vartype fired_time: ~datetime.datetime + :ivar anomaly_time: The time when the anomaly was detected (in UTC). Required. + :vartype anomaly_time: ~datetime.datetime + """ + + _validation = { + "fired_time": {"required": True}, + "anomaly_time": {"required": True}, + } + + _attribute_map = { + "fired_time": {"key": "firedTime", "type": "iso-8601"}, + "anomaly_time": {"key": "anomalyTime", "type": "iso-8601"}, + } + + def __init__(self, *, fired_time: datetime.datetime, anomaly_time: datetime.datetime, **kwargs: Any) -> None: + """ + :keyword fired_time: The time when the alert was fired (in UTC). Required. + :paramtype fired_time: ~datetime.datetime + :keyword anomaly_time: The time when the anomaly was detected (in UTC). Required. + :paramtype anomaly_time: ~datetime.datetime + """ + super().__init__(**kwargs) + self.fired_time = fired_time + self.anomaly_time = anomaly_time + + +class RelatedAlertData(_serialization.Model): + """The data details for alerts. + + All required parameters must be populated in order to send to server. + + :ivar fired_alert_id: The fired alert id. Required. + :vartype fired_alert_id: str + """ + + _validation = { + "fired_alert_id": {"required": True}, + } + + _attribute_map = { + "fired_alert_id": {"key": "firedAlertId", "type": "str"}, + } + + def __init__(self, *, fired_alert_id: str, **kwargs: Any) -> None: + """ + :keyword fired_alert_id: The fired alert id. Required. + :paramtype fired_alert_id: str + """ + super().__init__(**kwargs) + self.fired_alert_id = fired_alert_id + + +class RelatedAlertDetails(DetailsBase): + """A related alert details. + + All required parameters must be populated in order to send to server. + + :ivar details_type: The type of details. Required. Known values are: "Investigation", + "Finding", "AzureMetric", "AbnormalEvent", "RelatedAlert", "ResourceHealth", and "Diagnostics". + :vartype details_type: str or ~azure.mgmt.alertsmanagement.models.DetailsType + :ivar category: The details category. Required. Known values are: "Investigation", "Metric", + "Log", "Alert", "ResourceHealth", and "Diagnostics". + :vartype category: str or ~azure.mgmt.alertsmanagement.models.CategoryType + :ivar resource_ids: The resource ids related to the anomaly. + :vartype resource_ids: list[str] + :ivar data: The details data, which could be user generated or system generated. Required. + :vartype data: ~azure.mgmt.alertsmanagement.models.RelatedAlertData + :ivar insight: Insight about the anomaly, this is system generated. Required. + :vartype insight: ~azure.mgmt.alertsmanagement.models.RelatedAlertAnomalyInsight + """ + + _validation = { + "details_type": {"required": True}, + "category": {"required": True}, + "data": {"required": True}, + "insight": {"required": True}, + } + + _attribute_map = { + "details_type": {"key": "detailsType", "type": "str"}, + "category": {"key": "category", "type": "str"}, + "resource_ids": {"key": "resourceIds", "type": "[str]"}, + "data": {"key": "data", "type": "RelatedAlertData"}, + "insight": {"key": "insight", "type": "RelatedAlertAnomalyInsight"}, + } + + def __init__( + self, + *, + category: Union[str, "_models.CategoryType"], + data: "_models.RelatedAlertData", + insight: "_models.RelatedAlertAnomalyInsight", + resource_ids: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword category: The details category. Required. Known values are: "Investigation", "Metric", + "Log", "Alert", "ResourceHealth", and "Diagnostics". + :paramtype category: str or ~azure.mgmt.alertsmanagement.models.CategoryType + :keyword resource_ids: The resource ids related to the anomaly. + :paramtype resource_ids: list[str] + :keyword data: The details data, which could be user generated or system generated. Required. + :paramtype data: ~azure.mgmt.alertsmanagement.models.RelatedAlertData + :keyword insight: Insight about the anomaly, this is system generated. Required. + :paramtype insight: ~azure.mgmt.alertsmanagement.models.RelatedAlertAnomalyInsight + """ + super().__init__(category=category, resource_ids=resource_ids, **kwargs) + self.details_type: str = "RelatedAlert" + self.data = data + self.insight = insight + + +class RelatedAlerts(_serialization.Model): + """A list of related alerts. + + All required parameters must be populated in order to send to server. + + :ivar value: A list of related alerts. Required. + :vartype value: list[~azure.mgmt.alertsmanagement.models.RelatedAlert] + """ + + _validation = { + "value": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[RelatedAlert]"}, + } + + def __init__(self, *, value: List["_models.RelatedAlert"], **kwargs: Any) -> None: + """ + :keyword value: A list of related alerts. Required. + :paramtype value: list[~azure.mgmt.alertsmanagement.models.RelatedAlert] + """ + super().__init__(**kwargs) + self.value = value + + +class RelatedResource(_serialization.Model): + """Properties of a resource which is related to the issue. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The resource ID. Required. + :vartype id: str + :ivar relevance: The resource's relevance status. Required. Known values are: "None", + "Relevant", and "Irrelevant". + :vartype relevance: str or ~azure.mgmt.alertsmanagement.models.Relevance + :ivar origin: The source that related the resource to the issue. Required. + :vartype origin: ~azure.mgmt.alertsmanagement.models.Origin + :ivar added_at: The time this relation was added to the issue (in UTC). Required. + :vartype added_at: ~datetime.datetime + :ivar last_modified_at: The last update time of this relation (in UTC). Required. + :vartype last_modified_at: ~datetime.datetime """ _validation = { - "id": {"readonly": True}, - "name": {"readonly": True}, - "type": {"readonly": True}, - "system_data": {"readonly": True}, - "location": {"required": True}, - "scopes": {"required": True}, - "rules": {"required": True}, + "id": {"required": True}, + "relevance": {"required": True}, + "origin": {"required": True, "readonly": True}, + "added_at": {"required": True, "readonly": True}, + "last_modified_at": {"required": True, "readonly": True}, } _attribute_map = { "id": {"key": "id", "type": "str"}, - "name": {"key": "name", "type": "str"}, - "type": {"key": "type", "type": "str"}, - "system_data": {"key": "systemData", "type": "SystemData"}, - "tags": {"key": "tags", "type": "{str}"}, - "location": {"key": "location", "type": "str"}, - "description": {"key": "properties.description", "type": "str"}, - "enabled": {"key": "properties.enabled", "type": "bool"}, - "cluster_name": {"key": "properties.clusterName", "type": "str"}, - "scopes": {"key": "properties.scopes", "type": "[str]"}, - "interval": {"key": "properties.interval", "type": "str"}, - "rules": {"key": "properties.rules", "type": "[PrometheusRule]"}, + "relevance": {"key": "relevance", "type": "str"}, + "origin": {"key": "origin", "type": "Origin"}, + "added_at": {"key": "addedAt", "type": "iso-8601"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, } def __init__( - self, - *, - location: str, - scopes: List[str], - rules: List["_models.PrometheusRule"], - tags: Optional[Dict[str, str]] = None, - description: Optional[str] = None, - enabled: Optional[bool] = None, - cluster_name: Optional[str] = None, - interval: Optional[str] = None, - **kwargs - ): + self, *, id: str, relevance: Union[str, "_models.Relevance"], **kwargs: Any # pylint: disable=redefined-builtin + ) -> None: """ - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword location: The geo-location where the resource lives. Required. - :paramtype location: str - :keyword description: the description of the Prometheus rule group that will be included in the - alert email. - :paramtype description: str - :keyword enabled: the flag that indicates whether the Prometheus rule group is enabled. - :paramtype enabled: bool - :keyword cluster_name: the cluster name of the rule group evaluation. - :paramtype cluster_name: str - :keyword scopes: the list of resource id's that this rule group is scoped to. Required. - :paramtype scopes: list[str] - :keyword interval: the interval in which to run the Prometheus rule group represented in ISO - 8601 duration format. Should be between 1 and 15 minutes. - :paramtype interval: str - :keyword rules: defines the rules in the Prometheus rule group. Required. - :paramtype rules: list[~azure.mgmt.alertsmanagement.models.PrometheusRule] + :keyword id: The resource ID. Required. + :paramtype id: str + :keyword relevance: The resource's relevance status. Required. Known values are: "None", + "Relevant", and "Irrelevant". + :paramtype relevance: str or ~azure.mgmt.alertsmanagement.models.Relevance """ - super().__init__(tags=tags, location=location, **kwargs) - self.description = description - self.enabled = enabled - self.cluster_name = cluster_name - self.scopes = scopes - self.interval = interval - self.rules = rules + super().__init__(**kwargs) + self.id = id + self.relevance = relevance + self.origin: Optional["_models.Origin"] = None + self.added_at: Optional[datetime.datetime] = None + self.last_modified_at: Optional[datetime.datetime] = None -class PrometheusRuleGroupResourceCollection(_serialization.Model): - """Represents a collection of alert rule resources. +class RelatedResources(_serialization.Model): + """A list of related resources. - :ivar value: the values for the alert rule resources. - :vartype value: list[~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource] + All required parameters must be populated in order to send to server. + + :ivar value: A list of related resources. Required. + :vartype value: list[~azure.mgmt.alertsmanagement.models.RelatedResource] """ + _validation = { + "value": {"required": True}, + } + _attribute_map = { - "value": {"key": "value", "type": "[PrometheusRuleGroupResource]"}, + "value": {"key": "value", "type": "[RelatedResource]"}, } - def __init__(self, *, value: Optional[List["_models.PrometheusRuleGroupResource"]] = None, **kwargs): + def __init__(self, *, value: List["_models.RelatedResource"], **kwargs: Any) -> None: """ - :keyword value: the values for the alert rule resources. - :paramtype value: list[~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource] + :keyword value: A list of related resources. Required. + :paramtype value: list[~azure.mgmt.alertsmanagement.models.RelatedResource] """ super().__init__(**kwargs) self.value = value -class PrometheusRuleGroupResourcePatch(_serialization.Model): - """The Prometheus rule group resource for patch operations. +class RemoveAllActionGroups(Action): + """Indicates if all action groups should be removed. - :ivar tags: Resource tags. - :vartype tags: dict[str, str] - :ivar properties: - :vartype properties: - ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResourcePatchProperties + All required parameters must be populated in order to send to server. + + :ivar action_type: Action that should be applied. Required. Known values are: "AddActionGroups" + and "RemoveAllActionGroups". + :vartype action_type: str or ~azure.mgmt.alertsmanagement.models.ActionType """ + _validation = { + "action_type": {"required": True}, + } + _attribute_map = { - "tags": {"key": "tags", "type": "{str}"}, - "properties": {"key": "properties", "type": "PrometheusRuleGroupResourcePatchProperties"}, + "action_type": {"key": "actionType", "type": "str"}, + } + + def __init__(self, **kwargs: Any) -> None: + """ """ + super().__init__(**kwargs) + self.action_type: str = "RemoveAllActionGroups" + + +class ResourceHealthDetails(DetailsBase): + """A resource health details. + + All required parameters must be populated in order to send to server. + + :ivar details_type: The type of details. Required. Known values are: "Investigation", + "Finding", "AzureMetric", "AbnormalEvent", "RelatedAlert", "ResourceHealth", and "Diagnostics". + :vartype details_type: str or ~azure.mgmt.alertsmanagement.models.DetailsType + :ivar category: The details category. Required. Known values are: "Investigation", "Metric", + "Log", "Alert", "ResourceHealth", and "Diagnostics". + :vartype category: str or ~azure.mgmt.alertsmanagement.models.CategoryType + :ivar resource_ids: The resource ids related to the anomaly. + :vartype resource_ids: list[str] + :ivar insight: Insight about the anomaly, this is system generated. Required. + :vartype insight: ~azure.mgmt.alertsmanagement.models.ResourceHealthInsight + """ + + _validation = { + "details_type": {"required": True}, + "category": {"required": True}, + "insight": {"required": True}, + } + + _attribute_map = { + "details_type": {"key": "detailsType", "type": "str"}, + "category": {"key": "category", "type": "str"}, + "resource_ids": {"key": "resourceIds", "type": "[str]"}, + "insight": {"key": "insight", "type": "ResourceHealthInsight"}, } def __init__( self, *, - tags: Optional[Dict[str, str]] = None, - properties: Optional["_models.PrometheusRuleGroupResourcePatchProperties"] = None, - **kwargs - ): + category: Union[str, "_models.CategoryType"], + insight: "_models.ResourceHealthInsight", + resource_ids: Optional[List[str]] = None, + **kwargs: Any + ) -> None: """ - :keyword tags: Resource tags. - :paramtype tags: dict[str, str] - :keyword properties: - :paramtype properties: - ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResourcePatchProperties + :keyword category: The details category. Required. Known values are: "Investigation", "Metric", + "Log", "Alert", "ResourceHealth", and "Diagnostics". + :paramtype category: str or ~azure.mgmt.alertsmanagement.models.CategoryType + :keyword resource_ids: The resource ids related to the anomaly. + :paramtype resource_ids: list[str] + :keyword insight: Insight about the anomaly, this is system generated. Required. + :paramtype insight: ~azure.mgmt.alertsmanagement.models.ResourceHealthInsight """ - super().__init__(**kwargs) - self.tags = tags - self.properties = properties + super().__init__(category=category, resource_ids=resource_ids, **kwargs) + self.details_type: str = "ResourceHealth" + self.insight = insight -class PrometheusRuleGroupResourcePatchProperties(_serialization.Model): - """PrometheusRuleGroupResourcePatchProperties. +class ResourceHealthInsight(_serialization.Model): + """The insight for resource health. - :ivar enabled: the flag that indicates whether the Prometheus rule group is enabled. - :vartype enabled: bool + All required parameters must be populated in order to send to server. + + :ivar availability_state: The availability state of the resource. Required. Known values are: + "Available", "Degraded", "Unavailable", "Unknown", and "UserInitiated". + :vartype availability_state: str or ~azure.mgmt.alertsmanagement.models.AvailabilityState + :ivar title: The title of the resource health event. Required. + :vartype title: str + :ivar summary: The summary of the resource health event. Required. + :vartype summary: str + :ivar occurred_time: The time when the resource health event occurred (in UTC). Required. + :vartype occurred_time: ~datetime.datetime """ + _validation = { + "availability_state": {"required": True}, + "title": {"required": True}, + "summary": {"required": True}, + "occurred_time": {"required": True}, + } + _attribute_map = { - "enabled": {"key": "enabled", "type": "bool"}, + "availability_state": {"key": "availabilityState", "type": "str"}, + "title": {"key": "title", "type": "str"}, + "summary": {"key": "summary", "type": "str"}, + "occurred_time": {"key": "occurredTime", "type": "iso-8601"}, } - def __init__(self, *, enabled: Optional[bool] = None, **kwargs): + def __init__( + self, + *, + availability_state: Union[str, "_models.AvailabilityState"], + title: str, + summary: str, + occurred_time: datetime.datetime, + **kwargs: Any + ) -> None: """ - :keyword enabled: the flag that indicates whether the Prometheus rule group is enabled. - :paramtype enabled: bool + :keyword availability_state: The availability state of the resource. Required. Known values + are: "Available", "Degraded", "Unavailable", "Unknown", and "UserInitiated". + :paramtype availability_state: str or ~azure.mgmt.alertsmanagement.models.AvailabilityState + :keyword title: The title of the resource health event. Required. + :paramtype title: str + :keyword summary: The summary of the resource health event. Required. + :paramtype summary: str + :keyword occurred_time: The time when the resource health event occurred (in UTC). Required. + :paramtype occurred_time: ~datetime.datetime """ super().__init__(**kwargs) - self.enabled = enabled + self.availability_state = availability_state + self.title = title + self.summary = summary + self.occurred_time = occurred_time + + +class RuleArmTemplate(_serialization.Model): + """A complete ARM template to deploy the alert rules. + + All required parameters must be populated in order to send to server. + + :ivar schema: JSON schema reference. Required. + :vartype schema: str + :ivar content_version: A 4 number format for the version number of this template file. For + example, 1.0.0.0. Required. + :vartype content_version: str + :ivar variables: Variable definitions. Required. + :vartype variables: JSON + :ivar parameters: Input parameter definitions. Required. + :vartype parameters: JSON + :ivar resources: Alert rule resource definitions. Required. + :vartype resources: list[JSON] + """ + _validation = { + "schema": {"required": True}, + "content_version": {"required": True, "pattern": r"(^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$)"}, + "variables": {"required": True}, + "parameters": {"required": True}, + "resources": {"required": True}, + } -class PrometheusRuleResolveConfiguration(_serialization.Model): - """Specifies the Prometheus alert rule configuration. + _attribute_map = { + "schema": {"key": "$schema", "type": "str"}, + "content_version": {"key": "contentVersion", "type": "str"}, + "variables": {"key": "variables", "type": "object"}, + "parameters": {"key": "parameters", "type": "object"}, + "resources": {"key": "resources", "type": "[object]"}, + } - :ivar auto_resolved: the flag that indicates whether or not to auto resolve a fired alert. - :vartype auto_resolved: bool - :ivar time_to_resolve: the duration a rule must evaluate as healthy before the fired alert is - automatically resolved represented in ISO 8601 duration format. Should be between 1 and 15 - minutes. - :vartype time_to_resolve: str + def __init__( + self, + *, + schema: str, + content_version: str, + variables: JSON, + parameters: JSON, + resources: List[JSON], + **kwargs: Any + ) -> None: + """ + :keyword schema: JSON schema reference. Required. + :paramtype schema: str + :keyword content_version: A 4 number format for the version number of this template file. For + example, 1.0.0.0. Required. + :paramtype content_version: str + :keyword variables: Variable definitions. Required. + :paramtype variables: JSON + :keyword parameters: Input parameter definitions. Required. + :paramtype parameters: JSON + :keyword resources: Alert rule resource definitions. Required. + :paramtype resources: list[JSON] + """ + super().__init__(**kwargs) + self.schema = schema + self.content_version = content_version + self.variables = variables + self.parameters = parameters + self.resources = resources + + +class RulePreviewResult(_serialization.Model): + """A rule preview result containing a dimension combination and an array of evaluations. + + :ivar dimension_combinations: The list of dimensions for the evaluation. + :vartype dimension_combinations: + list[~azure.mgmt.alertsmanagement.models.DimensionNameAndValue] + :ivar evaluations: An array of evaluations. + :vartype evaluations: list[~azure.mgmt.alertsmanagement.models.Evaluation] """ _attribute_map = { - "auto_resolved": {"key": "autoResolved", "type": "bool"}, - "time_to_resolve": {"key": "timeToResolve", "type": "str"}, + "dimension_combinations": {"key": "dimensionCombinations", "type": "[DimensionNameAndValue]"}, + "evaluations": {"key": "evaluations", "type": "[Evaluation]"}, } - def __init__(self, *, auto_resolved: Optional[bool] = None, time_to_resolve: Optional[str] = None, **kwargs): + def __init__( + self, + *, + dimension_combinations: Optional[List["_models.DimensionNameAndValue"]] = None, + evaluations: Optional[List["_models.Evaluation"]] = None, + **kwargs: Any + ) -> None: """ - :keyword auto_resolved: the flag that indicates whether or not to auto resolve a fired alert. - :paramtype auto_resolved: bool - :keyword time_to_resolve: the duration a rule must evaluate as healthy before the fired alert - is automatically resolved represented in ISO 8601 duration format. Should be between 1 and 15 - minutes. - :paramtype time_to_resolve: str + :keyword dimension_combinations: The list of dimensions for the evaluation. + :paramtype dimension_combinations: + list[~azure.mgmt.alertsmanagement.models.DimensionNameAndValue] + :keyword evaluations: An array of evaluations. + :paramtype evaluations: list[~azure.mgmt.alertsmanagement.models.Evaluation] """ super().__init__(**kwargs) - self.auto_resolved = auto_resolved - self.time_to_resolve = time_to_resolve + self.dimension_combinations = dimension_combinations + self.evaluations = evaluations -class RemoveAllActionGroups(Action): - """Indicates if all action groups should be removed. +class RunParameters(_serialization.Model): + """The parameters used to run the investigation. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar action_type: Action that should be applied. Required. Known values are: "AddActionGroups" - and "RemoveAllActionGroups". - :vartype action_type: str or ~azure.mgmt.alertsmanagement.models.ActionType + :ivar impact_time: The impact time to investigate (in UTC). Required. + :vartype impact_time: ~datetime.datetime + :ivar alerts: The alerts used to run the investigation. Required. + :vartype alerts: list[~azure.mgmt.alertsmanagement.models.InvestigationScope] + :ivar resources: The resources used to run the investigation. Required. + :vartype resources: list[~azure.mgmt.alertsmanagement.models.InvestigationScope] """ _validation = { - "action_type": {"required": True}, + "impact_time": {"required": True}, + "alerts": {"required": True}, + "resources": {"required": True}, } _attribute_map = { - "action_type": {"key": "actionType", "type": "str"}, + "impact_time": {"key": "impactTime", "type": "iso-8601"}, + "alerts": {"key": "alerts", "type": "[InvestigationScope]"}, + "resources": {"key": "resources", "type": "[InvestigationScope]"}, } - def __init__(self, **kwargs): - """ """ + def __init__( + self, + *, + impact_time: datetime.datetime, + alerts: List["_models.InvestigationScope"], + resources: List["_models.InvestigationScope"], + **kwargs: Any + ) -> None: + """ + :keyword impact_time: The impact time to investigate (in UTC). Required. + :paramtype impact_time: ~datetime.datetime + :keyword alerts: The alerts used to run the investigation. Required. + :paramtype alerts: list[~azure.mgmt.alertsmanagement.models.InvestigationScope] + :keyword resources: The resources used to run the investigation. Required. + :paramtype resources: list[~azure.mgmt.alertsmanagement.models.InvestigationScope] + """ super().__init__(**kwargs) - self.action_type: str = "RemoveAllActionGroups" + self.impact_time = impact_time + self.alerts = alerts + self.resources = resources class Schedule(_serialization.Model): @@ -2068,8 +5738,8 @@ def __init__( effective_until: Optional[str] = None, time_zone: Optional[str] = None, recurrences: Optional[List["_models.Recurrence"]] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword effective_from: Scheduling effective from time. Date-Time in ISO-8601 format without timezone suffix. @@ -2089,7 +5759,7 @@ def __init__( self.recurrences = recurrences -class SmartGroup(Resource): # pylint: disable=too-many-instance-attributes +class SmartGroup(ResourceAutoGenerated): """Set of related alerts grouped together smartly by AMS. Variables are only populated by the server, and will be ignored when sending a request. @@ -2180,8 +5850,8 @@ def __init__( alert_states: Optional[List["_models.SmartGroupAggregatedProperty"]] = None, alert_severities: Optional[List["_models.SmartGroupAggregatedProperty"]] = None, next_link: Optional[str] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword alerts_count: Total number of alerts in smart group. :paramtype alerts_count: int @@ -2210,11 +5880,11 @@ def __init__( """ super().__init__(**kwargs) self.alerts_count = alerts_count - self.smart_group_state = None - self.severity = None - self.start_date_time = None - self.last_modified_date_time = None - self.last_modified_user_name = None + self.smart_group_state: Optional[Union[str, "_models.State"]] = None + self.severity: Optional[Union[str, "_models.Severity"]] = None + self.start_date_time: Optional[datetime.datetime] = None + self.last_modified_date_time: Optional[datetime.datetime] = None + self.last_modified_user_name: Optional[str] = None self.resources = resources self.resource_types = resource_types self.resource_groups = resource_groups @@ -2239,7 +5909,7 @@ class SmartGroupAggregatedProperty(_serialization.Model): "count": {"key": "count", "type": "int"}, } - def __init__(self, *, name: Optional[str] = None, count: Optional[int] = None, **kwargs): + def __init__(self, *, name: Optional[str] = None, count: Optional[int] = None, **kwargs: Any) -> None: """ :keyword name: Name of the type. :paramtype name: str @@ -2251,7 +5921,7 @@ def __init__(self, *, name: Optional[str] = None, count: Optional[int] = None, * self.count = count -class SmartGroupModification(Resource): +class SmartGroupModification(ResourceAutoGenerated): """Alert Modification details. Variables are only populated by the server, and will be ignored when sending a request. @@ -2279,7 +5949,9 @@ class SmartGroupModification(Resource): "properties": {"key": "properties", "type": "SmartGroupModificationProperties"}, } - def __init__(self, *, properties: Optional["_models.SmartGroupModificationProperties"] = None, **kwargs): + def __init__( + self, *, properties: Optional["_models.SmartGroupModificationProperties"] = None, **kwargs: Any + ) -> None: """ :keyword properties: Properties of the smartGroup modification item. :paramtype properties: ~azure.mgmt.alertsmanagement.models.SmartGroupModificationProperties @@ -2329,8 +6001,8 @@ def __init__( modified_by: Optional[str] = None, comments: Optional[str] = None, description: Optional[str] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword modification_event: Reason for the modification. Known values are: "SmartGroupCreated", "StateChange", "AlertAdded", and "AlertRemoved". @@ -2387,8 +6059,8 @@ def __init__( *, modifications: Optional[List["_models.SmartGroupModificationItem"]] = None, next_link: Optional[str] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword modifications: Modification details. :paramtype modifications: list[~azure.mgmt.alertsmanagement.models.SmartGroupModificationItem] @@ -2396,7 +6068,7 @@ def __init__( :paramtype next_link: str """ super().__init__(**kwargs) - self.smart_group_id = None + self.smart_group_id: Optional[str] = None self.modifications = modifications self.next_link = next_link @@ -2416,8 +6088,8 @@ class SmartGroupsList(_serialization.Model): } def __init__( - self, *, next_link: Optional[str] = None, value: Optional[List["_models.SmartGroup"]] = None, **kwargs - ): + self, *, next_link: Optional[str] = None, value: Optional[List["_models.SmartGroup"]] = None, **kwargs: Any + ) -> None: """ :keyword next_link: URL to fetch the next set of alerts. :paramtype next_link: str @@ -2429,6 +6101,97 @@ def __init__( self.value = value +class StartInvestigationParameters(_serialization.Model): + """Parameters provided to start an investigation operation. + + All required parameters must be populated in order to send to server. + + :ivar impact_time: The impact time to use for this investigation - by default, the impact time + from the issue is used (in UTC). + :vartype impact_time: ~datetime.datetime + :ivar investigation_scopes: The scope of the investigation (resources and alerts) - by default, + the resources and alerts related to the issue are used. Required. + :vartype investigation_scopes: list[~azure.mgmt.alertsmanagement.models.InvestigationScope] + """ + + _validation = { + "investigation_scopes": {"required": True}, + } + + _attribute_map = { + "impact_time": {"key": "impactTime", "type": "iso-8601"}, + "investigation_scopes": {"key": "investigationScopes", "type": "[InvestigationScope]"}, + } + + def __init__( + self, + *, + investigation_scopes: List["_models.InvestigationScope"], + impact_time: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> None: + """ + :keyword impact_time: The impact time to use for this investigation - by default, the impact + time from the issue is used (in UTC). + :paramtype impact_time: ~datetime.datetime + :keyword investigation_scopes: The scope of the investigation (resources and alerts) - by + default, the resources and alerts related to the issue are used. Required. + :paramtype investigation_scopes: list[~azure.mgmt.alertsmanagement.models.InvestigationScope] + """ + super().__init__(**kwargs) + self.impact_time = impact_time + self.investigation_scopes = investigation_scopes + + +class Summary(_serialization.Model): + """The text summary of the investigation entity. + + All required parameters must be populated in order to send to server. + + :ivar title: The title of the entity. Required. + :vartype title: str + :ivar what_happened: Description of what happened. Required. + :vartype what_happened: str + :ivar possible_explanation: Possible explanation of the entity. Required. + :vartype possible_explanation: str + :ivar what_can_be_done_next: Suggestions for next steps. Required. + :vartype what_can_be_done_next: str + """ + + _validation = { + "title": {"required": True}, + "what_happened": {"required": True}, + "possible_explanation": {"required": True}, + "what_can_be_done_next": {"required": True}, + } + + _attribute_map = { + "title": {"key": "title", "type": "str"}, + "what_happened": {"key": "whatHappened", "type": "str"}, + "possible_explanation": {"key": "possibleExplanation", "type": "str"}, + "what_can_be_done_next": {"key": "whatCanBeDoneNext", "type": "str"}, + } + + def __init__( + self, *, title: str, what_happened: str, possible_explanation: str, what_can_be_done_next: str, **kwargs: Any + ) -> None: + """ + :keyword title: The title of the entity. Required. + :paramtype title: str + :keyword what_happened: Description of what happened. Required. + :paramtype what_happened: str + :keyword possible_explanation: Possible explanation of the entity. Required. + :paramtype possible_explanation: str + :keyword what_can_be_done_next: Suggestions for next steps. Required. + :paramtype what_can_be_done_next: str + """ + super().__init__(**kwargs) + self.title = title + self.what_happened = what_happened + self.possible_explanation = possible_explanation + self.what_can_be_done_next = what_can_be_done_next + + class SystemData(_serialization.Model): """Metadata pertaining to creation and last modification of the resource. @@ -2466,8 +6229,8 @@ def __init__( last_modified_by: Optional[str] = None, last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, last_modified_at: Optional[datetime.datetime] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword created_by: The identity that created the resource. :paramtype created_by: str @@ -2493,10 +6256,202 @@ def __init__( self.last_modified_at = last_modified_at +class TracePatternAnomaly(_serialization.Model): + """The trace pattern anomaly. + + All required parameters must be populated in order to send to server. + + :ivar generated_message: A generated message that describes the anomalous trace pattern. + Required. + :vartype generated_message: str + :ivar pattern: The anomalous trace pattern that was detected in the Application Insights traces + table. Required. + :vartype pattern: str + :ivar sample_event: The sample event of the trace pattern. Required. + :vartype sample_event: str + :ivar count: The count of the trace occurrences. Required. + :vartype count: int + """ + + _validation = { + "generated_message": {"required": True}, + "pattern": {"required": True}, + "sample_event": {"required": True}, + "count": {"required": True}, + } + + _attribute_map = { + "generated_message": {"key": "generatedMessage", "type": "str"}, + "pattern": {"key": "pattern", "type": "str"}, + "sample_event": {"key": "sampleEvent", "type": "str"}, + "count": {"key": "count", "type": "int"}, + } + + def __init__(self, *, generated_message: str, pattern: str, sample_event: str, count: int, **kwargs: Any) -> None: + """ + :keyword generated_message: A generated message that describes the anomalous trace pattern. + Required. + :paramtype generated_message: str + :keyword pattern: The anomalous trace pattern that was detected in the Application Insights + traces table. Required. + :paramtype pattern: str + :keyword sample_event: The sample event of the trace pattern. Required. + :paramtype sample_event: str + :keyword count: The count of the trace occurrences. Required. + :paramtype count: int + """ + super().__init__(**kwargs) + self.generated_message = generated_message + self.pattern = pattern + self.sample_event = sample_event + self.count = count + + +class TransactionEdge(_serialization.Model): + """The edge of a transaction pattern. + + All required parameters must be populated in order to send to server. + + :ivar start: The textual identifier of the start node of the edge. Required. + :vartype start: str + :ivar end: The textual identifier of the end node of the edge. Required. + :vartype end: str + :ivar metadata: The edge's metadata. Required. + :vartype metadata: dict[str, str] + """ + + _validation = { + "start": {"required": True}, + "end": {"required": True}, + "metadata": {"required": True}, + } + + _attribute_map = { + "start": {"key": "start", "type": "str"}, + "end": {"key": "end", "type": "str"}, + "metadata": {"key": "metadata", "type": "{str}"}, + } + + def __init__(self, *, start: str, end: str, metadata: Dict[str, str], **kwargs: Any) -> None: + """ + :keyword start: The textual identifier of the start node of the edge. Required. + :paramtype start: str + :keyword end: The textual identifier of the end node of the edge. Required. + :paramtype end: str + :keyword metadata: The edge's metadata. Required. + :paramtype metadata: dict[str, str] + """ + super().__init__(**kwargs) + self.start = start + self.end = end + self.metadata = metadata + + +class TransactionNode(_serialization.Model): + """The node of a transaction pattern. + + All required parameters must be populated in order to send to server. + + :ivar id: The textual identifier of the transaction participant's node. Required. + :vartype id: str + :ivar metadata: The node's metadata. Required. + :vartype metadata: dict[str, str] + """ + + _validation = { + "id": {"required": True}, + "metadata": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "metadata": {"key": "metadata", "type": "{str}"}, + } + + def __init__( + self, *, id: str, metadata: Dict[str, str], **kwargs: Any # pylint: disable=redefined-builtin + ) -> None: + """ + :keyword id: The textual identifier of the transaction participant's node. Required. + :paramtype id: str + :keyword metadata: The node's metadata. Required. + :paramtype metadata: dict[str, str] + """ + super().__init__(**kwargs) + self.id = id + self.metadata = metadata + + +class TransactionPatternAnomaly(_serialization.Model): + """The transaction pattern anomaly. + + All required parameters must be populated in order to send to server. + + :ivar name: The name of the transaction pattern. Required. + :vartype name: str + :ivar generated_message: A generated message that describes the anomalous transaction pattern. + Required. + :vartype generated_message: str + :ivar target_node: The textual identifier of the target of the anomalous transaction. Required. + :vartype target_node: str + :ivar nodes: The nodes of the transaction pattern. Required. + :vartype nodes: list[~azure.mgmt.alertsmanagement.models.TransactionNode] + :ivar edges: The edges of the transaction pattern. Required. + :vartype edges: list[~azure.mgmt.alertsmanagement.models.TransactionEdge] + """ + + _validation = { + "name": {"required": True}, + "generated_message": {"required": True}, + "target_node": {"required": True}, + "nodes": {"required": True}, + "edges": {"required": True}, + } + + _attribute_map = { + "name": {"key": "name", "type": "str"}, + "generated_message": {"key": "generatedMessage", "type": "str"}, + "target_node": {"key": "targetNode", "type": "str"}, + "nodes": {"key": "nodes", "type": "[TransactionNode]"}, + "edges": {"key": "edges", "type": "[TransactionEdge]"}, + } + + def __init__( + self, + *, + name: str, + generated_message: str, + target_node: str, + nodes: List["_models.TransactionNode"], + edges: List["_models.TransactionEdge"], + **kwargs: Any + ) -> None: + """ + :keyword name: The name of the transaction pattern. Required. + :paramtype name: str + :keyword generated_message: A generated message that describes the anomalous transaction + pattern. Required. + :paramtype generated_message: str + :keyword target_node: The textual identifier of the target of the anomalous transaction. + Required. + :paramtype target_node: str + :keyword nodes: The nodes of the transaction pattern. Required. + :paramtype nodes: list[~azure.mgmt.alertsmanagement.models.TransactionNode] + :keyword edges: The edges of the transaction pattern. Required. + :paramtype edges: list[~azure.mgmt.alertsmanagement.models.TransactionEdge] + """ + super().__init__(**kwargs) + self.name = name + self.generated_message = generated_message + self.target_node = target_node + self.nodes = nodes + self.edges = edges + + class WeeklyRecurrence(Recurrence): """Weekly recurrence object. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar recurrence_type: Specifies when the recurrence should be applied. Required. Known values are: "Daily", "Weekly", and "Monthly". @@ -2527,8 +6482,8 @@ def __init__( days_of_week: List[Union[str, "_models.DaysOfWeek"]], start_time: Optional[str] = None, end_time: Optional[str] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword start_time: Start time for recurrence. :paramtype start_time: str diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/__init__.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/__init__.py index c8dd1e48dcf0..19989121f059 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/__init__.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/__init__.py @@ -5,23 +5,35 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._alert_processing_rules_operations import AlertProcessingRulesOperations -from ._prometheus_rule_groups_operations import PrometheusRuleGroupsOperations -from ._operations import Operations -from ._alerts_operations import AlertsOperations -from ._smart_groups_operations import SmartGroupsOperations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._prometheus_rule_groups_operations import PrometheusRuleGroupsOperations # type: ignore +from ._operations import Operations # type: ignore +from ._alerts_operations import AlertsOperations # type: ignore +from ._smart_groups_operations import SmartGroupsOperations # type: ignore +from ._alert_rule_recommendations_operations import AlertRuleRecommendationsOperations # type: ignore +from ._alert_processing_rules_operations import AlertProcessingRulesOperations # type: ignore +from ._issue_operations import IssueOperations # type: ignore +from ._alerts_management_client_operations import AlertsManagementClientOperationsMixin # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AlertProcessingRulesOperations", "PrometheusRuleGroupsOperations", "Operations", "AlertsOperations", "SmartGroupsOperations", + "AlertRuleRecommendationsOperations", + "AlertProcessingRulesOperations", + "IssueOperations", + "AlertsManagementClientOperationsMixin", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alert_processing_rules_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alert_processing_rules_operations.py index a9831118284f..78bce302a530 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alert_processing_rules_operations.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alert_processing_rules_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +6,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from collections.abc import MutableMapping +from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -19,20 +21,15 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +from .._configuration import AlertsManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -44,7 +41,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -55,7 +52,7 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -70,20 +67,20 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -100,21 +97,21 @@ def build_get_by_name_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{alertProcessingRuleName}", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "alertProcessingRuleName": _SERIALIZER.url("alert_processing_rule_name", alert_processing_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -131,7 +128,7 @@ def build_create_or_update_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -139,14 +136,14 @@ def build_create_or_update_request( _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{alertProcessingRuleName}", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "alertProcessingRuleName": _SERIALIZER.url("alert_processing_rule_name", alert_processing_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -165,21 +162,21 @@ def build_delete_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{alertProcessingRuleName}", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "alertProcessingRuleName": _SERIALIZER.url("alert_processing_rule_name", alert_processing_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -196,7 +193,7 @@ def build_update_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -204,14 +201,14 @@ def build_update_request( _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{alertProcessingRuleName}", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), "alertProcessingRuleName": _SERIALIZER.url("alert_processing_rule_name", alert_processing_rule_name, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -238,16 +235,15 @@ class AlertProcessingRulesOperations: def __init__(self, *args, **kwargs): input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AlertsManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AlertProcessingRule"]: """List all alert processing rules in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AlertProcessingRule or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.AlertProcessingRule] :raises ~azure.core.exceptions.HttpResponseError: @@ -255,10 +251,10 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AlertProcessi _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) cls: ClsType[_models.AlertProcessingRulesList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -269,22 +265,19 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.AlertProcessi def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AlertProcessingRulesList", pipeline_response) @@ -294,26 +287,23 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated4, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/actionRules" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -322,7 +312,6 @@ def list_by_resource_group( :param resource_group_name: Resource group name where the resource is created. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either AlertProcessingRule or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.AlertProcessingRule] :raises ~azure.core.exceptions.HttpResponseError: @@ -330,10 +319,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) cls: ClsType[_models.AlertProcessingRulesList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -344,23 +333,20 @@ def list_by_resource_group( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_group_request( + _request = build_list_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AlertProcessingRulesList", pipeline_response) @@ -370,26 +356,23 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated4, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules" - } - @distributed_trace def get_by_name( self, resource_group_name: str, alert_processing_rule_name: str, **kwargs: Any @@ -401,12 +384,11 @@ def get_by_name( :param alert_processing_rule_name: The name of the alert processing rule that needs to be fetched. Required. :type alert_processing_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertProcessingRule or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -417,45 +399,40 @@ def get_by_name( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) cls: ClsType[_models.AlertProcessingRule] = kwargs.pop("cls", None) - request = build_get_by_name_request( + _request = build_get_by_name_request( resource_group_name=resource_group_name, alert_processing_rule_name=alert_processing_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_by_name.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated4, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - deserialized = self._deserialize("AlertProcessingRule", pipeline_response) + deserialized = self._deserialize("AlertProcessingRule", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized + return cls(pipeline_response, deserialized, response_headers) # type: ignore - get_by_name.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{alertProcessingRuleName}" - } + return deserialized # type: ignore @overload def create_or_update( @@ -479,7 +456,6 @@ def create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertProcessingRule or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule :raises ~azure.core.exceptions.HttpResponseError: @@ -490,7 +466,7 @@ def create_or_update( self, resource_group_name: str, alert_processing_rule_name: str, - alert_processing_rule: IO, + alert_processing_rule: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -503,11 +479,10 @@ def create_or_update( created/updated. Required. :type alert_processing_rule_name: str :param alert_processing_rule: Alert processing rule to be created/updated. Required. - :type alert_processing_rule: IO + :type alert_processing_rule: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertProcessingRule or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule :raises ~azure.core.exceptions.HttpResponseError: @@ -518,7 +493,7 @@ def create_or_update( self, resource_group_name: str, alert_processing_rule_name: str, - alert_processing_rule: Union[_models.AlertProcessingRule, IO], + alert_processing_rule: Union[_models.AlertProcessingRule, IO[bytes]], **kwargs: Any ) -> _models.AlertProcessingRule: """Create or update an alert processing rule. @@ -528,18 +503,15 @@ def create_or_update( :param alert_processing_rule_name: The name of the alert processing rule that needs to be created/updated. Required. :type alert_processing_rule_name: str - :param alert_processing_rule: Alert processing rule to be created/updated. Is either a model - type or a IO type. Required. - :type alert_processing_rule: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param alert_processing_rule: Alert processing rule to be created/updated. Is either a + AlertProcessingRule type or a IO[bytes] type. Required. + :type alert_processing_rule: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule or + IO[bytes] :return: AlertProcessingRule or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -550,19 +522,19 @@ def create_or_update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AlertProcessingRule] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(alert_processing_rule, (IO, bytes)): + if isinstance(alert_processing_rule, (IOBase, bytes)): _content = alert_processing_rule else: _json = self._serialize.body(alert_processing_rule, "AlertProcessingRule") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, alert_processing_rule_name=alert_processing_rule_name, subscription_id=self._config.subscription_id, @@ -570,44 +542,33 @@ def create_or_update( content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated4, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} - if response.status_code == 200: - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - - deserialized = self._deserialize("AlertProcessingRule", pipeline_response) - - if response.status_code == 201: - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - deserialized = self._deserialize("AlertProcessingRule", pipeline_response) + deserialized = self._deserialize("AlertProcessingRule", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{alertProcessingRuleName}" - } - @distributed_trace def delete( # pylint: disable=inconsistent-return-statements self, resource_group_name: str, alert_processing_rule_name: str, **kwargs: Any @@ -619,12 +580,11 @@ def delete( # pylint: disable=inconsistent-return-statements :param alert_processing_rule_name: The name of the alert processing rule that needs to be deleted. Required. :type alert_processing_rule_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -635,45 +595,36 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, alert_processing_rule_name=alert_processing_rule_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated4, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} - if response.status_code == 200: - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - - if response.status_code == 204: - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) if cls: - return cls(pipeline_response, None, response_headers) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{alertProcessingRuleName}" - } + return cls(pipeline_response, None, response_headers) # type: ignore @overload def update( @@ -696,7 +647,6 @@ def update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertProcessingRule or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule :raises ~azure.core.exceptions.HttpResponseError: @@ -707,7 +657,7 @@ def update( self, resource_group_name: str, alert_processing_rule_name: str, - alert_processing_rule_patch: IO, + alert_processing_rule_patch: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -719,11 +669,10 @@ def update( :param alert_processing_rule_name: The name that needs to be updated. Required. :type alert_processing_rule_name: str :param alert_processing_rule_patch: Parameters supplied to the operation. Required. - :type alert_processing_rule_patch: IO + :type alert_processing_rule_patch: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertProcessingRule or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule :raises ~azure.core.exceptions.HttpResponseError: @@ -734,7 +683,7 @@ def update( self, resource_group_name: str, alert_processing_rule_name: str, - alert_processing_rule_patch: Union[_models.PatchObject, IO], + alert_processing_rule_patch: Union[_models.PatchObject, IO[bytes]], **kwargs: Any ) -> _models.AlertProcessingRule: """Enable, disable, or update tags for an alert processing rule. @@ -743,18 +692,14 @@ def update( :type resource_group_name: str :param alert_processing_rule_name: The name that needs to be updated. Required. :type alert_processing_rule_name: str - :param alert_processing_rule_patch: Parameters supplied to the operation. Is either a model - type or a IO type. Required. - :type alert_processing_rule_patch: ~azure.mgmt.alertsmanagement.models.PatchObject or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param alert_processing_rule_patch: Parameters supplied to the operation. Is either a + PatchObject type or a IO[bytes] type. Required. + :type alert_processing_rule_patch: ~azure.mgmt.alertsmanagement.models.PatchObject or IO[bytes] :return: AlertProcessingRule or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertProcessingRule :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -765,19 +710,19 @@ def update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-08-08"] = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2021-08-08-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.AlertProcessingRule] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(alert_processing_rule_patch, (IO, bytes)): + if isinstance(alert_processing_rule_patch, (IOBase, bytes)): _content = alert_processing_rule_patch else: _json = self._serialize.body(alert_processing_rule_patch, "PatchObject") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, alert_processing_rule_name=alert_processing_rule_name, subscription_id=self._config.subscription_id, @@ -785,34 +730,29 @@ def update( content_type=content_type, json=_json, content=_content, - template_url=self.update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated4, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) response_headers = {} response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - deserialized = self._deserialize("AlertProcessingRule", pipeline_response) + deserialized = self._deserialize("AlertProcessingRule", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized + return cls(pipeline_response, deserialized, response_headers) # type: ignore - update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{alertProcessingRuleName}" - } + return deserialized # type: ignore diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alert_rule_recommendations_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alert_rule_recommendations_operations.py new file mode 100644 index 000000000000..9522aae56080 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alert_rule_recommendations_operations.py @@ -0,0 +1,245 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._configuration import AlertsManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_by_resource_request(resource_uri: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{resourceUri}/providers/Microsoft.AlertsManagement/alertRuleRecommendations") + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_by_target_type_request(subscription_id: str, *, target_type: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-08-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alertRuleRecommendations" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["targetType"] = _SERIALIZER.query("target_type", target_type, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class AlertRuleRecommendationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.alertsmanagement.AlertsManagementClient`'s + :attr:`alert_rule_recommendations` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AlertsManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_by_resource(self, resource_uri: str, **kwargs: Any) -> Iterable["_models.AlertRuleRecommendationResource"]: + """Retrieve alert rule recommendations for a resource. + + :param resource_uri: The identifier of the resource. Required. + :type resource_uri: str + :return: An iterator like instance of either AlertRuleRecommendationResource or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.AlertRuleRecommendationResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-08-01-preview")) + cls: ClsType[_models.AlertRuleRecommendationsListResponse] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_resource_request( + resource_uri=resource_uri, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AlertRuleRecommendationsListResponse", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_by_target_type( + self, target_type: str, **kwargs: Any + ) -> Iterable["_models.AlertRuleRecommendationResource"]: + """Retrieve alert rule recommendations for a target type. + + :param target_type: The recommendations target type. Required. + :type target_type: str + :return: An iterator like instance of either AlertRuleRecommendationResource or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.AlertRuleRecommendationResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-08-01-preview")) + cls: ClsType[_models.AlertRuleRecommendationsListResponse] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_by_target_type_request( + subscription_id=self._config.subscription_id, + target_type=target_type, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AlertRuleRecommendationsListResponse", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alerts_management_client_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alerts_management_client_operations.py new file mode 100644 index 000000000000..38331287827e --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alerts_management_client_operations.py @@ -0,0 +1,166 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._configuration import AlertsManagementClientConfiguration +from .._utils.serialization import Serializer +from .._utils.utils import ClientMixinABC + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_preview_alert_rule_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/previewAlertRule" + ) + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class AlertsManagementClientOperationsMixin(ClientMixinABC[PipelineClient, AlertsManagementClientConfiguration]): + + @overload + def preview_alert_rule( + self, parameters: _models.PreviewAlertRuleRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PreviewAlertRuleResponse: + """Retrieves the results of a simulated historical execution of an alert rule. + + :param parameters: The alert rule to preview. Required. + :type parameters: ~azure.mgmt.alertsmanagement.models.PreviewAlertRuleRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PreviewAlertRuleResponse or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.PreviewAlertRuleResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def preview_alert_rule( + self, parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PreviewAlertRuleResponse: + """Retrieves the results of a simulated historical execution of an alert rule. + + :param parameters: The alert rule to preview. Required. + :type parameters: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PreviewAlertRuleResponse or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.PreviewAlertRuleResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def preview_alert_rule( + self, parameters: Union[_models.PreviewAlertRuleRequest, IO[bytes]], **kwargs: Any + ) -> _models.PreviewAlertRuleResponse: + """Retrieves the results of a simulated historical execution of an alert rule. + + :param parameters: The alert rule to preview. Is either a PreviewAlertRuleRequest type or a + IO[bytes] type. Required. + :type parameters: ~azure.mgmt.alertsmanagement.models.PreviewAlertRuleRequest or IO[bytes] + :return: PreviewAlertRuleResponse or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.PreviewAlertRuleResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PreviewAlertRuleResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IOBase, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "PreviewAlertRuleRequest") + + _request = build_preview_alert_rule_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("PreviewAlertRuleResponse", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alerts_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alerts_operations.py index f4835f11fa5b..50bfa1506e4e 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alerts_operations.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alerts_operations.py @@ -6,9 +6,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from collections.abc import MutableMapping +from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -19,20 +21,15 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +from .._configuration import AlertsManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -44,9 +41,7 @@ def build_meta_data_request(*, identifier: Union[str, _models.Identifier], **kwa _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -63,7 +58,7 @@ def build_meta_data_request(*, identifier: Union[str, _models.Identifier], **kwa def build_get_all_request( - subscription_id: str, + scope: str, *, target_resource: Optional[str] = None, target_resource_type: Optional[str] = None, @@ -87,18 +82,16 @@ def build_get_all_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts") + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.AlertsManagement/alerts") path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if target_resource is not None: @@ -143,25 +136,21 @@ def build_get_all_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_by_id_request(alert_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: +def build_get_by_id_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}" - ) # pylint: disable=line-too-long + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.AlertsManagement/alerts/{alertId}") path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), "alertId": _SERIALIZER.url("alert_id", alert_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -173,28 +162,23 @@ def build_get_by_id_request(alert_id: str, subscription_id: str, **kwargs: Any) def build_change_state_request( - alert_id: str, subscription_id: str, *, new_state: Union[str, _models.AlertState], **kwargs: Any + scope: str, alert_id: str, *, new_state: Union[str, _models.AlertState], **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop( - "template_url", - "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}/changestate", - ) # pylint: disable=line-too-long + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.AlertsManagement/alerts/{alertId}/changestate") path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), "alertId": _SERIALIZER.url("alert_id", alert_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -208,25 +192,21 @@ def build_change_state_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_history_request(alert_id: str, subscription_id: str, **kwargs: Any) -> HttpRequest: +def build_get_history_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}/history" - ) # pylint: disable=line-too-long + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.AlertsManagement/alerts/{alertId}/history") path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), "alertId": _SERIALIZER.url("alert_id", alert_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -238,7 +218,7 @@ def build_get_history_request(alert_id: str, subscription_id: str, **kwargs: Any def build_get_summary_request( - subscription_id: str, + scope: str, *, groupby: Union[str, _models.AlertsSummaryGroupByFields], include_smart_groups_count: Optional[bool] = None, @@ -257,20 +237,16 @@ def build_get_summary_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = kwargs.pop( - "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alertsSummary" - ) + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.AlertsManagement/alertsSummary") path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["groupby"] = _SERIALIZER.query("groupby", groupby, "str") @@ -306,6 +282,58 @@ def build_get_summary_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) +def build_list_enrichments_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{scope}/providers/Microsoft.AlertsManagement/alerts/{alertId}/enrichments") + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertId": _SERIALIZER.url("alert_id", alert_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_enrichments_request(scope: str, alert_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{scope}/providers/Microsoft.AlertsManagement/alerts/{alertId}/enrichments/default" + ) + path_format_arguments = { + "scope": _SERIALIZER.url("scope", scope, "str", skip_quote=True), + "alertId": _SERIALIZER.url("alert_id", alert_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + class AlertsOperations: """ .. warning:: @@ -320,10 +348,10 @@ class AlertsOperations: def __init__(self, *args, **kwargs): input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AlertsManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def meta_data(self, identifier: Union[str, _models.Identifier], **kwargs: Any) -> _models.AlertsMetaData: @@ -332,12 +360,11 @@ def meta_data(self, identifier: Union[str, _models.Identifier], **kwargs: Any) - :param identifier: Identification of the information to be retrieved by API call. "MonitorServiceList" Required. :type identifier: str or ~azure.mgmt.alertsmanagement.models.Identifier - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertsMetaData or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertsMetaData :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -348,44 +375,40 @@ def meta_data(self, identifier: Union[str, _models.Identifier], **kwargs: Any) - _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) cls: ClsType[_models.AlertsMetaData] = kwargs.pop("cls", None) - request = build_meta_data_request( + _request = build_meta_data_request( identifier=identifier, api_version=api_version, - template_url=self.meta_data.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertsMetaData", pipeline_response) + deserialized = self._deserialize("AlertsMetaData", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - meta_data.metadata = {"url": "/providers/Microsoft.AlertsManagement/alertsMetaData"} + return deserialized # type: ignore @distributed_trace def get_all( self, + scope: str, target_resource: Optional[str] = None, target_resource_type: Optional[str] = None, target_resource_group: Optional[str] = None, @@ -409,6 +432,8 @@ def get_all( (e.g. time range). The results can then be sorted on the basis specific fields, with the default being lastModifiedDateTime. + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str :param target_resource: Filter by target resource( which is full ARM ID) Default value is select all. Default value is None. :type target_resource: str @@ -422,7 +447,7 @@ def get_all( value is select all. Known values are: "Application Insights", "ActivityLog Administrative", "ActivityLog Security", "ActivityLog Recommendation", "ActivityLog Policy", "ActivityLog Autoscale", "Log Analytics", "Nagios", "Platform", "SCOM", "ServiceHealth", "SmartDetector", - "VM Insights", and "Zabbix". Default value is None. + "VM Insights", "Zabbix", and "Resource Health". Default value is None. :type monitor_service: str or ~azure.mgmt.alertsmanagement.models.MonitorService :param monitor_condition: Filter by monitor condition which is either 'Fired' or 'Resolved'. Default value is to select all. Known values are: "Fired" and "Resolved". Default value is @@ -432,7 +457,8 @@ def get_all( "Sev1", "Sev2", "Sev3", and "Sev4". Default value is None. :type severity: str or ~azure.mgmt.alertsmanagement.models.Severity :param alert_state: Filter by state of the alert instance. Default value is to select all. - Known values are: "New", "Acknowledged", and "Closed". Default value is None. + Known values are: "New", "Acknowledged", "Closed", "NoAlert", "Fired", "Firing", "Resolving", + and "Resolved". Default value is None. :type alert_state: str or ~azure.mgmt.alertsmanagement.models.AlertState :param alert_rule: Filter by specific alert rule. Default value is to select all. Default value is None. @@ -467,12 +493,11 @@ def get_all( :param time_range: Filter by time range by below listed values. Default value is 1 day. Known values are: "1h", "1d", "7d", and "30d". Default value is None. :type time_range: str or ~azure.mgmt.alertsmanagement.models.TimeRange - :param custom_time_range: Filter by custom time range in the format - :code:``/:code:`` where time is in (ISO-8601 format)'. Permissible - values is within 30 days from query time. Either timeRange or customTimeRange could be used - but not both. Default is none. Default value is None. + :param custom_time_range: Filter by custom time range in the format :code:``/\\ + :code:`` where time is in (ISO-8601 format)'. Permissible values is within 30 days + from query time. Either timeRange or customTimeRange could be used but not both. Default is + none. Default value is None. :type custom_time_range: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Alert or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.Alert] :raises ~azure.core.exceptions.HttpResponseError: @@ -480,12 +505,10 @@ def get_all( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) cls: ClsType[_models.AlertsList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -496,8 +519,8 @@ def get_all( def prepare_request(next_link=None): if not next_link: - request = build_get_all_request( - subscription_id=self._config.subscription_id, + _request = build_get_all_request( + scope=scope, target_resource=target_resource, target_resource_type=target_resource_type, target_resource_group=target_resource_group, @@ -516,19 +539,16 @@ def prepare_request(next_link=None): time_range=time_range, custom_time_range=custom_time_range, api_version=api_version, - template_url=self.get_all.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("AlertsList", pipeline_response) @@ -538,38 +558,38 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - get_all.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts"} - @distributed_trace - def get_by_id(self, alert_id: str, **kwargs: Any) -> _models.Alert: + def get_by_id(self, scope: str, alert_id: str, **kwargs: Any) -> _models.Alert: """Get a specific alert. Get information related to a specific alert. + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str :param alert_id: Unique ID of an alert instance. Required. :type alert_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -580,47 +600,41 @@ def get_by_id(self, alert_id: str, **kwargs: Any) -> _models.Alert: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) cls: ClsType[_models.Alert] = kwargs.pop("cls", None) - request = build_get_by_id_request( + _request = build_get_by_id_request( + scope=scope, alert_id=alert_id, - subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_by_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Alert", pipeline_response) + deserialized = self._deserialize("Alert", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_by_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}" - } + return deserialized # type: ignore @overload def change_state( self, + scope: str, alert_id: str, new_state: Union[str, _models.AlertState], comment: Optional[_models.Comments] = None, @@ -630,17 +644,18 @@ def change_state( ) -> _models.Alert: """Change the state of an alert. + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str :param alert_id: Unique ID of an alert instance. Required. :type alert_id: str - :param new_state: New state of the alert. Known values are: "New", "Acknowledged", and - "Closed". Required. + :param new_state: New state of the alert. Known values are: "New", "Acknowledged", "Closed", + "NoAlert", "Fired", "Firing", "Resolving", and "Resolved". Required. :type new_state: str or ~azure.mgmt.alertsmanagement.models.AlertState :param comment: reason of change alert state. Default value is None. :type comment: ~azure.mgmt.alertsmanagement.models.Comments :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: @@ -649,26 +664,28 @@ def change_state( @overload def change_state( self, + scope: str, alert_id: str, new_state: Union[str, _models.AlertState], - comment: Optional[IO] = None, + comment: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Alert: """Change the state of an alert. + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str :param alert_id: Unique ID of an alert instance. Required. :type alert_id: str - :param new_state: New state of the alert. Known values are: "New", "Acknowledged", and - "Closed". Required. + :param new_state: New state of the alert. Known values are: "New", "Acknowledged", "Closed", + "NoAlert", "Fired", "Firing", "Resolving", and "Resolved". Required. :type new_state: str or ~azure.mgmt.alertsmanagement.models.AlertState :param comment: reason of change alert state. Default value is None. - :type comment: IO + :type comment: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: @@ -677,30 +694,29 @@ def change_state( @distributed_trace def change_state( self, + scope: str, alert_id: str, new_state: Union[str, _models.AlertState], - comment: Optional[Union[_models.Comments, IO]] = None, + comment: Optional[Union[_models.Comments, IO[bytes]]] = None, **kwargs: Any ) -> _models.Alert: """Change the state of an alert. + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str :param alert_id: Unique ID of an alert instance. Required. :type alert_id: str - :param new_state: New state of the alert. Known values are: "New", "Acknowledged", and - "Closed". Required. + :param new_state: New state of the alert. Known values are: "New", "Acknowledged", "Closed", + "NoAlert", "Fired", "Firing", "Resolving", and "Resolved". Required. :type new_state: str or ~azure.mgmt.alertsmanagement.models.AlertState - :param comment: reason of change alert state. Is either a model type or a IO type. Default - value is None. - :type comment: ~azure.mgmt.alertsmanagement.models.Comments or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + :param comment: reason of change alert state. Is either a Comments type or a IO[bytes] type. Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :type comment: ~azure.mgmt.alertsmanagement.models.Comments or IO[bytes] :return: Alert or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.Alert :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -711,16 +727,14 @@ def change_state( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.Alert] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(comment, (IO, bytes)): + if isinstance(comment, (IOBase, bytes)): _content = comment else: if comment is not None: @@ -728,56 +742,52 @@ def change_state( else: _json = None - request = build_change_state_request( + _request = build_change_state_request( + scope=scope, alert_id=alert_id, - subscription_id=self._config.subscription_id, new_state=new_state, api_version=api_version, content_type=content_type, json=_json, content=_content, - template_url=self.change_state.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("Alert", pipeline_response) + deserialized = self._deserialize("Alert", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - change_state.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}/changestate" - } + return deserialized # type: ignore @distributed_trace - def get_history(self, alert_id: str, **kwargs: Any) -> _models.AlertModification: + def get_history(self, scope: str, alert_id: str, **kwargs: Any) -> _models.AlertModification: """Get the history of an alert, which captures any monitor condition changes (Fired/Resolved) and alert state changes (New/Acknowledged/Closed). + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str :param alert_id: Unique ID of an alert instance. Required. :type alert_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertModification or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertModification :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -788,47 +798,41 @@ def get_history(self, alert_id: str, **kwargs: Any) -> _models.AlertModification _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) cls: ClsType[_models.AlertModification] = kwargs.pop("cls", None) - request = build_get_history_request( + _request = build_get_history_request( + scope=scope, alert_id=alert_id, - subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_history.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertModification", pipeline_response) + deserialized = self._deserialize("AlertModification", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get_history.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}/history" - } + return deserialized # type: ignore @distributed_trace def get_summary( self, + scope: str, groupby: Union[str, _models.AlertsSummaryGroupByFields], include_smart_groups_count: Optional[bool] = None, target_resource: Optional[str] = None, @@ -846,6 +850,8 @@ def get_summary( """Get a summarized count of your alerts grouped by various parameters (e.g. grouping by 'Severity' returns the count of alerts for each severity). + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str :param groupby: This parameter allows the result set to be grouped by input fields (Maximum 2 comma separated fields supported). For example, groupby=severity or groupby=severity,alertstate. Known values are: "severity", "alertState", "monitorCondition", @@ -867,7 +873,7 @@ def get_summary( value is select all. Known values are: "Application Insights", "ActivityLog Administrative", "ActivityLog Security", "ActivityLog Recommendation", "ActivityLog Policy", "ActivityLog Autoscale", "Log Analytics", "Nagios", "Platform", "SCOM", "ServiceHealth", "SmartDetector", - "VM Insights", and "Zabbix". Default value is None. + "VM Insights", "Zabbix", and "Resource Health". Default value is None. :type monitor_service: str or ~azure.mgmt.alertsmanagement.models.MonitorService :param monitor_condition: Filter by monitor condition which is either 'Fired' or 'Resolved'. Default value is to select all. Known values are: "Fired" and "Resolved". Default value is @@ -877,7 +883,8 @@ def get_summary( "Sev1", "Sev2", "Sev3", and "Sev4". Default value is None. :type severity: str or ~azure.mgmt.alertsmanagement.models.Severity :param alert_state: Filter by state of the alert instance. Default value is to select all. - Known values are: "New", "Acknowledged", and "Closed". Default value is None. + Known values are: "New", "Acknowledged", "Closed", "NoAlert", "Fired", "Firing", "Resolving", + and "Resolved". Default value is None. :type alert_state: str or ~azure.mgmt.alertsmanagement.models.AlertState :param alert_rule: Filter by specific alert rule. Default value is to select all. Default value is None. @@ -885,17 +892,16 @@ def get_summary( :param time_range: Filter by time range by below listed values. Default value is 1 day. Known values are: "1h", "1d", "7d", and "30d". Default value is None. :type time_range: str or ~azure.mgmt.alertsmanagement.models.TimeRange - :param custom_time_range: Filter by custom time range in the format - :code:``/:code:`` where time is in (ISO-8601 format)'. Permissible - values is within 30 days from query time. Either timeRange or customTimeRange could be used - but not both. Default is none. Default value is None. + :param custom_time_range: Filter by custom time range in the format :code:``/\\ + :code:`` where time is in (ISO-8601 format)'. Permissible values is within 30 days + from query time. Either timeRange or customTimeRange could be used but not both. Default is + none. Default value is None. :type custom_time_range: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: AlertsSummary or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.AlertsSummary :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -906,13 +912,11 @@ def get_summary( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) cls: ClsType[_models.AlertsSummary] = kwargs.pop("cls", None) - request = build_get_summary_request( - subscription_id=self._config.subscription_id, + _request = build_get_summary_request( + scope=scope, groupby=groupby, include_smart_groups_count=include_smart_groups_count, target_resource=target_resource, @@ -926,29 +930,151 @@ def get_summary( time_range=time_range, custom_time_range=custom_time_range, api_version=api_version, - template_url=self.get_summary.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("AlertsSummary", pipeline_response) + deserialized = self._deserialize("AlertsSummary", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_enrichments(self, scope: str, alert_id: str, **kwargs: Any) -> Iterable["_models.AlertEnrichmentResponse"]: + """List the enrichments of an alert. It returns a collection of one object named default. + + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str + :param alert_id: Unique ID of an alert instance. Required. + :type alert_id: str + :return: An iterator like instance of either AlertEnrichmentResponse or the result of + cls(response) + :rtype: + ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.AlertEnrichmentResponse] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) + cls: ClsType[_models.AlertEnrichmentsList] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_enrichments_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("AlertEnrichmentsList", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - return deserialized + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_enrichments(self, scope: str, alert_id: str, **kwargs: Any) -> _models.AlertEnrichmentResponse: + """Get the enrichments of an alert. + + :param scope: scope here is resourceId for which alert is created. Required. + :type scope: str + :param alert_id: Unique ID of an alert instance. Required. + :type alert_id: str + :return: AlertEnrichmentResponse or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.AlertEnrichmentResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) + cls: ClsType[_models.AlertEnrichmentResponse] = kwargs.pop("cls", None) + + _request = build_get_enrichments_request( + scope=scope, + alert_id=alert_id, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("AlertEnrichmentResponse", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - get_summary.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alertsSummary"} + return deserialized # type: ignore diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_issue_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_issue_operations.py new file mode 100644 index 000000000000..9a74e080878e --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_issue_operations.py @@ -0,0 +1,1454 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict +from azure.mgmt.core.exceptions import ARMErrorFormat + +from .. import models as _models +from .._configuration import AlertsManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(resource_uri: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{resourceUri}/providers/Microsoft.AlertsManagement/issues") + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_request(resource_uri: str, issue_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{resourceUri}/providers/Microsoft.AlertsManagement/issues/{issueName}") + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), + "issueName": _SERIALIZER.url("issue_name", issue_name, "str", pattern=r"^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_request(resource_uri: str, issue_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{resourceUri}/providers/Microsoft.AlertsManagement/issues/{issueName}") + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), + "issueName": _SERIALIZER.url("issue_name", issue_name, "str", pattern=r"^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_update_request(resource_uri: str, issue_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{resourceUri}/providers/Microsoft.AlertsManagement/issues/{issueName}") + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), + "issueName": _SERIALIZER.url("issue_name", issue_name, "str", pattern=r"^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_delete_request(resource_uri: str, issue_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{resourceUri}/providers/Microsoft.AlertsManagement/issues/{issueName}") + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), + "issueName": _SERIALIZER.url("issue_name", issue_name, "str", pattern=r"^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_add_or_update_alerts_request(resource_uri: str, issue_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{resourceUri}/providers/Microsoft.AlertsManagement/issues/{issueName}/addOrUpdateAlerts" + ) + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), + "issueName": _SERIALIZER.url("issue_name", issue_name, "str", pattern=r"^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_add_or_update_resources_request(resource_uri: str, issue_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{resourceUri}/providers/Microsoft.AlertsManagement/issues/{issueName}/addOrUpdateResources" + ) + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), + "issueName": _SERIALIZER.url("issue_name", issue_name, "str", pattern=r"^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_fetch_investigation_result_request(resource_uri: str, issue_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{resourceUri}/providers/Microsoft.AlertsManagement/issues/{issueName}/fetchInvestigationResult", + ) + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), + "issueName": _SERIALIZER.url("issue_name", issue_name, "str", pattern=r"^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_alerts_request(resource_uri: str, issue_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{resourceUri}/providers/Microsoft.AlertsManagement/issues/{issueName}/listAlerts" + ) + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), + "issueName": _SERIALIZER.url("issue_name", issue_name, "str", pattern=r"^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_resources_request(resource_uri: str, issue_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{resourceUri}/providers/Microsoft.AlertsManagement/issues/{issueName}/listResources" + ) + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), + "issueName": _SERIALIZER.url("issue_name", issue_name, "str", pattern=r"^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_start_investigation_request(resource_uri: str, issue_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/{resourceUri}/providers/Microsoft.AlertsManagement/issues/{issueName}/startInvestigation" + ) + path_format_arguments = { + "resourceUri": _SERIALIZER.url("resource_uri", resource_uri, "str", skip_quote=True), + "issueName": _SERIALIZER.url("issue_name", issue_name, "str", pattern=r"^[A-Za-z0-9][A-Za-z0-9-]+[A-Za-z0-9]$"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class IssueOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.alertsmanagement.AlertsManagementClient`'s + :attr:`issue` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AlertsManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, resource_uri: str, **kwargs: Any) -> Iterable["_models.IssueResource"]: + """List all issues under the parent. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :return: An iterator like instance of either IssueResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.IssueResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + cls: ClsType[_models.IssueResourceListResult] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_request( + resource_uri=resource_uri, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("IssueResourceListResult", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get(self, resource_uri: str, **kwargs: Any) -> _models.IssueResource: + """Get issue properties. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :return: IssueResource or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.IssueResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + cls: ClsType[_models.IssueResource] = kwargs.pop("cls", None) + + _request = build_get_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("IssueResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, + resource_uri: str, + resource: _models.IssueResource, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.IssueResource: + """Create a new issue or updates an existing one. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param resource: Resource create parameters. Required. + :type resource: ~azure.mgmt.alertsmanagement.models.IssueResource + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: IssueResource or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.IssueResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, resource_uri: str, resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.IssueResource: + """Create a new issue or updates an existing one. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param resource: Resource create parameters. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: IssueResource or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.IssueResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create( + self, resource_uri: str, resource: Union[_models.IssueResource, IO[bytes]], **kwargs: Any + ) -> _models.IssueResource: + """Create a new issue or updates an existing one. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param resource: Resource create parameters. Is either a IssueResource type or a IO[bytes] + type. Required. + :type resource: ~azure.mgmt.alertsmanagement.models.IssueResource or IO[bytes] + :return: IssueResource or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.IssueResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.IssueResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _json = self._serialize.body(resource, "IssueResource") + + _request = build_create_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("IssueResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, + resource_uri: str, + properties: _models.IssueResourceUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.IssueResource: + """Update an issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param properties: The resource properties to be updated. Required. + :type properties: ~azure.mgmt.alertsmanagement.models.IssueResourceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: IssueResource or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.IssueResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, resource_uri: str, properties: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.IssueResource: + """Update an issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param properties: The resource properties to be updated. Required. + :type properties: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: IssueResource or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.IssueResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def update( + self, resource_uri: str, properties: Union[_models.IssueResourceUpdate, IO[bytes]], **kwargs: Any + ) -> _models.IssueResource: + """Update an issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param properties: The resource properties to be updated. Is either a IssueResourceUpdate type + or a IO[bytes] type. Required. + :type properties: ~azure.mgmt.alertsmanagement.models.IssueResourceUpdate or IO[bytes] + :return: IssueResource or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.IssueResource + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.IssueResource] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(properties, (IOBase, bytes)): + _content = properties + else: + _json = self._serialize.body(properties, "IssueResourceUpdate") + + _request = build_update_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("IssueResource", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete(self, resource_uri: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete an issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :return: None or the result of cls(response) + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_delete_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def add_or_update_alerts( + self, resource_uri: str, body: _models.RelatedAlerts, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RelatedAlerts: + """Add or update alerts in the issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: ~azure.mgmt.alertsmanagement.models.RelatedAlerts + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RelatedAlerts or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.RelatedAlerts + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def add_or_update_alerts( + self, resource_uri: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RelatedAlerts: + """Add or update alerts in the issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RelatedAlerts or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.RelatedAlerts + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def add_or_update_alerts( + self, resource_uri: str, body: Union[_models.RelatedAlerts, IO[bytes]], **kwargs: Any + ) -> _models.RelatedAlerts: + """Add or update alerts in the issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Is either a RelatedAlerts type or a IO[bytes] + type. Required. + :type body: ~azure.mgmt.alertsmanagement.models.RelatedAlerts or IO[bytes] + :return: RelatedAlerts or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.RelatedAlerts + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RelatedAlerts] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "RelatedAlerts") + + _request = build_add_or_update_alerts_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RelatedAlerts", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def add_or_update_resources( + self, + resource_uri: str, + body: _models.RelatedResources, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RelatedResources: + """Add or update resources in the issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: ~azure.mgmt.alertsmanagement.models.RelatedResources + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RelatedResources or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.RelatedResources + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def add_or_update_resources( + self, resource_uri: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RelatedResources: + """Add or update resources in the issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: RelatedResources or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.RelatedResources + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def add_or_update_resources( + self, resource_uri: str, body: Union[_models.RelatedResources, IO[bytes]], **kwargs: Any + ) -> _models.RelatedResources: + """Add or update resources in the issue. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Is either a RelatedResources type or a + IO[bytes] type. Required. + :type body: ~azure.mgmt.alertsmanagement.models.RelatedResources or IO[bytes] + :return: RelatedResources or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.RelatedResources + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.RelatedResources] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "RelatedResources") + + _request = build_add_or_update_resources_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("RelatedResources", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def fetch_investigation_result( + self, + resource_uri: str, + body: _models.FetchInvestigationResultParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.InvestigationResult: + """Fetch investigation results. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: ~azure.mgmt.alertsmanagement.models.FetchInvestigationResultParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: InvestigationResult or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.InvestigationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def fetch_investigation_result( + self, resource_uri: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.InvestigationResult: + """Fetch investigation results. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: InvestigationResult or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.InvestigationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def fetch_investigation_result( + self, resource_uri: str, body: Union[_models.FetchInvestigationResultParameters, IO[bytes]], **kwargs: Any + ) -> _models.InvestigationResult: + """Fetch investigation results. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Is either a FetchInvestigationResultParameters + type or a IO[bytes] type. Required. + :type body: ~azure.mgmt.alertsmanagement.models.FetchInvestigationResultParameters or IO[bytes] + :return: InvestigationResult or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.InvestigationResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.InvestigationResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "FetchInvestigationResultParameters") + + _request = build_fetch_investigation_result_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("InvestigationResult", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def list_alerts( + self, resource_uri: str, body: _models.ListParameter, *, content_type: str = "application/json", **kwargs: Any + ) -> Iterable["_models.RelatedAlert"]: + """List all alerts in the issue - this method uses pagination to return all alerts. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: ~azure.mgmt.alertsmanagement.models.ListParameter + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An iterator like instance of either RelatedAlert or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.RelatedAlert] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def list_alerts( + self, resource_uri: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> Iterable["_models.RelatedAlert"]: + """List all alerts in the issue - this method uses pagination to return all alerts. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An iterator like instance of either RelatedAlert or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.RelatedAlert] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def list_alerts( + self, resource_uri: str, body: Union[_models.ListParameter, IO[bytes]], **kwargs: Any + ) -> Iterable["_models.RelatedAlert"]: + """List all alerts in the issue - this method uses pagination to return all alerts. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Is either a ListParameter type or a IO[bytes] + type. Required. + :type body: ~azure.mgmt.alertsmanagement.models.ListParameter or IO[bytes] + :return: An iterator like instance of either RelatedAlert or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.RelatedAlert] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PagedRelatedAlert] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ListParameter") + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_alerts_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PagedRelatedAlert", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def list_resources( + self, resource_uri: str, body: _models.ListParameter, *, content_type: str = "application/json", **kwargs: Any + ) -> Iterable["_models.RelatedResource"]: + """List all resources in the issue - this method uses pagination to return all resources. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: ~azure.mgmt.alertsmanagement.models.ListParameter + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An iterator like instance of either RelatedResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.RelatedResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def list_resources( + self, resource_uri: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> Iterable["_models.RelatedResource"]: + """List all resources in the issue - this method uses pagination to return all resources. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An iterator like instance of either RelatedResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.RelatedResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def list_resources( + self, resource_uri: str, body: Union[_models.ListParameter, IO[bytes]], **kwargs: Any + ) -> Iterable["_models.RelatedResource"]: + """List all resources in the issue - this method uses pagination to return all resources. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Is either a ListParameter type or a IO[bytes] + type. Required. + :type body: ~azure.mgmt.alertsmanagement.models.ListParameter or IO[bytes] + :return: An iterator like instance of either RelatedResource or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.RelatedResource] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PagedRelatedResource] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "ListParameter") + + def prepare_request(next_link=None): + if not next_link: + + _request = build_list_resources_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + else: + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize("PagedRelatedResource", pipeline_response) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def start_investigation( + self, + resource_uri: str, + body: _models.StartInvestigationParameters, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.InvestigationMetadata: + """Start a new investigation. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: ~azure.mgmt.alertsmanagement.models.StartInvestigationParameters + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: InvestigationMetadata or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.InvestigationMetadata + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def start_investigation( + self, resource_uri: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.InvestigationMetadata: + """Start a new investigation. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: InvestigationMetadata or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.InvestigationMetadata + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def start_investigation( + self, resource_uri: str, body: Union[_models.StartInvestigationParameters, IO[bytes]], **kwargs: Any + ) -> _models.InvestigationMetadata: + """Start a new investigation. + + :param resource_uri: The fully qualified Azure Resource manager identifier of the resource. + Required. + :type resource_uri: str + :param body: The content of the action request. Is either a StartInvestigationParameters type + or a IO[bytes] type. Required. + :type body: ~azure.mgmt.alertsmanagement.models.StartInvestigationParameters or IO[bytes] + :return: InvestigationMetadata or the result of cls(response) + :rtype: ~azure.mgmt.alertsmanagement.models.InvestigationMetadata + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-03-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.InvestigationMetadata] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _json = self._serialize.body(body, "StartInvestigationParameters") + + _request = build_start_investigation_request( + resource_uri=resource_uri, + issue_name=self._config.issue_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + _request.url = self._client.format_url(_request.url) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated5, pipeline_response) + raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) + + deserialized = self._deserialize("InvestigationMetadata", pipeline_response.http_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_operations.py index a607bf0f4a25..c4382632e72a 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_operations.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from collections.abc import MutableMapping from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -19,20 +19,15 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request +from .._configuration import AlertsManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -44,9 +39,7 @@ def build_list_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -75,16 +68,15 @@ class Operations: def __init__(self, *args, **kwargs): input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AlertsManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: """List all operations available through Azure Alerts Management Resource Provider. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either Operation or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.Operation] :raises ~azure.core.exceptions.HttpResponseError: @@ -92,12 +84,10 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-01-preview")) cls: ClsType[_models.OperationsList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -108,21 +98,18 @@ def list(self, **kwargs: Any) -> Iterable["_models.Operation"]: def prepare_request(next_link=None): if not next_link: - request = build_list_request( + _request = build_list_request( api_version=api_version, - template_url=self.list.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("OperationsList", pipeline_response) @@ -132,20 +119,19 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - - list.metadata = {"url": "/providers/Microsoft.AlertsManagement/operations"} diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_prometheus_rule_groups_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_prometheus_rule_groups_operations.py index 02a44a95f241..49e86e465935 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_prometheus_rule_groups_operations.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_prometheus_rule_groups_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +6,11 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from collections.abc import MutableMapping +from io import IOBase from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -19,20 +21,15 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +from .._configuration import AlertsManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -44,20 +41,18 @@ def build_list_by_subscription_request(subscription_id: str, **kwargs: Any) -> H _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/prometheusRuleGroups" - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -72,16 +67,14 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "resourceGroupName": _SERIALIZER.url( @@ -89,7 +82,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ ), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -106,25 +99,23 @@ def build_get_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleGroupName": _SERIALIZER.url("rule_group_name", rule_group_name, "str"), + "ruleGroupName": _SERIALIZER.url("rule_group_name", rule_group_name, "str", pattern=r"^[^:@/#{}%&+*<>?]+$"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -141,9 +132,7 @@ def build_create_or_update_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -151,16 +140,16 @@ def build_create_or_update_request( _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleGroupName": _SERIALIZER.url("rule_group_name", rule_group_name, "str"), + "ruleGroupName": _SERIALIZER.url("rule_group_name", rule_group_name, "str", pattern=r"^[^:@/#{}%&+*<>?]+$"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -179,9 +168,7 @@ def build_update_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -189,16 +176,16 @@ def build_update_request( _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleGroupName": _SERIALIZER.url("rule_group_name", rule_group_name, "str"), + "ruleGroupName": _SERIALIZER.url("rule_group_name", rule_group_name, "str", pattern=r"^[^:@/#{}%&+*<>?]+$"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -217,25 +204,23 @@ def build_delete_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "resourceGroupName": _SERIALIZER.url( "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 ), - "ruleGroupName": _SERIALIZER.url("rule_group_name", rule_group_name, "str"), + "ruleGroupName": _SERIALIZER.url("rule_group_name", rule_group_name, "str", pattern=r"^[^:@/#{}%&+*<>?]+$"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -260,16 +245,15 @@ class PrometheusRuleGroupsOperations: def __init__(self, *args, **kwargs): input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AlertsManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.PrometheusRuleGroupResource"]: - """Retrieve Prometheus rule group definitions in a subscription. + """Retrieve Prometheus all rule group definitions in a subscription. - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrometheusRuleGroupResource or the result of cls(response) :rtype: @@ -279,12 +263,10 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.PrometheusRul _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) cls: ClsType[_models.PrometheusRuleGroupResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -295,22 +277,19 @@ def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.PrometheusRul def prepare_request(next_link=None): if not next_link: - request = build_list_by_subscription_request( + _request = build_list_by_subscription_request( subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_subscription.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("PrometheusRuleGroupResourceCollection", pipeline_response) @@ -320,26 +299,23 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - list_by_subscription.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/prometheusRuleGroups" - } - @distributed_trace def list_by_resource_group( self, resource_group_name: str, **kwargs: Any @@ -349,7 +325,6 @@ def list_by_resource_group( :param resource_group_name: The name of the resource group. The name is case insensitive. Required. :type resource_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrometheusRuleGroupResource or the result of cls(response) :rtype: @@ -359,12 +334,10 @@ def list_by_resource_group( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) cls: ClsType[_models.PrometheusRuleGroupResourceCollection] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -375,23 +348,20 @@ def list_by_resource_group( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_group_request( + _request = build_list_by_resource_group_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.list_by_resource_group.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("PrometheusRuleGroupResourceCollection", pipeline_response) @@ -401,26 +371,23 @@ def extract_data(pipeline_response): return None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data) - list_by_resource_group.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups" - } - @distributed_trace def get(self, resource_group_name: str, rule_group_name: str, **kwargs: Any) -> _models.PrometheusRuleGroupResource: """Retrieve a Prometheus rule group definition. @@ -430,12 +397,11 @@ def get(self, resource_group_name: str, rule_group_name: str, **kwargs: Any) -> :type resource_group_name: str :param rule_group_name: The name of the rule group. Required. :type rule_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrometheusRuleGroupResource or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -446,44 +412,37 @@ def get(self, resource_group_name: str, rule_group_name: str, **kwargs: Any) -> _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) cls: ClsType[_models.PrometheusRuleGroupResource] = kwargs.pop("cls", None) - request = build_get_request( + _request = build_get_request( resource_group_name=resource_group_name, rule_group_name=rule_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrometheusRuleGroupResource", pipeline_response) + deserialized = self._deserialize("PrometheusRuleGroupResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - get.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}" - } + return deserialized # type: ignore @overload def create_or_update( @@ -507,7 +466,6 @@ def create_or_update( :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrometheusRuleGroupResource or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -518,7 +476,7 @@ def create_or_update( self, resource_group_name: str, rule_group_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -531,11 +489,10 @@ def create_or_update( :param rule_group_name: The name of the rule group. Required. :type rule_group_name: str :param parameters: The parameters of the rule group to create or update. Required. - :type parameters: IO + :type parameters: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrometheusRuleGroupResource or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -546,7 +503,7 @@ def create_or_update( self, resource_group_name: str, rule_group_name: str, - parameters: Union[_models.PrometheusRuleGroupResource, IO], + parameters: Union[_models.PrometheusRuleGroupResource, IO[bytes]], **kwargs: Any ) -> _models.PrometheusRuleGroupResource: """Create or update a Prometheus rule group definition. @@ -556,18 +513,14 @@ def create_or_update( :type resource_group_name: str :param rule_group_name: The name of the rule group. Required. :type rule_group_name: str - :param parameters: The parameters of the rule group to create or update. Is either a model type - or a IO type. Required. - :type parameters: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param parameters: The parameters of the rule group to create or update. Is either a + PrometheusRuleGroupResource type or a IO[bytes] type. Required. + :type parameters: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource or IO[bytes] :return: PrometheusRuleGroupResource or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -578,21 +531,19 @@ def create_or_update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.PrometheusRuleGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "PrometheusRuleGroupResource") - request = build_create_or_update_request( + _request = build_create_or_update_request( resource_group_name=resource_group_name, rule_group_name=rule_group_name, subscription_id=self._config.subscription_id, @@ -600,45 +551,36 @@ def create_or_update( content_type=content_type, json=_json, content=_content, - template_url=self.create_or_update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - if response.status_code == 200: - deserialized = self._deserialize("PrometheusRuleGroupResource", pipeline_response) - - if response.status_code == 201: - deserialized = self._deserialize("PrometheusRuleGroupResource", pipeline_response) + deserialized = self._deserialize("PrometheusRuleGroupResource", pipeline_response.http_response) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - create_or_update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}" - } - @overload def update( self, resource_group_name: str, rule_group_name: str, - parameters: _models.PrometheusRuleGroupResourcePatch, + parameters: _models.PrometheusRuleGroupResourcePatchParameters, *, content_type: str = "application/json", **kwargs: Any @@ -651,11 +593,11 @@ def update( :param rule_group_name: The name of the rule group. Required. :type rule_group_name: str :param parameters: The parameters of the rule group to update. Required. - :type parameters: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResourcePatch + :type parameters: + ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResourcePatchParameters :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrometheusRuleGroupResource or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -666,7 +608,7 @@ def update( self, resource_group_name: str, rule_group_name: str, - parameters: IO, + parameters: IO[bytes], *, content_type: str = "application/json", **kwargs: Any @@ -679,11 +621,10 @@ def update( :param rule_group_name: The name of the rule group. Required. :type rule_group_name: str :param parameters: The parameters of the rule group to update. Required. - :type parameters: IO + :type parameters: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: PrometheusRuleGroupResource or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource :raises ~azure.core.exceptions.HttpResponseError: @@ -694,7 +635,7 @@ def update( self, resource_group_name: str, rule_group_name: str, - parameters: Union[_models.PrometheusRuleGroupResourcePatch, IO], + parameters: Union[_models.PrometheusRuleGroupResourcePatchParameters, IO[bytes]], **kwargs: Any ) -> _models.PrometheusRuleGroupResource: """Update an Prometheus rule group definition. @@ -704,18 +645,15 @@ def update( :type resource_group_name: str :param rule_group_name: The name of the rule group. Required. :type rule_group_name: str - :param parameters: The parameters of the rule group to update. Is either a model type or a IO - type. Required. - :type parameters: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResourcePatch or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword callable cls: A custom type or function that will be passed the direct response + :param parameters: The parameters of the rule group to update. Is either a + PrometheusRuleGroupResourcePatchParameters type or a IO[bytes] type. Required. + :type parameters: + ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResourcePatchParameters or IO[bytes] :return: PrometheusRuleGroupResource or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -726,21 +664,19 @@ def update( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) cls: ClsType[_models.PrometheusRuleGroupResource] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(parameters, (IO, bytes)): + if isinstance(parameters, (IOBase, bytes)): _content = parameters else: - _json = self._serialize.body(parameters, "PrometheusRuleGroupResourcePatch") + _json = self._serialize.body(parameters, "PrometheusRuleGroupResourcePatchParameters") - request = build_update_request( + _request = build_update_request( resource_group_name=resource_group_name, rule_group_name=rule_group_name, subscription_id=self._config.subscription_id, @@ -748,34 +684,29 @@ def update( content_type=content_type, json=_json, content=_content, - template_url=self.update.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("PrometheusRuleGroupResource", pipeline_response) + deserialized = self._deserialize("PrometheusRuleGroupResource", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized + return cls(pipeline_response, deserialized, {}) # type: ignore - update.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}" - } + return deserialized # type: ignore @distributed_trace def delete( # pylint: disable=inconsistent-return-statements @@ -788,12 +719,11 @@ def delete( # pylint: disable=inconsistent-return-statements :type resource_group_name: str :param rule_group_name: The name of the rule group. Required. :type rule_group_name: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -804,37 +734,30 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2021-07-22-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2021-07-22-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-03-01")) cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_request( + _request = build_delete_request( resource_group_name=resource_group_name, rule_group_name=rule_group_name, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.delete.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: - return cls(pipeline_response, None, {}) - - delete.metadata = { - "url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/prometheusRuleGroups/{ruleGroupName}" - } + return cls(pipeline_response, None, {}) # type: ignore diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_smart_groups_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_smart_groups_operations.py index cdb08c4cc687..34f9770f8199 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_smart_groups_operations.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_smart_groups_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,9 +5,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import sys +from collections.abc import MutableMapping from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union +from azure.core import PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -19,20 +19,15 @@ ) from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest +from azure.core.rest import HttpRequest, HttpResponse from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models -from .._serialization import Serializer -from .._vendor import _convert_request, _format_url_section +from .._configuration import AlertsManagementClientConfiguration +from .._utils.serialization import Deserializer, Serializer -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports -else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -59,9 +54,7 @@ def build_get_all_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-05-05-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -72,7 +65,7 @@ def build_get_all_request( "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters if target_resource is not None: @@ -109,22 +102,20 @@ def build_get_by_id_request(smart_group_id: str, subscription_id: str, **kwargs: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-05-05-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "smartGroupId": _SERIALIZER.url("smart_group_id", smart_group_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -141,22 +132,20 @@ def build_change_state_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-05-05-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}/changeState", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "smartGroupId": _SERIALIZER.url("smart_group_id", smart_group_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -172,22 +161,20 @@ def build_get_history_request(smart_group_id: str, subscription_id: str, **kwarg _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-05-05-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = kwargs.pop( "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}/history", - ) # pylint: disable=line-too-long + ) path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1), "smartGroupId": _SERIALIZER.url("smart_group_id", smart_group_id, "str"), } - _url: str = _format_url_section(_url, **path_format_arguments) # type: ignore + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -212,10 +199,10 @@ class SmartGroupsOperations: def __init__(self, *args, **kwargs): input_args = list(args) - self._client = input_args.pop(0) if input_args else kwargs.pop("client") - self._config = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AlertsManagementClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace def get_all( @@ -250,7 +237,7 @@ def get_all( value is select all. Known values are: "Application Insights", "ActivityLog Administrative", "ActivityLog Security", "ActivityLog Recommendation", "ActivityLog Policy", "ActivityLog Autoscale", "Log Analytics", "Nagios", "Platform", "SCOM", "ServiceHealth", "SmartDetector", - "VM Insights", and "Zabbix". Default value is None. + "VM Insights", "Zabbix", and "Resource Health". Default value is None. :type monitor_service: str or ~azure.mgmt.alertsmanagement.models.MonitorService :param monitor_condition: Filter by monitor condition which is either 'Fired' or 'Resolved'. Default value is to select all. Known values are: "Fired" and "Resolved". Default value is @@ -260,7 +247,8 @@ def get_all( "Sev1", "Sev2", "Sev3", and "Sev4". Default value is None. :type severity: str or ~azure.mgmt.alertsmanagement.models.Severity :param smart_group_state: Filter by state of the smart group. Default value is to select all. - Known values are: "New", "Acknowledged", and "Closed". Default value is None. + Known values are: "New", "Acknowledged", "Closed", "NoAlert", "Fired", "Firing", "Resolving", + and "Resolved". Default value is None. :type smart_group_state: str or ~azure.mgmt.alertsmanagement.models.AlertState :param time_range: Filter by time range by below listed values. Default value is 1 day. Known values are: "1h", "1d", "7d", and "30d". Default value is None. @@ -277,7 +265,6 @@ def get_all( value is 'desc' for time fields and 'asc' for others. Known values are: "asc" and "desc". Default value is None. :type sort_order: str or ~azure.mgmt.alertsmanagement.models.SortOrder - :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SmartGroup or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.SmartGroup] :raises ~azure.core.exceptions.HttpResponseError: @@ -285,12 +272,10 @@ def get_all( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-05-05-preview")) cls: ClsType[_models.SmartGroupsList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -301,7 +286,7 @@ def get_all( def prepare_request(next_link=None): if not next_link: - request = build_get_all_request( + _request = build_get_all_request( subscription_id=self._config.subscription_id, target_resource=target_resource, target_resource_group=target_resource_group, @@ -315,19 +300,16 @@ def prepare_request(next_link=None): sort_by=sort_by, sort_order=sort_order, api_version=api_version, - template_url=self.get_all.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request + _request = HttpRequest("GET", next_link) + _request.url = self._client.format_url(_request.url) + _request.method = "GET" + return _request def extract_data(pipeline_response): deserialized = self._deserialize("SmartGroupsList", pipeline_response) @@ -337,10 +319,11 @@ def extract_data(pipeline_response): return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -353,8 +336,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - get_all.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups"} - @distributed_trace def get_by_id(self, smart_group_id: str, **kwargs: Any) -> _models.SmartGroup: """Get information related to a specific Smart Group. @@ -363,12 +344,11 @@ def get_by_id(self, smart_group_id: str, **kwargs: Any) -> _models.SmartGroup: :param smart_group_id: Smart group unique id. Required. :type smart_group_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: SmartGroup or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.SmartGroup :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -379,24 +359,21 @@ def get_by_id(self, smart_group_id: str, **kwargs: Any) -> _models.SmartGroup: _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-05-05-preview")) cls: ClsType[_models.SmartGroup] = kwargs.pop("cls", None) - request = build_get_by_id_request( + _request = build_get_by_id_request( smart_group_id=smart_group_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_by_id.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -409,16 +386,12 @@ def get_by_id(self, smart_group_id: str, **kwargs: Any) -> _models.SmartGroup: response_headers = {} response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - deserialized = self._deserialize("SmartGroup", pipeline_response) + deserialized = self._deserialize("SmartGroup", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, response_headers) - - return deserialized + return cls(pipeline_response, deserialized, response_headers) # type: ignore - get_by_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}" - } + return deserialized # type: ignore @distributed_trace def change_state( @@ -428,15 +401,14 @@ def change_state( :param smart_group_id: Smart group unique id. Required. :type smart_group_id: str - :param new_state: New state of the alert. Known values are: "New", "Acknowledged", and - "Closed". Required. + :param new_state: New state of the alert. Known values are: "New", "Acknowledged", "Closed", + "NoAlert", "Fired", "Firing", "Resolving", and "Resolved". Required. :type new_state: str or ~azure.mgmt.alertsmanagement.models.AlertState - :keyword callable cls: A custom type or function that will be passed the direct response :return: SmartGroup or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.SmartGroup :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -447,25 +419,22 @@ def change_state( _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-05-05-preview")) cls: ClsType[_models.SmartGroup] = kwargs.pop("cls", None) - request = build_change_state_request( + _request = build_change_state_request( smart_group_id=smart_group_id, subscription_id=self._config.subscription_id, new_state=new_state, api_version=api_version, - template_url=self.change_state.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -478,16 +447,12 @@ def change_state( response_headers = {} response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - deserialized = self._deserialize("SmartGroup", pipeline_response) + deserialized = self._deserialize("SmartGroup", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized - - change_state.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}/changeState" - } + return deserialized # type: ignore @distributed_trace def get_history(self, smart_group_id: str, **kwargs: Any) -> _models.SmartGroupModification: @@ -496,12 +461,11 @@ def get_history(self, smart_group_id: str, **kwargs: Any) -> _models.SmartGroupM :param smart_group_id: Smart group unique id. Required. :type smart_group_id: str - :keyword callable cls: A custom type or function that will be passed the direct response :return: SmartGroupModification or the result of cls(response) :rtype: ~azure.mgmt.alertsmanagement.models.SmartGroupModification :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -512,24 +476,21 @@ def get_history(self, smart_group_id: str, **kwargs: Any) -> _models.SmartGroupM _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: Literal["2019-05-05-preview"] = kwargs.pop( - "api_version", _params.pop("api-version", "2019-05-05-preview") - ) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2019-05-05-preview")) cls: ClsType[_models.SmartGroupModification] = kwargs.pop("cls", None) - request = build_get_history_request( + _request = build_get_history_request( smart_group_id=smart_group_id, subscription_id=self._config.subscription_id, api_version=api_version, - template_url=self.get_history.metadata["url"], headers=_headers, params=_params, ) - request = _convert_request(request) - request.url = self._client.format_url(request.url) + _request.url = self._client.format_url(_request.url) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **kwargs + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -539,13 +500,9 @@ def get_history(self, smart_group_id: str, **kwargs: Any) -> _models.SmartGroupM error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated3, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize("SmartGroupModification", pipeline_response) + deserialized = self._deserialize("SmartGroupModification", pipeline_response.http_response) if cls: - return cls(pipeline_response, deserialized, {}) + return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized - - get_history.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}/history" - } + return deserialized # type: ignore diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_action_group_all_alerts_in_subscription.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_action_group_all_alerts_in_subscription.py index 16c15fa80e42..e27e4f8ebc1b 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_action_group_all_alerts_in_subscription.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_action_group_all_alerts_in_subscription.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="subId1", ) @@ -53,6 +56,6 @@ def main(): print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_add_action_group_all_alerts_in_subscription.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-08-08-preview/examples/AlertProcessingRules_Create_or_update_add_action_group_all_alerts_in_subscription.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_two_action_groups_all_sev0_sev1_two_resource_groups.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_two_action_groups_all_sev0_sev1_two_resource_groups.py index 301a8f60c27c..0b0251eeb065 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_two_action_groups_all_sev0_sev1_two_resource_groups.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_two_action_groups_all_sev0_sev1_two_resource_groups.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="subId1", ) @@ -55,6 +58,6 @@ def main(): print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_add_two_action_groups_all_Sev0_Sev1_two_resource_groups.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-08-08-preview/examples/AlertProcessingRules_Create_or_update_add_two_action_groups_all_Sev0_Sev1_two_resource_groups.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_from_specific_alert_rule.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_from_specific_alert_rule.py index 96a81089ab2d..91e4451707cf 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_from_specific_alert_rule.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_from_specific_alert_rule.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="subId1", ) @@ -55,6 +58,6 @@ def main(): print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_from_specific_alert_rule.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-08-08-preview/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_from_specific_alert_rule.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_outside_business_hours.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_outside_business_hours.py index 732b8a5157a9..8db6aedd309e 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_outside_business_hours.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_outside_business_hours.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="subId1", ) @@ -53,6 +56,6 @@ def main(): print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_outside_business_hours.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-08-08-preview/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_outside_business_hours.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_recurring_maintenance_window.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_recurring_maintenance_window.py index 2b2df653a6b8..cda1ae5077aa 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_recurring_maintenance_window.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_recurring_maintenance_window.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="subId1", ) @@ -64,6 +67,6 @@ def main(): print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_recurring_maintenance_window.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-08-08-preview/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_recurring_maintenance_window.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_specific_vm_oneoff_maintenance_window.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_specific_vm_oneoff_maintenance_window.py index 727053369ddf..7b0cb6a988a2 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_specific_vm_oneoff_maintenance_window.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_remove_all_action_groups_specific_vm_oneoff_maintenance_window.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="subId1", ) @@ -53,6 +56,6 @@ def main(): print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_specific_VM_one-off_maintenance_window.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-08-08-preview/examples/AlertProcessingRules_Create_or_update_remove_all_action_groups_specific_VM_one-off_maintenance_window.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_delete.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_delete.py index da1035a3ed6b..397ee20f99dc 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_delete.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_delete.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,16 +28,16 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="1e3ff1c0-771a-4119-a03b-be82a51e232d", ) - response = client.alert_processing_rules.delete( + client.alert_processing_rules.delete( resource_group_name="alertscorrelationrg", alert_processing_rule_name="DailySuppression", ) - print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Delete.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-08-08-preview/examples/AlertProcessingRules_Delete.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_get_by_id.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_get_by_id.py index 6e58d707a946..c57549356db8 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_get_by_id.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_get_by_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="1e3ff1c0-771a-4119-a03b-be82a51e232d", ) @@ -36,6 +39,6 @@ def main(): print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_GetById.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-08-08-preview/examples/AlertProcessingRules_GetById.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_list_resource_group.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_list_resource_group.py index df87df4c57e9..6c262c4d177e 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_list_resource_group.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_list_resource_group.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="1e3ff1c0-771a-4119-a03b-be82a51e232d", ) @@ -36,6 +39,6 @@ def main(): print(item) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_List_ResourceGroup.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-08-08-preview/examples/AlertProcessingRules_List_ResourceGroup.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_list_subscription.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_list_subscription.py index f60030923c9a..79b299282734 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_list_subscription.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_list_subscription.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="1e3ff1c0-771a-4119-a03b-be82a51e232d", ) @@ -34,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_List_Subscription.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-08-08-preview/examples/AlertProcessingRules_List_Subscription.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_patch.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_patch.py index 8e49a347b9b0..a03b1be4fd6f 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_patch.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_patch.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="1e3ff1c0-771a-4119-a03b-be82a51e232d", ) @@ -37,6 +40,6 @@ def main(): print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2021-08-08/examples/AlertProcessingRules_Patch.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-08-08-preview/examples/AlertProcessingRules_Patch.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_resource_mac.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_resource_mac.py new file mode 100644 index 000000000000..64829f768858 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_resource_mac.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python alert_rule_recommendations_get_by_resource_mac.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.alert_rule_recommendations.list_by_resource( + resource_uri="subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/resourceGroups/GenevaAlertRP-RunnerResources-eastus/providers/microsoft.monitor/accounts/alertsrp-eastus-pgms", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2023-08-01-preview/examples/AlertRuleRecommendations_GetByResource_MAC.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_resource_vm.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_resource_vm.py new file mode 100644 index 000000000000..88ea8b1df727 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_resource_vm.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python alert_rule_recommendations_get_by_resource_vm.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.alert_rule_recommendations.list_by_resource( + resource_uri="subscriptions/2f00cc51-6809-498f-9ffc-48c42aff570d/resourcegroups/test/providers/Microsoft.Compute/virtualMachines/testMachineCanBeSafelyDeleted", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2023-08-01-preview/examples/AlertRuleRecommendations_GetByResource_VM.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_subscription_mac.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_subscription_mac.py new file mode 100644 index 000000000000..d0cbcc23cf3d --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_subscription_mac.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python alert_rule_recommendations_get_by_subscription_mac.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", + subscription_id="2f00cc51-6809-498f-9ffc-48c42aff570d", + ) + + response = client.alert_rule_recommendations.list_by_target_type( + target_type="microsoft.monitor/accounts", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2023-08-01-preview/examples/AlertRuleRecommendations_GetBySubscription_MAC.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_subscription_vm.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_subscription_vm.py new file mode 100644 index 000000000000..f74ca98e73af --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_subscription_vm.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python alert_rule_recommendations_get_by_subscription_vm.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", + subscription_id="2f00cc51-6809-498f-9ffc-48c42aff570d", + ) + + response = client.alert_rule_recommendations.list_by_target_type( + target_type="microsoft.compute/virtualmachines", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2023-08-01-preview/examples/AlertRuleRecommendations_GetBySubscription_VM.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_change_state.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_change_state.py index 97ce6575b964..e2741411a49c 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_change_state.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_change_state.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,16 +28,18 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="9e261de7-c804-4b9d-9ebf-6f50fe350a9a", + issue_name="ISSUE_NAME", + subscription_id="SUBSCRIPTION_ID", ) response = client.alerts.change_state( + scope="subscriptions/9e261de7-c804-4b9d-9ebf-6f50fe350a9a", alert_id="66114d64-d9d9-478b-95c9-b789d6502100", new_state="Acknowledged", ) print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_ChangeState.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2024-01-01-preview/examples/Alerts_ChangeState.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_get_by_id.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_get_by_id.py index e4be181c404e..84468846d50f 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_get_by_id.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_get_by_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,15 +28,17 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="9e261de7-c804-4b9d-9ebf-6f50fe350a9a", + issue_name="ISSUE_NAME", + subscription_id="SUBSCRIPTION_ID", ) response = client.alerts.get_by_id( + scope="subscriptions/9e261de7-c804-4b9d-9ebf-6f50fe350a9a", alert_id="66114d64-d9d9-478b-95c9-b789d6502100", ) print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_GetById.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2024-01-01-preview/examples/Alerts_GetById.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_get_enrichments.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_get_enrichments.py new file mode 100644 index 000000000000..2d4eb04023fa --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_get_enrichments.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python alerts_get_enrichments.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.alerts.get_enrichments( + scope="subscriptions/72fa99ef-9c84-4a7c-b343-ec62da107d81", + alert_id="66114d64-d9d9-478b-95c9-b789d6502101", + ) + print(response) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2024-01-01-preview/examples/Alerts_GetEnrichments.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_history.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_history.py index 3d11c9aa1d13..4f90cc101db2 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_history.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_history.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,15 +28,17 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="9e261de7-c804-4b9d-9ebf-6f50fe350a9a", + issue_name="ISSUE_NAME", + subscription_id="SUBSCRIPTION_ID", ) response = client.alerts.get_history( + scope="subscriptions/9e261de7-c804-4b9d-9ebf-6f50fe350a9a", alert_id="66114d64-d9d9-478b-95c9-b789d6502100", ) print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_History.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2024-01-01-preview/examples/Alerts_History.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_list.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_list.py index 1aad26234d85..c2c4957cc02a 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_list.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,14 +28,17 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="1e3ff1c0-771a-4119-a03b-be82a51e232d", + issue_name="ISSUE_NAME", + subscription_id="SUBSCRIPTION_ID", ) - response = client.alerts.get_all() + response = client.alerts.get_all( + scope="subscriptions/1e3ff1c0-771a-4119-a03b-be82a51e232d", + ) for item in response: print(item) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_List.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2024-01-01-preview/examples/Alerts_List.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_list_enrichments.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_list_enrichments.py new file mode 100644 index 000000000000..bf23e793ff61 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_list_enrichments.py @@ -0,0 +1,45 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python alerts_list_enrichments.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.alerts.list_enrichments( + scope="subscriptions/72fa99ef-9c84-4a7c-b343-ec62da107d81", + alert_id="66114d64-d9d9-478b-95c9-b789d6502101", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2024-01-01-preview/examples/Alerts_ListEnrichments.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_meta_data_monitor_service.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_meta_data_monitor_service.py index 035559a1bbc3..09d979de633e 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_meta_data_monitor_service.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_meta_data_monitor_service.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="SUBSCRIPTION_ID", ) @@ -35,6 +38,6 @@ def main(): print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/AlertsMetaData_MonitorService.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2024-01-01-preview/examples/AlertsMetaData_MonitorService.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_summary.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_summary.py index 8794d5a0df8d..5e84f7e7d698 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_summary.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_summary.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,15 +28,17 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="1e3ff1c0-771a-4119-a03b-be82a51e232d", + issue_name="ISSUE_NAME", + subscription_id="SUBSCRIPTION_ID", ) response = client.alerts.get_summary( + scope="subscriptions/1e3ff1c0-771a-4119-a03b-be82a51e232d", groupby="severity,alertState", ) print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Alerts_Summary.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2024-01-01-preview/examples/Alerts_Summary.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/create_or_update_cluster_centric_rule_group.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/create_or_update_cluster_centric_rule_group.py new file mode 100644 index 000000000000..9c6d6b8d83e1 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/create_or_update_cluster_centric_rule_group.py @@ -0,0 +1,69 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python create_or_update_cluster_centric_rule_group.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", + ) + + response = client.prometheus_rule_groups.create_or_update( + resource_group_name="promResourceGroup", + rule_group_name="myPrometheusRuleGroup", + parameters={ + "location": "East US", + "properties": { + "clusterName": "myClusterName", + "description": "This is a rule group with culster centric configuration", + "interval": "PT10M", + "rules": [ + { + "actions": [], + "alert": "Billing_Processing_Very_Slow", + "annotations": {"annotationName1": "annotationValue1"}, + "enabled": True, + "expression": "job_type:billing_jobs_duration_seconds:99p5m > 30", + "for": "PT5M", + "labels": {"team": "prod"}, + "resolveConfiguration": {"autoResolved": True, "timeToResolve": "PT10M"}, + "severity": 2, + } + ], + "scopes": [ + "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/myResourceGroup/providers/microsoft.monitor/accounts/myAzureMonitorWorkspace", + "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/myResourceGroup/providers/Microsoft.ContainerService/managedClusters/myClusterName", + ], + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2023-03-01/examples/createOrUpdateClusterCentricRuleGroup.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/create_or_update_prometheus_rule_group.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/create_or_update_prometheus_rule_group.py index 98dab269a300..b640910b3fdd 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/create_or_update_prometheus_rule_group.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/create_or_update_prometheus_rule_group.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,16 +28,20 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="14ddf0c5-77c5-4b53-84f6-e1fa43ad68f7", + issue_name="ISSUE_NAME", + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", ) response = client.prometheus_rule_groups.create_or_update( - resource_group_name="giladstest", + resource_group_name="promResourceGroup", rule_group_name="myPrometheusRuleGroup", parameters={ "location": "East US", "properties": { - "description": "This is the description of the first rule group", + "clusterName": "myClusterName", + "description": "This is the description of the following rule group", + "enabled": True, + "interval": "PT10M", "rules": [ { "expression": 'histogram_quantile(0.99, sum(rate(jobs_duration_seconds_bucket{service="billing-processing"}[5m])) by (job_type))', @@ -45,12 +51,17 @@ def main(): { "actions": [ { - "actionGroupId": "/subscriptions/14ddf0c5-77c5-4b53-84f6-e1fa43ad68f7/resourcegroups/giladstest/providers/microsoft.insights/notificationgroups/group2", + "actionGroupId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourcegroups/myrg/providers/microsoft.insights/actiongroups/myactiongroup", "actionProperties": {"key11": "value11", "key12": "value12"}, - } + }, + { + "actionGroupId": "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourcegroups/myrg/providers/microsoft.insights/actiongroups/myotheractiongroup", + "actionProperties": {"key21": "value21", "key22": "value22"}, + }, ], "alert": "Billing_Processing_Very_Slow", "annotations": {"annotationName1": "annotationValue1"}, + "enabled": True, "expression": "job_type:billing_jobs_duration_seconds:99p5m > 30", "for": "PT5M", "labels": {"team": "prod"}, @@ -59,7 +70,7 @@ def main(): }, ], "scopes": [ - "/subscriptions/14ddf0c5-77c5-4b53-84f6-e1fa43ad68f7/resourceGroups/giladstest/providers/microsoft.monitor/accounts/myMonitoringAccount" + "/subscriptions/ffffffff-ffff-ffff-ffff-ffffffffffff/resourceGroups/myResourceGroup/providers/microsoft.monitor/accounts/myAzureMonitorWorkspace" ], }, }, @@ -67,6 +78,6 @@ def main(): print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-07-22-preview/examples/createOrUpdatePrometheusRuleGroup.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2023-03-01/examples/createOrUpdatePrometheusRuleGroup.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/delete_prometheus_rule_group.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/delete_prometheus_rule_group.py index 0c233d48f753..d697afa9084a 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/delete_prometheus_rule_group.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/delete_prometheus_rule_group.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,16 +28,16 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="14ddf0c5-77c5-4b53-84f6-e1fa43ad68f7", + issue_name="ISSUE_NAME", + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", ) - response = client.prometheus_rule_groups.delete( - resource_group_name="giladsteset", + client.prometheus_rule_groups.delete( + resource_group_name="promResourceGroup", rule_group_name="myPrometheusRuleGroup", ) - print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-07-22-preview/examples/deletePrometheusRuleGroup.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2023-03-01/examples/deletePrometheusRuleGroup.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/get_prometheus_rule_group.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/get_prometheus_rule_group.py index 41ae7fa00fe3..a2bd7277fbd0 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/get_prometheus_rule_group.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/get_prometheus_rule_group.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,16 +28,17 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="14ddf0c5-77c5-4b53-84f6-e1fa43ad68f7", + issue_name="ISSUE_NAME", + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", ) response = client.prometheus_rule_groups.get( - resource_group_name="giladstest", + resource_group_name="promResourceGroup", rule_group_name="myPrometheusRuleGroup", ) print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-07-22-preview/examples/getPrometheusRuleGroup.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2023-03-01/examples/getPrometheusRuleGroup.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_add_or_update_alerts_maximum_set_gen.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_add_or_update_alerts_maximum_set_gen.py new file mode 100644 index 000000000000..190e0afe25ca --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_add_or_update_alerts_maximum_set_gen.py @@ -0,0 +1,52 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python issue_add_or_update_alerts_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="3f29e1b2b05f8371595dc761fed8e8b3", + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.issue.add_or_update_alerts( + resource_uri="subscriptions/aceaa046-91f0-492a-96dc-45e10a9183dc/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1", + body={ + "value": [ + { + "id": "/subscriptions/aceaa046-91f0-492a-96dc-45e10a9183dc/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1/Microsoft.AlertsManagement/2ca4a194-dd28-4d38-92ca-df48f6a3efc3", + "origin": {"addedBy": "171a811c-2a3a-4e6c-b742-f78f5f6ca51c", "addedByType": "Manual"}, + "relevance": "Relevant", + } + ] + }, + ) + print(response) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2025-03-01-preview/examples/Issue_AddOrUpdateAlerts_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_add_or_update_resources_maximum_set_gen.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_add_or_update_resources_maximum_set_gen.py new file mode 100644 index 000000000000..f42f8e332f66 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_add_or_update_resources_maximum_set_gen.py @@ -0,0 +1,52 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python issue_add_or_update_resources_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="3f29e1b2b05f8371595dc761fed8e8b3", + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.issue.add_or_update_resources( + resource_uri="subscriptions/aceaa046-91f0-492a-96dc-45e10a9183dc/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1", + body={ + "value": [ + { + "id": "/subscriptions/aceaa046-91f0-492a-96dc-45e10a9183dc/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1", + "origin": {"addedBy": "171a811c-2a3a-4e6c-b742-f78f5f6ca51c", "addedByType": "Manual"}, + "relevance": "Relevant", + } + ] + }, + ) + print(response) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2025-03-01-preview/examples/Issue_AddOrUpdateResources_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_create_maximum_set_gen.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_create_maximum_set_gen.py new file mode 100644 index 000000000000..0e4141385e9d --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_create_maximum_set_gen.py @@ -0,0 +1,51 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python issue_create_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="3f29e1b2b05f8371595dc761fed8e8b3", + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.issue.create( + resource_uri="subscriptions/aceaa046-91f0-492a-96dc-45e10a9183dc/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1", + resource={ + "properties": { + "impactTime": "2024-12-13T02:45:33", + "severity": "Sev2", + "status": "New", + "title": "Alert fired on VM CPU", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2025-03-01-preview/examples/Issue_Create_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_delete_maximum_set_gen.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_delete_maximum_set_gen.py new file mode 100644 index 000000000000..a8959e96abc4 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_delete_maximum_set_gen.py @@ -0,0 +1,42 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python issue_delete_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="3f29e1b2b05f8371595dc761fed8e8b3", + subscription_id="SUBSCRIPTION_ID", + ) + + client.issue.delete( + resource_uri="subscriptions/aceaa046-91f0-492a-96dc-45e10a9183dc/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1", + ) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2025-03-01-preview/examples/Issue_Delete_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_fetch_investigation_result_maximum_set_gen.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_fetch_investigation_result_maximum_set_gen.py new file mode 100644 index 000000000000..74938249fb60 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_fetch_investigation_result_maximum_set_gen.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python issue_fetch_investigation_result_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="3f29e1b2b05f8371595dc761fed8e8b3", + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.issue.fetch_investigation_result( + resource_uri="subscriptions/aceaa046-91f0-492a-96dc-45e10a9183dc/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1", + body={"investigationId": "b7341c85-b2c7-46ea-9a7f-784823b71fbc"}, + ) + print(response) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2025-03-01-preview/examples/Issue_FetchInvestigationResult_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_get_maximum_set_gen.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_get_maximum_set_gen.py new file mode 100644 index 000000000000..99900b1d925f --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_get_maximum_set_gen.py @@ -0,0 +1,43 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python issue_get_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="3f29e1b2b05f8371595dc761fed8e8b3", + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.issue.get( + resource_uri="subscriptions/aceaa046-91f0-492a-96dc-45e10a9183dc/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1", + ) + print(response) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2025-03-01-preview/examples/Issue_Get_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_list_alerts_maximum_set_gen.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_list_alerts_maximum_set_gen.py new file mode 100644 index 000000000000..6161410bf430 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_list_alerts_maximum_set_gen.py @@ -0,0 +1,45 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python issue_list_alerts_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="3f29e1b2b05f8371595dc761fed8e8b3", + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.issue.list_alerts( + resource_uri="subscriptions/aceaa046-91f0-492a-96dc-45e10a9183dc/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1", + body={"filter": ""}, + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2025-03-01-preview/examples/Issue_ListAlerts_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_list_maximum_set_gen.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_list_maximum_set_gen.py new file mode 100644 index 000000000000..35e9868ed66b --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_list_maximum_set_gen.py @@ -0,0 +1,44 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python issue_list_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.issue.list( + resource_uri="subscriptions/aceaa046-91f0-492a-96dc-45e10a9183dc/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1", + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2025-03-01-preview/examples/Issue_List_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_list_resources_maximum_set_gen.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_list_resources_maximum_set_gen.py new file mode 100644 index 000000000000..f8ceebf486a3 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_list_resources_maximum_set_gen.py @@ -0,0 +1,45 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python issue_list_resources_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="3f29e1b2b05f8371595dc761fed8e8b3", + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.issue.list_resources( + resource_uri="subscriptions/aceaa046-91f0-492a-96dc-45e10a9183dc/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1", + body={"filter": ""}, + ) + for item in response: + print(item) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2025-03-01-preview/examples/Issue_ListResources_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_start_investigation_maximum_set_gen.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_start_investigation_maximum_set_gen.py new file mode 100644 index 000000000000..6495318c3166 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_start_investigation_maximum_set_gen.py @@ -0,0 +1,53 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python issue_start_investigation_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="3f29e1b2b05f8371595dc761fed8e8b3", + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.issue.start_investigation( + resource_uri="subscriptions/aceaa046-91f0-492a-96dc-45e10a9183dc/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1", + body={ + "impactTime": "2024-12-13T02:45:33", + "investigationScopes": [ + { + "id": "/subscriptions/aceaa046-91f0-492a-96dc-45e10a9183dc/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1", + "origin": {"addedBy": "171a811c-2a3a-4e6c-b742-f78f5f6ca51c", "addedByType": "Manual"}, + "relevance": "Relevant", + } + ], + }, + ) + print(response) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2025-03-01-preview/examples/Issue_StartInvestigation_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_update_maximum_set_gen.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_update_maximum_set_gen.py new file mode 100644 index 000000000000..ed39aeda9452 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/issue_update_maximum_set_gen.py @@ -0,0 +1,51 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python issue_update_maximum_set_gen.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="3f29e1b2b05f8371595dc761fed8e8b3", + subscription_id="SUBSCRIPTION_ID", + ) + + response = client.issue.update( + resource_uri="subscriptions/aceaa046-91f0-492a-96dc-45e10a9183dc/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/vm1", + properties={ + "properties": { + "impactTime": "2024-12-13T02:45:33", + "severity": "Sev2", + "status": "New", + "title": "Alert fired on VM CPU", + } + }, + ) + print(response) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2025-03-01-preview/examples/Issue_Update_MaximumSet_Gen.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/list_prometheus_rule_groups.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/list_prometheus_rule_groups.py index f300eb020d15..62bfe188457f 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/list_prometheus_rule_groups.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/list_prometheus_rule_groups.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,16 +28,17 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="14ddf0c5-77c5-4b53-84f6-e1fa43ad68f7", + issue_name="ISSUE_NAME", + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", ) response = client.prometheus_rule_groups.list_by_resource_group( - resource_group_name="giladstest", + resource_group_name="promResourceGroup", ) for item in response: print(item) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-07-22-preview/examples/listPrometheusRuleGroups.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2023-03-01/examples/listPrometheusRuleGroups.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/list_subscription_prometheus_rule_groups.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/list_subscription_prometheus_rule_groups.py index e2ea7530deb2..d8a0a159bc58 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/list_subscription_prometheus_rule_groups.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/list_subscription_prometheus_rule_groups.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,7 +28,8 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="14ddf0c5-77c5-4b53-84f6-e1fa43ad68f7", + issue_name="ISSUE_NAME", + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", ) response = client.prometheus_rule_groups.list_by_subscription() @@ -34,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-07-22-preview/examples/listSubscriptionPrometheusRuleGroups.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2023-03-01/examples/listSubscriptionPrometheusRuleGroups.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/operations_list.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/operations_list.py index 69a32c6a6873..e7714e0fabdf 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/operations_list.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/operations_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="SUBSCRIPTION_ID", ) @@ -34,6 +37,6 @@ def main(): print(item) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2019-05-05-preview/examples/Operations_List.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2024-01-01-preview/examples/Operations_List.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/patch_prometheus_rule_group.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/patch_prometheus_rule_group.py index d5d921aa0d34..cfc23f950f81 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/patch_prometheus_rule_group.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/patch_prometheus_rule_group.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,17 +28,18 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="14ddf0c5-77c5-4b53-84f6-e1fa43ad68f7", + issue_name="ISSUE_NAME", + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", ) response = client.prometheus_rule_groups.update( - resource_group_name="giladstest", + resource_group_name="promResourceGroup", rule_group_name="myPrometheusRuleGroup", - parameters={"properties": {"enabled": False}, "tags": {"tag1": "value1"}}, + parameters={"properties": {"enabled": False}, "tags": {"tag1": "tagValueFromPatch"}}, ) print(response) -# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2021-07-22-preview/examples/patchPrometheusRuleGroup.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/stable/2023-03-01/examples/patchPrometheusRuleGroup.json if __name__ == "__main__": main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/preview_dynamic_threshold_log_search_alert_rule.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/preview_dynamic_threshold_log_search_alert_rule.py new file mode 100644 index 000000000000..d69faeba1a72 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/preview_dynamic_threshold_log_search_alert_rule.py @@ -0,0 +1,83 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.mgmt.alertsmanagement import AlertsManagementClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-mgmt-alertsmanagement +# USAGE + python preview_dynamic_threshold_log_search_alert_rule.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = AlertsManagementClient( + credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", + subscription_id="dd4bfc94-a096-412b-9c43-4bd13e35afbc", + ) + + response = client.preview_alert_rule( + parameters={ + "location": "eastus", + "properties": { + "alertRuleProperties": { + "location": "eastus", + "properties": { + "checkWorkspaceAlertsStorageConfigured": True, + "criteria": { + "allOf": [ + { + "alertSensitivity": "Medium", + "criterionType": "DynamicThresholdCriterion", + "dimensions": [ + {"name": "ComputerIp", "operator": "Exclude", "values": ["192.168.1.1"]}, + {"name": "OSType", "operator": "Include", "values": ["*"]}, + ], + "ignoreDataBefore": "2024-06-01T21:00:00.000Z", + "metricMeasureColumn": "% Processor Time", + "operator": "GreaterOrLessThan", + "query": 'Perf | where ObjectName == "Processor"', + "resourceIdColumn": "resourceId", + "timeAggregation": "Average", + } + ] + }, + "description": "Performance rule", + "enabled": True, + "evaluationFrequency": "PT5M", + "muteActionsDuration": "PT30M", + "scopes": [ + "/subscriptions/aaf177ed-1330-a9f2-80ea-fd3d7783b147/resourceGroups/scopeResourceGroup1/providers/Microsoft.Compute/virtualMachines/vm1" + ], + "severity": 4, + "skipQueryValidation": True, + "windowSize": "PT10M", + }, + }, + "alertRuleType": "scheduledQueryRules", + "lookbackPeriod": "PT1D", + }, + }, + ) + print(response) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2025-05-01-preview/examples/previewDynamicThresholdLogSearchAlertRule.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_change_state.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_change_state.py index 7bf44c2b6487..32f7726f2ee6 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_change_state.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_change_state.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="dd91de05-d791-4ceb-b6dc-988682dc7d72", ) diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_get_by_id.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_get_by_id.py index 27fad7e322b3..dcef962e8a47 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_get_by_id.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_get_by_id.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="9e261de7-c804-4b9d-9ebf-6f50fe350a9a", ) diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_history.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_history.py index 4fedb8a5d1e7..df8405eb5816 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_history.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_history.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="9e261de7-c804-4b9d-9ebf-6f50fe350a9a", ) diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_list.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_list.py index 229f50a04cda..e22e4bb14f20 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_list.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_list.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,6 +8,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,6 +28,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), + issue_name="ISSUE_NAME", subscription_id="dd91de05-d791-4ceb-b6dc-988682dc7d72", ) diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/conftest.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/conftest.py new file mode 100644 index 000000000000..ba1984219349 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + alertsmanagement_subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + alertsmanagement_tenant_id = os.environ.get("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + alertsmanagement_client_id = os.environ.get("AZURE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + alertsmanagement_client_secret = os.environ.get("AZURE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=alertsmanagement_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=alertsmanagement_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=alertsmanagement_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=alertsmanagement_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management.py new file mode 100644 index 000000000000..136fc63448ac --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management.py @@ -0,0 +1,88 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagement(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_preview_alert_rule(self, resource_group): + response = self.client.preview_alert_rule( + parameters={ + "location": "str", + "properties": { + "alertRuleProperties": { + "location": "str", + "autoMitigate": bool, + "checkWorkspaceAlertsStorageConfigured": bool, + "createdWithApiVersion": "str", + "criteria": { + "allOf": [ + { + "alertSensitivity": "str", + "criterionType": "str", + "dimensions": [{"name": "str", "operator": "str", "values": ["str"]}], + "failingPeriods": {"minFailingPeriodsToAlert": 1, "numberOfEvaluationPeriods": 1}, + "ignoreDataBefore": "2020-02-20 00:00:00", + "metricMeasureColumn": "str", + "metricName": "str", + "operator": "str", + "query": "str", + "resourceIdColumn": "str", + "threshold": 0.0, + "timeAggregation": "str", + } + ] + }, + "description": "str", + "displayName": "str", + "enabled": bool, + "etag": "str", + "evaluationFrequency": "1 day, 0:00:00", + "id": "str", + "isLegacyLogAnalyticsRule": bool, + "isWorkspaceAlertsStorageConfigured": bool, + "kind": "str", + "muteActionsDuration": "1 day, 0:00:00", + "name": "str", + "overrideQueryTimeRange": "1 day, 0:00:00", + "resolveConfiguration": {"autoResolved": bool, "timeToResolve": "1 day, 0:00:00"}, + "scopes": ["str"], + "severity": 0, + "skipQueryValidation": bool, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "targetResourceTypes": ["str"], + "type": "str", + "windowSize": "1 day, 0:00:00", + }, + "alertRuleType": "str", + "lookbackPeriod": "str", + }, + }, + api_version="2025-05-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_processing_rules_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_processing_rules_operations.py new file mode 100644 index 000000000000..0020fd1bcf05 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_processing_rules_operations.py @@ -0,0 +1,117 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementAlertProcessingRulesOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alert_processing_rules_list_by_subscription(self, resource_group): + response = self.client.alert_processing_rules.list_by_subscription( + api_version="2021-08-08-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alert_processing_rules_list_by_resource_group(self, resource_group): + response = self.client.alert_processing_rules.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2021-08-08-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alert_processing_rules_get_by_name(self, resource_group): + response = self.client.alert_processing_rules.get_by_name( + resource_group_name=resource_group.name, + alert_processing_rule_name="str", + api_version="2021-08-08-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alert_processing_rules_create_or_update(self, resource_group): + response = self.client.alert_processing_rules.create_or_update( + resource_group_name=resource_group.name, + alert_processing_rule_name="str", + alert_processing_rule={ + "location": "str", + "id": "str", + "name": "str", + "properties": { + "actions": ["action"], + "scopes": ["str"], + "conditions": [{"field": "str", "operator": "str", "values": ["str"]}], + "description": "str", + "enabled": True, + "schedule": { + "effectiveFrom": "str", + "effectiveUntil": "str", + "recurrences": ["recurrence"], + "timeZone": "str", + }, + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2021-08-08-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alert_processing_rules_delete(self, resource_group): + response = self.client.alert_processing_rules.delete( + resource_group_name=resource_group.name, + alert_processing_rule_name="str", + api_version="2021-08-08-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alert_processing_rules_update(self, resource_group): + response = self.client.alert_processing_rules.update( + resource_group_name=resource_group.name, + alert_processing_rule_name="str", + alert_processing_rule_patch={"enabled": bool, "tags": {"str": "str"}}, + api_version="2021-08-08-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_processing_rules_operations_async.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_processing_rules_operations_async.py new file mode 100644 index 000000000000..a5a3163d98a0 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_processing_rules_operations_async.py @@ -0,0 +1,118 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement.aio import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementAlertProcessingRulesOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alert_processing_rules_list_by_subscription(self, resource_group): + response = self.client.alert_processing_rules.list_by_subscription( + api_version="2021-08-08-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alert_processing_rules_list_by_resource_group(self, resource_group): + response = self.client.alert_processing_rules.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2021-08-08-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alert_processing_rules_get_by_name(self, resource_group): + response = await self.client.alert_processing_rules.get_by_name( + resource_group_name=resource_group.name, + alert_processing_rule_name="str", + api_version="2021-08-08-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alert_processing_rules_create_or_update(self, resource_group): + response = await self.client.alert_processing_rules.create_or_update( + resource_group_name=resource_group.name, + alert_processing_rule_name="str", + alert_processing_rule={ + "location": "str", + "id": "str", + "name": "str", + "properties": { + "actions": ["action"], + "scopes": ["str"], + "conditions": [{"field": "str", "operator": "str", "values": ["str"]}], + "description": "str", + "enabled": True, + "schedule": { + "effectiveFrom": "str", + "effectiveUntil": "str", + "recurrences": ["recurrence"], + "timeZone": "str", + }, + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2021-08-08-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alert_processing_rules_delete(self, resource_group): + response = await self.client.alert_processing_rules.delete( + resource_group_name=resource_group.name, + alert_processing_rule_name="str", + api_version="2021-08-08-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alert_processing_rules_update(self, resource_group): + response = await self.client.alert_processing_rules.update( + resource_group_name=resource_group.name, + alert_processing_rule_name="str", + alert_processing_rule_patch={"enabled": bool, "tags": {"str": "str"}}, + api_version="2021-08-08-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_rule_recommendations_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_rule_recommendations_operations.py new file mode 100644 index 000000000000..5c58b67ea98b --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_rule_recommendations_operations.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementAlertRuleRecommendationsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alert_rule_recommendations_list_by_resource(self, resource_group): + response = self.client.alert_rule_recommendations.list_by_resource( + resource_uri="str", + api_version="2023-08-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alert_rule_recommendations_list_by_target_type(self, resource_group): + response = self.client.alert_rule_recommendations.list_by_target_type( + target_type="str", + api_version="2023-08-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_rule_recommendations_operations_async.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_rule_recommendations_operations_async.py new file mode 100644 index 000000000000..7905e3c84f5b --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_rule_recommendations_operations_async.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement.aio import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementAlertRuleRecommendationsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alert_rule_recommendations_list_by_resource(self, resource_group): + response = self.client.alert_rule_recommendations.list_by_resource( + resource_uri="str", + api_version="2023-08-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alert_rule_recommendations_list_by_target_type(self, resource_group): + response = self.client.alert_rule_recommendations.list_by_target_type( + target_type="str", + api_version="2023-08-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alerts_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alerts_operations.py new file mode 100644 index 000000000000..356c0b95d082 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alerts_operations.py @@ -0,0 +1,114 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementAlertsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alerts_meta_data(self, resource_group): + response = self.client.alerts.meta_data( + identifier="str", + api_version="2024-01-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alerts_get_all(self, resource_group): + response = self.client.alerts.get_all( + scope="str", + api_version="2024-01-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alerts_get_by_id(self, resource_group): + response = self.client.alerts.get_by_id( + scope="str", + alert_id="str", + api_version="2024-01-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alerts_change_state(self, resource_group): + response = self.client.alerts.change_state( + scope="str", + alert_id="str", + new_state="str", + api_version="2024-01-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alerts_get_history(self, resource_group): + response = self.client.alerts.get_history( + scope="str", + alert_id="str", + api_version="2024-01-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alerts_get_summary(self, resource_group): + response = self.client.alerts.get_summary( + scope="str", + groupby="str", + api_version="2024-01-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alerts_list_enrichments(self, resource_group): + response = self.client.alerts.list_enrichments( + scope="str", + alert_id="str", + api_version="2024-01-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_alerts_get_enrichments(self, resource_group): + response = self.client.alerts.get_enrichments( + scope="str", + alert_id="str", + api_version="2024-01-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alerts_operations_async.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alerts_operations_async.py new file mode 100644 index 000000000000..ab9a0e4ab583 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alerts_operations_async.py @@ -0,0 +1,115 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement.aio import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementAlertsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alerts_meta_data(self, resource_group): + response = await self.client.alerts.meta_data( + identifier="str", + api_version="2024-01-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alerts_get_all(self, resource_group): + response = self.client.alerts.get_all( + scope="str", + api_version="2024-01-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alerts_get_by_id(self, resource_group): + response = await self.client.alerts.get_by_id( + scope="str", + alert_id="str", + api_version="2024-01-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alerts_change_state(self, resource_group): + response = await self.client.alerts.change_state( + scope="str", + alert_id="str", + new_state="str", + api_version="2024-01-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alerts_get_history(self, resource_group): + response = await self.client.alerts.get_history( + scope="str", + alert_id="str", + api_version="2024-01-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alerts_get_summary(self, resource_group): + response = await self.client.alerts.get_summary( + scope="str", + groupby="str", + api_version="2024-01-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alerts_list_enrichments(self, resource_group): + response = self.client.alerts.list_enrichments( + scope="str", + alert_id="str", + api_version="2024-01-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_alerts_get_enrichments(self, resource_group): + response = await self.client.alerts.get_enrichments( + scope="str", + alert_id="str", + api_version="2024-01-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_async.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_async.py new file mode 100644 index 000000000000..e1ae108e6cfe --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_async.py @@ -0,0 +1,89 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement.aio import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_preview_alert_rule(self, resource_group): + response = await self.client.preview_alert_rule( + parameters={ + "location": "str", + "properties": { + "alertRuleProperties": { + "location": "str", + "autoMitigate": bool, + "checkWorkspaceAlertsStorageConfigured": bool, + "createdWithApiVersion": "str", + "criteria": { + "allOf": [ + { + "alertSensitivity": "str", + "criterionType": "str", + "dimensions": [{"name": "str", "operator": "str", "values": ["str"]}], + "failingPeriods": {"minFailingPeriodsToAlert": 1, "numberOfEvaluationPeriods": 1}, + "ignoreDataBefore": "2020-02-20 00:00:00", + "metricMeasureColumn": "str", + "metricName": "str", + "operator": "str", + "query": "str", + "resourceIdColumn": "str", + "threshold": 0.0, + "timeAggregation": "str", + } + ] + }, + "description": "str", + "displayName": "str", + "enabled": bool, + "etag": "str", + "evaluationFrequency": "1 day, 0:00:00", + "id": "str", + "isLegacyLogAnalyticsRule": bool, + "isWorkspaceAlertsStorageConfigured": bool, + "kind": "str", + "muteActionsDuration": "1 day, 0:00:00", + "name": "str", + "overrideQueryTimeRange": "1 day, 0:00:00", + "resolveConfiguration": {"autoResolved": bool, "timeToResolve": "1 day, 0:00:00"}, + "scopes": ["str"], + "severity": 0, + "skipQueryValidation": bool, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "targetResourceTypes": ["str"], + "type": "str", + "windowSize": "1 day, 0:00:00", + }, + "alertRuleType": "str", + "lookbackPeriod": "str", + }, + }, + api_version="2025-05-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_issue_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_issue_operations.py new file mode 100644 index 000000000000..6139eca7b95a --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_issue_operations.py @@ -0,0 +1,230 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementIssueOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_issue_list(self, resource_group): + response = self.client.issue.list( + resource_uri="str", + api_version="2025-03-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_issue_get(self, resource_group): + response = self.client.issue.get( + resource_uri="str", + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_issue_create(self, resource_group): + response = self.client.issue.create( + resource_uri="str", + resource={ + "id": "str", + "name": "str", + "properties": { + "impactTime": "2020-02-20 00:00:00", + "investigations": [ + { + "createdAt": "2020-02-20 00:00:00", + "execution": {"completedAt": "2020-02-20 00:00:00", "runState": "str"}, + "id": "str", + "runParameters": { + "alerts": [ + { + "id": "str", + "origin": {"addedBy": "str", "addedByType": "str"}, + "relevance": "str", + } + ], + "impactTime": "2020-02-20 00:00:00", + "resources": [ + { + "id": "str", + "origin": {"addedBy": "str", "addedByType": "str"}, + "relevance": "str", + } + ], + }, + } + ], + "investigationsCount": 0, + "severity": "str", + "status": "str", + "title": "str", + "provisioningState": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_issue_update(self, resource_group): + response = self.client.issue.update( + resource_uri="str", + properties={ + "id": "str", + "name": "str", + "properties": {"impactTime": "2020-02-20 00:00:00", "severity": "str", "status": "str", "title": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_issue_delete(self, resource_group): + response = self.client.issue.delete( + resource_uri="str", + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_issue_add_or_update_alerts(self, resource_group): + response = self.client.issue.add_or_update_alerts( + resource_uri="str", + body={ + "value": [ + { + "addedAt": "2020-02-20 00:00:00", + "id": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "origin": {"addedBy": "str", "addedByType": "str"}, + "relevance": "str", + } + ] + }, + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_issue_add_or_update_resources(self, resource_group): + response = self.client.issue.add_or_update_resources( + resource_uri="str", + body={ + "value": [ + { + "addedAt": "2020-02-20 00:00:00", + "id": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "origin": {"addedBy": "str", "addedByType": "str"}, + "relevance": "str", + } + ] + }, + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_issue_fetch_investigation_result(self, resource_group): + response = self.client.issue.fetch_investigation_result( + resource_uri="str", + body={"investigationId": "str"}, + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_issue_list_alerts(self, resource_group): + response = self.client.issue.list_alerts( + resource_uri="str", + body={"filter": "str"}, + api_version="2025-03-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_issue_list_resources(self, resource_group): + response = self.client.issue.list_resources( + resource_uri="str", + body={"filter": "str"}, + api_version="2025-03-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_issue_start_investigation(self, resource_group): + response = self.client.issue.start_investigation( + resource_uri="str", + body={ + "investigationScopes": [ + {"id": "str", "origin": {"addedBy": "str", "addedByType": "str"}, "relevance": "str"} + ], + "impactTime": "2020-02-20 00:00:00", + }, + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_issue_operations_async.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_issue_operations_async.py new file mode 100644 index 000000000000..94b300bf14ac --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_issue_operations_async.py @@ -0,0 +1,231 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement.aio import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementIssueOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_issue_list(self, resource_group): + response = self.client.issue.list( + resource_uri="str", + api_version="2025-03-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_issue_get(self, resource_group): + response = await self.client.issue.get( + resource_uri="str", + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_issue_create(self, resource_group): + response = await self.client.issue.create( + resource_uri="str", + resource={ + "id": "str", + "name": "str", + "properties": { + "impactTime": "2020-02-20 00:00:00", + "investigations": [ + { + "createdAt": "2020-02-20 00:00:00", + "execution": {"completedAt": "2020-02-20 00:00:00", "runState": "str"}, + "id": "str", + "runParameters": { + "alerts": [ + { + "id": "str", + "origin": {"addedBy": "str", "addedByType": "str"}, + "relevance": "str", + } + ], + "impactTime": "2020-02-20 00:00:00", + "resources": [ + { + "id": "str", + "origin": {"addedBy": "str", "addedByType": "str"}, + "relevance": "str", + } + ], + }, + } + ], + "investigationsCount": 0, + "severity": "str", + "status": "str", + "title": "str", + "provisioningState": "str", + }, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_issue_update(self, resource_group): + response = await self.client.issue.update( + resource_uri="str", + properties={ + "id": "str", + "name": "str", + "properties": {"impactTime": "2020-02-20 00:00:00", "severity": "str", "status": "str", "title": "str"}, + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "type": "str", + }, + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_issue_delete(self, resource_group): + response = await self.client.issue.delete( + resource_uri="str", + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_issue_add_or_update_alerts(self, resource_group): + response = await self.client.issue.add_or_update_alerts( + resource_uri="str", + body={ + "value": [ + { + "addedAt": "2020-02-20 00:00:00", + "id": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "origin": {"addedBy": "str", "addedByType": "str"}, + "relevance": "str", + } + ] + }, + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_issue_add_or_update_resources(self, resource_group): + response = await self.client.issue.add_or_update_resources( + resource_uri="str", + body={ + "value": [ + { + "addedAt": "2020-02-20 00:00:00", + "id": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "origin": {"addedBy": "str", "addedByType": "str"}, + "relevance": "str", + } + ] + }, + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_issue_fetch_investigation_result(self, resource_group): + response = await self.client.issue.fetch_investigation_result( + resource_uri="str", + body={"investigationId": "str"}, + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_issue_list_alerts(self, resource_group): + response = self.client.issue.list_alerts( + resource_uri="str", + body={"filter": "str"}, + api_version="2025-03-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_issue_list_resources(self, resource_group): + response = self.client.issue.list_resources( + resource_uri="str", + body={"filter": "str"}, + api_version="2025-03-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_issue_start_investigation(self, resource_group): + response = await self.client.issue.start_investigation( + resource_uri="str", + body={ + "investigationScopes": [ + {"id": "str", "origin": {"addedBy": "str", "addedByType": "str"}, "relevance": "str"} + ], + "impactTime": "2020-02-20 00:00:00", + }, + api_version="2025-03-01-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_operations.py new file mode 100644 index 000000000000..742a2accb0e1 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_operations.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2024-01-01-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_operations_async.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_operations_async.py new file mode 100644 index 000000000000..378b489699bc --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_operations_async.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement.aio import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_operations_list(self, resource_group): + response = self.client.operations.list( + api_version="2024-01-01-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_prometheus_rule_groups_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_prometheus_rule_groups_operations.py new file mode 100644 index 000000000000..5fe43e09259f --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_prometheus_rule_groups_operations.py @@ -0,0 +1,123 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementPrometheusRuleGroupsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_prometheus_rule_groups_list_by_subscription(self, resource_group): + response = self.client.prometheus_rule_groups.list_by_subscription( + api_version="2023-03-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_prometheus_rule_groups_list_by_resource_group(self, resource_group): + response = self.client.prometheus_rule_groups.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2023-03-01", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_prometheus_rule_groups_get(self, resource_group): + response = self.client.prometheus_rule_groups.get( + resource_group_name=resource_group.name, + rule_group_name="str", + api_version="2023-03-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_prometheus_rule_groups_create_or_update(self, resource_group): + response = self.client.prometheus_rule_groups.create_or_update( + resource_group_name=resource_group.name, + rule_group_name="str", + parameters={ + "location": "str", + "rules": [ + { + "expression": "str", + "actions": [{"actionGroupId": "str", "actionProperties": {"str": "str"}}], + "alert": "str", + "annotations": {"str": "str"}, + "enabled": bool, + "for": "1 day, 0:00:00", + "labels": {"str": "str"}, + "record": "str", + "resolveConfiguration": {"autoResolved": bool, "timeToResolve": "1 day, 0:00:00"}, + "severity": 0, + } + ], + "scopes": ["str"], + "clusterName": "str", + "description": "str", + "enabled": bool, + "id": "str", + "interval": "1 day, 0:00:00", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2023-03-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_prometheus_rule_groups_update(self, resource_group): + response = self.client.prometheus_rule_groups.update( + resource_group_name=resource_group.name, + rule_group_name="str", + parameters={"enabled": bool, "tags": {"str": "str"}}, + api_version="2023-03-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_prometheus_rule_groups_delete(self, resource_group): + response = self.client.prometheus_rule_groups.delete( + resource_group_name=resource_group.name, + rule_group_name="str", + api_version="2023-03-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_prometheus_rule_groups_operations_async.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_prometheus_rule_groups_operations_async.py new file mode 100644 index 000000000000..d393c9e08550 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_prometheus_rule_groups_operations_async.py @@ -0,0 +1,124 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement.aio import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementPrometheusRuleGroupsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_prometheus_rule_groups_list_by_subscription(self, resource_group): + response = self.client.prometheus_rule_groups.list_by_subscription( + api_version="2023-03-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_prometheus_rule_groups_list_by_resource_group(self, resource_group): + response = self.client.prometheus_rule_groups.list_by_resource_group( + resource_group_name=resource_group.name, + api_version="2023-03-01", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_prometheus_rule_groups_get(self, resource_group): + response = await self.client.prometheus_rule_groups.get( + resource_group_name=resource_group.name, + rule_group_name="str", + api_version="2023-03-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_prometheus_rule_groups_create_or_update(self, resource_group): + response = await self.client.prometheus_rule_groups.create_or_update( + resource_group_name=resource_group.name, + rule_group_name="str", + parameters={ + "location": "str", + "rules": [ + { + "expression": "str", + "actions": [{"actionGroupId": "str", "actionProperties": {"str": "str"}}], + "alert": "str", + "annotations": {"str": "str"}, + "enabled": bool, + "for": "1 day, 0:00:00", + "labels": {"str": "str"}, + "record": "str", + "resolveConfiguration": {"autoResolved": bool, "timeToResolve": "1 day, 0:00:00"}, + "severity": 0, + } + ], + "scopes": ["str"], + "clusterName": "str", + "description": "str", + "enabled": bool, + "id": "str", + "interval": "1 day, 0:00:00", + "name": "str", + "systemData": { + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByType": "str", + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + }, + "tags": {"str": "str"}, + "type": "str", + }, + api_version="2023-03-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_prometheus_rule_groups_update(self, resource_group): + response = await self.client.prometheus_rule_groups.update( + resource_group_name=resource_group.name, + rule_group_name="str", + parameters={"enabled": bool, "tags": {"str": "str"}}, + api_version="2023-03-01", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_prometheus_rule_groups_delete(self, resource_group): + response = await self.client.prometheus_rule_groups.delete( + resource_group_name=resource_group.name, + rule_group_name="str", + api_version="2023-03-01", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_smart_groups_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_smart_groups_operations.py new file mode 100644 index 000000000000..50afe45b4276 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_smart_groups_operations.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer, recorded_by_proxy + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementSmartGroupsOperations(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_smart_groups_get_all(self, resource_group): + response = self.client.smart_groups.get_all( + api_version="2019-05-05-preview", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_smart_groups_get_by_id(self, resource_group): + response = self.client.smart_groups.get_by_id( + smart_group_id="str", + api_version="2019-05-05-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_smart_groups_change_state(self, resource_group): + response = self.client.smart_groups.change_state( + smart_group_id="str", + new_state="str", + api_version="2019-05-05-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_smart_groups_get_history(self, resource_group): + response = self.client.smart_groups.get_history( + smart_group_id="str", + api_version="2019-05-05-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_smart_groups_operations_async.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_smart_groups_operations_async.py new file mode 100644 index 000000000000..7f696f2e22a2 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_smart_groups_operations_async.py @@ -0,0 +1,64 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from azure.mgmt.alertsmanagement.aio import AlertsManagementClient + +from devtools_testutils import AzureMgmtRecordedTestCase, RandomNameResourceGroupPreparer +from devtools_testutils.aio import recorded_by_proxy_async + +AZURE_LOCATION = "eastus" + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAlertsManagementSmartGroupsOperationsAsync(AzureMgmtRecordedTestCase): + def setup_method(self, method): + self.client = self.create_mgmt_client(AlertsManagementClient, is_async=True) + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_smart_groups_get_all(self, resource_group): + response = self.client.smart_groups.get_all( + api_version="2019-05-05-preview", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_smart_groups_get_by_id(self, resource_group): + response = await self.client.smart_groups.get_by_id( + smart_group_id="str", + api_version="2019-05-05-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_smart_groups_change_state(self, resource_group): + response = await self.client.smart_groups.change_state( + smart_group_id="str", + new_state="str", + api_version="2019-05-05-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_smart_groups_get_history(self, resource_group): + response = await self.client.smart_groups.get_history( + smart_group_id="str", + api_version="2019-05-05-preview", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/setup.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/setup.py index 5d5ea95810ad..a7e4966c6089 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/setup.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/setup.py @@ -1,10 +1,10 @@ #!/usr/bin/env python -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- import re import os.path @@ -16,64 +16,67 @@ PACKAGE_PPRINT_NAME = "Alerts Management" # a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace('-', '/') +package_folder_path = PACKAGE_NAME.replace("-", "/") # a-b-c => a.b.c -namespace_name = PACKAGE_NAME.replace('-', '.') +namespace_name = PACKAGE_NAME.replace("-", ".") # Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, 'version.py') - if os.path.exists(os.path.join(package_folder_path, 'version.py')) - else os.path.join(package_folder_path, '_version.py'), 'r') as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', - fd.read(), re.MULTILINE).group(1) +with open( + os.path.join(package_folder_path, "version.py") + if os.path.exists(os.path.join(package_folder_path, "version.py")) + else os.path.join(package_folder_path, "_version.py"), + "r", +) as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: - raise RuntimeError('Cannot find version information') + raise RuntimeError("Cannot find version information") -with open('README.md', encoding='utf-8') as f: +with open("README.md", encoding="utf-8") as f: readme = f.read() -with open('CHANGELOG.md', encoding='utf-8') as f: +with open("CHANGELOG.md", encoding="utf-8") as f: changelog = f.read() setup( name=PACKAGE_NAME, version=version, - description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), - long_description=readme + '\n\n' + changelog, - long_description_content_type='text/markdown', - license='MIT License', - author='Microsoft Corporation', - author_email='azpysdkhelp@microsoft.com', - url='https://github.com/Azure/azure-sdk-for-python', + description="Microsoft Azure {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + long_description=readme + "\n\n" + changelog, + long_description_content_type="text/markdown", + license="MIT License", + author="Microsoft Corporation", + author_email="azpysdkhelp@microsoft.com", + url="https://github.com/Azure/azure-sdk-for-python", keywords="azure, azure sdk", # update with search keywords relevant to the azure service / product classifiers=[ - 'Development Status :: 4 - Beta', - 'Programming Language :: Python', - 'Programming Language :: Python :: 3 :: Only', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'License :: OSI Approved :: MIT License', + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: MIT License", ], zip_safe=False, - packages=find_packages(exclude=[ - 'tests', - # Exclude packages that will be covered by PEP420 or nspkg - 'azure', - 'azure.mgmt', - ]), + packages=find_packages( + exclude=[ + "tests", + # Exclude packages that will be covered by PEP420 or nspkg + "azure", + "azure.mgmt", + ] + ), include_package_data=True, package_data={ - 'pytyped': ['py.typed'], + "pytyped": ["py.typed"], }, install_requires=[ - "msrest>=0.7.1", - "azure-common~=1.1", - "azure-mgmt-core>=1.3.2,<2.0.0", - "typing-extensions>=4.3.0; python_version<'3.8.0'", + "isodate>=0.6.1", + "typing-extensions>=4.6.0", + "azure-common>=1.1", + "azure-mgmt-core>=1.5.0", ], - python_requires=">=3.7" + python_requires=">=3.9", )