From dc916ef3ee2accd2c363806c28668ecf77a859ef Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Tue, 22 Oct 2024 10:39:54 +0000 Subject: [PATCH] CodeGen from PR 3542 in test-repo-billy/azure-rest-api-specs Merge e716ca33776754a44d41bddc7864dbc1fd166425 into 6c6e1713f03acaf37e5c89652b023dd2c9eae16e --- .../azure-mgmt-alertsmanagement/README.md | 55 +- .../azure-mgmt-alertsmanagement/_meta.json | 12 +- .../_alerts_management_client.py | 50 +- .../mgmt/alertsmanagement/_configuration.py | 7 +- .../mgmt/alertsmanagement/_serialization.py | 197 +- .../azure/mgmt/alertsmanagement/_vendor.py | 27 - .../azure/mgmt/alertsmanagement/_version.py | 2 +- .../aio/_alerts_management_client.py | 52 +- .../alertsmanagement/aio/_configuration.py | 7 +- .../aio/operations/__init__.py | 6 +- .../_alert_processing_rules_operations.py | 226 +-- .../_alert_rule_recommendations_operations.py | 199 +++ .../aio/operations/_alerts_operations.py | 363 ++-- .../aio/operations/_operations.py | 45 +- .../_prometheus_rule_groups_operations.py | 286 +-- .../operations/_smart_groups_operations.py | 123 +- .../mgmt/alertsmanagement/models/__init__.py | 52 +- .../models/_alerts_management_client_enums.py | 70 + .../alertsmanagement/models/_models_py3.py | 1588 ++++++++++++++--- .../alertsmanagement/operations/__init__.py | 6 +- .../_alert_processing_rules_operations.py | 250 +-- .../_alert_rule_recommendations_operations.py | 248 +++ .../operations/_alerts_operations.py | 484 +++-- .../operations/_operations.py | 49 +- .../_prometheus_rule_groups_operations.py | 355 +--- .../operations/_smart_groups_operations.py | 147 +- ...action_group_all_alerts_in_subscription.py | 3 +- ..._rules_create_or_update_add_correlation.py | 60 + ...dd_correlation_with_correlation_updates.py | 68 + ...roups_all_sev0_sev1_two_resource_groups.py | 3 +- ..._action_groups_from_specific_alert_rule.py | 3 +- ...ll_action_groups_outside_business_hours.py | 3 +- ...ion_groups_recurring_maintenance_window.py | 3 +- ...s_specific_vm_oneoff_maintenance_window.py | 3 +- .../alert_processing_rules_delete.py | 6 +- .../alert_processing_rules_get_by_id.py | 3 +- ...rt_processing_rules_list_resource_group.py | 3 +- ...lert_processing_rules_list_subscription.py | 3 +- .../alert_processing_rules_patch.py | 3 +- ...ule_recommendations_get_by_resource_mac.py | 42 + ...rule_recommendations_get_by_resource_vm.py | 42 + ...recommendations_get_by_subscription_mac.py | 42 + ..._recommendations_get_by_subscription_vm.py | 42 + .../generated_samples/alerts_change_state.py | 6 +- .../generated_samples/alerts_get_by_id.py | 6 +- .../alerts_get_enrichments.py | 42 + .../generated_samples/alerts_history.py | 6 +- .../generated_samples/alerts_list.py | 9 +- ...e_groups.py => alerts_list_enrichments.py} | 12 +- .../alerts_meta_data_monitor_service.py | 3 +- .../generated_samples/alerts_summary.py | 6 +- ...te_or_update_cluster_centric_rule_group.py | 67 + .../create_or_update_prometheus_rule_group.py | 23 +- .../delete_prometheus_rule_group.py | 10 +- .../get_prometheus_rule_group.py | 7 +- ...ist_subscription_prometheus_rule_groups.py | 5 +- .../generated_samples/operations_list.py | 3 +- .../patch_prometheus_rule_group.py | 9 +- .../smart_groups_change_state.py | 1 + .../smart_groups_get_by_id.py | 1 + .../generated_samples/smart_groups_history.py | 1 + .../generated_samples/smart_groups_list.py | 1 + .../generated_tests/conftest.py | 35 + ...ement_alert_processing_rules_operations.py | 117 ++ ...alert_processing_rules_operations_async.py | 118 ++ ...t_alert_rule_recommendations_operations.py | 41 + ...t_rule_recommendations_operations_async.py | 42 + ...est_alerts_management_alerts_operations.py | 114 ++ ...erts_management_alerts_operations_async.py | 115 ++ .../test_alerts_management_operations.py | 29 + ...test_alerts_management_operations_async.py | 30 + ...ement_prometheus_rule_groups_operations.py | 112 ++ ...prometheus_rule_groups_operations_async.py | 113 ++ ...erts_management_smart_groups_operations.py | 63 + ...anagement_smart_groups_operations_async.py | 64 + .../azure-mgmt-alertsmanagement/setup.py | 86 +- 76 files changed, 4671 insertions(+), 1864 deletions(-) delete mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_vendor.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alert_rule_recommendations_operations.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alert_rule_recommendations_operations.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_correlation.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_correlation_with_correlation_updates.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_resource_mac.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_resource_vm.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_subscription_mac.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_subscription_vm.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_get_enrichments.py rename sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/{list_prometheus_rule_groups.py => alerts_list_enrichments.py} (78%) create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/create_or_update_cluster_centric_rule_group.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/conftest.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_processing_rules_operations.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_processing_rules_operations_async.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_rule_recommendations_operations.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alert_rule_recommendations_operations_async.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alerts_operations.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_alerts_operations_async.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_operations.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_operations_async.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_prometheus_rule_groups_operations.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_prometheus_rule_groups_operations_async.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_smart_groups_operations.py create mode 100644 sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_smart_groups_operations_async.py diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/README.md b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/README.md index 1656574ab19c..c6664d44b582 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.8+. 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.8+ 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 +``` + +### Authentication + +By default, [Azure Active Directory](https://aka.ms/awps/aad) token authentication depends on correct configure of 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. - - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fazure-mgmt-alertsmanagement%2FREADME.png) diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/_meta.json b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/_meta.json index 4acb590471e5..5c5c906831de 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/_meta.json +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/_meta.json @@ -1,11 +1,11 @@ { - "commit": "e37a57df67daaa82f9c3758fc450bc8655812a08", - "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest": "3.9.2", + "commit": "f253eb885c704880cf0e1de329aa256b88018ced", + "repository_url": "https://github.com/test-repo-billy/azure-rest-api-specs", + "autorest": "3.10.2", "use": [ - "@autorest/python@6.2.7", - "@autorest/modelerfour@4.24.3" + "@autorest/python@6.19.0", + "@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.19.0 --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/_alerts_management_client.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_alerts_management_client.py index e896dc0a388c..1a2e56ce8b53 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 @@ -8,15 +8,19 @@ from copy import deepcopy from typing import Any, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient +from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy from . import models as _models from ._configuration import AlertsManagementClientConfiguration from ._serialization import Deserializer, Serializer from .operations import ( AlertProcessingRulesOperations, + AlertRuleRecommendationsOperations, AlertsOperations, Operations, PrometheusRuleGroupsOperations, @@ -31,9 +35,6 @@ class AlertsManagementClient: # pylint: disable=client-accepts-api-version-keyword """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,6 +44,12 @@ 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 :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The ID of the target subscription. Required. @@ -61,23 +68,44 @@ def __init__( self._config = AlertsManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **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=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 + ) - 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 +125,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..111d7015e13a 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_configuration.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_configuration.py @@ -8,7 +8,6 @@ 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 @@ -19,7 +18,7 @@ from azure.core.credentials import TokenCredential -class AlertsManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class AlertsManagementClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for AlertsManagementClient. Note that all parameters used to create this instance are saved as instance @@ -32,7 +31,6 @@ class AlertsManagementClientConfiguration(Configuration): # pylint: disable=too """ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(AlertsManagementClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: @@ -42,6 +40,7 @@ def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs 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 +49,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/_serialization.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_serialization.py index 2c170e28dbca..8139854b97bb 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_serialization.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/_serialization.py @@ -38,7 +38,22 @@ 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, + TypeVar, + MutableMapping, + Type, + List, + Mapping, +) try: from urllib import quote # type: ignore @@ -48,12 +63,14 @@ import isodate # type: ignore -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") +ModelType = TypeVar("ModelType", bound="Model") +JSON = MutableMapping[str, Any] + class RawDeserializer: @@ -107,7 +124,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 +143,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 @@ -153,13 +172,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: @@ -277,8 +289,8 @@ class Model(object): _attribute_map: Dict[str, Dict[str, Any]] = {} _validation: Dict[str, Dict[str, Any]] = {} - def __init__(self, **kwargs): - self.additional_properties = {} + def __init__(self, **kwargs: Any) -> None: + self.additional_properties: Optional[Dict[str, Any]] = {} for k in kwargs: 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__) @@ -287,25 +299,25 @@ def __init__(self, **kwargs): else: setattr(self, k, kwargs[k]) - def __eq__(self, other): + def __eq__(self, other: Any) -> bool: """Compare objects by comparing all attributes.""" if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False - def __ne__(self, other): + def __ne__(self, other: Any) -> bool: """Compare objects by comparing all attributes.""" 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: @@ -322,8 +334,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 +346,15 @@ 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(self, keep_readonly=keep_readonly, **kwargs) # type: ignore - 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: @@ -368,7 +385,7 @@ def my_key_transformer(key, attr_desc, value): :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore @classmethod def _infer_class_models(cls): @@ -384,7 +401,7 @@ def _infer_class_models(cls): return client_models @classmethod - def deserialize(cls, data, content_type=None): + def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. @@ -393,10 +410,15 @@ def deserialize(cls, data, content_type=None): :raises: DeserializationError if something went wrong """ 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: Type[ModelType], + data: Any, + key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> ModelType: """Parse a dict using given key extractor return a model. By default consider key @@ -409,8 +431,8 @@ def from_dict(cls, data, key_extractors=None, content_type=None): :raises: DeserializationError if something went wrong """ 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 +440,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): @@ -518,7 +540,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): self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -534,7 +556,7 @@ 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 @@ -602,7 +624,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): @@ -622,12 +644,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,12 +657,13 @@ 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) + raise SerializationError(msg) from err else: return serialized @@ -656,8 +678,8 @@ def body(self, data, data_type, **kwargs): """ # 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: @@ -683,7 +705,7 @@ def body(self, data, data_type, **kwargs): ] data = deserializer._deserialize(data_type, data) 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) @@ -703,6 +725,7 @@ 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: @@ -715,7 +738,9 @@ def query(self, name, data, data_type, **kwargs): :param data: The data to be serialized. :param str data_type: The type to be serialized from. - :rtype: str + :keyword bool skip_quote: Whether to skip quote the serialized result. + Defaults to False. + :rtype: str, list :raises: TypeError if serialization fails. :raises: ValueError if data is None """ @@ -723,10 +748,8 @@ def query(self, name, data, data_type, **kwargs): # 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) @@ -777,6 +800,8 @@ def serialize_data(self, data, data_type, **kwargs): 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) @@ -795,7 +820,7 @@ 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) + raise SerializationError(msg.format(data, data_type)) from err else: return self._serialize(data, **kwargs) @@ -863,6 +888,8 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): 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'. + :keyword bool do_quote: Whether to quote the serialized result of each iterable element. + Defaults to False. :rtype: list, str """ if isinstance(data, str): @@ -875,9 +902,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) @@ -922,7 +954,9 @@ def serialize_dict(self, attr, dict_type, **kwargs): 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: @@ -955,7 +989,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) @@ -1132,10 +1166,10 @@ 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): @@ -1161,7 +1195,8 @@ def rest_key_extractor(attr, attr_desc, data): 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,7 +1205,6 @@ 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:]) @@ -1191,7 +1225,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:]) @@ -1242,7 +1275,7 @@ 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 @@ -1266,7 +1299,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): @@ -1332,7 +1365,7 @@ class Deserializer(object): 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}]?") - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1352,7 +1385,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 @@ -1405,12 +1438,12 @@ 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): 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 @@ -1442,7 +1475,7 @@ 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) + raise DeserializationError(msg) from err else: additional_properties = self._build_additional_properties(attributes, data) return self._instantiate_model(response, d_attrs, additional_properties) @@ -1471,22 +1504,22 @@ 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. """ 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 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,7 +1529,7 @@ 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. """ try: @@ -1539,7 +1572,7 @@ 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 @@ -1613,7 +1646,7 @@ 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) + raise DeserializationError(msg) from err else: return self._deserialize(obj_type, data) @@ -1661,7 +1694,7 @@ def deserialize_object(self, attr, **kwargs): 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: @@ -1718,7 +1751,7 @@ def deserialize_basic(self, attr, data_type): if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, basestring): + elif isinstance(attr, str): if attr.lower() in ["true", "1"]: return True elif attr.lower() in ["false", "0"]: @@ -1769,7 +1802,6 @@ 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: @@ -1823,10 +1855,10 @@ def deserialize_decimal(attr): 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): @@ -1854,7 +1886,7 @@ 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) + raise DeserializationError(msg) from err else: return duration @@ -1871,7 +1903,7 @@ def deserialize_date(attr): 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): @@ -1906,7 +1938,7 @@ def deserialize_rfc(attr): 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) + raise DeserializationError(msg) from err else: return date_obj @@ -1943,7 +1975,7 @@ 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) + raise DeserializationError(msg) from err else: return date_obj @@ -1959,9 +1991,10 @@ def deserialize_unix(attr): 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) + raise DeserializationError(msg) from err else: return date_obj 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..e5754a47ce68 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 = "1.0.0b1" 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..a1a6882e52c5 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 @@ -8,15 +8,19 @@ from copy import deepcopy from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient +from azure.mgmt.core.policies import AsyncARMAutoResourceProviderRegistrationPolicy from .. import models as _models from .._serialization import Deserializer, Serializer from ._configuration import AlertsManagementClientConfiguration from .operations import ( AlertProcessingRulesOperations, + AlertRuleRecommendationsOperations, AlertsOperations, Operations, PrometheusRuleGroupsOperations, @@ -31,9 +35,6 @@ class AlertsManagementClient: # pylint: disable=client-accepts-api-version-keyword """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,6 +44,12 @@ 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 :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The ID of the target subscription. Required. @@ -61,23 +68,46 @@ def __init__( self._config = AlertsManagementClientConfiguration( credential=credential, subscription_id=subscription_id, **kwargs ) - self._client = AsyncARMPipelineClient(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), + 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=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 + ) - 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 +127,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..af57b46eae16 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,7 +8,6 @@ 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 @@ -19,7 +18,7 @@ from azure.core.credentials_async import AsyncTokenCredential -class AlertsManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class AlertsManagementClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for AlertsManagementClient. Note that all parameters used to create this instance are saved as instance @@ -32,7 +31,6 @@ class AlertsManagementClientConfiguration(Configuration): # pylint: disable=too """ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: - super(AlertsManagementClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: @@ -42,6 +40,7 @@ def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **k 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 +49,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..bab3e18425ab 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 @@ -6,22 +6,24 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -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 ._alert_rule_recommendations_operations import AlertRuleRecommendationsOperations +from ._alert_processing_rules_operations import AlertProcessingRulesOperations from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AlertProcessingRulesOperations", "PrometheusRuleGroupsOperations", "Operations", "AlertsOperations", "SmartGroupsOperations", + "AlertRuleRecommendationsOperations", + "AlertProcessingRulesOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) _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..43b2c03a053f 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,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,8 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( @@ -19,15 +20,13 @@ 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 ...operations._alert_processing_rules_operations import ( build_create_or_update_request, build_delete_request, @@ -37,10 +36,10 @@ build_update_request, ) -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -68,7 +67,6 @@ def __init__(self, *args, **kwargs) -> None: 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 +75,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", "2024-03-01-preview")) cls: ClsType[_models.AlertProcessingRulesList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -91,22 +89,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 +111,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 +136,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 +144,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", "2024-03-01-preview")) cls: ClsType[_models.AlertProcessingRulesList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -167,23 +158,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 +181,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 +209,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -240,45 +224,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", "2024-03-01-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 +281,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 +291,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 +304,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 +318,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 +328,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -373,19 +347,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", "2024-03-01-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,44 +367,33 @@ 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 @@ -442,12 +405,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -458,45 +420,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", "2024-03-01-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 +472,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 +482,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 +494,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 +508,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 +517,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -588,19 +535,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", "2024-03-01-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 +555,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..61590eff966a --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alert_rule_recommendations_operations.py @@ -0,0 +1,199 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 sys +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar + +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 ...operations._alert_rule_recommendations_operations import ( + build_list_by_resource_request, + build_list_by_target_type_request, +) + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +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 = 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") + + @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[int, Type[HttpResponseError]] = { + 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[int, Type[HttpResponseError]] = { + 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_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_alerts_operations.py index 4e3955d1a17e..f052578c17c2 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,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,8 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( @@ -19,28 +20,28 @@ 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 ...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, ) -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -71,12 +72,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -87,44 +87,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 +144,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 +159,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 @@ -211,7 +209,6 @@ def get_all( 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 +216,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -235,8 +230,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 +250,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 +269,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -319,47 +311,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,6 +355,8 @@ 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 @@ -379,7 +367,6 @@ async def change_state( :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 +375,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. :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 +405,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. :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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -450,16 +438,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 +453,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -527,47 +509,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 +561,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 +584,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 @@ -629,12 +607,11 @@ async def get_summary( 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[int, Type[HttpResponseError]] = { 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[int, Type[HttpResponseError]] = { + 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[int, Type[HttpResponseError]] = { + 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/_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/aio/operations/_operations.py index 16de0c077489..1cd3a0fda200 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,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( @@ -19,20 +19,18 @@ 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 ...operations._operations import build_list_request -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -60,7 +58,6 @@ def __init__(self, *args, **kwargs) -> None: 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 +65,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -84,21 +79,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 +100,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..dccc0bcd61d9 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,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,8 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, Type, TypeVar, Union, overload from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( @@ -19,28 +20,25 @@ 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 ...operations._prometheus_rule_groups_operations import ( build_create_or_update_request, build_delete_request, build_get_request, - build_list_by_resource_group_request, build_list_by_subscription_request, build_update_request, ) -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -66,9 +64,8 @@ def __init__(self, *args, **kwargs) -> None: @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,92 +75,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") - ) - cls: ClsType[_models.PrometheusRuleGroupResourceCollection] = kwargs.pop("cls", None) - - error_map = { - 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_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) - - else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - 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) - 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) - - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **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) - 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 - ) -> AsyncIterable["_models.PrometheusRuleGroupResource"]: - """Retrieve Prometheus rule group definitions in a 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: - ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -174,23 +89,19 @@ def list_by_resource_group( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_group_request( - resource_group_name=resource_group_name, + _request = build_list_by_subscription_request( 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 +111,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 +139,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -247,44 +154,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 +208,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 +218,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 +231,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 +245,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 +255,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -379,21 +273,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 +293,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 +335,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 +350,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 +363,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 +377,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 +387,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -527,21 +406,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,34 +426,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.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 @@ -589,12 +461,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -605,37 +476,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..933de264f2f7 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,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import sys -from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union +from typing import Any, AsyncIterable, Callable, Dict, Optional, Type, TypeVar, Union from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( @@ -19,15 +19,13 @@ 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 ...operations._smart_groups_operations import ( build_change_state_request, build_get_all_request, @@ -35,10 +33,10 @@ build_get_history_request, ) -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] @@ -95,7 +93,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 @@ -122,7 +120,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 +127,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -146,7 +141,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 +155,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 +174,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 +191,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 +199,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -224,24 +214,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 +241,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( @@ -276,12 +259,11 @@ async def change_state( :param new_state: New state of the alert. Known values are: "New", "Acknowledged", and "Closed". 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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -292,25 +274,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 +302,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 +316,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -357,24 +331,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 +355,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..34fb1df8ca13 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 @@ -10,6 +10,10 @@ from ._models_py3 import ActionStatus from ._models_py3 import AddActionGroups from ._models_py3 import Alert +from ._models_py3 import AlertEnrichmentItem +from ._models_py3 import AlertEnrichmentProperties +from ._models_py3 import AlertEnrichmentResponse +from ._models_py3 import AlertEnrichmentsList from ._models_py3 import AlertModification from ._models_py3 import AlertModificationItem from ._models_py3 import AlertModificationProperties @@ -17,6 +21,8 @@ from ._models_py3 import AlertProcessingRuleProperties from ._models_py3 import AlertProcessingRulesList from ._models_py3 import AlertProperties +from ._models_py3 import AlertRuleRecommendationResource +from ._models_py3 import AlertRuleRecommendationsListResponse from ._models_py3 import AlertsList from ._models_py3 import AlertsMetaData from ._models_py3 import AlertsMetaDataProperties @@ -25,13 +31,19 @@ from ._models_py3 import AlertsSummaryGroupItem from ._models_py3 import Comments from ._models_py3 import Condition +from ._models_py3 import CorrelateAlerts +from ._models_py3 import CorrelateBy +from ._models_py3 import CorrelationDetails +from ._models_py3 import CorrelationUpdates from ._models_py3 import DailyRecurrence from ._models_py3 import ErrorAdditionalInfo from ._models_py3 import ErrorDetail +from ._models_py3 import ErrorDetailAutoGenerated from ._models_py3 import ErrorResponse from ._models_py3 import ErrorResponseAutoGenerated from ._models_py3 import ErrorResponseAutoGenerated2 from ._models_py3 import ErrorResponseAutoGenerated3 +from ._models_py3 import ErrorResponseAutoGenerated4 from ._models_py3 import ErrorResponseBody from ._models_py3 import ErrorResponseBodyAutoGenerated from ._models_py3 import ErrorResponseBodyAutoGenerated2 @@ -44,17 +56,22 @@ from ._models_py3 import OperationDisplay from ._models_py3 import OperationsList from ._models_py3 import PatchObject +from ._models_py3 import PrometheusEnrichmentItem +from ._models_py3 import PrometheusInstantQuery +from ._models_py3 import PrometheusRangeQuery 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 PrometheusRuleGroupResourcePatchParameters from ._models_py3 import PrometheusRuleResolveConfiguration +from ._models_py3 import ProxyResource from ._models_py3 import Recurrence from ._models_py3 import RemoveAllActionGroups from ._models_py3 import Resource from ._models_py3 import ResourceAutoGenerated +from ._models_py3 import ResourceAutoGenerated2 +from ._models_py3 import RuleArmTemplate from ._models_py3 import Schedule from ._models_py3 import SmartGroup from ._models_py3 import SmartGroupAggregatedProperty @@ -76,8 +93,10 @@ 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 MetricAlertsDisplayUnit from ._alerts_management_client_enums import MonitorCondition from ._alerts_management_client_enums import MonitorService +from ._alerts_management_client_enums import NotificationsForCorrelatedAlerts from ._alerts_management_client_enums import Operator from ._alerts_management_client_enums import RecurrenceType from ._alerts_management_client_enums import Severity @@ -86,7 +105,10 @@ 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 Status from ._alerts_management_client_enums import TimeRange +from ._alerts_management_client_enums import Type +from ._alerts_management_client_enums import UpdateType from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk @@ -96,6 +118,10 @@ "ActionStatus", "AddActionGroups", "Alert", + "AlertEnrichmentItem", + "AlertEnrichmentProperties", + "AlertEnrichmentResponse", + "AlertEnrichmentsList", "AlertModification", "AlertModificationItem", "AlertModificationProperties", @@ -103,6 +129,8 @@ "AlertProcessingRuleProperties", "AlertProcessingRulesList", "AlertProperties", + "AlertRuleRecommendationResource", + "AlertRuleRecommendationsListResponse", "AlertsList", "AlertsMetaData", "AlertsMetaDataProperties", @@ -111,13 +139,19 @@ "AlertsSummaryGroupItem", "Comments", "Condition", + "CorrelateAlerts", + "CorrelateBy", + "CorrelationDetails", + "CorrelationUpdates", "DailyRecurrence", "ErrorAdditionalInfo", "ErrorDetail", + "ErrorDetailAutoGenerated", "ErrorResponse", "ErrorResponseAutoGenerated", "ErrorResponseAutoGenerated2", "ErrorResponseAutoGenerated3", + "ErrorResponseAutoGenerated4", "ErrorResponseBody", "ErrorResponseBodyAutoGenerated", "ErrorResponseBodyAutoGenerated2", @@ -130,17 +164,22 @@ "OperationDisplay", "OperationsList", "PatchObject", + "PrometheusEnrichmentItem", + "PrometheusInstantQuery", + "PrometheusRangeQuery", "PrometheusRule", "PrometheusRuleGroupAction", "PrometheusRuleGroupResource", "PrometheusRuleGroupResourceCollection", - "PrometheusRuleGroupResourcePatch", - "PrometheusRuleGroupResourcePatchProperties", + "PrometheusRuleGroupResourcePatchParameters", "PrometheusRuleResolveConfiguration", + "ProxyResource", "Recurrence", "RemoveAllActionGroups", "Resource", "ResourceAutoGenerated", + "ResourceAutoGenerated2", + "RuleArmTemplate", "Schedule", "SmartGroup", "SmartGroupAggregatedProperty", @@ -161,8 +200,10 @@ "Field", "Identifier", "MetadataIdentifier", + "MetricAlertsDisplayUnit", "MonitorCondition", "MonitorService", + "NotificationsForCorrelatedAlerts", "Operator", "RecurrenceType", "Severity", @@ -171,7 +212,10 @@ "SmartGroupsSortByFields", "SortOrder", "State", + "Status", "TimeRange", + "Type", + "UpdateType", ] __all__.extend([p for p in _patch_all if p not in __all__]) _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..e87c2733ac35 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 @@ -15,6 +15,7 @@ class ActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): ADD_ACTION_GROUPS = "AddActionGroups" REMOVE_ALL_ACTION_GROUPS = "RemoveAllActionGroups" + CORRELATE_ALERTS = "CorrelateAlerts" class AlertModificationEvent(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -114,6 +115,47 @@ class MetadataIdentifier(str, Enum, metaclass=CaseInsensitiveEnumMeta): 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 +180,14 @@ class MonitorService(str, Enum, metaclass=CaseInsensitiveEnumMeta): SMART_DETECTOR = "SmartDetector" VM_INSIGHTS = "VM Insights" ZABBIX = "Zabbix" + RESOURCE_HEALTH = "Resource Health" + + +class NotificationsForCorrelatedAlerts(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Indicates how to handle child alerts notifications.""" + + NOTIFY_ALWAYS = "NotifyAlways" + SUPPRESS_ALWAYS = "SuppressAlways" class Operator(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -209,6 +259,13 @@ 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" + + class TimeRange(str, Enum, metaclass=CaseInsensitiveEnumMeta): """TimeRange.""" @@ -216,3 +273,16 @@ 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" + + +class UpdateType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of update that needs to be performed.""" + + TIME_BASED = "timeBased" 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..dace6bccbf6b 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 @@ -8,25 +8,32 @@ # -------------------------------------------------------------------------- import datetime -from typing import Dict, List, Optional, TYPE_CHECKING, Union +import sys +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union from .. import _serialization +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from .. import models as _models +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object class Action(_serialization.Model): """Action to be applied. You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AddActionGroups, RemoveAllActionGroups + AddActionGroups, CorrelateAlerts, 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". + :ivar action_type: Action that should be applied. Required. Known values are: + "AddActionGroups", "RemoveAllActionGroups", and "CorrelateAlerts". :vartype action_type: str or ~azure.mgmt.alertsmanagement.models.ActionType """ @@ -39,10 +46,14 @@ class Action(_serialization.Model): } _subtype_map = { - "action_type": {"AddActionGroups": "AddActionGroups", "RemoveAllActionGroups": "RemoveAllActionGroups"} + "action_type": { + "AddActionGroups": "AddActionGroups", + "CorrelateAlerts": "CorrelateAlerts", + "RemoveAllActionGroups": "RemoveAllActionGroups", + } } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.action_type: Optional[str] = None @@ -59,7 +70,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,10 +82,10 @@ 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". + :ivar action_type: Action that should be applied. Required. Known values are: + "AddActionGroups", "RemoveAllActionGroups", and "CorrelateAlerts". :vartype action_type: str or ~azure.mgmt.alertsmanagement.models.ActionType :ivar action_group_ids: List of action group Ids to add to alert processing rule. Required. :vartype action_group_ids: list[str] @@ -90,7 +101,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 +111,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,7 +136,7 @@ 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 @@ -133,7 +144,7 @@ def __init__(self, **kwargs): self.name = 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 +172,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 +181,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" and "Failed". + :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" and "Failed". + :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 = 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}". # pylint: disable=line-too-long + :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 = None + self.name = None + self.type = None + self.system_data = 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}". # pylint: disable=line-too-long + :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 +423,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 +473,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,7 +524,7 @@ 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] @@ -309,12 +534,12 @@ def __init__(self, *, modifications: Optional[List["_models.AlertModificationIte 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 +568,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 +585,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 +627,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 @@ -418,9 +643,10 @@ def __init__( 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 +685,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 +725,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,7 +767,7 @@ 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 @@ -548,6 +778,178 @@ def __init__(self, *, essentials: Optional["_models.Essentials"] = None, **kwarg self.egress_config = None +class Resource(_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. Ex - + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long + :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 = None + self.name = None + self.type = None + self.system_data = 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}. # pylint: disable=line-too-long + :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}. # pylint: disable=line-too-long + :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. @@ -562,7 +964,9 @@ class AlertsList(_serialization.Model): "value": {"key": "value", "type": "[Alert]"}, } - def __init__(self, *, next_link: Optional[str] = None, value: Optional[List["_models.Alert"]] = None, **kwargs): + 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 @@ -585,7 +989,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 +1004,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 +1021,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 +1055,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 +1091,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 +1137,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 @@ -763,7 +1167,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 @@ -772,49 +1176,225 @@ def __init__(self, *, comments: Optional[str] = None, **kwargs): self.comments = comments -class Condition(_serialization.Model): - """Condition to trigger an alert processing rule. +class Condition(_serialization.Model): + """Condition to trigger an alert processing rule. + + :ivar field: Field for a given condition. Known values are: "Severity", "MonitorService", + "MonitorCondition", "SignalType", "TargetResourceType", "TargetResource", + "TargetResourceGroup", "AlertRuleId", "AlertRuleName", "Description", and "AlertContext". + :vartype field: str or ~azure.mgmt.alertsmanagement.models.Field + :ivar operator: Operator for a given condition. Known values are: "Equals", "NotEquals", + "Contains", and "DoesNotContain". + :vartype operator: str or ~azure.mgmt.alertsmanagement.models.Operator + :ivar values: List of values to match for a given condition. + :vartype values: list[str] + """ + + _attribute_map = { + "field": {"key": "field", "type": "str"}, + "operator": {"key": "operator", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, + } + + def __init__( + self, + *, + field: Optional[Union[str, "_models.Field"]] = None, + operator: Optional[Union[str, "_models.Operator"]] = None, + values: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword field: Field for a given condition. Known values are: "Severity", "MonitorService", + "MonitorCondition", "SignalType", "TargetResourceType", "TargetResource", + "TargetResourceGroup", "AlertRuleId", "AlertRuleName", "Description", and "AlertContext". + :paramtype field: str or ~azure.mgmt.alertsmanagement.models.Field + :keyword operator: Operator for a given condition. Known values are: "Equals", "NotEquals", + "Contains", and "DoesNotContain". + :paramtype operator: str or ~azure.mgmt.alertsmanagement.models.Operator + :keyword values: List of values to match for a given condition. + :paramtype values: list[str] + """ + super().__init__(**kwargs) + self.field = field + self.operator = operator + self.values = values + + +class CorrelateAlerts(Action): + """Add logic for alerts correlation. + + 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", "RemoveAllActionGroups", and "CorrelateAlerts". + :vartype action_type: str or ~azure.mgmt.alertsmanagement.models.ActionType + :ivar correlate_by: The list of conditions for the alerts correlations. Required. + :vartype correlate_by: list[~azure.mgmt.alertsmanagement.models.CorrelateBy] + :ivar correlation_interval: The required duration (in ISO8601 format) for the alerts + correlation. Required. + :vartype correlation_interval: str + :ivar priority: The priority of this correlation. Required. + :vartype priority: int + :ivar notifications_for_correlated_alerts: Indicates how to handle child alerts notifications. + Known values are: "NotifyAlways" and "SuppressAlways". + :vartype notifications_for_correlated_alerts: str or + ~azure.mgmt.alertsmanagement.models.NotificationsForCorrelatedAlerts + :ivar correlation_updates: Defines the updates to be applied for correlation. + :vartype correlation_updates: ~azure.mgmt.alertsmanagement.models.CorrelationUpdates + """ + + _validation = { + "action_type": {"required": True}, + "correlate_by": {"required": True}, + "correlation_interval": {"required": True}, + "priority": {"required": True}, + } + + _attribute_map = { + "action_type": {"key": "actionType", "type": "str"}, + "correlate_by": {"key": "correlateBy", "type": "[CorrelateBy]"}, + "correlation_interval": {"key": "correlationInterval", "type": "str"}, + "priority": {"key": "priority", "type": "int"}, + "notifications_for_correlated_alerts": {"key": "notificationsForCorrelatedAlerts", "type": "str"}, + "correlation_updates": {"key": "correlationUpdates", "type": "CorrelationUpdates"}, + } + + def __init__( + self, + *, + correlate_by: List["_models.CorrelateBy"], + correlation_interval: str, + priority: int, + notifications_for_correlated_alerts: Union[str, "_models.NotificationsForCorrelatedAlerts"] = "SuppressAlways", + correlation_updates: Optional["_models.CorrelationUpdates"] = None, + **kwargs: Any + ) -> None: + """ + :keyword correlate_by: The list of conditions for the alerts correlations. Required. + :paramtype correlate_by: list[~azure.mgmt.alertsmanagement.models.CorrelateBy] + :keyword correlation_interval: The required duration (in ISO8601 format) for the alerts + correlation. Required. + :paramtype correlation_interval: str + :keyword priority: The priority of this correlation. Required. + :paramtype priority: int + :keyword notifications_for_correlated_alerts: Indicates how to handle child alerts + notifications. Known values are: "NotifyAlways" and "SuppressAlways". + :paramtype notifications_for_correlated_alerts: str or + ~azure.mgmt.alertsmanagement.models.NotificationsForCorrelatedAlerts + :keyword correlation_updates: Defines the updates to be applied for correlation. + :paramtype correlation_updates: ~azure.mgmt.alertsmanagement.models.CorrelationUpdates + """ + super().__init__(**kwargs) + self.action_type: str = "CorrelateAlerts" + self.correlate_by = correlate_by + self.correlation_interval = correlation_interval + self.priority = priority + self.notifications_for_correlated_alerts = notifications_for_correlated_alerts + self.correlation_updates = correlation_updates + + +class CorrelateBy(_serialization.Model): + """The logic for the correlation. + + :ivar field: The JPath of the property that the alerts should be correlated by. + :vartype field: str + """ + + _attribute_map = { + "field": {"key": "field", "type": "str"}, + } + + def __init__(self, *, field: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword field: The JPath of the property that the alerts should be correlated by. + :paramtype field: str + """ + super().__init__(**kwargs) + self.field = field + + +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 = None + self.correlation_date_time = None + self.alert_processing_rule = None + + +class CorrelationUpdates(_serialization.Model): + """Defines the updates to be applied for correlation. - :ivar field: Field for a given condition. Known values are: "Severity", "MonitorService", - "MonitorCondition", "SignalType", "TargetResourceType", "TargetResource", - "TargetResourceGroup", "AlertRuleId", "AlertRuleName", "Description", and "AlertContext". - :vartype field: str or ~azure.mgmt.alertsmanagement.models.Field - :ivar operator: Operator for a given condition. Known values are: "Equals", "NotEquals", - "Contains", and "DoesNotContain". - :vartype operator: str or ~azure.mgmt.alertsmanagement.models.Operator - :ivar values: List of values to match for a given condition. - :vartype values: list[str] + All required parameters must be populated in order to send to server. + + :ivar update_type: The type of update that needs to be performed. "timeBased" + :vartype update_type: str or ~azure.mgmt.alertsmanagement.models.UpdateType + :ivar update_interval: The update interval for notification updates in ISO8601 format. + Required. + :vartype update_interval: str + :ivar action_groups: The action group ids. Required. + :vartype action_groups: list[str] """ + _validation = { + "update_type": {"required": True}, + "update_interval": {"required": True}, + "action_groups": {"required": True}, + } + _attribute_map = { - "field": {"key": "field", "type": "str"}, - "operator": {"key": "operator", "type": "str"}, - "values": {"key": "values", "type": "[str]"}, + "update_type": {"key": "updateType", "type": "str"}, + "update_interval": {"key": "updateInterval", "type": "str"}, + "action_groups": {"key": "actionGroups", "type": "[str]"}, } def __init__( self, *, - field: Optional[Union[str, "_models.Field"]] = None, - operator: Optional[Union[str, "_models.Operator"]] = None, - values: Optional[List[str]] = None, - **kwargs - ): - """ - :keyword field: Field for a given condition. Known values are: "Severity", "MonitorService", - "MonitorCondition", "SignalType", "TargetResourceType", "TargetResource", - "TargetResourceGroup", "AlertRuleId", "AlertRuleName", "Description", and "AlertContext". - :paramtype field: str or ~azure.mgmt.alertsmanagement.models.Field - :keyword operator: Operator for a given condition. Known values are: "Equals", "NotEquals", - "Contains", and "DoesNotContain". - :paramtype operator: str or ~azure.mgmt.alertsmanagement.models.Operator - :keyword values: List of values to match for a given condition. - :paramtype values: list[str] + update_type: Union[str, "_models.UpdateType"] = "timeBased", + update_interval: str, + action_groups: List[str], + **kwargs: Any + ) -> None: + """ + :keyword update_type: The type of update that needs to be performed. "timeBased" + :paramtype update_type: str or ~azure.mgmt.alertsmanagement.models.UpdateType + :keyword update_interval: The update interval for notification updates in ISO8601 format. + Required. + :paramtype update_interval: str + :keyword action_groups: The action group ids. Required. + :paramtype action_groups: list[str] """ super().__init__(**kwargs) - self.field = field - self.operator = operator - self.values = values + self.update_type = update_type + self.update_interval = update_interval + self.action_groups = action_groups class Recurrence(_serialization.Model): @@ -823,7 +1403,7 @@ class Recurrence(_serialization.Model): 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 +1428,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 +1444,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 +1465,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 @@ -917,7 +1497,7 @@ 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 @@ -957,7 +1537,50 @@ 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 + + +class ErrorDetailAutoGenerated(_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.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 = None @@ -968,6 +1591,27 @@ def __init__(self, **kwargs): 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. @@ -978,7 +1622,7 @@ class ErrorResponse(_serialization.Model): "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 +1631,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 +1663,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 +1672,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 +1683,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 @@ -1074,8 +1719,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 +1765,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 +1811,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 @@ -1214,7 +1859,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 +1888,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 +1910,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 +1934,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 +1948,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,6 +1967,8 @@ 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 @@ -1330,6 +1990,9 @@ def __init__( self.last_modified_user_name = None self.action_status = action_status self.description = description + self.has_enrichments = None + self.is_stateful_alert = None + self.correlation_details = correlation_details class MonitorServiceDetails(_serialization.Model): @@ -1346,7 +2009,7 @@ class MonitorServiceDetails(_serialization.Model): "display_name": {"key": "displayName", "type": "str"}, } - def __init__(self, *, name: Optional[str] = None, display_name: Optional[str] = None, **kwargs): + def __init__(self, *, name: Optional[str] = None, display_name: Optional[str] = None, **kwargs: Any) -> None: """ :keyword name: Monitor service name. :paramtype name: str @@ -1361,7 +2024,7 @@ def __init__(self, *, name: Optional[str] = None, display_name: Optional[str] = class MonitorServiceList(AlertsMetaDataProperties): """Monitor service details. - 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" @@ -1380,7 +2043,7 @@ class MonitorServiceList(AlertsMetaDataProperties): "data": {"key": "data", "type": "[MonitorServiceDetails]"}, } - def __init__(self, *, data: List["_models.MonitorServiceDetails"], **kwargs): + def __init__(self, *, data: List["_models.MonitorServiceDetails"], **kwargs: Any) -> None: """ :keyword data: Array of operations. Required. :paramtype data: list[~azure.mgmt.alertsmanagement.models.MonitorServiceDetails] @@ -1393,7 +2056,7 @@ def __init__(self, *, data: List["_models.MonitorServiceDetails"], **kwargs): class MonthlyRecurrence(Recurrence): """Monthly 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". @@ -1419,8 +2082,13 @@ class MonthlyRecurrence(Recurrence): } def __init__( - self, *, days_of_month: List[int], start_time: Optional[str] = None, end_time: Optional[str] = None, **kwargs - ): + 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 @@ -1457,8 +2125,8 @@ def __init__( name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, origin: Optional[str] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword name: Name of the operation. :paramtype name: str @@ -1500,8 +2168,8 @@ def __init__( resource: Optional[str] = None, operation: Optional[str] = None, description: Optional[str] = None, - **kwargs - ): + **kwargs: Any + ) -> None: """ :keyword provider: Provider name. :paramtype provider: str @@ -1522,7 +2190,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 +2207,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 @@ -1565,7 +2233,7 @@ class PatchObject(_serialization.Model): "enabled": {"key": "properties.enabled", "type": "bool"}, } - def __init__(self, *, tags: Optional[Dict[str, str]] = None, enabled: Optional[bool] = None, **kwargs): + 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] @@ -1577,32 +2245,357 @@ def __init__(self, *, tags: Optional[Dict[str, str]] = None, enabled: Optional[b self.enabled = enabled +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" and "Failed". + :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" and "Failed". + :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" and "Failed". + :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" and "Failed". + :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): # pylint: disable=too-many-instance-attributes + """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" and "Failed". + :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, + *, + 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 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" and "Failed". + :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__( + 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 +2610,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 +2625,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 +2668,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 +2691,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,56 +2708,16 @@ 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. - - 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 = { - "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): - """ """ - super().__init__(**kwargs) - self.id = None - self.name = None - self.type = None - self.system_data = None - - -class TrackedResource(ResourceAutoGenerated): - """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'. +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 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}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -1789,7 +2750,7 @@ class TrackedResource(ResourceAutoGenerated): "location": {"key": "location", "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 tags: Resource tags. :paramtype tags: dict[str, str] @@ -1806,10 +2767,10 @@ class PrometheusRuleGroupResource(TrackedResource): # pylint: disable=too-many- 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}. + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. # pylint: disable=line-too-long :vartype id: str :ivar name: The name of the resource. :vartype name: str @@ -1823,19 +2784,19 @@ class PrometheusRuleGroupResource(TrackedResource): # pylint: disable=too-many- :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. + :ivar description: Rule group description. :vartype description: str - :ivar enabled: the flag that indicates whether the Prometheus rule group is enabled. + :ivar enabled: Enable/disable rule group. :vartype enabled: bool - :ivar cluster_name: the cluster name of the rule group evaluation. + :ivar cluster_name: Apply rule to data from a specific cluster. :vartype cluster_name: str - :ivar scopes: the list of resource id's that this rule group is scoped to. Required. + :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 + :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 interval: ~datetime.timedelta + :ivar rules: Defines the rules in the Prometheus rule group. Required. :vartype rules: list[~azure.mgmt.alertsmanagement.models.PrometheusRule] """ @@ -1860,7 +2821,7 @@ class PrometheusRuleGroupResource(TrackedResource): # pylint: disable=too-many- "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"}, + "interval": {"key": "properties.interval", "type": "duration"}, "rules": {"key": "properties.rules", "type": "[PrometheusRule]"}, } @@ -1874,27 +2835,27 @@ def __init__( description: Optional[str] = None, enabled: Optional[bool] = None, cluster_name: Optional[str] = None, - interval: Optional[str] = None, - **kwargs - ): + 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: the description of the Prometheus rule group that will be included in the - alert email. + :keyword description: Rule group description. :paramtype description: str - :keyword enabled: the flag that indicates whether the Prometheus rule group is enabled. + :keyword enabled: Enable/disable rule group. :paramtype enabled: bool - :keyword cluster_name: the cluster name of the rule group evaluation. + :keyword cluster_name: Apply rule to data from a specific cluster. :paramtype cluster_name: str - :keyword scopes: the list of resource id's that this rule group is scoped to. Required. + :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 + :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 interval: ~datetime.timedelta + :keyword rules: Defines the rules in the Prometheus rule group. Required. :paramtype rules: list[~azure.mgmt.alertsmanagement.models.PrometheusRule] """ super().__init__(tags=tags, location=location, **kwargs) @@ -1917,7 +2878,7 @@ class PrometheusRuleGroupResourceCollection(_serialization.Model): "value": {"key": "value", "type": "[PrometheusRuleGroupResource]"}, } - def __init__(self, *, value: Optional[List["_models.PrometheusRuleGroupResource"]] = None, **kwargs): + 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] @@ -1926,84 +2887,58 @@ def __init__(self, *, value: Optional[List["_models.PrometheusRuleGroupResource" self.value = value -class PrometheusRuleGroupResourcePatch(_serialization.Model): +class PrometheusRuleGroupResourcePatchParameters(_serialization.Model): # pylint: disable=name-too-long """The Prometheus rule group resource for patch operations. :ivar tags: Resource tags. :vartype tags: dict[str, str] - :ivar properties: - :vartype properties: - ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResourcePatchProperties + :ivar enabled: the flag that indicates whether the Prometheus rule group is enabled. + :vartype enabled: bool """ _attribute_map = { "tags": {"key": "tags", "type": "{str}"}, - "properties": {"key": "properties", "type": "PrometheusRuleGroupResourcePatchProperties"}, + "enabled": {"key": "properties.enabled", "type": "bool"}, } - def __init__( - self, - *, - tags: Optional[Dict[str, str]] = None, - properties: Optional["_models.PrometheusRuleGroupResourcePatchProperties"] = None, - **kwargs - ): + 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 properties: - :paramtype properties: - ~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResourcePatchProperties - """ - super().__init__(**kwargs) - self.tags = tags - self.properties = properties - - -class PrometheusRuleGroupResourcePatchProperties(_serialization.Model): - """PrometheusRuleGroupResourcePatchProperties. - - :ivar enabled: the flag that indicates whether the Prometheus rule group is enabled. - :vartype enabled: bool - """ - - _attribute_map = { - "enabled": {"key": "enabled", "type": "bool"}, - } - - def __init__(self, *, enabled: Optional[bool] = None, **kwargs): - """ :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: the flag that indicates whether or not to auto resolve a fired alert. + :ivar auto_resolved: Enable alert auto-resolution. :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 + :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": "str"}, + "time_to_resolve": {"key": "timeToResolve", "type": "duration"}, } - def __init__(self, *, auto_resolved: Optional[bool] = None, time_to_resolve: Optional[str] = None, **kwargs): + 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. + :keyword auto_resolved: Enable alert auto-resolution. :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 time_to_resolve: Alert auto-resolution timeout. + :paramtype time_to_resolve: ~datetime.timedelta """ super().__init__(**kwargs) self.auto_resolved = auto_resolved @@ -2013,10 +2948,10 @@ def __init__(self, *, auto_resolved: Optional[bool] = None, time_to_resolve: Opt class RemoveAllActionGroups(Action): """Indicates if all action groups should be removed. - 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". + :ivar action_type: Action that should be applied. Required. Known values are: + "AddActionGroups", "RemoveAllActionGroups", and "CorrelateAlerts". :vartype action_type: str or ~azure.mgmt.alertsmanagement.models.ActionType """ @@ -2028,12 +2963,77 @@ class RemoveAllActionGroups(Action): "action_type": {"key": "actionType", "type": "str"}, } - def __init__(self, **kwargs): + def __init__(self, **kwargs: Any) -> None: """ """ super().__init__(**kwargs) self.action_type: str = "RemoveAllActionGroups" +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}, + } + + _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]"}, + } + + 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 Schedule(_serialization.Model): """Scheduling configuration for a given alert processing rule. @@ -2068,8 +3068,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 +3089,7 @@ def __init__( self.recurrences = recurrences -class SmartGroup(Resource): # pylint: disable=too-many-instance-attributes +class SmartGroup(ResourceAutoGenerated): # pylint: disable=too-many-instance-attributes """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 +3180,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 @@ -2239,7 +3239,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 +3251,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 +3279,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 +3331,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 +3389,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] @@ -2416,8 +3418,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 @@ -2466,8 +3468,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 @@ -2496,7 +3498,7 @@ def __init__( 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 +3529,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..bab3e18425ab 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 @@ -6,22 +6,24 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -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 ._alert_rule_recommendations_operations import AlertRuleRecommendationsOperations +from ._alert_processing_rules_operations import AlertProcessingRulesOperations from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AlertProcessingRulesOperations", "PrometheusRuleGroupsOperations", "Operations", "AlertsOperations", "SmartGroupsOperations", + "AlertRuleRecommendationsOperations", + "AlertProcessingRulesOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) _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..6ee310f82fd1 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=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,8 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Iterable, Optional, Type, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -19,20 +20,18 @@ ) 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 -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -44,7 +43,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", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -55,7 +54,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,7 +69,7 @@ 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", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -83,7 +82,7 @@ def build_list_by_resource_group_request(resource_group_name: str, subscription_ "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,7 +99,7 @@ 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", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -114,7 +113,7 @@ def build_get_by_name_request( "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 +130,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", "2024-03-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -146,7 +145,7 @@ def build_create_or_update_request( "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,7 +164,7 @@ 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", "2024-03-01-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -179,7 +178,7 @@ def build_delete_request( "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 +195,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", "2024-03-01-preview")) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) accept = _headers.pop("Accept", "application/json") @@ -211,7 +210,7 @@ def build_update_request( "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") @@ -247,7 +246,6 @@ def __init__(self, *args, **kwargs): 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 +253,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", "2024-03-01-preview")) cls: ClsType[_models.AlertProcessingRulesList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -269,22 +267,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 +289,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 +314,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 +321,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", "2024-03-01-preview")) cls: ClsType[_models.AlertProcessingRulesList] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -344,23 +335,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 +358,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 +386,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -417,45 +401,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", "2024-03-01-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 +458,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 +468,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 +481,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 +495,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 +505,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -550,19 +524,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", "2024-03-01-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 +544,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 +582,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -635,45 +597,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", "2024-03-01-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 +649,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 +659,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 +671,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 +685,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 +694,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -765,19 +712,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", "2024-03-01-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 +732,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..b966f36271f3 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alert_rule_recommendations_operations.py @@ -0,0 +1,248 @@ +# pylint: disable=too-many-lines,too-many-statements +# 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 sys +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar + +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 .._serialization import Serializer + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +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" + ) # pylint: disable=line-too-long + 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 = 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") + + @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[int, Type[HttpResponseError]] = { + 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[int, Type[HttpResponseError]] = { + 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_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_alerts_operations.py index f4835f11fa5b..49724aa52963 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 @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,8 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Iterable, Optional, Type, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -19,20 +20,18 @@ ) 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 -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -44,9 +43,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 +60,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 +84,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 +138,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 +164,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 +194,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 +220,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 +239,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 +284,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:: @@ -332,12 +362,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -348,44 +377,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 +434,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 +449,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 @@ -472,7 +499,6 @@ def get_all( 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 +506,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -496,8 +520,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 +540,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 +559,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -580,47 +601,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,6 +645,8 @@ 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 @@ -640,7 +657,6 @@ def change_state( :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 +665,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. :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 +695,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. :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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -711,16 +728,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 +743,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -788,47 +799,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 +851,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 +874,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 @@ -890,12 +897,11 @@ def get_summary( 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[int, Type[HttpResponseError]] = { 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[int, Type[HttpResponseError]] = { + 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[int, Type[HttpResponseError]] = { + 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/_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/azure/mgmt/alertsmanagement/operations/_operations.py index a607bf0f4a25..4aa32c2a36ed 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,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar from azure.core.exceptions import ( ClientAuthenticationError, @@ -19,20 +19,18 @@ ) 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 -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -44,9 +42,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 @@ -84,7 +80,6 @@ def __init__(self, *args, **kwargs): 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 +87,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -108,21 +101,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 +122,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..9d936f886657 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=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,8 +6,9 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Iterable, Optional, Type, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, @@ -19,20 +20,18 @@ ) 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 -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -44,9 +43,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-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 @@ -57,39 +54,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 - - # 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_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - _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") - ) - 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( - "resource_group_name", resource_group_name, "str", max_length=90, 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") @@ -106,9 +71,7 @@ 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 @@ -121,10 +84,10 @@ def build_get_request( "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 +104,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") @@ -157,10 +118,10 @@ def build_create_or_update_request( "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 +140,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") @@ -195,10 +154,10 @@ def build_update_request( "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,9 +176,7 @@ 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 @@ -232,10 +189,10 @@ def build_delete_request( "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") @@ -267,89 +224,8 @@ def __init__(self, *args, **kwargs): @distributed_trace def list_by_subscription(self, **kwargs: Any) -> Iterable["_models.PrometheusRuleGroupResource"]: - """Retrieve Prometheus 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: - ~azure.core.paging.ItemPaged[~azure.mgmt.alertsmanagement.models.PrometheusRuleGroupResource] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _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") - ) - cls: ClsType[_models.PrometheusRuleGroupResourceCollection] = kwargs.pop("cls", None) - - error_map = { - 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_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) - - else: - request = HttpRequest("GET", next_link) - request = _convert_request(request) - request.url = self._client.format_url(request.url) - request.method = "GET" - return request - - def extract_data(pipeline_response): - deserialized = self._deserialize("PrometheusRuleGroupResourceCollection", pipeline_response) - list_of_elem = deserialized.value - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return None, iter(list_of_elem) + """Retrieve Prometheus all rule group definitions in a subscription. - def get_next(next_link=None): - request = prepare_request(next_link) - - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, stream=False, **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) - 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 - ) -> Iterable["_models.PrometheusRuleGroupResource"]: - """Retrieve Prometheus rule group definitions in a 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 +235,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -375,23 +249,19 @@ def list_by_resource_group( def prepare_request(next_link=None): if not next_link: - request = build_list_by_resource_group_request( - resource_group_name=resource_group_name, + _request = build_list_by_subscription_request( 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 +271,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 +297,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -446,44 +312,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 +366,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 +376,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 +389,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 +403,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 +413,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -578,21 +431,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 +451,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 +493,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 +508,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 +521,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 +535,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 +545,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -726,21 +564,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 +584,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 +619,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -804,37 +634,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..1a5146fef22f 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,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,too-many-statements # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,7 +7,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import sys -from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union +from typing import Any, Callable, Dict, Iterable, Optional, Type, TypeVar, Union from azure.core.exceptions import ( ClientAuthenticationError, @@ -19,20 +19,18 @@ ) 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 -if sys.version_info >= (3, 8): - from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping else: - from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -59,9 +57,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 +68,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,9 +105,7 @@ 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 @@ -124,7 +118,7 @@ def build_get_by_id_request(smart_group_id: str, subscription_id: str, **kwargs: "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,9 +135,7 @@ 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 @@ -156,7 +148,7 @@ def build_change_state_request( "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,9 +164,7 @@ 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 @@ -187,7 +177,7 @@ def build_get_history_request(smart_group_id: str, subscription_id: str, **kwarg "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") @@ -250,7 +240,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 @@ -277,7 +267,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 +274,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -301,7 +288,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 +302,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 +321,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 +338,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 +346,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -379,24 +361,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 +388,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 cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized - - get_by_id.metadata = { - "url": "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}" - } + return deserialized # type: ignore @distributed_trace def change_state( @@ -431,12 +406,11 @@ def change_state( :param new_state: New state of the alert. Known values are: "New", "Acknowledged", and "Closed". 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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -447,25 +421,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 +449,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 +463,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[int, Type[HttpResponseError]] = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -512,24 +478,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 +502,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 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/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..5e48b3384110 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -53,6 +54,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/2024-03-01-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_correlation.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_correlation.py new file mode 100644 index 000000000000..b63383d3bd08 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_correlation.py @@ -0,0 +1,60 @@ +# 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_processing_rules_create_or_update_add_correlation.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(), + subscription_id="subId1", + ) + + response = client.alert_processing_rules.create_or_update( + resource_group_name="alertscorrelationrg", + alert_processing_rule_name="CorrelateAlerts", + alert_processing_rule={ + "location": "Global", + "properties": { + "actions": [ + { + "actionType": "CorrelateAlerts", + "correlateBy": [{"field": "essentials.alertRule"}], + "correlationInterval": "PT30M", + "notificationsForCorrelatedAlerts": "SuppressAlways", + "priority": 50, + } + ], + "description": "Correlate Alerts Example.", + "enabled": True, + "scopes": ["/subscriptions/subId1"], + }, + "tags": {}, + }, + ) + print(response) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2024-03-01-preview/examples/AlertProcessingRules_Create_or_update_add_correlation.json +if __name__ == "__main__": + main() diff --git a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_correlation_with_correlation_updates.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_correlation_with_correlation_updates.py new file mode 100644 index 000000000000..05a19480ff18 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_processing_rules_create_or_update_add_correlation_with_correlation_updates.py @@ -0,0 +1,68 @@ +# 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_processing_rules_create_or_update_add_correlation_with_correlation_updates.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(), + subscription_id="subId1", + ) + + response = client.alert_processing_rules.create_or_update( + resource_group_name="alertscorrelationrg", + alert_processing_rule_name="CorrelateAlerts", + alert_processing_rule={ + "location": "Global", + "properties": { + "actions": [ + { + "actionType": "CorrelateAlerts", + "correlateBy": [{"field": "essentials.alertRule"}], + "correlationInterval": "PT30M", + "correlationUpdates": { + "actionGroups": [ + "/subscriptions/subId1/resourcegroups/RGId1/providers/microsoft.insights/actiongroups/AGId1", + "/subscriptions/subId1/resourcegroups/RGId1/providers/microsoft.insights/actiongroups/AGId2", + ], + "updateInterval": "PT15M", + "updateType": "timeBased", + }, + "notificationsForCorrelatedAlerts": "SuppressAlways", + "priority": 50, + } + ], + "description": "Correlate Alerts Example.", + "enabled": True, + "scopes": ["/subscriptions/subId1"], + }, + "tags": {}, + }, + ) + print(response) + + +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2024-03-01-preview/examples/AlertProcessingRules_Create_or_update_add_correlation_with_correlation_updates.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..b11f83f3a62e 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -55,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_two_action_groups_all_Sev0_Sev1_two_resource_groups.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2024-03-01-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..ad4fecda215f 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -55,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_from_specific_alert_rule.json +# x-ms-original-file: specification/alertsmanagement/resource-manager/Microsoft.AlertsManagement/preview/2024-03-01-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..4db48f066baa 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -53,6 +54,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/2024-03-01-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..91de196178a9 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -64,6 +65,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/2024-03-01-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..8e1ded45b3da 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -53,6 +54,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/2024-03-01-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..bfc9421213af 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -29,13 +30,12 @@ def main(): 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/2024-03-01-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..e19433560749 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -36,6 +37,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/2024-03-01-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..0ebd2d5015f6 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -36,6 +37,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/2024-03-01-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..32af1124115d 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -34,6 +35,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/2024-03-01-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..b204bf3404bf 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -37,6 +38,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/2024-03-01-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..9055a24826f9 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_resource_mac.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. +# -------------------------------------------------------------------------- + +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(), + 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..580b8048ff01 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_resource_vm.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. +# -------------------------------------------------------------------------- + +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(), + 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..339d92cc2c0d --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_subscription_mac.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. +# -------------------------------------------------------------------------- + +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(), + 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..512ad5f48cbd --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alert_rule_recommendations_get_by_subscription_vm.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. +# -------------------------------------------------------------------------- + +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(), + 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..30171db57a19 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,16 +27,17 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="9e261de7-c804-4b9d-9ebf-6f50fe350a9a", + 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..4f782adf2280 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,15 +27,16 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="9e261de7-c804-4b9d-9ebf-6f50fe350a9a", + 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..bee95c1bda42 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_get_enrichments.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. +# -------------------------------------------------------------------------- + +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(), + 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..08033535bf0c 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_history.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_history.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,15 +27,16 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="9e261de7-c804-4b9d-9ebf-6f50fe350a9a", + 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..c70a7e0bcd4e 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_list.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_list.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,14 +27,16 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="1e3ff1c0-771a-4119-a03b-be82a51e232d", + 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/list_prometheus_rule_groups.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_list_enrichments.py similarity index 78% rename from sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/list_prometheus_rule_groups.py rename to sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_list_enrichments.py index f300eb020d15..8ae5cfccf90a 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/list_prometheus_rule_groups.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_list_enrichments.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -14,7 +15,7 @@ pip install azure-identity pip install azure-mgmt-alertsmanagement # USAGE - python list_prometheus_rule_groups.py + 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, @@ -26,16 +27,17 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="14ddf0c5-77c5-4b53-84f6-e1fa43ad68f7", + subscription_id="SUBSCRIPTION_ID", ) - response = client.prometheus_rule_groups.list_by_resource_group( - resource_group_name="giladstest", + 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/2021-07-22-preview/examples/listPrometheusRuleGroups.json +# 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..18202fccdef8 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -35,6 +36,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..7d05394ab6bc 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_summary.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/alerts_summary.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,15 +27,16 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="1e3ff1c0-771a-4119-a03b-be82a51e232d", + 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..2569d191b676 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/create_or_update_cluster_centric_rule_group.py @@ -0,0 +1,67 @@ +# 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(), + 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..5ee6d2541d9f 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,16 +27,19 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="14ddf0c5-77c5-4b53-84f6-e1fa43ad68f7", + 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 +49,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 +68,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 +76,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..18350b3eb506 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,16 +27,15 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="14ddf0c5-77c5-4b53-84f6-e1fa43ad68f7", + 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..b4909305a322 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,16 +27,16 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="14ddf0c5-77c5-4b53-84f6-e1fa43ad68f7", + 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/list_subscription_prometheus_rule_groups.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/list_subscription_prometheus_rule_groups.py index e2ea7530deb2..1883ab25ff96 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,7 +27,7 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="14ddf0c5-77c5-4b53-84f6-e1fa43ad68f7", + subscription_id="ffffffff-ffff-ffff-ffff-ffffffffffff", ) response = client.prometheus_rule_groups.list_by_subscription() @@ -34,6 +35,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..b4d6263fa8b0 100644 --- a/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/operations_list.py +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/operations_list.py @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -34,6 +35,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..bde5abb241b7 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ @@ -26,17 +27,17 @@ def main(): client = AlertsManagementClient( credential=DefaultAzureCredential(), - subscription_id="14ddf0c5-77c5-4b53-84f6-e1fa43ad68f7", + 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/smart_groups_change_state.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_samples/smart_groups_change_state.py index 7bf44c2b6487..3d0a183eff78 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ 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..e125dee6324f 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ 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..c8d5da586245 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ 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..e5c51665930d 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 @@ -7,6 +7,7 @@ # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential + from azure.mgmt.alertsmanagement import AlertsManagementClient """ 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..b7aad5238021 --- /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() + + +# aovid 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_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..13d08def5c07 --- /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_list_by_subscription(self, resource_group): + response = self.client.alert_processing_rules.list_by_subscription( + api_version="2024-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_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="2024-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_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="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_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="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_delete(self, resource_group): + response = self.client.alert_processing_rules.delete( + resource_group_name=resource_group.name, + alert_processing_rule_name="str", + api_version="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy + def test_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="2024-03-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_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..658114002eee --- /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_list_by_subscription(self, resource_group): + response = self.client.alert_processing_rules.list_by_subscription( + api_version="2024-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_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="2024-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_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="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_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="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_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="2024-03-01-preview", + ) + + # please add some check logic here by yourself + # ... + + @RandomNameResourceGroupPreparer(location=AZURE_LOCATION) + @recorded_by_proxy_async + async def test_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="2024-03-01-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..55ea0e29072a --- /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_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_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..c2fbf96b9d97 --- /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_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_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..e8cf9d038ae9 --- /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_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_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_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_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_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_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_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_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..5a8278764c9f --- /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_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_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_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_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_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_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_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_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_operations.py b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_operations.py new file mode 100644 index 000000000000..d2f7c57e685a --- /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_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..b47caa92ecf6 --- /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_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..e4be765891f6 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_prometheus_rule_groups_operations.py @@ -0,0 +1,112 @@ +# 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_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_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_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_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_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..7673c077b312 --- /dev/null +++ b/sdk/alertsmanagement/azure-mgmt-alertsmanagement/generated_tests/test_alerts_management_prometheus_rule_groups_operations_async.py @@ -0,0 +1,113 @@ +# 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_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_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_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_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_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..47ac2efa8724 --- /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_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_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_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_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..ae5de73636d1 --- /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_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_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_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_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..812865133853 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,68 @@ 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.8", + "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.3.2", ], - python_requires=">=3.7" + python_requires=">=3.8", )