diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/_meta.json b/sdk/policyinsights/azure-mgmt-policyinsights/_meta.json index 303d3fa72556..d523cf225e5a 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/_meta.json +++ b/sdk/policyinsights/azure-mgmt-policyinsights/_meta.json @@ -1,11 +1,11 @@ { - "autorest": "3.4.5", + "autorest": "3.9.2", "use": [ - "@autorest/python@5.8.4", - "@autorest/modelerfour@4.19.2" + "@autorest/python@6.1.6", + "@autorest/modelerfour@4.24.3" ], - "commit": "4a2c1e8f277dd11a0da89d56eab8ff1a922d3a69", + "commit": "4994cbed850f3726721ec6fd3235a474e8d08fcc", "repository_url": "https://github.com/Azure/azure-rest-api-specs", - "autorest_command": "autorest specification/policyinsights/resource-manager/readme.md --multiapi --python --python-mode=update --python-sdks-folder=/home/vsts/work/1/s/azure-sdk-for-python/sdk --track2 --use=@autorest/python@5.8.4 --use=@autorest/modelerfour@4.19.2 --version=3.4.5", + "autorest_command": "autorest specification/policyinsights/resource-manager/readme.md --python --python-sdks-folder=/mnt/vss/_work/1/s/azure-sdk-for-python/sdk --use=@autorest/python@6.1.6 --use=@autorest/modelerfour@4.24.3 --version=3.9.2 --version-tolerant=False", "readme": "specification/policyinsights/resource-manager/readme.md" } \ No newline at end of file diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/__init__.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/__init__.py index 73baa5525320..bd5b5ad29e97 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/__init__.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/__init__.py @@ -10,10 +10,15 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['PolicyInsightsClient'] try: - from ._patch import patch_sdk # type: ignore - patch_sdk() + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import except ImportError: - pass + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["PolicyInsightsClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_configuration.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_configuration.py index 19c469285655..191075095bf1 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_configuration.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_configuration.py @@ -6,65 +6,58 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +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 +from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy from ._version import VERSION if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class PolicyInsightsClientConfiguration(Configuration): +class PolicyInsightsClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for PolicyInsightsClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str """ - def __init__( - self, - credential, # type: "TokenCredential" - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, credential: "TokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(PolicyInsightsClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(PolicyInsightsClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-policyinsights/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-policyinsights/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - 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.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + 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.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_metadata.json b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_metadata.json deleted file mode 100644 index 418a808d8184..000000000000 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_metadata.json +++ /dev/null @@ -1,110 +0,0 @@ -{ - "chosen_version": "", - "total_api_version_list": ["2018-07-01-preview", "2019-10-01", "2020-07-01", "2021-01-01", "2021-10-01"], - "client": { - "name": "PolicyInsightsClient", - "filename": "_policy_insights_client", - "description": "PolicyInsightsClient.", - "base_url": "\u0027https://management.azure.com\u0027", - "custom_base_url": null, - "azure_arm": true, - "has_lro_operations": true, - "client_side_validation": false, - "sync_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"ARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"PolicyInsightsClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}}}", - "async_imports": "{\"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}, \"regular\": {\"azurecore\": {\"azure.profiles\": [\"KnownProfiles\", \"ProfileDefinition\"], \"azure.profiles.multiapiclient\": [\"MultiApiClientMixin\"], \"msrest\": [\"Deserializer\", \"Serializer\"], \"azure.mgmt.core\": [\"AsyncARMPipelineClient\"]}, \"local\": {\"._configuration\": [\"PolicyInsightsClientConfiguration\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Optional\"]}, \"azurecore\": {\"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}}}" - }, - "global_parameters": { - "sync": { - "credential": { - "signature": "credential, # type: \"TokenCredential\"", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials.TokenCredential", - "required": true - }, - "subscription_id": { - "signature": "subscription_id, # type: str", - "description": "Microsoft Azure subscription ID.", - "docstring_type": "str", - "required": true - } - }, - "async": { - "credential": { - "signature": "credential: \"AsyncTokenCredential\",", - "description": "Credential needed for the client to connect to Azure.", - "docstring_type": "~azure.core.credentials_async.AsyncTokenCredential", - "required": true - }, - "subscription_id": { - "signature": "subscription_id: str,", - "description": "Microsoft Azure subscription ID.", - "docstring_type": "str", - "required": true - } - }, - "constant": { - }, - "call": "credential, subscription_id", - "service_client_specific": { - "sync": { - "api_version": { - "signature": "api_version=None, # type: Optional[str]", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url=None, # type: Optional[str]", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile=KnownProfiles.default, # type: KnownProfiles", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - }, - "async": { - "api_version": { - "signature": "api_version: Optional[str] = None,", - "description": "API version to use if no profile is provided, or if missing in profile.", - "docstring_type": "str", - "required": false - }, - "base_url": { - "signature": "base_url: Optional[str] = None,", - "description": "Service URL", - "docstring_type": "str", - "required": false - }, - "profile": { - "signature": "profile: KnownProfiles = KnownProfiles.default,", - "description": "A profile definition, from KnownProfiles to dict.", - "docstring_type": "azure.profiles.KnownProfiles", - "required": false - } - } - } - }, - "config": { - "credential": true, - "credential_scopes": ["https://management.azure.com/.default"], - "credential_default_policy_type": "BearerTokenCredentialPolicy", - "credential_default_policy_type_has_async_version": true, - "credential_key_header_name": null, - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"], \"azure.mgmt.core.policies\": [\"ARMHttpLoggingPolicy\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" - }, - "operation_groups": { - "policy_tracked_resources": "PolicyTrackedResourcesOperations", - "remediations": "RemediationsOperations", - "policy_events": "PolicyEventsOperations", - "policy_states": "PolicyStatesOperations", - "operations": "Operations", - "policy_metadata": "PolicyMetadataOperations", - "policy_restrictions": "PolicyRestrictionsOperations", - "attestations": "AttestationsOperations" - } -} \ No newline at end of file diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_patch.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_policy_insights_client.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_policy_insights_client.py index 33c6cc7c635e..f03a3c9e6c22 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_policy_insights_client.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_policy_insights_client.py @@ -6,35 +6,37 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from copy import deepcopy +from typing import Any, TYPE_CHECKING +from azure.core.rest import HttpRequest, HttpResponse from azure.mgmt.core import ARMPipelineClient -from msrest import Deserializer, Serializer + +from . import models +from ._configuration import PolicyInsightsClientConfiguration +from ._serialization import Deserializer, Serializer +from .operations import ( + AttestationsOperations, + Operations, + PolicyEventsOperations, + PolicyMetadataOperations, + PolicyRestrictionsOperations, + PolicyStatesOperations, + PolicyTrackedResourcesOperations, + RemediationsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Optional - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import PolicyInsightsClientConfiguration -from .operations import PolicyTrackedResourcesOperations -from .operations import RemediationsOperations -from .operations import PolicyEventsOperations -from .operations import PolicyStatesOperations -from .operations import Operations -from .operations import PolicyMetadataOperations -from .operations import PolicyRestrictionsOperations -from .operations import AttestationsOperations -from . import models -class PolicyInsightsClient(object): +class PolicyInsightsClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """PolicyInsightsClient. :ivar policy_tracked_resources: PolicyTrackedResourcesOperations operations - :vartype policy_tracked_resources: azure.mgmt.policyinsights.operations.PolicyTrackedResourcesOperations + :vartype policy_tracked_resources: + azure.mgmt.policyinsights.operations.PolicyTrackedResourcesOperations :ivar remediations: RemediationsOperations operations :vartype remediations: azure.mgmt.policyinsights.operations.RemediationsOperations :ivar policy_events: PolicyEventsOperations operations @@ -49,66 +51,66 @@ class PolicyInsightsClient(object): :vartype policy_restrictions: azure.mgmt.policyinsights.operations.PolicyRestrictionsOperations :ivar attestations: AttestationsOperations operations :vartype attestations: azure.mgmt.policyinsights.operations.AttestationsOperations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials.TokenCredential - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param str base_url: Service URL - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( self, - credential, # type: "TokenCredential" - subscription_id, # type: str - base_url=None, # type: Optional[str] - **kwargs # type: Any - ): - # type: (...) -> None - if not base_url: - base_url = 'https://management.azure.com' - self._config = PolicyInsightsClientConfiguration(credential, subscription_id, **kwargs) + credential: "TokenCredential", + subscription_id: str, + base_url: str = "https://management.azure.com", + **kwargs: Any + ) -> None: + self._config = PolicyInsightsClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.policy_tracked_resources = PolicyTrackedResourcesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.remediations = RemediationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.policy_events = PolicyEventsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.policy_states = PolicyStatesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) - self.policy_metadata = PolicyMetadataOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.remediations = RemediationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.policy_events = PolicyEventsOperations(self._client, self._config, self._serialize, self._deserialize) + self.policy_states = PolicyStatesOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.policy_metadata = PolicyMetadataOperations(self._client, self._config, self._serialize, self._deserialize) self.policy_restrictions = PolicyRestrictionsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.attestations = AttestationsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.attestations = AttestationsOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_serialization.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_serialization.py new file mode 100644 index 000000000000..7c1dedb5133d --- /dev/null +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_serialization.py @@ -0,0 +1,1970 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote # type: ignore +import xml.etree.ElementTree as ET + +import isodate + +from typing import Dict, Any, cast, TYPE_CHECKING + +from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +if TYPE_CHECKING: + from typing import Optional, Union, AnyStr, IO, Mapping + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data, content_type=None): + # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError: + # 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 + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # 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("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes, headers): + # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +try: + basestring # type: ignore + unicode_str = unicode # type: ignore +except NameError: + basestring = str # type: ignore + unicode_str = str # type: ignore + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + + +try: + from datetime import timezone as _FixedOffset +except ImportError: # Python 2.7 + + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + + +try: + from datetime import timezone + + TZ_UTC = timezone.utc # type: ignore +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes=None): + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize(self, target_obj, data_type=None, **kwargs): + """Serialize data into a string according to type. + + :param target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises: SerializationError if serialization fails. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() + try: + attributes = target_obj._attribute_map + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized.update(target_obj.additional_properties) + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) + continue + if xml_desc.get("text", False): + serialized.text = new_attr + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) + 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) + serialized.append(local_node) + else: # JSON + for k in reversed(keys): + unflattened = {k: new_attr} + new_attr = unflattened + + _new_attr = new_attr + _serialized = serialized + for k in keys: + if k not in _serialized: + _serialized.update(_new_attr) + _new_attr = _new_attr[k] + _serialized = _serialized[k] + except ValueError: + continue + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise_with_traceback(SerializationError, msg, err) + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] + if not kwargs.get("skip_quote", False): + data = [quote(str(d), safe="") for d in data] + return str(self.serialize_iter(data, internal_data_type, **kwargs)) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise_with_traceback(SerializationError, msg.format(data, data_type), err) + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError: + serialized.append(None) + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + 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: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) + return result + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise_with_traceback(SerializationError, msg, err) + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise_with_traceback(TypeError, msg, err) + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + # https://github.com/Azure/msrest-for-python/issues/197 + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_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:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key.""" + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + 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) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # 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) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + else: + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + else: # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer(object): + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes=None): + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies = 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 + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, basestring): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None: + return data + try: + attributes = response._attribute_map + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name + raise_with_traceback(DeserializationError, msg, err) + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + 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. + """ + if target is None: + return None, None + + if isinstance(target, basestring): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + 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 content_type: Swagger "produces" if available. + """ + try: + return self(target_obj, data, content_type=content_type) + except: + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param raw_data: Data to be processed. + :param content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + 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"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise_with_traceback(DeserializationError, msg, err) + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, basestring): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, basestring): + if attr.lower() in ["true", "1"]: + return True + elif attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + 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: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) + attr = attr + padding + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(attr) + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise_with_traceback(DeserializationError, msg, err) + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise_with_traceback(DeserializationError, msg, err) + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + 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) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) + try: + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise_with_traceback(DeserializationError, msg, err) + else: + return date_obj diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_vendor.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_vendor.py new file mode 100644 index 000000000000..9aad73fc743e --- /dev/null +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# 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/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_version.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_version.py index f1fb63697cf5..e5754a47ce68 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_version.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.1.0b2" +VERSION = "1.0.0b1" diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/__init__.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/__init__.py index 251847234d31..c2978f920566 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/__init__.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/__init__.py @@ -7,4 +7,15 @@ # -------------------------------------------------------------------------- from ._policy_insights_client import PolicyInsightsClient -__all__ = ['PolicyInsightsClient'] + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["PolicyInsightsClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/_configuration.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/_configuration.py index d84c30d4c8db..68371755dd09 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/_configuration.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/_configuration.py @@ -10,7 +10,7 @@ from azure.core.configuration import Configuration from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy +from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy from .._version import VERSION @@ -19,48 +19,42 @@ from azure.core.credentials_async import AsyncTokenCredential -class PolicyInsightsClientConfiguration(Configuration): +class PolicyInsightsClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for PolicyInsightsClient. Note that all parameters used to create this instance are saved as instance attributes. - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str """ - def __init__( - self, - credential: "AsyncTokenCredential", - subscription_id: str, - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any) -> None: + super(PolicyInsightsClientConfiguration, self).__init__(**kwargs) if credential is None: raise ValueError("Parameter 'credential' must not be None.") if subscription_id is None: raise ValueError("Parameter 'subscription_id' must not be None.") - super(PolicyInsightsClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'mgmt-policyinsights/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "mgmt-policyinsights/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - 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.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + 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.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/_patch.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/_policy_insights_client.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/_policy_insights_client.py index 0556529830fd..2cdf5a83f518 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/_policy_insights_client.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/_policy_insights_client.py @@ -6,33 +6,37 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Optional, TYPE_CHECKING +from copy import deepcopy +from typing import Any, Awaitable, TYPE_CHECKING -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient -from msrest import Deserializer, Serializer + +from .. import models +from .._serialization import Deserializer, Serializer +from ._configuration import PolicyInsightsClientConfiguration +from .operations import ( + AttestationsOperations, + Operations, + PolicyEventsOperations, + PolicyMetadataOperations, + PolicyRestrictionsOperations, + PolicyStatesOperations, + PolicyTrackedResourcesOperations, + RemediationsOperations, +) if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential -from ._configuration import PolicyInsightsClientConfiguration -from .operations import PolicyTrackedResourcesOperations -from .operations import RemediationsOperations -from .operations import PolicyEventsOperations -from .operations import PolicyStatesOperations -from .operations import Operations -from .operations import PolicyMetadataOperations -from .operations import PolicyRestrictionsOperations -from .operations import AttestationsOperations -from .. import models - -class PolicyInsightsClient(object): +class PolicyInsightsClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes """PolicyInsightsClient. :ivar policy_tracked_resources: PolicyTrackedResourcesOperations operations - :vartype policy_tracked_resources: azure.mgmt.policyinsights.aio.operations.PolicyTrackedResourcesOperations + :vartype policy_tracked_resources: + azure.mgmt.policyinsights.aio.operations.PolicyTrackedResourcesOperations :ivar remediations: RemediationsOperations operations :vartype remediations: azure.mgmt.policyinsights.aio.operations.RemediationsOperations :ivar policy_events: PolicyEventsOperations operations @@ -44,67 +48,70 @@ class PolicyInsightsClient(object): :ivar policy_metadata: PolicyMetadataOperations operations :vartype policy_metadata: azure.mgmt.policyinsights.aio.operations.PolicyMetadataOperations :ivar policy_restrictions: PolicyRestrictionsOperations operations - :vartype policy_restrictions: azure.mgmt.policyinsights.aio.operations.PolicyRestrictionsOperations + :vartype policy_restrictions: + azure.mgmt.policyinsights.aio.operations.PolicyRestrictionsOperations :ivar attestations: AttestationsOperations operations :vartype attestations: azure.mgmt.policyinsights.aio.operations.AttestationsOperations - :param credential: Credential needed for the client to connect to Azure. + :param credential: Credential needed for the client to connect to Azure. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param str base_url: Service URL - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :param base_url: Service URL. Default value is "https://management.azure.com". + :type base_url: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, - base_url: Optional[str] = None, + base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: - if not base_url: - base_url = 'https://management.azure.com' - self._config = PolicyInsightsClientConfiguration(credential, subscription_id, **kwargs) + self._config = PolicyInsightsClientConfiguration( + credential=credential, subscription_id=subscription_id, **kwargs + ) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) - + self._serialize.client_side_validation = False self.policy_tracked_resources = PolicyTrackedResourcesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.remediations = RemediationsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.policy_events = PolicyEventsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.policy_states = PolicyStatesOperations( - self._client, self._config, self._serialize, self._deserialize) - self.operations = Operations( - self._client, self._config, self._serialize, self._deserialize) - self.policy_metadata = PolicyMetadataOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.remediations = RemediationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.policy_events = PolicyEventsOperations(self._client, self._config, self._serialize, self._deserialize) + self.policy_states = PolicyStatesOperations(self._client, self._config, self._serialize, self._deserialize) + self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) + self.policy_metadata = PolicyMetadataOperations(self._client, self._config, self._serialize, self._deserialize) self.policy_restrictions = PolicyRestrictionsOperations( - self._client, self._config, self._serialize, self._deserialize) - self.attestations = AttestationsOperations( - self._client, self._config, self._serialize, self._deserialize) + self._client, self._config, self._serialize, self._deserialize + ) + self.attestations = AttestationsOperations(self._client, self._config, self._serialize, self._deserialize) - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy = deepcopy(request) + request_copy.url = self._client.format_url(request_copy.url) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/__init__.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/__init__.py index 91acca23d156..6e81e19fe418 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/__init__.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/__init__.py @@ -15,13 +15,19 @@ from ._policy_restrictions_operations import PolicyRestrictionsOperations from ._attestations_operations import AttestationsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'PolicyTrackedResourcesOperations', - 'RemediationsOperations', - 'PolicyEventsOperations', - 'PolicyStatesOperations', - 'Operations', - 'PolicyMetadataOperations', - 'PolicyRestrictionsOperations', - 'AttestationsOperations', + "PolicyTrackedResourcesOperations", + "RemediationsOperations", + "PolicyEventsOperations", + "PolicyStatesOperations", + "Operations", + "PolicyMetadataOperations", + "PolicyRestrictionsOperations", + "AttestationsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_attestations_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_attestations_operations.py index 4f275f504f4f..31def27081d0 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_attestations_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_attestations_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,101 +6,123 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import 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 azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._attestations_operations import ( + build_create_or_update_at_resource_group_request, + build_create_or_update_at_resource_request, + build_create_or_update_at_subscription_request, + build_delete_at_resource_group_request, + build_delete_at_resource_request, + build_delete_at_subscription_request, + build_get_at_resource_group_request, + build_get_at_resource_request, + build_get_at_subscription_request, + build_list_for_resource_group_request, + build_list_for_resource_request, + build_list_for_subscription_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class AttestationsOperations: - """AttestationsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class AttestationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s + :attr:`attestations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_for_subscription( - self, - query_options: Optional["_models.QueryOptions"] = None, - **kwargs: Any - ) -> AsyncIterable["_models.AttestationListResult"]: + self, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> AsyncIterable["_models.Attestation"]: """Gets all attestations for the subscription. - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AttestationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.AttestationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Attestation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AttestationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AttestationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - api_version = "2021-01-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_for_subscription_request( + subscription_id=self._config.subscription_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AttestationListResult', pipeline_response) + deserialized = self._deserialize("AttestationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -108,311 +131,386 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, response) 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 - ) - list_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations"} # type: ignore async def _create_or_update_at_subscription_initial( - self, - attestation_name: str, - parameters: "_models.Attestation", - **kwargs: Any - ) -> "_models.Attestation": - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] + self, attestation_name: str, parameters: Union[_models.Attestation, IO], **kwargs: Any + ) -> _models.Attestation: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._create_or_update_at_subscription_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Attestation') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Attestation") + + request = build_create_or_update_at_subscription_request( + attestation_name=attestation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_at_subscription_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_at_subscription_initial.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + _create_or_update_at_subscription_initial.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @overload async def begin_create_or_update_at_subscription( self, attestation_name: str, - parameters: "_models.Attestation", + parameters: _models.Attestation, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.Attestation"]: + ) -> AsyncLROPoller[_models.Attestation]: """Creates or updates an attestation at subscription scope. - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_name: str - :param parameters: The attestation parameters. + :param parameters: The attestation parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.Attestation + :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 :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either Attestation or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Attestation or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_create_or_update_at_subscription( + self, attestation_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.Attestation]: + """Creates or updates an attestation at subscription scope. + + :param attestation_name: The name of the attestation. Required. + :type attestation_name: str + :param parameters: The attestation parameters. Required. + :type parameters: IO + :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 + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Attestation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update_at_subscription( + self, attestation_name: str, parameters: Union[_models.Attestation, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.Attestation]: + """Creates or updates an attestation at subscription scope. + + :param attestation_name: The name of the attestation. Required. + :type attestation_name: str + :param parameters: The attestation parameters. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.Attestation 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 + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Attestation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._create_or_update_at_subscription_initial( + raw_result = await self._create_or_update_at_subscription_initial( # type: ignore attestation_name=attestation_name, parameters=parameters, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Attestation', pipeline_response) - + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - async def get_at_subscription( - self, - attestation_name: str, - **kwargs: Any - ) -> "_models.Attestation": + begin_create_or_update_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @distributed_trace_async + async def get_at_subscription(self, attestation_name: str, **kwargs: Any) -> _models.Attestation: """Gets an existing attestation at subscription scope. - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Attestation, or the result of cls(response) + :return: Attestation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Attestation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - accept = "application/json" - - # Construct URL - url = self.get_at_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + request = build_get_at_subscription_request( + attestation_name=attestation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore - async def delete_at_subscription( - self, - attestation_name: str, - **kwargs: Any + get_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @distributed_trace_async + async def delete_at_subscription( # pylint: disable=inconsistent-return-statements + self, attestation_name: str, **kwargs: Any ) -> None: """Deletes an existing attestation at subscription scope. - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_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) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - accept = "application/json" - - # Construct URL - url = self.delete_at_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_at_subscription_request( + attestation_name=attestation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + delete_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + @distributed_trace def list_for_resource_group( - self, - resource_group_name: str, - query_options: Optional["_models.QueryOptions"] = None, - **kwargs: Any - ) -> AsyncIterable["_models.AttestationListResult"]: + self, resource_group_name: str, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> AsyncIterable["_models.Attestation"]: """Gets all attestations for the resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AttestationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.AttestationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Attestation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AttestationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AttestationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - api_version = "2021-01-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AttestationListResult', pipeline_response) + deserialized = self._deserialize("AttestationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -421,325 +519,412 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, response) 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 - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations"} # type: ignore async def _create_or_update_at_resource_group_initial( - self, - resource_group_name: str, - attestation_name: str, - parameters: "_models.Attestation", - **kwargs: Any - ) -> "_models.Attestation": - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] + self, resource_group_name: str, attestation_name: str, parameters: Union[_models.Attestation, IO], **kwargs: Any + ) -> _models.Attestation: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._create_or_update_at_resource_group_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Attestation') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Attestation") + + request = build_create_or_update_at_resource_group_request( + resource_group_name=resource_group_name, + attestation_name=attestation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_at_resource_group_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_at_resource_group_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + _create_or_update_at_resource_group_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @overload async def begin_create_or_update_at_resource_group( self, resource_group_name: str, attestation_name: str, - parameters: "_models.Attestation", + parameters: _models.Attestation, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.Attestation"]: + ) -> AsyncLROPoller[_models.Attestation]: """Creates or updates an attestation at resource group scope. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_name: str - :param parameters: The attestation parameters. + :param parameters: The attestation parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.Attestation + :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 :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either Attestation or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Attestation or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_create_or_update_at_resource_group( + self, + resource_group_name: str, + attestation_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Attestation]: + """Creates or updates an attestation at resource group scope. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param attestation_name: The name of the attestation. Required. + :type attestation_name: str + :param parameters: The attestation parameters. Required. + :type parameters: IO + :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 + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Attestation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update_at_resource_group( + self, resource_group_name: str, attestation_name: str, parameters: Union[_models.Attestation, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.Attestation]: + """Creates or updates an attestation at resource group scope. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param attestation_name: The name of the attestation. Required. + :type attestation_name: str + :param parameters: The attestation parameters. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.Attestation 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 + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Attestation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._create_or_update_at_resource_group_initial( + raw_result = await self._create_or_update_at_resource_group_initial( # type: ignore resource_group_name=resource_group_name, attestation_name=attestation_name, parameters=parameters, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Attestation', pipeline_response) - + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_create_or_update_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + @distributed_trace_async async def get_at_resource_group( - self, - resource_group_name: str, - attestation_name: str, - **kwargs: Any - ) -> "_models.Attestation": + self, resource_group_name: str, attestation_name: str, **kwargs: Any + ) -> _models.Attestation: """Gets an existing attestation at resource group scope. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Attestation, or the result of cls(response) + :return: Attestation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Attestation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - accept = "application/json" - - # Construct URL - url = self.get_at_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + + request = build_get_at_resource_group_request( + resource_group_name=resource_group_name, + attestation_name=attestation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore - async def delete_at_resource_group( - self, - resource_group_name: str, - attestation_name: str, - **kwargs: Any + get_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @distributed_trace_async + async def delete_at_resource_group( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, attestation_name: str, **kwargs: Any ) -> None: """Deletes an existing attestation at resource group scope. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_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) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - accept = "application/json" - - # Construct URL - url = self.delete_at_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_at_resource_group_request( + resource_group_name=resource_group_name, + attestation_name=attestation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + delete_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + @distributed_trace def list_for_resource( - self, - resource_id: str, - query_options: Optional["_models.QueryOptions"] = None, - **kwargs: Any - ) -> AsyncIterable["_models.AttestationListResult"]: + self, resource_id: str, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> AsyncIterable["_models.Attestation"]: """Gets all attestations for a resource. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AttestationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.AttestationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Attestation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AttestationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AttestationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - api_version = "2021-01-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_for_resource_request( + resource_id=resource_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('AttestationListResult', pipeline_response) + deserialized = self._deserialize("AttestationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -748,257 +933,340 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, response) 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 - ) - list_for_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/attestations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/attestations"} # type: ignore async def _create_or_update_at_resource_initial( - self, - resource_id: str, - attestation_name: str, - parameters: "_models.Attestation", - **kwargs: Any - ) -> "_models.Attestation": - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] + self, resource_id: str, attestation_name: str, parameters: Union[_models.Attestation, IO], **kwargs: Any + ) -> _models.Attestation: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._create_or_update_at_resource_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Attestation') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Attestation") + + request = build_create_or_update_at_resource_request( + resource_id=resource_id, + attestation_name=attestation_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_at_resource_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_at_resource_initial.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + _create_or_update_at_resource_initial.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @overload async def begin_create_or_update_at_resource( self, resource_id: str, attestation_name: str, - parameters: "_models.Attestation", + parameters: _models.Attestation, + *, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller["_models.Attestation"]: + ) -> AsyncLROPoller[_models.Attestation]: """Creates or updates an attestation at resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_name: str - :param parameters: The attestation parameters. + :param parameters: The attestation parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.Attestation + :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 :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncLROPoller that returns either Attestation or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Attestation or the result of + cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + async def begin_create_or_update_at_resource( + self, + resource_id: str, + attestation_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[_models.Attestation]: + """Creates or updates an attestation at resource scope. + + :param resource_id: Resource ID. Required. + :type resource_id: str + :param attestation_name: The name of the attestation. Required. + :type attestation_name: str + :param parameters: The attestation parameters. Required. + :type parameters: IO + :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 + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Attestation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def begin_create_or_update_at_resource( + self, resource_id: str, attestation_name: str, parameters: Union[_models.Attestation, IO], **kwargs: Any + ) -> AsyncLROPoller[_models.Attestation]: + """Creates or updates an attestation at resource scope. + + :param resource_id: Resource ID. Required. + :type resource_id: str + :param attestation_name: The name of the attestation. Required. + :type attestation_name: str + :param parameters: The attestation parameters. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.Attestation 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 + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. + :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of AsyncLROPoller that returns either Attestation or the result of + cls(response) + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._create_or_update_at_resource_initial( + raw_result = await self._create_or_update_at_resource_initial( # type: ignore resource_id=resource_id, attestation_name=attestation_name, parameters=parameters, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Attestation', pipeline_response) - + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - async def get_at_resource( - self, - resource_id: str, - attestation_name: str, - **kwargs: Any - ) -> "_models.Attestation": + begin_create_or_update_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @distributed_trace_async + async def get_at_resource(self, resource_id: str, attestation_name: str, **kwargs: Any) -> _models.Attestation: """Gets an existing attestation at resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Attestation, or the result of cls(response) + :return: Attestation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Attestation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - accept = "application/json" - - # Construct URL - url = self.get_at_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + + request = build_get_at_resource_request( + resource_id=resource_id, + attestation_name=attestation_name, + api_version=api_version, + template_url=self.get_at_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore - async def delete_at_resource( - self, - resource_id: str, - attestation_name: str, - **kwargs: Any + get_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @distributed_trace_async + async def delete_at_resource( # pylint: disable=inconsistent-return-statements + self, resource_id: str, attestation_name: str, **kwargs: Any ) -> None: """Deletes an existing attestation at individual resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_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) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - accept = "application/json" - - # Construct URL - url = self.delete_at_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_delete_at_resource_request( + resource_id=resource_id, + attestation_name=attestation_name, + api_version=api_version, + template_url=self.delete_at_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + delete_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_operations.py index 641f29cf3ee3..1af359bde522 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,84 +6,98 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._operations import build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class Operations: - """Operations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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") - async def list( - self, - **kwargs: Any - ) -> "_models.OperationsListResults": + @distributed_trace_async + async def list(self, **kwargs: Any) -> _models.OperationsListResults: """Lists available operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: OperationsListResults, or the result of cls(response) + :return: OperationsListResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.OperationsListResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationsListResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct URL - url = self.list.metadata['url'] # type: ignore + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationsListResults] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + 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) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('OperationsListResults', pipeline_response) + deserialized = self._deserialize("OperationsListResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': '/providers/Microsoft.PolicyInsights/operations'} # type: ignore + + list.metadata = {"url": "/providers/Microsoft.PolicyInsights/operations"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_patch.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_events_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_events_operations.py index ad883b494f7d..2949d345d96d 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_events_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_events_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,140 +6,176 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import 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 - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._policy_events_operations import ( + build_list_query_results_for_management_group_request, + build_list_query_results_for_policy_definition_request, + build_list_query_results_for_policy_set_definition_request, + build_list_query_results_for_resource_group_level_policy_assignment_request, + build_list_query_results_for_resource_group_request, + build_list_query_results_for_resource_request, + build_list_query_results_for_subscription_level_policy_assignment_request, + build_list_query_results_for_subscription_request, + build_next_link_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PolicyEventsOperations: - """PolicyEventsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PolicyEventsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s + :attr:`policy_events` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_query_results_for_management_group( self, + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], management_group_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyEventsQueryResults"]: + ) -> AsyncIterable["_models.PolicyEvent"]: """Queries policy events for the resources under the management group. - :param management_group_name: Management group name. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param management_group_name: Management group name. Required. :type management_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - policy_events_resource = "default" - management_groups_namespace = "Microsoft.Management" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupName': self._serialize.url("management_group_name", management_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_management_group_request( + policy_events_resource=policy_events_resource, + management_group_name=management_group_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.list_query_results_for_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -147,116 +184,131 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_query_results_for_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore + @distributed_trace def list_query_results_for_subscription( self, + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], subscription_id: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyEventsQueryResults"]: + ) -> AsyncIterable["_models.PolicyEvent"]: """Queries policy events for the resources under the subscription. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - policy_events_resource = "default" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_subscription_request( + policy_events_resource=policy_events_resource, + subscription_id=subscription_id, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + api_version=api_version, + template_url=self.list_query_results_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -265,120 +317,135 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_query_results_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore + + @distributed_trace def list_query_results_for_resource_group( self, + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], subscription_id: str, resource_group_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyEventsQueryResults"]: + ) -> AsyncIterable["_models.PolicyEvent"]: """Queries policy events for the resources under the resource group. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - policy_events_resource = "default" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_resource_group_request( + policy_events_resource=policy_events_resource, + subscription_id=subscription_id, + resource_group_name=resource_group_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + api_version=api_version, + template_url=self.list_query_results_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -387,120 +454,136 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_query_results_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore + @distributed_trace def list_query_results_for_resource( self, + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], resource_id: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyEventsQueryResults"]: + ) -> AsyncIterable["_models.PolicyEvent"]: """Queries policy events for the resource. - :param resource_id: Resource ID. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param resource_id: Resource ID. Required. :type resource_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _expand = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _expand = query_options.expand - _skip_token = query_options.skip_token - policy_events_resource = "default" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", _expand, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _expand = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _expand = query_options.expand + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_resource_request( + policy_events_resource=policy_events_resource, + resource_id=resource_id, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + expand=_expand, + skip_token=_skip_token, + api_version=api_version, + template_url=self.list_query_results_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _expand = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _expand = query_options.expand + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -509,122 +592,141 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_query_results_for_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore + @distributed_trace def list_query_results_for_policy_set_definition( self, + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], subscription_id: str, policy_set_definition_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyEventsQueryResults"]: + ) -> AsyncIterable["_models.PolicyEvent"]: """Queries policy events for the subscription level policy set definition. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_set_definition_name: Policy set definition name. + :param policy_set_definition_name: Policy set definition name. Required. :type policy_set_definition_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - policy_events_resource = "default" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_policy_set_definition.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policySetDefinitionName': self._serialize.url("policy_set_definition_name", policy_set_definition_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_policy_set_definition_request( + policy_events_resource=policy_events_resource, + subscription_id=subscription_id, + policy_set_definition_name=policy_set_definition_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_policy_set_definition.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -633,122 +735,141 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_policy_set_definition.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_query_results_for_policy_set_definition.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore + + @distributed_trace def list_query_results_for_policy_definition( self, + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], subscription_id: str, policy_definition_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyEventsQueryResults"]: + ) -> AsyncIterable["_models.PolicyEvent"]: """Queries policy events for the subscription level policy definition. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_definition_name: Policy definition name. + :param policy_definition_name: Policy definition name. Required. :type policy_definition_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - policy_events_resource = "default" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_policy_definition.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyDefinitionName': self._serialize.url("policy_definition_name", policy_definition_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_policy_definition_request( + policy_events_resource=policy_events_resource, + subscription_id=subscription_id, + policy_definition_name=policy_definition_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_policy_definition.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -757,122 +878,141 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_policy_definition.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_query_results_for_policy_definition.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore + + @distributed_trace def list_query_results_for_subscription_level_policy_assignment( self, + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], subscription_id: str, policy_assignment_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyEventsQueryResults"]: + ) -> AsyncIterable["_models.PolicyEvent"]: """Queries policy events for the subscription level policy assignment. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_assignment_name: Policy assignment name. + :param policy_assignment_name: Policy assignment name. Required. :type policy_assignment_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - policy_events_resource = "default" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_subscription_level_policy_assignment.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyAssignmentName': self._serialize.url("policy_assignment_name", policy_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_subscription_level_policy_assignment_request( + policy_events_resource=policy_events_resource, + subscription_id=subscription_id, + policy_assignment_name=policy_assignment_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_subscription_level_policy_assignment.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -881,126 +1021,145 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_subscription_level_policy_assignment.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_query_results_for_subscription_level_policy_assignment.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore + @distributed_trace def list_query_results_for_resource_group_level_policy_assignment( self, + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], subscription_id: str, resource_group_name: str, policy_assignment_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyEventsQueryResults"]: + ) -> AsyncIterable["_models.PolicyEvent"]: """Queries policy events for the resource group level policy assignment. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param policy_assignment_name: Policy assignment name. + :param policy_assignment_name: Policy assignment name. Required. :type policy_assignment_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - policy_events_resource = "default" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource_group_level_policy_assignment.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyAssignmentName': self._serialize.url("policy_assignment_name", policy_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_resource_group_level_policy_assignment_request( + policy_events_resource=policy_events_resource, + subscription_id=subscription_id, + resource_group_name=resource_group_name, + policy_assignment_name=policy_assignment_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_resource_group_level_policy_assignment.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1009,17 +1168,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_resource_group_level_policy_assignment.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_query_results_for_resource_group_level_policy_assignment.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_metadata_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_metadata_operations.py index e9e5c96bd425..abb80c67c4cc 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_metadata_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_metadata_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,145 +6,160 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import 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._policy_metadata_operations import build_get_resource_request, build_list_request -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PolicyMetadataOperations: - """PolicyMetadataOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PolicyMetadataOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s + :attr:`policy_metadata` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - async def get_resource( - self, - resource_name: str, - **kwargs: Any - ) -> "_models.PolicyMetadata": + 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_async + async def get_resource(self, resource_name: str, **kwargs: Any) -> _models.PolicyMetadata: """Get policy metadata resource. - :param resource_name: The name of the policy metadata resource. + :param resource_name: The name of the policy metadata resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PolicyMetadata, or the result of cls(response) + :return: PolicyMetadata or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.PolicyMetadata - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyMetadata"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.get_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceName': self._serialize.url("resource_name", resource_name, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyMetadata] + + request = build_get_resource_request( + resource_name=resource_name, + api_version=api_version, + template_url=self.get_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(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, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PolicyMetadata', pipeline_response) + deserialized = self._deserialize("PolicyMetadata", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_resource.metadata = {'url': '/providers/Microsoft.PolicyInsights/policyMetadata/{resourceName}'} # type: ignore + get_resource.metadata = {"url": "/providers/Microsoft.PolicyInsights/policyMetadata/{resourceName}"} # type: ignore + + @distributed_trace def list( - self, - query_options: Optional["_models.QueryOptions"] = None, - **kwargs: Any - ) -> AsyncIterable["_models.PolicyMetadataCollection"]: + self, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> AsyncIterable["_models.SlimPolicyMetadata"]: """Get a list of the policy metadata resources. - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyMetadataCollection or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyMetadataCollection] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either SlimPolicyMetadata or the result of cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.SlimPolicyMetadata] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyMetadataCollection"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyMetadataCollection] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - if query_options is not None: - _top = query_options.top - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + if query_options is not None: + _top = query_options.top + + request = build_list_request( + top=_top, + 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) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyMetadataCollection', pipeline_response) + deserialized = self._deserialize("PolicyMetadataCollection", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -152,17 +168,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, response) 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.metadata = {'url': '/providers/Microsoft.PolicyInsights/policyMetadata'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.PolicyInsights/policyMetadata"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_restrictions_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_restrictions_operations.py index d9496ceb4a23..4df7e11ac8ee 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_restrictions_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_restrictions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,160 +6,418 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models +from ..._vendor import _convert_request +from ...operations._policy_restrictions_operations import ( + build_check_at_management_group_scope_request, + build_check_at_resource_group_scope_request, + build_check_at_subscription_scope_request, +) -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PolicyRestrictionsOperations: - """PolicyRestrictionsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PolicyRestrictionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s + :attr:`policy_restrictions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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") + @overload async def check_at_subscription_scope( - self, - parameters: "_models.CheckRestrictionsRequest", - **kwargs: Any - ) -> "_models.CheckRestrictionsResult": + self, parameters: _models.CheckRestrictionsRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckRestrictionsResult: """Checks what restrictions Azure Policy will place on a resource within a subscription. - :param parameters: The check policy restrictions parameters. + :param parameters: The check policy restrictions parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.CheckRestrictionsRequest + :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: CheckRestrictionsResult or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_at_subscription_scope( + self, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckRestrictionsResult: + """Checks what restrictions Azure Policy will place on a resource within a subscription. + + :param parameters: The check policy restrictions parameters. Required. + :type parameters: IO + :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: CheckRestrictionsResult, or the result of cls(response) + :return: CheckRestrictionsResult or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_at_subscription_scope( + self, parameters: Union[_models.CheckRestrictionsRequest, IO], **kwargs: Any + ) -> _models.CheckRestrictionsResult: + """Checks what restrictions Azure Policy will place on a resource within a subscription. + + :param parameters: The check policy restrictions parameters. Is either a model type or a IO + type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.CheckRestrictionsRequest 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 + :return: CheckRestrictionsResult or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckRestrictionsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-07-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.check_at_subscription_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'CheckRestrictionsRequest') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckRestrictionsResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CheckRestrictionsRequest") + + request = build_check_at_subscription_scope_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.check_at_subscription_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # 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, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckRestrictionsResult', pipeline_response) + deserialized = self._deserialize("CheckRestrictionsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_at_subscription_scope.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions'} # type: ignore + check_at_subscription_scope.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions"} # type: ignore + + @overload async def check_at_resource_group_scope( self, resource_group_name: str, - parameters: "_models.CheckRestrictionsRequest", + parameters: _models.CheckRestrictionsRequest, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.CheckRestrictionsResult": + ) -> _models.CheckRestrictionsResult: """Checks what restrictions Azure Policy will place on a resource within a resource group. Use this when the resource group the resource will be created in is already known. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param parameters: The check policy restrictions parameters. + :param parameters: The check policy restrictions parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.CheckRestrictionsRequest + :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: CheckRestrictionsResult or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_at_resource_group_scope( + self, resource_group_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckRestrictionsResult: + """Checks what restrictions Azure Policy will place on a resource within a resource group. Use + this when the resource group the resource will be created in is already known. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param parameters: The check policy restrictions parameters. Required. + :type parameters: IO + :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: CheckRestrictionsResult or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_at_resource_group_scope( + self, resource_group_name: str, parameters: Union[_models.CheckRestrictionsRequest, IO], **kwargs: Any + ) -> _models.CheckRestrictionsResult: + """Checks what restrictions Azure Policy will place on a resource within a resource group. Use + this when the resource group the resource will be created in is already known. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param parameters: The check policy restrictions parameters. Is either a model type or a IO + type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.CheckRestrictionsRequest 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 - :return: CheckRestrictionsResult, or the result of cls(response) + :return: CheckRestrictionsResult or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckRestrictionsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-07-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.check_at_resource_group_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckRestrictionsResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CheckRestrictionsRequest") + + request = build_check_at_resource_group_scope_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.check_at_resource_group_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # 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) + + deserialized = self._deserialize("CheckRestrictionsResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + check_at_resource_group_scope.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions"} # type: ignore + + @overload + async def check_at_management_group_scope( + self, + management_group_id: str, + parameters: _models.CheckManagementGroupRestrictionsRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckRestrictionsResult: + """Checks what restrictions Azure Policy will place on resources within a management group. + + :param management_group_id: Management group ID. Required. + :type management_group_id: str + :param parameters: The check policy restrictions parameters. Required. + :type parameters: ~azure.mgmt.policyinsights.models.CheckManagementGroupRestrictionsRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckRestrictionsResult or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def check_at_management_group_scope( + self, management_group_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckRestrictionsResult: + """Checks what restrictions Azure Policy will place on resources within a management group. + + :param management_group_id: Management group ID. Required. + :type management_group_id: str + :param parameters: The check policy restrictions parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckRestrictionsResult or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def check_at_management_group_scope( + self, + management_group_id: str, + parameters: Union[_models.CheckManagementGroupRestrictionsRequest, IO], + **kwargs: Any + ) -> _models.CheckRestrictionsResult: + """Checks what restrictions Azure Policy will place on resources within a management group. + + :param management_group_id: Management group ID. Required. + :type management_group_id: str + :param parameters: The check policy restrictions parameters. Is either a model type or a IO + type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.CheckManagementGroupRestrictionsRequest or + IO + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str + :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 + :return: CheckRestrictionsResult or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'CheckRestrictionsRequest') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckRestrictionsResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CheckManagementGroupRestrictionsRequest") + + request = build_check_at_management_group_scope_request( + management_group_id=management_group_id, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.check_at_management_group_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # 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, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckRestrictionsResult', pipeline_response) + deserialized = self._deserialize("CheckRestrictionsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_at_resource_group_scope.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions'} # type: ignore + + check_at_management_group_scope.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_states_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_states_operations.py index 1781596a2e6d..e15af09ede1a 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_states_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_states_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,146 +6,190 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod +from azure.core.rest import 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 azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._policy_states_operations import ( + build_list_query_results_for_management_group_request, + build_list_query_results_for_policy_definition_request, + build_list_query_results_for_policy_set_definition_request, + build_list_query_results_for_resource_group_level_policy_assignment_request, + build_list_query_results_for_resource_group_request, + build_list_query_results_for_resource_request, + build_list_query_results_for_subscription_level_policy_assignment_request, + build_list_query_results_for_subscription_request, + build_next_link_request, + build_summarize_for_management_group_request, + build_summarize_for_policy_definition_request, + build_summarize_for_policy_set_definition_request, + build_summarize_for_resource_group_level_policy_assignment_request, + build_summarize_for_resource_group_request, + build_summarize_for_resource_request, + build_summarize_for_subscription_level_policy_assignment_request, + build_summarize_for_subscription_request, + build_trigger_resource_group_evaluation_request, + build_trigger_subscription_evaluation_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PolicyStatesOperations: - """PolicyStatesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PolicyStatesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s + :attr:`policy_states` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_query_results_for_management_group( self, policy_states_resource: Union[str, "_models.PolicyStatesResource"], management_group_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyStatesQueryResults"]: + ) -> AsyncIterable["_models.PolicyState"]: """Queries policy states for the resources under the management group. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param management_group_name: Management group name. + :param management_group_name: Management group name. Required. :type management_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - management_groups_namespace = "Microsoft.Management" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupName': self._serialize.url("management_group_name", management_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_management_group_request( + policy_states_resource=policy_states_resource, + management_group_name=management_group_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.list_query_results_for_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -153,199 +198,221 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_query_results_for_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + @distributed_trace_async async def summarize_for_management_group( self, + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], management_group_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> "_models.SummarizeResults": + ) -> _models.SummarizeResults: """Summarizes policy states for the resources under the management group. - :param management_group_name: Management group name. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param management_group_name: Management group name. Required. :type management_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - management_groups_namespace = "Microsoft.Management" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupName': self._serialize.url("management_group_name", management_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_management_group_request( + policy_states_summary_resource=policy_states_summary_resource, + management_group_name=management_group_name, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.summarize_for_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore + summarize_for_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore + + @distributed_trace def list_query_results_for_subscription( self, policy_states_resource: Union[str, "_models.PolicyStatesResource"], subscription_id: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyStatesQueryResults"]: + ) -> AsyncIterable["_models.PolicyState"]: """Queries policy states for the resources under the subscription. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_subscription_request( + policy_states_resource=policy_states_resource, + subscription_id=subscription_id, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + api_version=api_version, + template_url=self.list_query_results_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -354,201 +421,219 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_query_results_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + + @distributed_trace_async async def summarize_for_subscription( self, + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], subscription_id: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> "_models.SummarizeResults": + ) -> _models.SummarizeResults: """Summarizes policy states for the resources under the subscription. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_subscription_request( + policy_states_summary_resource=policy_states_summary_resource, + subscription_id=subscription_id, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + api_version=api_version, + template_url=self.summarize_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore + summarize_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore + + @distributed_trace def list_query_results_for_resource_group( self, policy_states_resource: Union[str, "_models.PolicyStatesResource"], subscription_id: str, resource_group_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyStatesQueryResults"]: + ) -> AsyncIterable["_models.PolicyState"]: """Queries policy states for the resources under the resource group. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_resource_group_request( + policy_states_resource=policy_states_resource, + subscription_id=subscription_id, + resource_group_name=resource_group_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + api_version=api_version, + template_url=self.list_query_results_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -557,205 +642,224 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_query_results_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + + @distributed_trace_async async def summarize_for_resource_group( self, + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], subscription_id: str, resource_group_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> "_models.SummarizeResults": + ) -> _models.SummarizeResults: """Summarizes policy states for the resources under the resource group. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_resource_group_request( + policy_states_summary_resource=policy_states_summary_resource, + subscription_id=subscription_id, + resource_group_name=resource_group_name, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + api_version=api_version, + template_url=self.summarize_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore + summarize_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore + + @distributed_trace def list_query_results_for_resource( self, policy_states_resource: Union[str, "_models.PolicyStatesResource"], resource_id: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyStatesQueryResults"]: + ) -> AsyncIterable["_models.PolicyState"]: """Queries policy states for the resource. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _expand = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _expand = query_options.expand - _skip_token = query_options.skip_token - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", _expand, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _expand = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _expand = query_options.expand + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_resource_request( + policy_states_resource=policy_states_resource, + resource_id=resource_id, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + expand=_expand, + skip_token=_skip_token, + api_version=api_version, + template_url=self.list_query_results_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _expand = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _expand = query_options.expand + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -764,410 +868,437 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_query_results_for_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + @distributed_trace_async async def summarize_for_resource( self, + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], resource_id: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> "_models.SummarizeResults": + ) -> _models.SummarizeResults: """Summarizes policy states for the resource. - :param resource_id: Resource ID. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param resource_id: Resource ID. Required. :type resource_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_resource_request( + policy_states_summary_resource=policy_states_summary_resource, + resource_id=resource_id, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + api_version=api_version, + template_url=self.summarize_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore - async def _trigger_subscription_evaluation_initial( - self, - subscription_id: str, - **kwargs: Any + summarize_for_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore + + async def _trigger_subscription_evaluation_initial( # pylint: disable=inconsistent-return-statements + self, subscription_id: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self._trigger_subscription_evaluation_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_trigger_subscription_evaluation_request( + subscription_id=subscription_id, + api_version=api_version, + template_url=self._trigger_subscription_evaluation_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _trigger_subscription_evaluation_initial.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation'} # type: ignore + _trigger_subscription_evaluation_initial.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation"} # type: ignore - async def begin_trigger_subscription_evaluation( - self, - subscription_id: str, - **kwargs: Any - ) -> AsyncLROPoller[None]: + @distributed_trace_async + async def begin_trigger_subscription_evaluation(self, subscription_id: str, **kwargs: Any) -> AsyncLROPoller[None]: """Triggers a policy evaluation scan for all the resources under the subscription. - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._trigger_subscription_evaluation_initial( + raw_result = await self._trigger_subscription_evaluation_initial( # type: ignore subscription_id=subscription_id, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) + kwargs.pop("error_map", None) - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) - - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - path_format_arguments = { - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_trigger_subscription_evaluation.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - async def _trigger_resource_group_evaluation_initial( - self, - subscription_id: str, - resource_group_name: str, - **kwargs: Any + begin_trigger_subscription_evaluation.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation"} # type: ignore + + async def _trigger_resource_group_evaluation_initial( # pylint: disable=inconsistent-return-statements + self, subscription_id: str, resource_group_name: str, **kwargs: Any ) -> None: - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self._trigger_resource_group_evaluation_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_trigger_resource_group_evaluation_request( + subscription_id=subscription_id, + resource_group_name=resource_group_name, + api_version=api_version, + template_url=self._trigger_resource_group_evaluation_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _trigger_resource_group_evaluation_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation'} # type: ignore + _trigger_resource_group_evaluation_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation"} # type: ignore + @distributed_trace_async async def begin_trigger_resource_group_evaluation( - self, - subscription_id: str, - resource_group_name: str, - **kwargs: Any + self, subscription_id: str, resource_group_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Triggers a policy evaluation scan for all the resources under the resource group. - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for + this operation to not poll, or pass in your own initialized polling object for a personal + polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = await self._trigger_resource_group_evaluation_initial( + raw_result = await self._trigger_resource_group_evaluation_initial( # type: ignore subscription_id=subscription_id, resource_group_name=resource_group_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) + kwargs.pop("error_map", None) - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) - - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - path_format_arguments = { - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - } - - if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = AsyncNoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: AsyncPollingMethod + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_trigger_resource_group_evaluation.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation'} # type: ignore + return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_trigger_resource_group_evaluation.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation"} # type: ignore + + @distributed_trace def list_query_results_for_policy_set_definition( self, policy_states_resource: Union[str, "_models.PolicyStatesResource"], subscription_id: str, policy_set_definition_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyStatesQueryResults"]: + ) -> AsyncIterable["_models.PolicyState"]: """Queries policy states for the subscription level policy set definition. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_set_definition_name: Policy set definition name. + :param policy_set_definition_name: Policy set definition name. Required. :type policy_set_definition_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_policy_set_definition.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policySetDefinitionName': self._serialize.url("policy_set_definition_name", policy_set_definition_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_policy_set_definition_request( + policy_states_resource=policy_states_resource, + subscription_id=subscription_id, + policy_set_definition_name=policy_set_definition_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_policy_set_definition.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1176,209 +1307,235 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_policy_set_definition.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_query_results_for_policy_set_definition.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + @distributed_trace_async async def summarize_for_policy_set_definition( self, + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], subscription_id: str, policy_set_definition_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> "_models.SummarizeResults": + ) -> _models.SummarizeResults: """Summarizes policy states for the subscription level policy set definition. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_set_definition_name: Policy set definition name. + :param policy_set_definition_name: Policy set definition name. Required. :type policy_set_definition_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_policy_set_definition.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policySetDefinitionName': self._serialize.url("policy_set_definition_name", policy_set_definition_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_policy_set_definition_request( + policy_states_summary_resource=policy_states_summary_resource, + subscription_id=subscription_id, + policy_set_definition_name=policy_set_definition_name, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.summarize_for_policy_set_definition.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_policy_set_definition.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore + summarize_for_policy_set_definition.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore + + @distributed_trace def list_query_results_for_policy_definition( self, policy_states_resource: Union[str, "_models.PolicyStatesResource"], subscription_id: str, policy_definition_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyStatesQueryResults"]: + ) -> AsyncIterable["_models.PolicyState"]: """Queries policy states for the subscription level policy definition. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_definition_name: Policy definition name. + :param policy_definition_name: Policy definition name. Required. :type policy_definition_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_policy_definition.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyDefinitionName': self._serialize.url("policy_definition_name", policy_definition_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_policy_definition_request( + policy_states_resource=policy_states_resource, + subscription_id=subscription_id, + policy_definition_name=policy_definition_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_policy_definition.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1387,209 +1544,235 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_policy_definition.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_query_results_for_policy_definition.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + + @distributed_trace_async async def summarize_for_policy_definition( self, + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], subscription_id: str, policy_definition_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> "_models.SummarizeResults": + ) -> _models.SummarizeResults: """Summarizes policy states for the subscription level policy definition. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_definition_name: Policy definition name. + :param policy_definition_name: Policy definition name. Required. :type policy_definition_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_policy_definition.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyDefinitionName': self._serialize.url("policy_definition_name", policy_definition_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_policy_definition_request( + policy_states_summary_resource=policy_states_summary_resource, + subscription_id=subscription_id, + policy_definition_name=policy_definition_name, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.summarize_for_policy_definition.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_policy_definition.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore + summarize_for_policy_definition.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore + + @distributed_trace def list_query_results_for_subscription_level_policy_assignment( self, policy_states_resource: Union[str, "_models.PolicyStatesResource"], subscription_id: str, policy_assignment_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyStatesQueryResults"]: + ) -> AsyncIterable["_models.PolicyState"]: """Queries policy states for the subscription level policy assignment. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_assignment_name: Policy assignment name. + :param policy_assignment_name: Policy assignment name. Required. :type policy_assignment_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_subscription_level_policy_assignment.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyAssignmentName': self._serialize.url("policy_assignment_name", policy_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_subscription_level_policy_assignment_request( + policy_states_resource=policy_states_resource, + subscription_id=subscription_id, + policy_assignment_name=policy_assignment_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_subscription_level_policy_assignment.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1598,213 +1781,239 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_subscription_level_policy_assignment.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_query_results_for_subscription_level_policy_assignment.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + + @distributed_trace_async async def summarize_for_subscription_level_policy_assignment( self, + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], subscription_id: str, policy_assignment_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> "_models.SummarizeResults": + ) -> _models.SummarizeResults: """Summarizes policy states for the subscription level policy assignment. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_assignment_name: Policy assignment name. + :param policy_assignment_name: Policy assignment name. Required. :type policy_assignment_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_subscription_level_policy_assignment.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyAssignmentName': self._serialize.url("policy_assignment_name", policy_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_subscription_level_policy_assignment_request( + policy_states_summary_resource=policy_states_summary_resource, + subscription_id=subscription_id, + policy_assignment_name=policy_assignment_name, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.summarize_for_subscription_level_policy_assignment.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_subscription_level_policy_assignment.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore + summarize_for_subscription_level_policy_assignment.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore + + @distributed_trace def list_query_results_for_resource_group_level_policy_assignment( self, policy_states_resource: Union[str, "_models.PolicyStatesResource"], subscription_id: str, resource_group_name: str, policy_assignment_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyStatesQueryResults"]: + ) -> AsyncIterable["_models.PolicyState"]: """Queries policy states for the resource group level policy assignment. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param policy_assignment_name: Policy assignment name. + :param policy_assignment_name: Policy assignment name. Required. :type policy_assignment_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource_group_level_policy_assignment.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyAssignmentName': self._serialize.url("policy_assignment_name", policy_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_resource_group_level_policy_assignment_request( + policy_states_resource=policy_states_resource, + subscription_id=subscription_id, + resource_group_name=resource_group_name, + policy_assignment_name=policy_assignment_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_resource_group_level_policy_assignment.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1813,104 +2022,115 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_resource_group_level_policy_assignment.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_query_results_for_resource_group_level_policy_assignment.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + + @distributed_trace_async async def summarize_for_resource_group_level_policy_assignment( self, + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], subscription_id: str, resource_group_name: str, policy_assignment_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> "_models.SummarizeResults": + ) -> _models.SummarizeResults: """Summarizes policy states for the resource group level policy assignment. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param policy_assignment_name: Policy assignment name. + :param policy_assignment_name: Policy assignment name. Required. :type policy_assignment_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_resource_group_level_policy_assignment.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyAssignmentName': self._serialize.url("policy_assignment_name", policy_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_resource_group_level_policy_assignment_request( + policy_states_summary_resource=policy_states_summary_resource, + subscription_id=subscription_id, + resource_group_name=resource_group_name, + policy_assignment_name=policy_assignment_name, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.summarize_for_resource_group_level_policy_assignment.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_resource_group_level_policy_assignment.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore + + summarize_for_resource_group_level_policy_assignment.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_tracked_resources_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_tracked_resources_operations.py index 284d2241b3b8..c4cd7e6df94d 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_tracked_resources_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_tracked_resources_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,106 +6,131 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar -import warnings +from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import 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 - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._policy_tracked_resources_operations import ( + build_list_query_results_for_management_group_request, + build_list_query_results_for_resource_group_request, + build_list_query_results_for_resource_request, + build_list_query_results_for_subscription_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class PolicyTrackedResourcesOperations: - """PolicyTrackedResourcesOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class PolicyTrackedResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s + :attr:`policy_tracked_resources` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_query_results_for_management_group( self, management_group_name: str, - query_options: Optional["_models.QueryOptions"] = None, + policy_tracked_resources_resource: Union[str, "_models.PolicyTrackedResourcesResourceType"], + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyTrackedResourcesQueryResults"]: + ) -> AsyncIterable["_models.PolicyTrackedResource"]: """Queries policy tracked resources under the management group. - :param management_group_name: Management group name. + :param management_group_name: Management group name. Required. :type management_group_name: str - :param query_options: Parameter group. + :param policy_tracked_resources_resource: The name of the virtual resource under + PolicyTrackedResources resource type; only "default" is allowed. "default" Required. + :type policy_tracked_resources_resource: str or + ~azure.mgmt.policyinsights.models.PolicyTrackedResourcesResourceType + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyTrackedResourcesQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResourcesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyTrackedResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyTrackedResourcesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyTrackedResourcesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - management_groups_namespace = "Microsoft.Management" - policy_tracked_resources_resource = "default" - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupName': self._serialize.url("management_group_name", management_group_name, 'str'), - 'policyTrackedResourcesResource': self._serialize.url("policy_tracked_resources_resource", policy_tracked_resources_resource, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_query_results_for_management_group_request( + management_group_name=management_group_name, + policy_tracked_resources_resource=policy_tracked_resources_resource, + top=_top, + filter=_filter, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.list_query_results_for_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyTrackedResourcesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyTrackedResourcesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -113,80 +139,88 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_query_results_for_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults"} # type: ignore + @distributed_trace def list_query_results_for_subscription( self, - query_options: Optional["_models.QueryOptions"] = None, + policy_tracked_resources_resource: Union[str, "_models.PolicyTrackedResourcesResourceType"], + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyTrackedResourcesQueryResults"]: + ) -> AsyncIterable["_models.PolicyTrackedResource"]: """Queries policy tracked resources under the subscription. - :param query_options: Parameter group. + :param policy_tracked_resources_resource: The name of the virtual resource under + PolicyTrackedResources resource type; only "default" is allowed. "default" Required. + :type policy_tracked_resources_resource: str or + ~azure.mgmt.policyinsights.models.PolicyTrackedResourcesResourceType + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyTrackedResourcesQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResourcesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyTrackedResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyTrackedResourcesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyTrackedResourcesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - policy_tracked_resources_resource = "default" - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'policyTrackedResourcesResource': self._serialize.url("policy_tracked_resources_resource", policy_tracked_resources_resource, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_query_results_for_subscription_request( + policy_tracked_resources_resource=policy_tracked_resources_resource, + subscription_id=self._config.subscription_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_query_results_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyTrackedResourcesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyTrackedResourcesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -195,84 +229,92 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_query_results_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults"} # type: ignore + @distributed_trace def list_query_results_for_resource_group( self, resource_group_name: str, - query_options: Optional["_models.QueryOptions"] = None, + policy_tracked_resources_resource: Union[str, "_models.PolicyTrackedResourcesResourceType"], + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyTrackedResourcesQueryResults"]: + ) -> AsyncIterable["_models.PolicyTrackedResource"]: """Queries policy tracked resources under the resource group. - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param query_options: Parameter group. + :param policy_tracked_resources_resource: The name of the virtual resource under + PolicyTrackedResources resource type; only "default" is allowed. "default" Required. + :type policy_tracked_resources_resource: str or + ~azure.mgmt.policyinsights.models.PolicyTrackedResourcesResourceType + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyTrackedResourcesQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResourcesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyTrackedResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyTrackedResourcesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyTrackedResourcesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - policy_tracked_resources_resource = "default" - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'policyTrackedResourcesResource': self._serialize.url("policy_tracked_resources_resource", policy_tracked_resources_resource, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_query_results_for_resource_group_request( + resource_group_name=resource_group_name, + policy_tracked_resources_resource=policy_tracked_resources_resource, + subscription_id=self._config.subscription_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_query_results_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyTrackedResourcesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyTrackedResourcesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -281,83 +323,91 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_query_results_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults"} # type: ignore + + @distributed_trace def list_query_results_for_resource( self, resource_id: str, - query_options: Optional["_models.QueryOptions"] = None, + policy_tracked_resources_resource: Union[str, "_models.PolicyTrackedResourcesResourceType"], + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.PolicyTrackedResourcesQueryResults"]: + ) -> AsyncIterable["_models.PolicyTrackedResource"]: """Queries policy tracked resources under the resource. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param query_options: Parameter group. + :param policy_tracked_resources_resource: The name of the virtual resource under + PolicyTrackedResources resource type; only "default" is allowed. "default" Required. + :type policy_tracked_resources_resource: str or + ~azure.mgmt.policyinsights.models.PolicyTrackedResourcesResourceType + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyTrackedResourcesQueryResults or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResourcesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyTrackedResource or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyTrackedResourcesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyTrackedResourcesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - policy_tracked_resources_resource = "default" - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'policyTrackedResourcesResource': self._serialize.url("policy_tracked_resources_resource", policy_tracked_resources_resource, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_query_results_for_resource_request( + resource_id=resource_id, + policy_tracked_resources_resource=policy_tracked_resources_resource, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_query_results_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyTrackedResourcesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyTrackedResourcesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -366,17 +416,18 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return AsyncItemPaged( - get_next, extract_data - ) - list_query_results_for_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_query_results_for_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_remediations_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_remediations_operations.py index 3979e9042b2e..f79615e11956 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_remediations_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_remediations_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,104 +6,147 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union -import warnings +from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import 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 - -T = TypeVar('T') +from ..._vendor import _convert_request +from ...operations._remediations_operations import ( + build_cancel_at_management_group_request, + build_cancel_at_resource_group_request, + build_cancel_at_resource_request, + build_cancel_at_subscription_request, + build_create_or_update_at_management_group_request, + build_create_or_update_at_resource_group_request, + build_create_or_update_at_resource_request, + build_create_or_update_at_subscription_request, + build_delete_at_management_group_request, + build_delete_at_resource_group_request, + build_delete_at_resource_request, + build_delete_at_subscription_request, + build_get_at_management_group_request, + build_get_at_resource_group_request, + build_get_at_resource_request, + build_get_at_subscription_request, + build_list_deployments_at_management_group_request, + build_list_deployments_at_resource_group_request, + build_list_deployments_at_resource_request, + build_list_deployments_at_subscription_request, + build_list_for_management_group_request, + build_list_for_resource_group_request, + build_list_for_resource_request, + build_list_for_subscription_request, +) + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class RemediationsOperations: - """RemediationsOperations async operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +class RemediationsOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.aio.PolicyInsightsClient`'s + :attr:`remediations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer) -> None: - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_deployments_at_management_group( self, management_group_id: str, remediation_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.RemediationDeploymentsListResult"]: + ) -> AsyncIterable["_models.RemediationDeployment"]: """Gets all deployments for a remediation at management group scope. - :param management_group_id: Management group ID. + :param management_group_id: Management group ID. Required. :type management_group_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationDeploymentsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationDeploymentsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RemediationDeployment or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationDeployment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationDeploymentsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationDeploymentsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - if query_options is not None: - _top = query_options.top - management_groups_namespace = "Microsoft.Management" - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_deployments_at_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupId': self._serialize.url("management_group_id", management_group_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + if query_options is not None: + _top = query_options.top + + request = build_list_deployments_at_management_group_request( + management_group_id=management_group_id, + remediation_name=remediation_name, + top=_top, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.list_deployments_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationDeploymentsListResult', pipeline_response) + deserialized = self._deserialize("RemediationDeploymentsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -111,143 +155,152 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_deployments_at_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_deployments_at_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments"} # type: ignore + + @distributed_trace_async async def cancel_at_management_group( - self, - management_group_id: str, - remediation_name: str, - **kwargs: Any - ) -> "_models.Remediation": + self, management_group_id: str, remediation_name: str, **kwargs: Any + ) -> _models.Remediation: """Cancels a remediation at management group scope. - :param management_group_id: Management group ID. + :param management_group_id: Management group ID. Required. :type management_group_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - management_groups_namespace = "Microsoft.Management" - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.cancel_at_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupId': self._serialize.url("management_group_id", management_group_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + request = build_cancel_at_management_group_request( + management_group_id=management_group_id, + remediation_name=remediation_name, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.cancel_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - cancel_at_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel'} # type: ignore + cancel_at_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel"} # type: ignore + + @distributed_trace def list_for_management_group( - self, - management_group_id: str, - query_options: Optional["_models.QueryOptions"] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RemediationListResult"]: + self, management_group_id: str, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> AsyncIterable["_models.Remediation"]: """Gets all remediations for the management group. - :param management_group_id: Management group ID. + :param management_group_id: Management group ID. Required. :type management_group_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Remediation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.Remediation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - management_groups_namespace = "Microsoft.Management" - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupId': self._serialize.url("management_group_id", management_group_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_for_management_group_request( + management_group_id=management_group_id, + top=_top, + filter=_filter, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.list_for_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationListResult', pipeline_response) + deserialized = self._deserialize("RemediationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -256,272 +309,363 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_for_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_for_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations"} # type: ignore + + @overload async def create_or_update_at_management_group( self, management_group_id: str, remediation_name: str, - parameters: "_models.Remediation", + parameters: _models.Remediation, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Remediation": + ) -> _models.Remediation: """Creates or updates a remediation at management group scope. - :param management_group_id: Management group ID. + :param management_group_id: Management group ID. Required. :type management_group_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param parameters: The remediation parameters. + :param parameters: The remediation parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.Remediation + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_management_group( + self, + management_group_id: str, + remediation_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at management group scope. + + :param management_group_id: Management group ID. Required. + :type management_group_id: str + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_management_group( + self, management_group_id: str, remediation_name: str, parameters: Union[_models.Remediation, IO], **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at management group scope. + + :param management_group_id: Management group ID. Required. + :type management_group_id: str + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.Remediation or IO + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str + :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 + :return: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - management_groups_namespace = "Microsoft.Management" - api_version = "2021-10-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_at_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupId': self._serialize.url("management_group_id", management_group_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Remediation') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Remediation") + + request = build_create_or_update_at_management_group_request( + management_group_id=management_group_id, + remediation_name=remediation_name, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **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, 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('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_at_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + create_or_update_at_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace_async async def get_at_management_group( - self, - management_group_id: str, - remediation_name: str, - **kwargs: Any - ) -> "_models.Remediation": + self, management_group_id: str, remediation_name: str, **kwargs: Any + ) -> _models.Remediation: """Gets an existing remediation at management group scope. - :param management_group_id: Management group ID. + :param management_group_id: Management group ID. Required. :type management_group_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - management_groups_namespace = "Microsoft.Management" - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.get_at_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupId': self._serialize.url("management_group_id", management_group_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + request = build_get_at_management_group_request( + management_group_id=management_group_id, + remediation_name=remediation_name, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.get_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_at_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + get_at_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace_async async def delete_at_management_group( - self, - management_group_id: str, - remediation_name: str, - **kwargs: Any - ) -> Optional["_models.Remediation"]: + self, management_group_id: str, remediation_name: str, **kwargs: Any + ) -> Optional[_models.Remediation]: """Deletes an existing remediation at management group scope. - :param management_group_id: Management group ID. + :param management_group_id: Management group ID. Required. :type management_group_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or None or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Remediation"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - management_groups_namespace = "Microsoft.Management" - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.delete_at_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupId': self._serialize.url("management_group_id", management_group_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Remediation]] + + request = build_delete_at_management_group_request( + management_group_id=management_group_id, + remediation_name=remediation_name, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.delete_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **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, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_at_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + delete_at_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace def list_deployments_at_subscription( - self, - remediation_name: str, - query_options: Optional["_models.QueryOptions"] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RemediationDeploymentsListResult"]: + self, remediation_name: str, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> AsyncIterable["_models.RemediationDeployment"]: """Gets all deployments for a remediation at subscription scope. - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationDeploymentsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationDeploymentsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RemediationDeployment or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationDeployment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationDeploymentsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationDeploymentsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - if query_options is not None: - _top = query_options.top - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_deployments_at_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + if query_options is not None: + _top = query_options.top + + request = build_list_deployments_at_subscription_request( + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + top=_top, + api_version=api_version, + template_url=self.list_deployments_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationDeploymentsListResult', pipeline_response) + deserialized = self._deserialize("RemediationDeploymentsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -530,133 +674,134 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_deployments_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def cancel_at_subscription( - self, - remediation_name: str, - **kwargs: Any - ) -> "_models.Remediation": + list_deployments_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments"} # type: ignore + + @distributed_trace_async + async def cancel_at_subscription(self, remediation_name: str, **kwargs: Any) -> _models.Remediation: """Cancels a remediation at subscription scope. - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.cancel_at_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + request = build_cancel_at_subscription_request( + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.cancel_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - cancel_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel'} # type: ignore + cancel_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel"} # type: ignore + + @distributed_trace def list_for_subscription( - self, - query_options: Optional["_models.QueryOptions"] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RemediationListResult"]: + self, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> AsyncIterable["_models.Remediation"]: """Gets all remediations for the subscription. - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Remediation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.Remediation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_for_subscription_request( + subscription_id=self._config.subscription_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationListResult', pipeline_response) + deserialized = self._deserialize("RemediationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -665,261 +810,323 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations"} # type: ignore + @overload async def create_or_update_at_subscription( self, remediation_name: str, - parameters: "_models.Remediation", + parameters: _models.Remediation, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Remediation": + ) -> _models.Remediation: """Creates or updates a remediation at subscription scope. - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param parameters: The remediation parameters. + :param parameters: The remediation parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.Remediation + :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: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_subscription( + self, remediation_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at subscription scope. + + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Required. + :type parameters: IO + :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: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_subscription( + self, remediation_name: str, parameters: Union[_models.Remediation, IO], **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at subscription scope. + + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.Remediation 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 + :return: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_at_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Remediation') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Remediation") + + request = build_create_or_update_at_subscription_request( + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **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, 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('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore - async def get_at_subscription( - self, - remediation_name: str, - **kwargs: Any - ) -> "_models.Remediation": + create_or_update_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace_async + async def get_at_subscription(self, remediation_name: str, **kwargs: Any) -> _models.Remediation: """Gets an existing remediation at subscription scope. - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.get_at_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + request = build_get_at_subscription_request( + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore - async def delete_at_subscription( - self, - remediation_name: str, - **kwargs: Any - ) -> Optional["_models.Remediation"]: + get_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace_async + async def delete_at_subscription(self, remediation_name: str, **kwargs: Any) -> Optional[_models.Remediation]: """Deletes an existing remediation at subscription scope. - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or None or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Remediation"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.delete_at_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Remediation]] + + request = build_delete_at_subscription_request( + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **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, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + delete_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace def list_deployments_at_resource_group( self, resource_group_name: str, remediation_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.RemediationDeploymentsListResult"]: + ) -> AsyncIterable["_models.RemediationDeployment"]: """Gets all deployments for a remediation at resource group scope. - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationDeploymentsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationDeploymentsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RemediationDeployment or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationDeployment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationDeploymentsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationDeploymentsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - if query_options is not None: - _top = query_options.top - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_deployments_at_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + if query_options is not None: + _top = query_options.top + + request = build_list_deployments_at_resource_group_request( + resource_group_name=resource_group_name, + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + top=_top, + api_version=api_version, + template_url=self.list_deployments_at_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationDeploymentsListResult', pipeline_response) + deserialized = self._deserialize("RemediationDeploymentsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -928,141 +1135,142 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_deployments_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_deployments_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments"} # type: ignore + @distributed_trace_async async def cancel_at_resource_group( - self, - resource_group_name: str, - remediation_name: str, - **kwargs: Any - ) -> "_models.Remediation": + self, resource_group_name: str, remediation_name: str, **kwargs: Any + ) -> _models.Remediation: """Cancels a remediation at resource group scope. - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.cancel_at_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + request = build_cancel_at_resource_group_request( + resource_group_name=resource_group_name, + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.cancel_at_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - cancel_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel'} # type: ignore + cancel_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel"} # type: ignore + + @distributed_trace def list_for_resource_group( - self, - resource_group_name: str, - query_options: Optional["_models.QueryOptions"] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RemediationListResult"]: + self, resource_group_name: str, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> AsyncIterable["_models.Remediation"]: """Gets all remediations for the subscription. - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Remediation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.Remediation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationListResult', pipeline_response) + deserialized = self._deserialize("RemediationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1071,272 +1279,346 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations"} # type: ignore + @overload async def create_or_update_at_resource_group( self, resource_group_name: str, remediation_name: str, - parameters: "_models.Remediation", + parameters: _models.Remediation, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Remediation": + ) -> _models.Remediation: """Creates or updates a remediation at resource group scope. - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param parameters: The remediation parameters. + :param parameters: The remediation parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.Remediation + :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: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_resource_group( + self, + resource_group_name: str, + remediation_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at resource group scope. + + :param resource_group_name: Resource group name. Required. + :type resource_group_name: str + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Required. + :type parameters: IO + :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: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_resource_group( + self, resource_group_name: str, remediation_name: str, parameters: Union[_models.Remediation, IO], **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at resource group scope. + + :param resource_group_name: Resource group name. Required. + :type resource_group_name: str + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.Remediation 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 - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_at_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Remediation') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Remediation") + + request = build_create_or_update_at_resource_group_request( + resource_group_name=resource_group_name, + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **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, 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('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + create_or_update_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace_async async def get_at_resource_group( - self, - resource_group_name: str, - remediation_name: str, - **kwargs: Any - ) -> "_models.Remediation": + self, resource_group_name: str, remediation_name: str, **kwargs: Any + ) -> _models.Remediation: """Gets an existing remediation at resource group scope. - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.get_at_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + request = build_get_at_resource_group_request( + resource_group_name=resource_group_name, + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + get_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace_async async def delete_at_resource_group( - self, - resource_group_name: str, - remediation_name: str, - **kwargs: Any - ) -> Optional["_models.Remediation"]: + self, resource_group_name: str, remediation_name: str, **kwargs: Any + ) -> Optional[_models.Remediation]: """Deletes an existing remediation at resource group scope. - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or None or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Remediation"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.delete_at_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Remediation]] + + request = build_delete_at_resource_group_request( + resource_group_name=resource_group_name, + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **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, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + delete_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace def list_deployments_at_resource( self, resource_id: str, remediation_name: str, - query_options: Optional["_models.QueryOptions"] = None, + query_options: Optional[_models.QueryOptions] = None, **kwargs: Any - ) -> AsyncIterable["_models.RemediationDeploymentsListResult"]: + ) -> AsyncIterable["_models.RemediationDeployment"]: """Gets all deployments for a remediation at resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationDeploymentsListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationDeploymentsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RemediationDeployment or the result of + cls(response) + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationDeployment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationDeploymentsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationDeploymentsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - if query_options is not None: - _top = query_options.top - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_deployments_at_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + if query_options is not None: + _top = query_options.top + + request = build_list_deployments_at_resource_request( + resource_id=resource_id, + remediation_name=remediation_name, + top=_top, + api_version=api_version, + template_url=self.list_deployments_at_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationDeploymentsListResult', pipeline_response) + deserialized = self._deserialize("RemediationDeploymentsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1345,139 +1627,138 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_deployments_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments'} # type: ignore + return AsyncItemPaged(get_next, extract_data) - async def cancel_at_resource( - self, - resource_id: str, - remediation_name: str, - **kwargs: Any - ) -> "_models.Remediation": + list_deployments_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments"} # type: ignore + + @distributed_trace_async + async def cancel_at_resource(self, resource_id: str, remediation_name: str, **kwargs: Any) -> _models.Remediation: """Cancel a remediation at resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.cancel_at_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_cancel_at_resource_request( + resource_id=resource_id, + remediation_name=remediation_name, + api_version=api_version, + template_url=self.cancel_at_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - cancel_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel'} # type: ignore + cancel_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel"} # type: ignore + + @distributed_trace def list_for_resource( - self, - resource_id: str, - query_options: Optional["_models.QueryOptions"] = None, - **kwargs: Any - ) -> AsyncIterable["_models.RemediationListResult"]: + self, resource_id: str, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> AsyncIterable["_models.Remediation"]: """Gets all remediations for a resource. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationListResult or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.RemediationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Remediation or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.Remediation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_for_resource_request( + resource_id=resource_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request async def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationListResult', pipeline_response) + deserialized = self._deserialize("RemediationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1486,205 +1767,273 @@ async def extract_data(pipeline_response): async def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_for_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/remediations'} # type: ignore + return AsyncItemPaged(get_next, extract_data) + list_for_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/remediations"} # type: ignore + + @overload async def create_or_update_at_resource( self, resource_id: str, remediation_name: str, - parameters: "_models.Remediation", + parameters: _models.Remediation, + *, + content_type: str = "application/json", **kwargs: Any - ) -> "_models.Remediation": + ) -> _models.Remediation: """Creates or updates a remediation at resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param parameters: The remediation parameters. + :param parameters: The remediation parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.Remediation + :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: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_or_update_at_resource( + self, + resource_id: str, + remediation_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at resource scope. + + :param resource_id: Resource ID. Required. + :type resource_id: str + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Required. + :type parameters: IO + :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: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_or_update_at_resource( + self, resource_id: str, remediation_name: str, parameters: Union[_models.Remediation, IO], **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at resource scope. + + :param resource_id: Resource ID. Required. + :type resource_id: str + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.Remediation 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 + :return: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_at_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Remediation') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Remediation") + + request = build_create_or_update_at_resource_request( + resource_id=resource_id, + remediation_name=remediation_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **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, 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('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore - async def get_at_resource( - self, - resource_id: str, - remediation_name: str, - **kwargs: Any - ) -> "_models.Remediation": + create_or_update_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace_async + async def get_at_resource(self, resource_id: str, remediation_name: str, **kwargs: Any) -> _models.Remediation: """Gets an existing remediation at resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.get_at_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + request = build_get_at_resource_request( + resource_id=resource_id, + remediation_name=remediation_name, + api_version=api_version, + template_url=self.get_at_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + get_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace_async async def delete_at_resource( - self, - resource_id: str, - remediation_name: str, - **kwargs: Any - ) -> Optional["_models.Remediation"]: + self, resource_id: str, remediation_name: str, **kwargs: Any + ) -> Optional[_models.Remediation]: """Deletes an existing remediation at individual resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or None or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Remediation"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.delete_at_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Remediation]] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_delete_at_resource_request( + resource_id=resource_id, + remediation_name=remediation_name, + api_version=api_version, + template_url=self.delete_at_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = await self._client._pipeline.run(request, stream=False, **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, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + + delete_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/__init__.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/__init__.py index a9874d02f749..be6ccec9ce7a 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/__init__.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/__init__.py @@ -6,198 +6,148 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -try: - from ._models_py3 import Attestation - from ._models_py3 import AttestationEvidence - from ._models_py3 import AttestationListResult - from ._models_py3 import CheckRestrictionsRequest - from ._models_py3 import CheckRestrictionsResourceDetails - from ._models_py3 import CheckRestrictionsResult - from ._models_py3 import CheckRestrictionsResultContentEvaluationResult - from ._models_py3 import ComplianceDetail - from ._models_py3 import ComponentEventDetails - from ._models_py3 import ComponentStateDetails - from ._models_py3 import ErrorDefinition - from ._models_py3 import ErrorDefinitionAutoGenerated - from ._models_py3 import ErrorDefinitionAutoGenerated2 - from ._models_py3 import ErrorResponse - from ._models_py3 import ErrorResponseAutoGenerated - from ._models_py3 import ErrorResponseAutoGenerated2 - from ._models_py3 import ExpressionEvaluationDetails - from ._models_py3 import FieldRestriction - from ._models_py3 import FieldRestrictions - from ._models_py3 import IfNotExistsEvaluationDetails - from ._models_py3 import Operation - from ._models_py3 import OperationDisplay - from ._models_py3 import OperationsListResults - from ._models_py3 import PendingField - from ._models_py3 import PolicyAssignmentSummary - from ._models_py3 import PolicyDefinitionSummary - from ._models_py3 import PolicyDetails - from ._models_py3 import PolicyEvaluationDetails - from ._models_py3 import PolicyEvaluationResult - from ._models_py3 import PolicyEvent - from ._models_py3 import PolicyEventsQueryResults - from ._models_py3 import PolicyGroupSummary - from ._models_py3 import PolicyMetadata - from ._models_py3 import PolicyMetadataCollection - from ._models_py3 import PolicyMetadataProperties - from ._models_py3 import PolicyMetadataSlimProperties - from ._models_py3 import PolicyReference - from ._models_py3 import PolicyState - from ._models_py3 import PolicyStatesQueryResults - from ._models_py3 import PolicyTrackedResource - from ._models_py3 import PolicyTrackedResourcesQueryResults - from ._models_py3 import QueryFailure - from ._models_py3 import QueryFailureError - from ._models_py3 import QueryOptions - from ._models_py3 import Remediation - from ._models_py3 import RemediationDeployment - from ._models_py3 import RemediationDeploymentSummary - from ._models_py3 import RemediationDeploymentsListResult - from ._models_py3 import RemediationFilters - from ._models_py3 import RemediationListResult - from ._models_py3 import RemediationPropertiesFailureThreshold - from ._models_py3 import Resource - from ._models_py3 import SlimPolicyMetadata - from ._models_py3 import SummarizeResults - from ._models_py3 import Summary - from ._models_py3 import SummaryResults - from ._models_py3 import SystemData - from ._models_py3 import TrackedResourceModificationDetails - from ._models_py3 import TypedErrorInfo -except (SyntaxError, ImportError): - from ._models import Attestation # type: ignore - from ._models import AttestationEvidence # type: ignore - from ._models import AttestationListResult # type: ignore - from ._models import CheckRestrictionsRequest # type: ignore - from ._models import CheckRestrictionsResourceDetails # type: ignore - from ._models import CheckRestrictionsResult # type: ignore - from ._models import CheckRestrictionsResultContentEvaluationResult # type: ignore - from ._models import ComplianceDetail # type: ignore - from ._models import ComponentEventDetails # type: ignore - from ._models import ComponentStateDetails # type: ignore - from ._models import ErrorDefinition # type: ignore - from ._models import ErrorDefinitionAutoGenerated # type: ignore - from ._models import ErrorDefinitionAutoGenerated2 # type: ignore - from ._models import ErrorResponse # type: ignore - from ._models import ErrorResponseAutoGenerated # type: ignore - from ._models import ErrorResponseAutoGenerated2 # type: ignore - from ._models import ExpressionEvaluationDetails # type: ignore - from ._models import FieldRestriction # type: ignore - from ._models import FieldRestrictions # type: ignore - from ._models import IfNotExistsEvaluationDetails # type: ignore - from ._models import Operation # type: ignore - from ._models import OperationDisplay # type: ignore - from ._models import OperationsListResults # type: ignore - from ._models import PendingField # type: ignore - from ._models import PolicyAssignmentSummary # type: ignore - from ._models import PolicyDefinitionSummary # type: ignore - from ._models import PolicyDetails # type: ignore - from ._models import PolicyEvaluationDetails # type: ignore - from ._models import PolicyEvaluationResult # type: ignore - from ._models import PolicyEvent # type: ignore - from ._models import PolicyEventsQueryResults # type: ignore - from ._models import PolicyGroupSummary # type: ignore - from ._models import PolicyMetadata # type: ignore - from ._models import PolicyMetadataCollection # type: ignore - from ._models import PolicyMetadataProperties # type: ignore - from ._models import PolicyMetadataSlimProperties # type: ignore - from ._models import PolicyReference # type: ignore - from ._models import PolicyState # type: ignore - from ._models import PolicyStatesQueryResults # type: ignore - from ._models import PolicyTrackedResource # type: ignore - from ._models import PolicyTrackedResourcesQueryResults # type: ignore - from ._models import QueryFailure # type: ignore - from ._models import QueryFailureError # type: ignore - from ._models import QueryOptions # type: ignore - from ._models import Remediation # type: ignore - from ._models import RemediationDeployment # type: ignore - from ._models import RemediationDeploymentSummary # type: ignore - from ._models import RemediationDeploymentsListResult # type: ignore - from ._models import RemediationFilters # type: ignore - from ._models import RemediationListResult # type: ignore - from ._models import RemediationPropertiesFailureThreshold # type: ignore - from ._models import Resource # type: ignore - from ._models import SlimPolicyMetadata # type: ignore - from ._models import SummarizeResults # type: ignore - from ._models import Summary # type: ignore - from ._models import SummaryResults # type: ignore - from ._models import SystemData # type: ignore - from ._models import TrackedResourceModificationDetails # type: ignore - from ._models import TypedErrorInfo # type: ignore +from ._models_py3 import Attestation +from ._models_py3 import AttestationEvidence +from ._models_py3 import AttestationListResult +from ._models_py3 import CheckManagementGroupRestrictionsRequest +from ._models_py3 import CheckRestrictionsRequest +from ._models_py3 import CheckRestrictionsResourceDetails +from ._models_py3 import CheckRestrictionsResult +from ._models_py3 import CheckRestrictionsResultContentEvaluationResult +from ._models_py3 import ComplianceDetail +from ._models_py3 import ComponentEventDetails +from ._models_py3 import ComponentStateDetails +from ._models_py3 import ErrorDefinition +from ._models_py3 import ErrorDefinitionAutoGenerated +from ._models_py3 import ErrorDefinitionAutoGenerated2 +from ._models_py3 import ErrorResponse +from ._models_py3 import ErrorResponseAutoGenerated +from ._models_py3 import ErrorResponseAutoGenerated2 +from ._models_py3 import ExpressionEvaluationDetails +from ._models_py3 import FieldRestriction +from ._models_py3 import FieldRestrictions +from ._models_py3 import IfNotExistsEvaluationDetails +from ._models_py3 import Operation +from ._models_py3 import OperationDisplay +from ._models_py3 import OperationsListResults +from ._models_py3 import PendingField +from ._models_py3 import PolicyAssignmentSummary +from ._models_py3 import PolicyDefinitionSummary +from ._models_py3 import PolicyDetails +from ._models_py3 import PolicyEvaluationDetails +from ._models_py3 import PolicyEvaluationResult +from ._models_py3 import PolicyEvent +from ._models_py3 import PolicyEventsQueryResults +from ._models_py3 import PolicyGroupSummary +from ._models_py3 import PolicyMetadata +from ._models_py3 import PolicyMetadataCollection +from ._models_py3 import PolicyMetadataProperties +from ._models_py3 import PolicyMetadataSlimProperties +from ._models_py3 import PolicyReference +from ._models_py3 import PolicyState +from ._models_py3 import PolicyStatesQueryResults +from ._models_py3 import PolicyTrackedResource +from ._models_py3 import PolicyTrackedResourcesQueryResults +from ._models_py3 import QueryFailure +from ._models_py3 import QueryFailureError +from ._models_py3 import QueryOptions +from ._models_py3 import Remediation +from ._models_py3 import RemediationDeployment +from ._models_py3 import RemediationDeploymentSummary +from ._models_py3 import RemediationDeploymentsListResult +from ._models_py3 import RemediationFilters +from ._models_py3 import RemediationListResult +from ._models_py3 import RemediationPropertiesFailureThreshold +from ._models_py3 import Resource +from ._models_py3 import SlimPolicyMetadata +from ._models_py3 import SummarizeResults +from ._models_py3 import Summary +from ._models_py3 import SummaryResults +from ._models_py3 import SystemData +from ._models_py3 import TrackedResourceModificationDetails +from ._models_py3 import TypedErrorInfo -from ._policy_insights_client_enums import ( - ComplianceState, - CreatedByType, - FieldRestrictionResult, - PolicyStatesResource, - ResourceDiscoveryMode, -) +from ._policy_insights_client_enums import ComplianceState +from ._policy_insights_client_enums import CreatedByType +from ._policy_insights_client_enums import FieldRestrictionResult +from ._policy_insights_client_enums import PolicyEventsResourceType +from ._policy_insights_client_enums import PolicyStatesResource +from ._policy_insights_client_enums import PolicyStatesSummaryResourceType +from ._policy_insights_client_enums import PolicyTrackedResourcesResourceType +from ._policy_insights_client_enums import ResourceDiscoveryMode +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk __all__ = [ - 'Attestation', - 'AttestationEvidence', - 'AttestationListResult', - 'CheckRestrictionsRequest', - 'CheckRestrictionsResourceDetails', - 'CheckRestrictionsResult', - 'CheckRestrictionsResultContentEvaluationResult', - 'ComplianceDetail', - 'ComponentEventDetails', - 'ComponentStateDetails', - 'ErrorDefinition', - 'ErrorDefinitionAutoGenerated', - 'ErrorDefinitionAutoGenerated2', - 'ErrorResponse', - 'ErrorResponseAutoGenerated', - 'ErrorResponseAutoGenerated2', - 'ExpressionEvaluationDetails', - 'FieldRestriction', - 'FieldRestrictions', - 'IfNotExistsEvaluationDetails', - 'Operation', - 'OperationDisplay', - 'OperationsListResults', - 'PendingField', - 'PolicyAssignmentSummary', - 'PolicyDefinitionSummary', - 'PolicyDetails', - 'PolicyEvaluationDetails', - 'PolicyEvaluationResult', - 'PolicyEvent', - 'PolicyEventsQueryResults', - 'PolicyGroupSummary', - 'PolicyMetadata', - 'PolicyMetadataCollection', - 'PolicyMetadataProperties', - 'PolicyMetadataSlimProperties', - 'PolicyReference', - 'PolicyState', - 'PolicyStatesQueryResults', - 'PolicyTrackedResource', - 'PolicyTrackedResourcesQueryResults', - 'QueryFailure', - 'QueryFailureError', - 'QueryOptions', - 'Remediation', - 'RemediationDeployment', - 'RemediationDeploymentSummary', - 'RemediationDeploymentsListResult', - 'RemediationFilters', - 'RemediationListResult', - 'RemediationPropertiesFailureThreshold', - 'Resource', - 'SlimPolicyMetadata', - 'SummarizeResults', - 'Summary', - 'SummaryResults', - 'SystemData', - 'TrackedResourceModificationDetails', - 'TypedErrorInfo', - 'ComplianceState', - 'CreatedByType', - 'FieldRestrictionResult', - 'PolicyStatesResource', - 'ResourceDiscoveryMode', + "Attestation", + "AttestationEvidence", + "AttestationListResult", + "CheckManagementGroupRestrictionsRequest", + "CheckRestrictionsRequest", + "CheckRestrictionsResourceDetails", + "CheckRestrictionsResult", + "CheckRestrictionsResultContentEvaluationResult", + "ComplianceDetail", + "ComponentEventDetails", + "ComponentStateDetails", + "ErrorDefinition", + "ErrorDefinitionAutoGenerated", + "ErrorDefinitionAutoGenerated2", + "ErrorResponse", + "ErrorResponseAutoGenerated", + "ErrorResponseAutoGenerated2", + "ExpressionEvaluationDetails", + "FieldRestriction", + "FieldRestrictions", + "IfNotExistsEvaluationDetails", + "Operation", + "OperationDisplay", + "OperationsListResults", + "PendingField", + "PolicyAssignmentSummary", + "PolicyDefinitionSummary", + "PolicyDetails", + "PolicyEvaluationDetails", + "PolicyEvaluationResult", + "PolicyEvent", + "PolicyEventsQueryResults", + "PolicyGroupSummary", + "PolicyMetadata", + "PolicyMetadataCollection", + "PolicyMetadataProperties", + "PolicyMetadataSlimProperties", + "PolicyReference", + "PolicyState", + "PolicyStatesQueryResults", + "PolicyTrackedResource", + "PolicyTrackedResourcesQueryResults", + "QueryFailure", + "QueryFailureError", + "QueryOptions", + "Remediation", + "RemediationDeployment", + "RemediationDeploymentSummary", + "RemediationDeploymentsListResult", + "RemediationFilters", + "RemediationListResult", + "RemediationPropertiesFailureThreshold", + "Resource", + "SlimPolicyMetadata", + "SummarizeResults", + "Summary", + "SummaryResults", + "SystemData", + "TrackedResourceModificationDetails", + "TypedErrorInfo", + "ComplianceState", + "CreatedByType", + "FieldRestrictionResult", + "PolicyEventsResourceType", + "PolicyStatesResource", + "PolicyStatesSummaryResourceType", + "PolicyTrackedResourcesResourceType", + "ResourceDiscoveryMode", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/_models.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/_models.py deleted file mode 100644 index 77670f3e4f05..000000000000 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/_models.py +++ /dev/null @@ -1,2503 +0,0 @@ -# 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.core.exceptions import HttpResponseError -import msrest.serialization - - -class Resource(msrest.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 - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) - self.id = None - self.name = None - self.type = None - - -class Attestation(Resource): - """An attestation resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to Azure. - - :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.policyinsights.models.SystemData - :param policy_assignment_id: Required. The resource ID of the policy assignment that the - attestation is setting the state for. - :type policy_assignment_id: str - :param policy_definition_reference_id: The policy definition reference ID from a policy set - definition that the attestation is setting the state for. If the policy assignment assigns a - policy set definition the attestation can choose a definition within the set definition with - this property or omit this and set the state for the entire set definition. - :type policy_definition_reference_id: str - :param compliance_state: The compliance state that should be set on the resource. Possible - values include: "Compliant", "NonCompliant", "Unknown". - :type compliance_state: str or ~azure.mgmt.policyinsights.models.ComplianceState - :param expires_on: The time the compliance state should expire. - :type expires_on: ~datetime.datetime - :param owner: The person responsible for setting the state of the resource. This value is - typically an Azure Active Directory object ID. - :type owner: str - :param comments: Comments describing why this attestation was created. - :type comments: str - :param evidence: The evidence supporting the compliance state set in this attestation. - :type evidence: list[~azure.mgmt.policyinsights.models.AttestationEvidence] - :ivar provisioning_state: The status of the attestation. - :vartype provisioning_state: str - :ivar last_compliance_state_change_at: The time the compliance state was last changed in this - attestation. - :vartype last_compliance_state_change_at: ~datetime.datetime - """ - - _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'policy_assignment_id': {'required': True}, - 'provisioning_state': {'readonly': True}, - 'last_compliance_state_change_at': {'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'}, - 'policy_assignment_id': {'key': 'properties.policyAssignmentId', 'type': 'str'}, - 'policy_definition_reference_id': {'key': 'properties.policyDefinitionReferenceId', 'type': 'str'}, - 'compliance_state': {'key': 'properties.complianceState', 'type': 'str'}, - 'expires_on': {'key': 'properties.expiresOn', 'type': 'iso-8601'}, - 'owner': {'key': 'properties.owner', 'type': 'str'}, - 'comments': {'key': 'properties.comments', 'type': 'str'}, - 'evidence': {'key': 'properties.evidence', 'type': '[AttestationEvidence]'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'last_compliance_state_change_at': {'key': 'properties.lastComplianceStateChangeAt', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(Attestation, self).__init__(**kwargs) - self.system_data = None - self.policy_assignment_id = kwargs['policy_assignment_id'] - self.policy_definition_reference_id = kwargs.get('policy_definition_reference_id', None) - self.compliance_state = kwargs.get('compliance_state', None) - self.expires_on = kwargs.get('expires_on', None) - self.owner = kwargs.get('owner', None) - self.comments = kwargs.get('comments', None) - self.evidence = kwargs.get('evidence', None) - self.provisioning_state = None - self.last_compliance_state_change_at = None - - -class AttestationEvidence(msrest.serialization.Model): - """A piece of evidence supporting the compliance state set in the attestation. - - :param description: The description for this piece of evidence. - :type description: str - :param source_uri: The URI location of the evidence. - :type source_uri: str - """ - - _attribute_map = { - 'description': {'key': 'description', 'type': 'str'}, - 'source_uri': {'key': 'sourceUri', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AttestationEvidence, self).__init__(**kwargs) - self.description = kwargs.get('description', None) - self.source_uri = kwargs.get('source_uri', None) - - -class AttestationListResult(msrest.serialization.Model): - """List of attestations. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: Array of attestation definitions. - :vartype value: list[~azure.mgmt.policyinsights.models.Attestation] - :ivar next_link: The URL to get the next set of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Attestation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(AttestationListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class CheckRestrictionsRequest(msrest.serialization.Model): - """The check policy restrictions parameters describing the resource that is being evaluated. - - All required parameters must be populated in order to send to Azure. - - :param resource_details: Required. The information about the resource that will be evaluated. - :type resource_details: ~azure.mgmt.policyinsights.models.CheckRestrictionsResourceDetails - :param pending_fields: The list of fields and values that should be evaluated for potential - restrictions. - :type pending_fields: list[~azure.mgmt.policyinsights.models.PendingField] - """ - - _validation = { - 'resource_details': {'required': True}, - } - - _attribute_map = { - 'resource_details': {'key': 'resourceDetails', 'type': 'CheckRestrictionsResourceDetails'}, - 'pending_fields': {'key': 'pendingFields', 'type': '[PendingField]'}, - } - - def __init__( - self, - **kwargs - ): - super(CheckRestrictionsRequest, self).__init__(**kwargs) - self.resource_details = kwargs['resource_details'] - self.pending_fields = kwargs.get('pending_fields', None) - - -class CheckRestrictionsResourceDetails(msrest.serialization.Model): - """The information about the resource that will be evaluated. - - All required parameters must be populated in order to send to Azure. - - :param resource_content: Required. The resource content. This should include whatever - properties are already known and can be a partial set of all resource properties. - :type resource_content: any - :param api_version: The api-version of the resource content. - :type api_version: str - :param scope: The scope where the resource is being created. For example, if the resource is a - child resource this would be the parent resource's resource ID. - :type scope: str - """ - - _validation = { - 'resource_content': {'required': True}, - } - - _attribute_map = { - 'resource_content': {'key': 'resourceContent', 'type': 'object'}, - 'api_version': {'key': 'apiVersion', 'type': 'str'}, - 'scope': {'key': 'scope', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(CheckRestrictionsResourceDetails, self).__init__(**kwargs) - self.resource_content = kwargs['resource_content'] - self.api_version = kwargs.get('api_version', None) - self.scope = kwargs.get('scope', None) - - -class CheckRestrictionsResult(msrest.serialization.Model): - """The result of a check policy restrictions evaluation on a resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar field_restrictions: The restrictions that will be placed on various fields in the - resource by policy. - :vartype field_restrictions: list[~azure.mgmt.policyinsights.models.FieldRestrictions] - :ivar content_evaluation_result: Evaluation results for the provided partial resource content. - :vartype content_evaluation_result: - ~azure.mgmt.policyinsights.models.CheckRestrictionsResultContentEvaluationResult - """ - - _validation = { - 'field_restrictions': {'readonly': True}, - 'content_evaluation_result': {'readonly': True}, - } - - _attribute_map = { - 'field_restrictions': {'key': 'fieldRestrictions', 'type': '[FieldRestrictions]'}, - 'content_evaluation_result': {'key': 'contentEvaluationResult', 'type': 'CheckRestrictionsResultContentEvaluationResult'}, - } - - def __init__( - self, - **kwargs - ): - super(CheckRestrictionsResult, self).__init__(**kwargs) - self.field_restrictions = None - self.content_evaluation_result = None - - -class CheckRestrictionsResultContentEvaluationResult(msrest.serialization.Model): - """Evaluation results for the provided partial resource content. - - :param policy_evaluations: Policy evaluation results against the given resource content. This - will indicate if the partial content that was provided will be denied as-is. - :type policy_evaluations: list[~azure.mgmt.policyinsights.models.PolicyEvaluationResult] - """ - - _attribute_map = { - 'policy_evaluations': {'key': 'policyEvaluations', 'type': '[PolicyEvaluationResult]'}, - } - - def __init__( - self, - **kwargs - ): - super(CheckRestrictionsResultContentEvaluationResult, self).__init__(**kwargs) - self.policy_evaluations = kwargs.get('policy_evaluations', None) - - -class ComplianceDetail(msrest.serialization.Model): - """The compliance state rollup. - - :param compliance_state: The compliance state. - :type compliance_state: str - :param count: Summarized count value for this compliance state. - :type count: int - """ - - _attribute_map = { - 'compliance_state': {'key': 'complianceState', 'type': 'str'}, - 'count': {'key': 'count', 'type': 'int'}, - } - - def __init__( - self, - **kwargs - ): - super(ComplianceDetail, self).__init__(**kwargs) - self.compliance_state = kwargs.get('compliance_state', None) - self.count = kwargs.get('count', None) - - -class ComponentEventDetails(msrest.serialization.Model): - """Component event details. - - :param additional_properties: Unmatched properties from the message are deserialized to this - collection. - :type additional_properties: dict[str, any] - :param id: Component Id. - :type id: str - :param type: Component type. - :type type: str - :param name: Component name. - :type name: str - :param timestamp: Timestamp for component policy event record. - :type timestamp: ~datetime.datetime - :param tenant_id: Tenant ID for the policy event record. - :type tenant_id: str - :param principal_oid: Principal object ID for the user who initiated the resource component - operation that triggered the policy event. - :type principal_oid: str - :param policy_definition_action: Policy definition action, i.e. effect. - :type policy_definition_action: str - """ - - _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'timestamp': {'key': 'timestamp', 'type': 'iso-8601'}, - 'tenant_id': {'key': 'tenantId', 'type': 'str'}, - 'principal_oid': {'key': 'principalOid', 'type': 'str'}, - 'policy_definition_action': {'key': 'policyDefinitionAction', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ComponentEventDetails, self).__init__(**kwargs) - self.additional_properties = kwargs.get('additional_properties', None) - self.id = kwargs.get('id', None) - self.type = kwargs.get('type', None) - self.name = kwargs.get('name', None) - self.timestamp = kwargs.get('timestamp', None) - self.tenant_id = kwargs.get('tenant_id', None) - self.principal_oid = kwargs.get('principal_oid', None) - self.policy_definition_action = kwargs.get('policy_definition_action', None) - - -class ComponentStateDetails(msrest.serialization.Model): - """Component state details. - - :param additional_properties: Unmatched properties from the message are deserialized to this - collection. - :type additional_properties: dict[str, any] - :param id: Component Id. - :type id: str - :param type: Component type. - :type type: str - :param name: Component name. - :type name: str - :param timestamp: Component compliance evaluation timestamp. - :type timestamp: ~datetime.datetime - :param compliance_state: Component compliance state. - :type compliance_state: str - """ - - _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'timestamp': {'key': 'timestamp', 'type': 'iso-8601'}, - 'compliance_state': {'key': 'complianceState', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ComponentStateDetails, self).__init__(**kwargs) - self.additional_properties = kwargs.get('additional_properties', None) - self.id = kwargs.get('id', None) - self.type = kwargs.get('type', None) - self.name = kwargs.get('name', None) - self.timestamp = kwargs.get('timestamp', None) - self.compliance_state = kwargs.get('compliance_state', None) - - -class ErrorDefinition(msrest.serialization.Model): - """Error definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: Service specific error code which serves as the substatus for the HTTP error code. - :vartype code: str - :ivar message: Description of the error. - :vartype message: str - :ivar target: The target of the error. - :vartype target: str - :ivar details: Internal error details. - :vartype details: list[~azure.mgmt.policyinsights.models.ErrorDefinition] - :ivar additional_info: Additional scenario specific error details. - :vartype additional_info: list[~azure.mgmt.policyinsights.models.TypedErrorInfo] - """ - - _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': '[ErrorDefinition]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[TypedErrorInfo]'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDefinition, self).__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorDefinitionAutoGenerated(msrest.serialization.Model): - """Error definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: Service specific error code which serves as the substatus for the HTTP error code. - :vartype code: str - :ivar message: Description of the error. - :vartype message: str - :ivar target: The target of the error. - :vartype target: str - :ivar details: Internal error details. - :vartype details: list[~azure.mgmt.policyinsights.models.ErrorDefinitionAutoGenerated] - :ivar additional_info: Additional scenario specific error details. - :vartype additional_info: list[~azure.mgmt.policyinsights.models.TypedErrorInfo] - """ - - _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': '[ErrorDefinitionAutoGenerated]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[TypedErrorInfo]'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDefinitionAutoGenerated, self).__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorDefinitionAutoGenerated2(msrest.serialization.Model): - """Error definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: Service specific error code which serves as the substatus for the HTTP error code. - :vartype code: str - :ivar message: Description of the error. - :vartype message: str - :ivar target: The target of the error. - :vartype target: str - :ivar details: Internal error details. - :vartype details: list[~azure.mgmt.policyinsights.models.ErrorDefinitionAutoGenerated2] - :ivar additional_info: Additional scenario specific error details. - :vartype additional_info: list[~azure.mgmt.policyinsights.models.TypedErrorInfo] - """ - - _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': '[ErrorDefinitionAutoGenerated2]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[TypedErrorInfo]'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorDefinitionAutoGenerated2, self).__init__(**kwargs) - self.code = None - self.message = None - self.target = None - self.details = None - self.additional_info = None - - -class ErrorResponse(msrest.serialization.Model): - """Error response. - - :param error: The error details. - :type error: ~azure.mgmt.policyinsights.models.ErrorDefinition - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinition'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class ErrorResponseAutoGenerated(msrest.serialization.Model): - """Error response. - - :param error: The error details. - :type error: ~azure.mgmt.policyinsights.models.ErrorDefinitionAutoGenerated - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinitionAutoGenerated'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponseAutoGenerated, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class ErrorResponseAutoGenerated2(msrest.serialization.Model): - """Error response. - - :param error: The error details. - :type error: ~azure.mgmt.policyinsights.models.ErrorDefinitionAutoGenerated2 - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinitionAutoGenerated2'}, - } - - def __init__( - self, - **kwargs - ): - super(ErrorResponseAutoGenerated2, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class ExpressionEvaluationDetails(msrest.serialization.Model): - """Evaluation details of policy language expressions. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param result: Evaluation result. - :type result: str - :param expression: Expression evaluated. - :type expression: str - :ivar expression_kind: The kind of expression that was evaluated. - :vartype expression_kind: str - :param path: Property path if the expression is a field or an alias. - :type path: str - :param expression_value: Value of the expression. - :type expression_value: any - :param target_value: Target value to be compared with the expression value. - :type target_value: any - :param operator: Operator to compare the expression value and the target value. - :type operator: str - """ - - _validation = { - 'expression_kind': {'readonly': True}, - } - - _attribute_map = { - 'result': {'key': 'result', 'type': 'str'}, - 'expression': {'key': 'expression', 'type': 'str'}, - 'expression_kind': {'key': 'expressionKind', 'type': 'str'}, - 'path': {'key': 'path', 'type': 'str'}, - 'expression_value': {'key': 'expressionValue', 'type': 'object'}, - 'target_value': {'key': 'targetValue', 'type': 'object'}, - 'operator': {'key': 'operator', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(ExpressionEvaluationDetails, self).__init__(**kwargs) - self.result = kwargs.get('result', None) - self.expression = kwargs.get('expression', None) - self.expression_kind = None - self.path = kwargs.get('path', None) - self.expression_value = kwargs.get('expression_value', None) - self.target_value = kwargs.get('target_value', None) - self.operator = kwargs.get('operator', None) - - -class FieldRestriction(msrest.serialization.Model): - """The restrictions on a field imposed by a specific policy. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar result: The type of restriction that is imposed on the field. Possible values include: - "Required", "Removed", "Deny". - :vartype result: str or ~azure.mgmt.policyinsights.models.FieldRestrictionResult - :ivar default_value: The value that policy will set for the field if the user does not provide - a value. - :vartype default_value: str - :ivar values: The values that policy either requires or denies for the field. - :vartype values: list[str] - :ivar policy: The details of the policy that is causing the field restriction. - :vartype policy: ~azure.mgmt.policyinsights.models.PolicyReference - """ - - _validation = { - 'result': {'readonly': True}, - 'default_value': {'readonly': True}, - 'values': {'readonly': True}, - 'policy': {'readonly': True}, - } - - _attribute_map = { - 'result': {'key': 'result', 'type': 'str'}, - 'default_value': {'key': 'defaultValue', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, - 'policy': {'key': 'policy', 'type': 'PolicyReference'}, - } - - def __init__( - self, - **kwargs - ): - super(FieldRestriction, self).__init__(**kwargs) - self.result = None - self.default_value = None - self.values = None - self.policy = None - - -class FieldRestrictions(msrest.serialization.Model): - """The restrictions that will be placed on a field in the resource by policy. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar field: The name of the field. This can be a top-level property like 'name' or 'type' or - an Azure Policy field alias. - :vartype field: str - :param restrictions: The restrictions placed on that field by policy. - :type restrictions: list[~azure.mgmt.policyinsights.models.FieldRestriction] - """ - - _validation = { - 'field': {'readonly': True}, - } - - _attribute_map = { - 'field': {'key': 'field', 'type': 'str'}, - 'restrictions': {'key': 'restrictions', 'type': '[FieldRestriction]'}, - } - - def __init__( - self, - **kwargs - ): - super(FieldRestrictions, self).__init__(**kwargs) - self.field = None - self.restrictions = kwargs.get('restrictions', None) - - -class IfNotExistsEvaluationDetails(msrest.serialization.Model): - """Evaluation details of IfNotExists effect. - - :param resource_id: ID of the last evaluated resource for IfNotExists effect. - :type resource_id: str - :param total_resources: Total number of resources to which the existence condition is - applicable. - :type total_resources: int - """ - - _attribute_map = { - 'resource_id': {'key': 'resourceId', 'type': 'str'}, - 'total_resources': {'key': 'totalResources', 'type': 'int'}, - } - - def __init__( - self, - **kwargs - ): - super(IfNotExistsEvaluationDetails, self).__init__(**kwargs) - self.resource_id = kwargs.get('resource_id', None) - self.total_resources = kwargs.get('total_resources', None) - - -class Operation(msrest.serialization.Model): - """Operation definition. - - :param name: Operation name. - :type name: str - :param display: Display metadata associated with the operation. - :type display: ~azure.mgmt.policyinsights.models.OperationDisplay - """ - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - } - - def __init__( - self, - **kwargs - ): - super(Operation, self).__init__(**kwargs) - self.name = kwargs.get('name', None) - self.display = kwargs.get('display', None) - - -class OperationDisplay(msrest.serialization.Model): - """Display metadata associated with the operation. - - :param provider: Resource provider name. - :type provider: str - :param resource: Resource name on which the operation is performed. - :type resource: str - :param operation: Operation name. - :type operation: str - :param description: Operation description. - :type description: str - """ - - _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationDisplay, self).__init__(**kwargs) - self.provider = kwargs.get('provider', None) - self.resource = kwargs.get('resource', None) - self.operation = kwargs.get('operation', None) - self.description = kwargs.get('description', None) - - -class OperationsListResults(msrest.serialization.Model): - """List of available operations. - - :param odata_count: OData entity count; represents the number of operations returned. - :type odata_count: int - :param value: List of available operations. - :type value: list[~azure.mgmt.policyinsights.models.Operation] - """ - - _validation = { - 'odata_count': {'minimum': 1}, - } - - _attribute_map = { - 'odata_count': {'key': '@odata\\.count', 'type': 'int'}, - 'value': {'key': 'value', 'type': '[Operation]'}, - } - - def __init__( - self, - **kwargs - ): - super(OperationsListResults, self).__init__(**kwargs) - self.odata_count = kwargs.get('odata_count', None) - self.value = kwargs.get('value', None) - - -class PendingField(msrest.serialization.Model): - """A field that should be evaluated against Azure Policy to determine restrictions. - - All required parameters must be populated in order to send to Azure. - - :param field: Required. The name of the field. This can be a top-level property like 'name' or - 'type' or an Azure Policy field alias. - :type field: str - :param values: The list of potential values for the field that should be evaluated against - Azure Policy. - :type values: list[str] - """ - - _validation = { - 'field': {'required': True}, - } - - _attribute_map = { - 'field': {'key': 'field', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(PendingField, self).__init__(**kwargs) - self.field = kwargs['field'] - self.values = kwargs.get('values', None) - - -class PolicyAssignmentSummary(msrest.serialization.Model): - """Policy assignment summary. - - :param policy_assignment_id: Policy assignment ID. - :type policy_assignment_id: str - :param policy_set_definition_id: Policy set definition ID, if the policy assignment is for a - policy set. - :type policy_set_definition_id: str - :param results: Compliance summary for the policy assignment. - :type results: ~azure.mgmt.policyinsights.models.SummaryResults - :param policy_definitions: Policy definitions summary. - :type policy_definitions: list[~azure.mgmt.policyinsights.models.PolicyDefinitionSummary] - :param policy_groups: Policy definition group summary. - :type policy_groups: list[~azure.mgmt.policyinsights.models.PolicyGroupSummary] - """ - - _attribute_map = { - 'policy_assignment_id': {'key': 'policyAssignmentId', 'type': 'str'}, - 'policy_set_definition_id': {'key': 'policySetDefinitionId', 'type': 'str'}, - 'results': {'key': 'results', 'type': 'SummaryResults'}, - 'policy_definitions': {'key': 'policyDefinitions', 'type': '[PolicyDefinitionSummary]'}, - 'policy_groups': {'key': 'policyGroups', 'type': '[PolicyGroupSummary]'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyAssignmentSummary, self).__init__(**kwargs) - self.policy_assignment_id = kwargs.get('policy_assignment_id', None) - self.policy_set_definition_id = kwargs.get('policy_set_definition_id', None) - self.results = kwargs.get('results', None) - self.policy_definitions = kwargs.get('policy_definitions', None) - self.policy_groups = kwargs.get('policy_groups', None) - - -class PolicyDefinitionSummary(msrest.serialization.Model): - """Policy definition summary. - - :param policy_definition_id: Policy definition ID. - :type policy_definition_id: str - :param policy_definition_reference_id: Policy definition reference ID. - :type policy_definition_reference_id: str - :param policy_definition_group_names: Policy definition group names. - :type policy_definition_group_names: list[str] - :param effect: Policy effect, i.e. policy definition action. - :type effect: str - :param results: Compliance summary for the policy definition. - :type results: ~azure.mgmt.policyinsights.models.SummaryResults - """ - - _attribute_map = { - 'policy_definition_id': {'key': 'policyDefinitionId', 'type': 'str'}, - 'policy_definition_reference_id': {'key': 'policyDefinitionReferenceId', 'type': 'str'}, - 'policy_definition_group_names': {'key': 'policyDefinitionGroupNames', 'type': '[str]'}, - 'effect': {'key': 'effect', 'type': 'str'}, - 'results': {'key': 'results', 'type': 'SummaryResults'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyDefinitionSummary, self).__init__(**kwargs) - self.policy_definition_id = kwargs.get('policy_definition_id', None) - self.policy_definition_reference_id = kwargs.get('policy_definition_reference_id', None) - self.policy_definition_group_names = kwargs.get('policy_definition_group_names', None) - self.effect = kwargs.get('effect', None) - self.results = kwargs.get('results', None) - - -class PolicyDetails(msrest.serialization.Model): - """The policy details. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar policy_definition_id: The ID of the policy definition. - :vartype policy_definition_id: str - :ivar policy_assignment_id: The ID of the policy assignment. - :vartype policy_assignment_id: str - :ivar policy_assignment_display_name: The display name of the policy assignment. - :vartype policy_assignment_display_name: str - :ivar policy_assignment_scope: The scope of the policy assignment. - :vartype policy_assignment_scope: str - :ivar policy_set_definition_id: The ID of the policy set definition. - :vartype policy_set_definition_id: str - :ivar policy_definition_reference_id: The policy definition reference ID within the policy set - definition. - :vartype policy_definition_reference_id: str - """ - - _validation = { - 'policy_definition_id': {'readonly': True}, - 'policy_assignment_id': {'readonly': True}, - 'policy_assignment_display_name': {'readonly': True}, - 'policy_assignment_scope': {'readonly': True}, - 'policy_set_definition_id': {'readonly': True}, - 'policy_definition_reference_id': {'readonly': True}, - } - - _attribute_map = { - 'policy_definition_id': {'key': 'policyDefinitionId', 'type': 'str'}, - 'policy_assignment_id': {'key': 'policyAssignmentId', 'type': 'str'}, - 'policy_assignment_display_name': {'key': 'policyAssignmentDisplayName', 'type': 'str'}, - 'policy_assignment_scope': {'key': 'policyAssignmentScope', 'type': 'str'}, - 'policy_set_definition_id': {'key': 'policySetDefinitionId', 'type': 'str'}, - 'policy_definition_reference_id': {'key': 'policyDefinitionReferenceId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyDetails, self).__init__(**kwargs) - self.policy_definition_id = None - self.policy_assignment_id = None - self.policy_assignment_display_name = None - self.policy_assignment_scope = None - self.policy_set_definition_id = None - self.policy_definition_reference_id = None - - -class PolicyEvaluationDetails(msrest.serialization.Model): - """Policy evaluation details. - - :param evaluated_expressions: Details of the evaluated expressions. - :type evaluated_expressions: - list[~azure.mgmt.policyinsights.models.ExpressionEvaluationDetails] - :param if_not_exists_details: Evaluation details of IfNotExists effect. - :type if_not_exists_details: ~azure.mgmt.policyinsights.models.IfNotExistsEvaluationDetails - """ - - _attribute_map = { - 'evaluated_expressions': {'key': 'evaluatedExpressions', 'type': '[ExpressionEvaluationDetails]'}, - 'if_not_exists_details': {'key': 'ifNotExistsDetails', 'type': 'IfNotExistsEvaluationDetails'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyEvaluationDetails, self).__init__(**kwargs) - self.evaluated_expressions = kwargs.get('evaluated_expressions', None) - self.if_not_exists_details = kwargs.get('if_not_exists_details', None) - - -class PolicyEvaluationResult(msrest.serialization.Model): - """The result of a non-compliant policy evaluation against the given resource content. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar policy_info: The details of the policy that was evaluated. - :vartype policy_info: ~azure.mgmt.policyinsights.models.PolicyReference - :ivar evaluation_result: The result of the policy evaluation against the resource. This will - typically be 'NonCompliant' but may contain other values if errors were encountered. - :vartype evaluation_result: str - :ivar evaluation_details: The detailed results of the policy expressions and values that were - evaluated. - :vartype evaluation_details: ~azure.mgmt.policyinsights.models.PolicyEvaluationDetails - """ - - _validation = { - 'policy_info': {'readonly': True}, - 'evaluation_result': {'readonly': True}, - 'evaluation_details': {'readonly': True}, - } - - _attribute_map = { - 'policy_info': {'key': 'policyInfo', 'type': 'PolicyReference'}, - 'evaluation_result': {'key': 'evaluationResult', 'type': 'str'}, - 'evaluation_details': {'key': 'evaluationDetails', 'type': 'PolicyEvaluationDetails'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyEvaluationResult, self).__init__(**kwargs) - self.policy_info = None - self.evaluation_result = None - self.evaluation_details = None - - -class PolicyEvent(msrest.serialization.Model): - """Policy event record. - - :param additional_properties: Unmatched properties from the message are deserialized to this - collection. - :type additional_properties: dict[str, any] - :param odata_id: OData entity ID; always set to null since policy event records do not have an - entity ID. - :type odata_id: str - :param odata_context: OData context string; used by OData clients to resolve type information - based on metadata. - :type odata_context: str - :param timestamp: Timestamp for the policy event record. - :type timestamp: ~datetime.datetime - :param resource_id: Resource ID. - :type resource_id: str - :param policy_assignment_id: Policy assignment ID. - :type policy_assignment_id: str - :param policy_definition_id: Policy definition ID. - :type policy_definition_id: str - :param effective_parameters: Effective parameters for the policy assignment. - :type effective_parameters: str - :param is_compliant: Flag which states whether the resource is compliant against the policy - assignment it was evaluated against. - :type is_compliant: bool - :param subscription_id: Subscription ID. - :type subscription_id: str - :param resource_type: Resource type. - :type resource_type: str - :param resource_location: Resource location. - :type resource_location: str - :param resource_group: Resource group name. - :type resource_group: str - :param resource_tags: List of resource tags. - :type resource_tags: str - :param policy_assignment_name: Policy assignment name. - :type policy_assignment_name: str - :param policy_assignment_owner: Policy assignment owner. - :type policy_assignment_owner: str - :param policy_assignment_parameters: Policy assignment parameters. - :type policy_assignment_parameters: str - :param policy_assignment_scope: Policy assignment scope. - :type policy_assignment_scope: str - :param policy_definition_name: Policy definition name. - :type policy_definition_name: str - :param policy_definition_action: Policy definition action, i.e. effect. - :type policy_definition_action: str - :param policy_definition_category: Policy definition category. - :type policy_definition_category: str - :param policy_set_definition_id: Policy set definition ID, if the policy assignment is for a - policy set. - :type policy_set_definition_id: str - :param policy_set_definition_name: Policy set definition name, if the policy assignment is for - a policy set. - :type policy_set_definition_name: str - :param policy_set_definition_owner: Policy set definition owner, if the policy assignment is - for a policy set. - :type policy_set_definition_owner: str - :param policy_set_definition_category: Policy set definition category, if the policy assignment - is for a policy set. - :type policy_set_definition_category: str - :param policy_set_definition_parameters: Policy set definition parameters, if the policy - assignment is for a policy set. - :type policy_set_definition_parameters: str - :param management_group_ids: Comma separated list of management group IDs, which represent the - hierarchy of the management groups the resource is under. - :type management_group_ids: str - :param policy_definition_reference_id: Reference ID for the policy definition inside the policy - set, if the policy assignment is for a policy set. - :type policy_definition_reference_id: str - :param compliance_state: Compliance state of the resource. - :type compliance_state: str - :param tenant_id: Tenant ID for the policy event record. - :type tenant_id: str - :param principal_oid: Principal object ID for the user who initiated the resource operation - that triggered the policy event. - :type principal_oid: str - :param components: Components events records populated only when URL contains - $expand=components clause. - :type components: list[~azure.mgmt.policyinsights.models.ComponentEventDetails] - """ - - _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'odata_id': {'key': '@odata\\.id', 'type': 'str'}, - 'odata_context': {'key': '@odata\\.context', 'type': 'str'}, - 'timestamp': {'key': 'timestamp', 'type': 'iso-8601'}, - 'resource_id': {'key': 'resourceId', 'type': 'str'}, - 'policy_assignment_id': {'key': 'policyAssignmentId', 'type': 'str'}, - 'policy_definition_id': {'key': 'policyDefinitionId', 'type': 'str'}, - 'effective_parameters': {'key': 'effectiveParameters', 'type': 'str'}, - 'is_compliant': {'key': 'isCompliant', 'type': 'bool'}, - 'subscription_id': {'key': 'subscriptionId', 'type': 'str'}, - 'resource_type': {'key': 'resourceType', 'type': 'str'}, - 'resource_location': {'key': 'resourceLocation', 'type': 'str'}, - 'resource_group': {'key': 'resourceGroup', 'type': 'str'}, - 'resource_tags': {'key': 'resourceTags', 'type': 'str'}, - 'policy_assignment_name': {'key': 'policyAssignmentName', 'type': 'str'}, - 'policy_assignment_owner': {'key': 'policyAssignmentOwner', 'type': 'str'}, - 'policy_assignment_parameters': {'key': 'policyAssignmentParameters', 'type': 'str'}, - 'policy_assignment_scope': {'key': 'policyAssignmentScope', 'type': 'str'}, - 'policy_definition_name': {'key': 'policyDefinitionName', 'type': 'str'}, - 'policy_definition_action': {'key': 'policyDefinitionAction', 'type': 'str'}, - 'policy_definition_category': {'key': 'policyDefinitionCategory', 'type': 'str'}, - 'policy_set_definition_id': {'key': 'policySetDefinitionId', 'type': 'str'}, - 'policy_set_definition_name': {'key': 'policySetDefinitionName', 'type': 'str'}, - 'policy_set_definition_owner': {'key': 'policySetDefinitionOwner', 'type': 'str'}, - 'policy_set_definition_category': {'key': 'policySetDefinitionCategory', 'type': 'str'}, - 'policy_set_definition_parameters': {'key': 'policySetDefinitionParameters', 'type': 'str'}, - 'management_group_ids': {'key': 'managementGroupIds', 'type': 'str'}, - 'policy_definition_reference_id': {'key': 'policyDefinitionReferenceId', 'type': 'str'}, - 'compliance_state': {'key': 'complianceState', 'type': 'str'}, - 'tenant_id': {'key': 'tenantId', 'type': 'str'}, - 'principal_oid': {'key': 'principalOid', 'type': 'str'}, - 'components': {'key': 'components', 'type': '[ComponentEventDetails]'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyEvent, self).__init__(**kwargs) - self.additional_properties = kwargs.get('additional_properties', None) - self.odata_id = kwargs.get('odata_id', None) - self.odata_context = kwargs.get('odata_context', None) - self.timestamp = kwargs.get('timestamp', None) - self.resource_id = kwargs.get('resource_id', None) - self.policy_assignment_id = kwargs.get('policy_assignment_id', None) - self.policy_definition_id = kwargs.get('policy_definition_id', None) - self.effective_parameters = kwargs.get('effective_parameters', None) - self.is_compliant = kwargs.get('is_compliant', None) - self.subscription_id = kwargs.get('subscription_id', None) - self.resource_type = kwargs.get('resource_type', None) - self.resource_location = kwargs.get('resource_location', None) - self.resource_group = kwargs.get('resource_group', None) - self.resource_tags = kwargs.get('resource_tags', None) - self.policy_assignment_name = kwargs.get('policy_assignment_name', None) - self.policy_assignment_owner = kwargs.get('policy_assignment_owner', None) - self.policy_assignment_parameters = kwargs.get('policy_assignment_parameters', None) - self.policy_assignment_scope = kwargs.get('policy_assignment_scope', None) - self.policy_definition_name = kwargs.get('policy_definition_name', None) - self.policy_definition_action = kwargs.get('policy_definition_action', None) - self.policy_definition_category = kwargs.get('policy_definition_category', None) - self.policy_set_definition_id = kwargs.get('policy_set_definition_id', None) - self.policy_set_definition_name = kwargs.get('policy_set_definition_name', None) - self.policy_set_definition_owner = kwargs.get('policy_set_definition_owner', None) - self.policy_set_definition_category = kwargs.get('policy_set_definition_category', None) - self.policy_set_definition_parameters = kwargs.get('policy_set_definition_parameters', None) - self.management_group_ids = kwargs.get('management_group_ids', None) - self.policy_definition_reference_id = kwargs.get('policy_definition_reference_id', None) - self.compliance_state = kwargs.get('compliance_state', None) - self.tenant_id = kwargs.get('tenant_id', None) - self.principal_oid = kwargs.get('principal_oid', None) - self.components = kwargs.get('components', None) - - -class PolicyEventsQueryResults(msrest.serialization.Model): - """Query results. - - :param odata_context: OData context string; used by OData clients to resolve type information - based on metadata. - :type odata_context: str - :param odata_count: OData entity count; represents the number of policy event records returned. - :type odata_count: int - :param odata_next_link: Odata next link; URL to get the next set of results. - :type odata_next_link: str - :param value: Query results. - :type value: list[~azure.mgmt.policyinsights.models.PolicyEvent] - """ - - _validation = { - 'odata_count': {'minimum': 0}, - } - - _attribute_map = { - 'odata_context': {'key': '@odata\\.context', 'type': 'str'}, - 'odata_count': {'key': '@odata\\.count', 'type': 'int'}, - 'odata_next_link': {'key': '@odata\\.nextLink', 'type': 'str'}, - 'value': {'key': 'value', 'type': '[PolicyEvent]'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyEventsQueryResults, self).__init__(**kwargs) - self.odata_context = kwargs.get('odata_context', None) - self.odata_count = kwargs.get('odata_count', None) - self.odata_next_link = kwargs.get('odata_next_link', None) - self.value = kwargs.get('value', None) - - -class PolicyGroupSummary(msrest.serialization.Model): - """Policy definition group summary. - - :param policy_group_name: Policy group name. - :type policy_group_name: str - :param results: Compliance summary for the policy definition group. - :type results: ~azure.mgmt.policyinsights.models.SummaryResults - """ - - _attribute_map = { - 'policy_group_name': {'key': 'policyGroupName', 'type': 'str'}, - 'results': {'key': 'results', 'type': 'SummaryResults'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyGroupSummary, self).__init__(**kwargs) - self.policy_group_name = kwargs.get('policy_group_name', None) - self.results = kwargs.get('results', None) - - -class PolicyMetadata(msrest.serialization.Model): - """Policy metadata resource definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The ID of the policy metadata. - :vartype id: str - :ivar type: The type of the policy metadata. - :vartype type: str - :ivar name: The name of the policy metadata. - :vartype name: str - :ivar metadata_id: The policy metadata identifier. - :vartype metadata_id: str - :ivar category: The category of the policy metadata. - :vartype category: str - :ivar title: The title of the policy metadata. - :vartype title: str - :ivar owner: The owner of the policy metadata. - :vartype owner: str - :ivar additional_content_url: Url for getting additional content about the resource metadata. - :vartype additional_content_url: str - :ivar metadata: Additional metadata. - :vartype metadata: any - :ivar description: The description of the policy metadata. - :vartype description: str - :ivar requirements: The requirements of the policy metadata. - :vartype requirements: str - """ - - _validation = { - 'id': {'readonly': True}, - 'type': {'readonly': True}, - 'name': {'readonly': True}, - 'metadata_id': {'readonly': True}, - 'category': {'readonly': True}, - 'title': {'readonly': True}, - 'owner': {'readonly': True}, - 'additional_content_url': {'readonly': True}, - 'metadata': {'readonly': True}, - 'description': {'readonly': True}, - 'requirements': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'metadata_id': {'key': 'properties.metadataId', 'type': 'str'}, - 'category': {'key': 'properties.category', 'type': 'str'}, - 'title': {'key': 'properties.title', 'type': 'str'}, - 'owner': {'key': 'properties.owner', 'type': 'str'}, - 'additional_content_url': {'key': 'properties.additionalContentUrl', 'type': 'str'}, - 'metadata': {'key': 'properties.metadata', 'type': 'object'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'requirements': {'key': 'properties.requirements', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyMetadata, self).__init__(**kwargs) - self.id = None - self.type = None - self.name = None - self.metadata_id = None - self.category = None - self.title = None - self.owner = None - self.additional_content_url = None - self.metadata = None - self.description = None - self.requirements = None - - -class PolicyMetadataCollection(msrest.serialization.Model): - """Collection of policy metadata resources. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: Array of policy metadata definitions. - :vartype value: list[~azure.mgmt.policyinsights.models.SlimPolicyMetadata] - :ivar next_link: The URL to get the next set of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[SlimPolicyMetadata]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyMetadataCollection, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class PolicyMetadataSlimProperties(msrest.serialization.Model): - """The properties of the policy metadata, excluding properties containing large strings. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar metadata_id: The policy metadata identifier. - :vartype metadata_id: str - :ivar category: The category of the policy metadata. - :vartype category: str - :ivar title: The title of the policy metadata. - :vartype title: str - :ivar owner: The owner of the policy metadata. - :vartype owner: str - :ivar additional_content_url: Url for getting additional content about the resource metadata. - :vartype additional_content_url: str - :ivar metadata: Additional metadata. - :vartype metadata: any - """ - - _validation = { - 'metadata_id': {'readonly': True}, - 'category': {'readonly': True}, - 'title': {'readonly': True}, - 'owner': {'readonly': True}, - 'additional_content_url': {'readonly': True}, - 'metadata': {'readonly': True}, - } - - _attribute_map = { - 'metadata_id': {'key': 'metadataId', 'type': 'str'}, - 'category': {'key': 'category', 'type': 'str'}, - 'title': {'key': 'title', 'type': 'str'}, - 'owner': {'key': 'owner', 'type': 'str'}, - 'additional_content_url': {'key': 'additionalContentUrl', 'type': 'str'}, - 'metadata': {'key': 'metadata', 'type': 'object'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyMetadataSlimProperties, self).__init__(**kwargs) - self.metadata_id = None - self.category = None - self.title = None - self.owner = None - self.additional_content_url = None - self.metadata = None - - -class PolicyMetadataProperties(PolicyMetadataSlimProperties): - """The properties of the policy metadata. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar metadata_id: The policy metadata identifier. - :vartype metadata_id: str - :ivar category: The category of the policy metadata. - :vartype category: str - :ivar title: The title of the policy metadata. - :vartype title: str - :ivar owner: The owner of the policy metadata. - :vartype owner: str - :ivar additional_content_url: Url for getting additional content about the resource metadata. - :vartype additional_content_url: str - :ivar metadata: Additional metadata. - :vartype metadata: any - :ivar description: The description of the policy metadata. - :vartype description: str - :ivar requirements: The requirements of the policy metadata. - :vartype requirements: str - """ - - _validation = { - 'metadata_id': {'readonly': True}, - 'category': {'readonly': True}, - 'title': {'readonly': True}, - 'owner': {'readonly': True}, - 'additional_content_url': {'readonly': True}, - 'metadata': {'readonly': True}, - 'description': {'readonly': True}, - 'requirements': {'readonly': True}, - } - - _attribute_map = { - 'metadata_id': {'key': 'metadataId', 'type': 'str'}, - 'category': {'key': 'category', 'type': 'str'}, - 'title': {'key': 'title', 'type': 'str'}, - 'owner': {'key': 'owner', 'type': 'str'}, - 'additional_content_url': {'key': 'additionalContentUrl', 'type': 'str'}, - 'metadata': {'key': 'metadata', 'type': 'object'}, - 'description': {'key': 'description', 'type': 'str'}, - 'requirements': {'key': 'requirements', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyMetadataProperties, self).__init__(**kwargs) - self.description = None - self.requirements = None - - -class PolicyReference(msrest.serialization.Model): - """Resource identifiers for a policy. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar policy_definition_id: The resource identifier of the policy definition. - :vartype policy_definition_id: str - :ivar policy_set_definition_id: The resource identifier of the policy set definition. - :vartype policy_set_definition_id: str - :ivar policy_definition_reference_id: The reference identifier of a specific policy definition - within a policy set definition. - :vartype policy_definition_reference_id: str - :ivar policy_assignment_id: The resource identifier of the policy assignment. - :vartype policy_assignment_id: str - """ - - _validation = { - 'policy_definition_id': {'readonly': True}, - 'policy_set_definition_id': {'readonly': True}, - 'policy_definition_reference_id': {'readonly': True}, - 'policy_assignment_id': {'readonly': True}, - } - - _attribute_map = { - 'policy_definition_id': {'key': 'policyDefinitionId', 'type': 'str'}, - 'policy_set_definition_id': {'key': 'policySetDefinitionId', 'type': 'str'}, - 'policy_definition_reference_id': {'key': 'policyDefinitionReferenceId', 'type': 'str'}, - 'policy_assignment_id': {'key': 'policyAssignmentId', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyReference, self).__init__(**kwargs) - self.policy_definition_id = None - self.policy_set_definition_id = None - self.policy_definition_reference_id = None - self.policy_assignment_id = None - - -class PolicyState(msrest.serialization.Model): - """Policy state record. - - Variables are only populated by the server, and will be ignored when sending a request. - - :param additional_properties: Unmatched properties from the message are deserialized to this - collection. - :type additional_properties: dict[str, any] - :param odata_id: OData entity ID; always set to null since policy state records do not have an - entity ID. - :type odata_id: str - :param odata_context: OData context string; used by OData clients to resolve type information - based on metadata. - :type odata_context: str - :param timestamp: Timestamp for the policy state record. - :type timestamp: ~datetime.datetime - :param resource_id: Resource ID. - :type resource_id: str - :param policy_assignment_id: Policy assignment ID. - :type policy_assignment_id: str - :param policy_definition_id: Policy definition ID. - :type policy_definition_id: str - :param effective_parameters: Effective parameters for the policy assignment. - :type effective_parameters: str - :param is_compliant: Flag which states whether the resource is compliant against the policy - assignment it was evaluated against. This property is deprecated; please use ComplianceState - instead. - :type is_compliant: bool - :param subscription_id: Subscription ID. - :type subscription_id: str - :param resource_type: Resource type. - :type resource_type: str - :param resource_location: Resource location. - :type resource_location: str - :param resource_group: Resource group name. - :type resource_group: str - :param resource_tags: List of resource tags. - :type resource_tags: str - :param policy_assignment_name: Policy assignment name. - :type policy_assignment_name: str - :param policy_assignment_owner: Policy assignment owner. - :type policy_assignment_owner: str - :param policy_assignment_parameters: Policy assignment parameters. - :type policy_assignment_parameters: str - :param policy_assignment_scope: Policy assignment scope. - :type policy_assignment_scope: str - :param policy_definition_name: Policy definition name. - :type policy_definition_name: str - :param policy_definition_action: Policy definition action, i.e. effect. - :type policy_definition_action: str - :param policy_definition_category: Policy definition category. - :type policy_definition_category: str - :param policy_set_definition_id: Policy set definition ID, if the policy assignment is for a - policy set. - :type policy_set_definition_id: str - :param policy_set_definition_name: Policy set definition name, if the policy assignment is for - a policy set. - :type policy_set_definition_name: str - :param policy_set_definition_owner: Policy set definition owner, if the policy assignment is - for a policy set. - :type policy_set_definition_owner: str - :param policy_set_definition_category: Policy set definition category, if the policy assignment - is for a policy set. - :type policy_set_definition_category: str - :param policy_set_definition_parameters: Policy set definition parameters, if the policy - assignment is for a policy set. - :type policy_set_definition_parameters: str - :param management_group_ids: Comma separated list of management group IDs, which represent the - hierarchy of the management groups the resource is under. - :type management_group_ids: str - :param policy_definition_reference_id: Reference ID for the policy definition inside the policy - set, if the policy assignment is for a policy set. - :type policy_definition_reference_id: str - :param compliance_state: Compliance state of the resource. - :type compliance_state: str - :param policy_evaluation_details: Policy evaluation details. - :type policy_evaluation_details: ~azure.mgmt.policyinsights.models.PolicyEvaluationDetails - :param policy_definition_group_names: Policy definition group names. - :type policy_definition_group_names: list[str] - :param components: Components state compliance records populated only when URL contains - $expand=components clause. - :type components: list[~azure.mgmt.policyinsights.models.ComponentStateDetails] - :ivar policy_definition_version: Evaluated policy definition version. - :vartype policy_definition_version: str - :ivar policy_set_definition_version: Evaluated policy set definition version. - :vartype policy_set_definition_version: str - :ivar policy_assignment_version: Evaluated policy assignment version. - :vartype policy_assignment_version: str - """ - - _validation = { - 'policy_definition_version': {'readonly': True}, - 'policy_set_definition_version': {'readonly': True}, - 'policy_assignment_version': {'readonly': True}, - } - - _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'odata_id': {'key': '@odata\\.id', 'type': 'str'}, - 'odata_context': {'key': '@odata\\.context', 'type': 'str'}, - 'timestamp': {'key': 'timestamp', 'type': 'iso-8601'}, - 'resource_id': {'key': 'resourceId', 'type': 'str'}, - 'policy_assignment_id': {'key': 'policyAssignmentId', 'type': 'str'}, - 'policy_definition_id': {'key': 'policyDefinitionId', 'type': 'str'}, - 'effective_parameters': {'key': 'effectiveParameters', 'type': 'str'}, - 'is_compliant': {'key': 'isCompliant', 'type': 'bool'}, - 'subscription_id': {'key': 'subscriptionId', 'type': 'str'}, - 'resource_type': {'key': 'resourceType', 'type': 'str'}, - 'resource_location': {'key': 'resourceLocation', 'type': 'str'}, - 'resource_group': {'key': 'resourceGroup', 'type': 'str'}, - 'resource_tags': {'key': 'resourceTags', 'type': 'str'}, - 'policy_assignment_name': {'key': 'policyAssignmentName', 'type': 'str'}, - 'policy_assignment_owner': {'key': 'policyAssignmentOwner', 'type': 'str'}, - 'policy_assignment_parameters': {'key': 'policyAssignmentParameters', 'type': 'str'}, - 'policy_assignment_scope': {'key': 'policyAssignmentScope', 'type': 'str'}, - 'policy_definition_name': {'key': 'policyDefinitionName', 'type': 'str'}, - 'policy_definition_action': {'key': 'policyDefinitionAction', 'type': 'str'}, - 'policy_definition_category': {'key': 'policyDefinitionCategory', 'type': 'str'}, - 'policy_set_definition_id': {'key': 'policySetDefinitionId', 'type': 'str'}, - 'policy_set_definition_name': {'key': 'policySetDefinitionName', 'type': 'str'}, - 'policy_set_definition_owner': {'key': 'policySetDefinitionOwner', 'type': 'str'}, - 'policy_set_definition_category': {'key': 'policySetDefinitionCategory', 'type': 'str'}, - 'policy_set_definition_parameters': {'key': 'policySetDefinitionParameters', 'type': 'str'}, - 'management_group_ids': {'key': 'managementGroupIds', 'type': 'str'}, - 'policy_definition_reference_id': {'key': 'policyDefinitionReferenceId', 'type': 'str'}, - 'compliance_state': {'key': 'complianceState', 'type': 'str'}, - 'policy_evaluation_details': {'key': 'policyEvaluationDetails', 'type': 'PolicyEvaluationDetails'}, - 'policy_definition_group_names': {'key': 'policyDefinitionGroupNames', 'type': '[str]'}, - 'components': {'key': 'components', 'type': '[ComponentStateDetails]'}, - 'policy_definition_version': {'key': 'policyDefinitionVersion', 'type': 'str'}, - 'policy_set_definition_version': {'key': 'policySetDefinitionVersion', 'type': 'str'}, - 'policy_assignment_version': {'key': 'policyAssignmentVersion', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyState, self).__init__(**kwargs) - self.additional_properties = kwargs.get('additional_properties', None) - self.odata_id = kwargs.get('odata_id', None) - self.odata_context = kwargs.get('odata_context', None) - self.timestamp = kwargs.get('timestamp', None) - self.resource_id = kwargs.get('resource_id', None) - self.policy_assignment_id = kwargs.get('policy_assignment_id', None) - self.policy_definition_id = kwargs.get('policy_definition_id', None) - self.effective_parameters = kwargs.get('effective_parameters', None) - self.is_compliant = kwargs.get('is_compliant', None) - self.subscription_id = kwargs.get('subscription_id', None) - self.resource_type = kwargs.get('resource_type', None) - self.resource_location = kwargs.get('resource_location', None) - self.resource_group = kwargs.get('resource_group', None) - self.resource_tags = kwargs.get('resource_tags', None) - self.policy_assignment_name = kwargs.get('policy_assignment_name', None) - self.policy_assignment_owner = kwargs.get('policy_assignment_owner', None) - self.policy_assignment_parameters = kwargs.get('policy_assignment_parameters', None) - self.policy_assignment_scope = kwargs.get('policy_assignment_scope', None) - self.policy_definition_name = kwargs.get('policy_definition_name', None) - self.policy_definition_action = kwargs.get('policy_definition_action', None) - self.policy_definition_category = kwargs.get('policy_definition_category', None) - self.policy_set_definition_id = kwargs.get('policy_set_definition_id', None) - self.policy_set_definition_name = kwargs.get('policy_set_definition_name', None) - self.policy_set_definition_owner = kwargs.get('policy_set_definition_owner', None) - self.policy_set_definition_category = kwargs.get('policy_set_definition_category', None) - self.policy_set_definition_parameters = kwargs.get('policy_set_definition_parameters', None) - self.management_group_ids = kwargs.get('management_group_ids', None) - self.policy_definition_reference_id = kwargs.get('policy_definition_reference_id', None) - self.compliance_state = kwargs.get('compliance_state', None) - self.policy_evaluation_details = kwargs.get('policy_evaluation_details', None) - self.policy_definition_group_names = kwargs.get('policy_definition_group_names', None) - self.components = kwargs.get('components', None) - self.policy_definition_version = None - self.policy_set_definition_version = None - self.policy_assignment_version = None - - -class PolicyStatesQueryResults(msrest.serialization.Model): - """Query results. - - :param odata_context: OData context string; used by OData clients to resolve type information - based on metadata. - :type odata_context: str - :param odata_count: OData entity count; represents the number of policy state records returned. - :type odata_count: int - :param odata_next_link: Odata next link; URL to get the next set of results. - :type odata_next_link: str - :param value: Query results. - :type value: list[~azure.mgmt.policyinsights.models.PolicyState] - """ - - _validation = { - 'odata_count': {'minimum': 0}, - } - - _attribute_map = { - 'odata_context': {'key': '@odata\\.context', 'type': 'str'}, - 'odata_count': {'key': '@odata\\.count', 'type': 'int'}, - 'odata_next_link': {'key': '@odata\\.nextLink', 'type': 'str'}, - 'value': {'key': 'value', 'type': '[PolicyState]'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyStatesQueryResults, self).__init__(**kwargs) - self.odata_context = kwargs.get('odata_context', None) - self.odata_count = kwargs.get('odata_count', None) - self.odata_next_link = kwargs.get('odata_next_link', None) - self.value = kwargs.get('value', None) - - -class PolicyTrackedResource(msrest.serialization.Model): - """Policy tracked resource record. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar tracked_resource_id: The ID of the policy tracked resource. - :vartype tracked_resource_id: str - :ivar policy_details: The details of the policy that require the tracked resource. - :vartype policy_details: ~azure.mgmt.policyinsights.models.PolicyDetails - :ivar created_by: The details of the policy triggered deployment that created the tracked - resource. - :vartype created_by: ~azure.mgmt.policyinsights.models.TrackedResourceModificationDetails - :ivar last_modified_by: The details of the policy triggered deployment that modified the - tracked resource. - :vartype last_modified_by: ~azure.mgmt.policyinsights.models.TrackedResourceModificationDetails - :ivar last_update_utc: Timestamp of the last update to the tracked resource. - :vartype last_update_utc: ~datetime.datetime - """ - - _validation = { - 'tracked_resource_id': {'readonly': True}, - 'policy_details': {'readonly': True}, - 'created_by': {'readonly': True}, - 'last_modified_by': {'readonly': True}, - 'last_update_utc': {'readonly': True}, - } - - _attribute_map = { - 'tracked_resource_id': {'key': 'trackedResourceId', 'type': 'str'}, - 'policy_details': {'key': 'policyDetails', 'type': 'PolicyDetails'}, - 'created_by': {'key': 'createdBy', 'type': 'TrackedResourceModificationDetails'}, - 'last_modified_by': {'key': 'lastModifiedBy', 'type': 'TrackedResourceModificationDetails'}, - 'last_update_utc': {'key': 'lastUpdateUtc', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyTrackedResource, self).__init__(**kwargs) - self.tracked_resource_id = None - self.policy_details = None - self.created_by = None - self.last_modified_by = None - self.last_update_utc = None - - -class PolicyTrackedResourcesQueryResults(msrest.serialization.Model): - """Query results. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: Query results. - :vartype value: list[~azure.mgmt.policyinsights.models.PolicyTrackedResource] - :ivar next_link: The URL to get the next set of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[PolicyTrackedResource]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyTrackedResourcesQueryResults, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class QueryFailure(msrest.serialization.Model): - """Error response. - - :param error: Error definition. - :type error: ~azure.mgmt.policyinsights.models.QueryFailureError - """ - - _attribute_map = { - 'error': {'key': 'error', 'type': 'QueryFailureError'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryFailure, self).__init__(**kwargs) - self.error = kwargs.get('error', None) - - -class QueryFailureError(msrest.serialization.Model): - """Error definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar code: Service specific error code which serves as the substatus for the HTTP error code. - :vartype code: str - :ivar message: Description of the error. - :vartype message: str - """ - - _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryFailureError, self).__init__(**kwargs) - self.code = None - self.message = None - - -class QueryOptions(msrest.serialization.Model): - """Parameter group. - - :param top: Maximum number of records to return. - :type top: int - :param filter: OData filter expression. - :type filter: str - :param order_by: Ordering expression using OData notation. One or more comma-separated column - names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, - ResourceId asc". - :type order_by: str - :param select: Select expression using OData notation. Limits the columns on each record to - just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". - :type select: str - :param from_property: ISO 8601 formatted timestamp specifying the start time of the interval to - query. When not specified, the service uses ($to - 1-day). - :type from_property: ~datetime.datetime - :param to: ISO 8601 formatted timestamp specifying the end time of the interval to query. When - not specified, the service uses request time. - :type to: ~datetime.datetime - :param apply: OData apply expression for aggregations. - :type apply: str - :param skip_token: Skiptoken is only provided if a previous response returned a partial result - as a part of nextLink element. - :type skip_token: str - :param expand: The $expand query parameter. For example, to expand components use - $expand=components. - :type expand: str - """ - - _validation = { - 'top': {'minimum': 0}, - } - - _attribute_map = { - 'top': {'key': 'Top', 'type': 'int'}, - 'filter': {'key': 'Filter', 'type': 'str'}, - 'order_by': {'key': 'OrderBy', 'type': 'str'}, - 'select': {'key': 'Select', 'type': 'str'}, - 'from_property': {'key': 'FromProperty', 'type': 'iso-8601'}, - 'to': {'key': 'To', 'type': 'iso-8601'}, - 'apply': {'key': 'Apply', 'type': 'str'}, - 'skip_token': {'key': 'SkipToken', 'type': 'str'}, - 'expand': {'key': 'Expand', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(QueryOptions, self).__init__(**kwargs) - self.top = kwargs.get('top', None) - self.filter = kwargs.get('filter', None) - self.order_by = kwargs.get('order_by', None) - self.select = kwargs.get('select', None) - self.from_property = kwargs.get('from_property', None) - self.to = kwargs.get('to', None) - self.apply = kwargs.get('apply', None) - self.skip_token = kwargs.get('skip_token', None) - self.expand = kwargs.get('expand', None) - - -class Remediation(msrest.serialization.Model): - """The remediation definition. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The ID of the remediation. - :vartype id: str - :ivar type: The type of the remediation. - :vartype type: str - :ivar name: The name of the remediation. - :vartype name: str - :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy - information. - :vartype system_data: ~azure.mgmt.policyinsights.models.SystemData - :param policy_assignment_id: The resource ID of the policy assignment that should be - remediated. - :type policy_assignment_id: str - :param policy_definition_reference_id: The policy definition reference ID of the individual - definition that should be remediated. Required when the policy assignment being remediated - assigns a policy set definition. - :type policy_definition_reference_id: str - :param resource_discovery_mode: The way resources to remediate are discovered. Defaults to - ExistingNonCompliant if not specified. Possible values include: "ExistingNonCompliant", - "ReEvaluateCompliance". - :type resource_discovery_mode: str or ~azure.mgmt.policyinsights.models.ResourceDiscoveryMode - :ivar provisioning_state: The status of the remediation. - :vartype provisioning_state: str - :ivar created_on: The time at which the remediation was created. - :vartype created_on: ~datetime.datetime - :ivar last_updated_on: The time at which the remediation was last updated. - :vartype last_updated_on: ~datetime.datetime - :param filters: The filters that will be applied to determine which resources to remediate. - :type filters: ~azure.mgmt.policyinsights.models.RemediationFilters - :ivar deployment_status: The deployment status summary for all deployments created by the - remediation. - :vartype deployment_status: ~azure.mgmt.policyinsights.models.RemediationDeploymentSummary - :ivar status_message: The remediation status message. Provides additional details regarding the - state of the remediation. - :vartype status_message: str - :ivar correlation_id: The remediation correlation Id. Can be used to find events related to the - remediation in the activity log. - :vartype correlation_id: str - :param resource_count: Determines the max number of resources that can be remediated by the - remediation job. If not provided, the default resource count is used. - :type resource_count: int - :param parallel_deployments: Determines how many resources to remediate at any given time. Can - be used to increase or reduce the pace of the remediation. If not provided, the default - parallel deployments value is used. - :type parallel_deployments: int - :param failure_threshold: The remediation failure threshold settings. - :type failure_threshold: - ~azure.mgmt.policyinsights.models.RemediationPropertiesFailureThreshold - """ - - _validation = { - 'id': {'readonly': True}, - 'type': {'readonly': True}, - 'name': {'readonly': True}, - 'system_data': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'created_on': {'readonly': True}, - 'last_updated_on': {'readonly': True}, - 'deployment_status': {'readonly': True}, - 'status_message': {'readonly': True}, - 'correlation_id': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'policy_assignment_id': {'key': 'properties.policyAssignmentId', 'type': 'str'}, - 'policy_definition_reference_id': {'key': 'properties.policyDefinitionReferenceId', 'type': 'str'}, - 'resource_discovery_mode': {'key': 'properties.resourceDiscoveryMode', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'last_updated_on': {'key': 'properties.lastUpdatedOn', 'type': 'iso-8601'}, - 'filters': {'key': 'properties.filters', 'type': 'RemediationFilters'}, - 'deployment_status': {'key': 'properties.deploymentStatus', 'type': 'RemediationDeploymentSummary'}, - 'status_message': {'key': 'properties.statusMessage', 'type': 'str'}, - 'correlation_id': {'key': 'properties.correlationId', 'type': 'str'}, - 'resource_count': {'key': 'properties.resourceCount', 'type': 'int'}, - 'parallel_deployments': {'key': 'properties.parallelDeployments', 'type': 'int'}, - 'failure_threshold': {'key': 'properties.failureThreshold', 'type': 'RemediationPropertiesFailureThreshold'}, - } - - def __init__( - self, - **kwargs - ): - super(Remediation, self).__init__(**kwargs) - self.id = None - self.type = None - self.name = None - self.system_data = None - self.policy_assignment_id = kwargs.get('policy_assignment_id', None) - self.policy_definition_reference_id = kwargs.get('policy_definition_reference_id', None) - self.resource_discovery_mode = kwargs.get('resource_discovery_mode', None) - self.provisioning_state = None - self.created_on = None - self.last_updated_on = None - self.filters = kwargs.get('filters', None) - self.deployment_status = None - self.status_message = None - self.correlation_id = None - self.resource_count = kwargs.get('resource_count', None) - self.parallel_deployments = kwargs.get('parallel_deployments', None) - self.failure_threshold = kwargs.get('failure_threshold', None) - - -class RemediationDeployment(msrest.serialization.Model): - """Details of a single deployment created by the remediation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar remediated_resource_id: Resource ID of the resource that is being remediated by the - deployment. - :vartype remediated_resource_id: str - :ivar deployment_id: Resource ID of the template deployment that will remediate the resource. - :vartype deployment_id: str - :ivar status: Status of the remediation deployment. - :vartype status: str - :ivar resource_location: Location of the resource that is being remediated. - :vartype resource_location: str - :ivar error: Error encountered while remediated the resource. - :vartype error: ~azure.mgmt.policyinsights.models.ErrorDefinition - :ivar created_on: The time at which the remediation was created. - :vartype created_on: ~datetime.datetime - :ivar last_updated_on: The time at which the remediation deployment was last updated. - :vartype last_updated_on: ~datetime.datetime - """ - - _validation = { - 'remediated_resource_id': {'readonly': True}, - 'deployment_id': {'readonly': True}, - 'status': {'readonly': True}, - 'resource_location': {'readonly': True}, - 'error': {'readonly': True}, - 'created_on': {'readonly': True}, - 'last_updated_on': {'readonly': True}, - } - - _attribute_map = { - 'remediated_resource_id': {'key': 'remediatedResourceId', 'type': 'str'}, - 'deployment_id': {'key': 'deploymentId', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'resource_location': {'key': 'resourceLocation', 'type': 'str'}, - 'error': {'key': 'error', 'type': 'ErrorDefinition'}, - 'created_on': {'key': 'createdOn', 'type': 'iso-8601'}, - 'last_updated_on': {'key': 'lastUpdatedOn', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(RemediationDeployment, self).__init__(**kwargs) - self.remediated_resource_id = None - self.deployment_id = None - self.status = None - self.resource_location = None - self.error = None - self.created_on = None - self.last_updated_on = None - - -class RemediationDeploymentsListResult(msrest.serialization.Model): - """List of deployments for a remediation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: Array of deployments for the remediation. - :vartype value: list[~azure.mgmt.policyinsights.models.RemediationDeployment] - :ivar next_link: The URL to get the next set of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[RemediationDeployment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RemediationDeploymentsListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class RemediationDeploymentSummary(msrest.serialization.Model): - """The deployment status summary for all deployments created by the remediation. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar total_deployments: The number of deployments required by the remediation. - :vartype total_deployments: int - :ivar successful_deployments: The number of deployments required by the remediation that have - succeeded. - :vartype successful_deployments: int - :ivar failed_deployments: The number of deployments required by the remediation that have - failed. - :vartype failed_deployments: int - """ - - _validation = { - 'total_deployments': {'readonly': True}, - 'successful_deployments': {'readonly': True}, - 'failed_deployments': {'readonly': True}, - } - - _attribute_map = { - 'total_deployments': {'key': 'totalDeployments', 'type': 'int'}, - 'successful_deployments': {'key': 'successfulDeployments', 'type': 'int'}, - 'failed_deployments': {'key': 'failedDeployments', 'type': 'int'}, - } - - def __init__( - self, - **kwargs - ): - super(RemediationDeploymentSummary, self).__init__(**kwargs) - self.total_deployments = None - self.successful_deployments = None - self.failed_deployments = None - - -class RemediationFilters(msrest.serialization.Model): - """The filters that will be applied to determine which resources to remediate. - - :param locations: The resource locations that will be remediated. - :type locations: list[str] - """ - - _attribute_map = { - 'locations': {'key': 'locations', 'type': '[str]'}, - } - - def __init__( - self, - **kwargs - ): - super(RemediationFilters, self).__init__(**kwargs) - self.locations = kwargs.get('locations', None) - - -class RemediationListResult(msrest.serialization.Model): - """List of remediations. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar value: Array of remediation definitions. - :vartype value: list[~azure.mgmt.policyinsights.models.Remediation] - :ivar next_link: The URL to get the next set of results. - :vartype next_link: str - """ - - _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, - } - - _attribute_map = { - 'value': {'key': 'value', 'type': '[Remediation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(RemediationListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None - - -class RemediationPropertiesFailureThreshold(msrest.serialization.Model): - """The remediation failure threshold settings. - - :param percentage: A number between 0.0 to 1.0 representing the percentage failure threshold. - The remediation will fail if the percentage of failed remediation operations (i.e. failed - deployments) exceeds this threshold. - :type percentage: float - """ - - _attribute_map = { - 'percentage': {'key': 'percentage', 'type': 'float'}, - } - - def __init__( - self, - **kwargs - ): - super(RemediationPropertiesFailureThreshold, self).__init__(**kwargs) - self.percentage = kwargs.get('percentage', None) - - -class SlimPolicyMetadata(msrest.serialization.Model): - """Slim version of policy metadata resource definition, excluding properties with large strings. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar id: The ID of the policy metadata. - :vartype id: str - :ivar type: The type of the policy metadata. - :vartype type: str - :ivar name: The name of the policy metadata. - :vartype name: str - :ivar metadata_id: The policy metadata identifier. - :vartype metadata_id: str - :ivar category: The category of the policy metadata. - :vartype category: str - :ivar title: The title of the policy metadata. - :vartype title: str - :ivar owner: The owner of the policy metadata. - :vartype owner: str - :ivar additional_content_url: Url for getting additional content about the resource metadata. - :vartype additional_content_url: str - :ivar metadata: Additional metadata. - :vartype metadata: any - """ - - _validation = { - 'id': {'readonly': True}, - 'type': {'readonly': True}, - 'name': {'readonly': True}, - 'metadata_id': {'readonly': True}, - 'category': {'readonly': True}, - 'title': {'readonly': True}, - 'owner': {'readonly': True}, - 'additional_content_url': {'readonly': True}, - 'metadata': {'readonly': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'metadata_id': {'key': 'properties.metadataId', 'type': 'str'}, - 'category': {'key': 'properties.category', 'type': 'str'}, - 'title': {'key': 'properties.title', 'type': 'str'}, - 'owner': {'key': 'properties.owner', 'type': 'str'}, - 'additional_content_url': {'key': 'properties.additionalContentUrl', 'type': 'str'}, - 'metadata': {'key': 'properties.metadata', 'type': 'object'}, - } - - def __init__( - self, - **kwargs - ): - super(SlimPolicyMetadata, self).__init__(**kwargs) - self.id = None - self.type = None - self.name = None - self.metadata_id = None - self.category = None - self.title = None - self.owner = None - self.additional_content_url = None - self.metadata = None - - -class SummarizeResults(msrest.serialization.Model): - """Summarize action results. - - :param odata_context: OData context string; used by OData clients to resolve type information - based on metadata. - :type odata_context: str - :param odata_count: OData entity count; represents the number of summaries returned; always set - to 1. - :type odata_count: int - :param value: Summarize action results. - :type value: list[~azure.mgmt.policyinsights.models.Summary] - """ - - _validation = { - 'odata_count': {'maximum': 1, 'minimum': 1}, - } - - _attribute_map = { - 'odata_context': {'key': '@odata\\.context', 'type': 'str'}, - 'odata_count': {'key': '@odata\\.count', 'type': 'int'}, - 'value': {'key': 'value', 'type': '[Summary]'}, - } - - def __init__( - self, - **kwargs - ): - super(SummarizeResults, self).__init__(**kwargs) - self.odata_context = kwargs.get('odata_context', None) - self.odata_count = kwargs.get('odata_count', None) - self.value = kwargs.get('value', None) - - -class Summary(msrest.serialization.Model): - """Summary results. - - :param odata_id: OData entity ID; always set to null since summaries do not have an entity ID. - :type odata_id: str - :param odata_context: OData context string; used by OData clients to resolve type information - based on metadata. - :type odata_context: str - :param results: Compliance summary for all policy assignments. - :type results: ~azure.mgmt.policyinsights.models.SummaryResults - :param policy_assignments: Policy assignments summary. - :type policy_assignments: list[~azure.mgmt.policyinsights.models.PolicyAssignmentSummary] - """ - - _attribute_map = { - 'odata_id': {'key': '@odata\\.id', 'type': 'str'}, - 'odata_context': {'key': '@odata\\.context', 'type': 'str'}, - 'results': {'key': 'results', 'type': 'SummaryResults'}, - 'policy_assignments': {'key': 'policyAssignments', 'type': '[PolicyAssignmentSummary]'}, - } - - def __init__( - self, - **kwargs - ): - super(Summary, self).__init__(**kwargs) - self.odata_id = kwargs.get('odata_id', None) - self.odata_context = kwargs.get('odata_context', None) - self.results = kwargs.get('results', None) - self.policy_assignments = kwargs.get('policy_assignments', None) - - -class SummaryResults(msrest.serialization.Model): - """Compliance summary on a particular summary level. - - :param query_results_uri: HTTP POST URI for queryResults action on Microsoft.PolicyInsights to - retrieve raw results for the compliance summary. This property will not be available by default - in future API versions, but could be queried explicitly. - :type query_results_uri: str - :param non_compliant_resources: Number of non-compliant resources. - :type non_compliant_resources: int - :param non_compliant_policies: Number of non-compliant policies. - :type non_compliant_policies: int - :param resource_details: The resources summary at this level. - :type resource_details: list[~azure.mgmt.policyinsights.models.ComplianceDetail] - :param policy_details: The policy artifact summary at this level. For query scope level, it - represents policy assignment summary. For policy assignment level, it represents policy - definitions summary. - :type policy_details: list[~azure.mgmt.policyinsights.models.ComplianceDetail] - :param policy_group_details: The policy definition group summary at this level. - :type policy_group_details: list[~azure.mgmt.policyinsights.models.ComplianceDetail] - """ - - _validation = { - 'non_compliant_resources': {'minimum': 0}, - 'non_compliant_policies': {'minimum': 0}, - } - - _attribute_map = { - 'query_results_uri': {'key': 'queryResultsUri', 'type': 'str'}, - 'non_compliant_resources': {'key': 'nonCompliantResources', 'type': 'int'}, - 'non_compliant_policies': {'key': 'nonCompliantPolicies', 'type': 'int'}, - 'resource_details': {'key': 'resourceDetails', 'type': '[ComplianceDetail]'}, - 'policy_details': {'key': 'policyDetails', 'type': '[ComplianceDetail]'}, - 'policy_group_details': {'key': 'policyGroupDetails', 'type': '[ComplianceDetail]'}, - } - - def __init__( - self, - **kwargs - ): - super(SummaryResults, self).__init__(**kwargs) - self.query_results_uri = kwargs.get('query_results_uri', None) - self.non_compliant_resources = kwargs.get('non_compliant_resources', None) - self.non_compliant_policies = kwargs.get('non_compliant_policies', None) - self.resource_details = kwargs.get('resource_details', None) - self.policy_details = kwargs.get('policy_details', None) - self.policy_group_details = kwargs.get('policy_group_details', None) - - -class SystemData(msrest.serialization.Model): - """Metadata pertaining to creation and last modification of the resource. - - :param created_by: The identity that created the resource. - :type created_by: str - :param created_by_type: The type of identity that created the resource. Possible values - include: "User", "Application", "ManagedIdentity", "Key". - :type created_by_type: str or ~azure.mgmt.policyinsights.models.CreatedByType - :param created_at: The timestamp of resource creation (UTC). - :type created_at: ~datetime.datetime - :param last_modified_by: The identity that last modified the resource. - :type last_modified_by: str - :param last_modified_by_type: The type of identity that last modified the resource. Possible - values include: "User", "Application", "ManagedIdentity", "Key". - :type last_modified_by_type: str or ~azure.mgmt.policyinsights.models.CreatedByType - :param last_modified_at: The timestamp of resource last modification (UTC). - :type last_modified_at: ~datetime.datetime - """ - - _attribute_map = { - 'created_by': {'key': 'createdBy', 'type': 'str'}, - 'created_by_type': {'key': 'createdByType', 'type': 'str'}, - 'created_at': {'key': 'createdAt', 'type': 'iso-8601'}, - 'last_modified_by': {'key': 'lastModifiedBy', 'type': 'str'}, - 'last_modified_by_type': {'key': 'lastModifiedByType', 'type': 'str'}, - 'last_modified_at': {'key': 'lastModifiedAt', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(SystemData, self).__init__(**kwargs) - self.created_by = kwargs.get('created_by', None) - self.created_by_type = kwargs.get('created_by_type', None) - self.created_at = kwargs.get('created_at', None) - self.last_modified_by = kwargs.get('last_modified_by', None) - self.last_modified_by_type = kwargs.get('last_modified_by_type', None) - self.last_modified_at = kwargs.get('last_modified_at', None) - - -class TrackedResourceModificationDetails(msrest.serialization.Model): - """The details of the policy triggered deployment that created or modified the tracked resource. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar policy_details: The details of the policy that created or modified the tracked resource. - :vartype policy_details: ~azure.mgmt.policyinsights.models.PolicyDetails - :ivar deployment_id: The ID of the deployment that created or modified the tracked resource. - :vartype deployment_id: str - :ivar deployment_time: Timestamp of the deployment that created or modified the tracked - resource. - :vartype deployment_time: ~datetime.datetime - """ - - _validation = { - 'policy_details': {'readonly': True}, - 'deployment_id': {'readonly': True}, - 'deployment_time': {'readonly': True}, - } - - _attribute_map = { - 'policy_details': {'key': 'policyDetails', 'type': 'PolicyDetails'}, - 'deployment_id': {'key': 'deploymentId', 'type': 'str'}, - 'deployment_time': {'key': 'deploymentTime', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(TrackedResourceModificationDetails, self).__init__(**kwargs) - self.policy_details = None - self.deployment_id = None - self.deployment_time = None - - -class TypedErrorInfo(msrest.serialization.Model): - """Scenario specific error details. - - Variables are only populated by the server, and will be ignored when sending a request. - - :ivar type: The type of included error details. - :vartype type: str - :ivar info: The scenario specific error details. - :vartype info: any - """ - - _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, - } - - _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, - } - - def __init__( - self, - **kwargs - ): - super(TypedErrorInfo, self).__init__(**kwargs) - self.type = None - self.info = None diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/_models_py3.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/_models_py3.py index 44be9e043bfc..82a498e1371a 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/_models_py3.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/_models_py3.py @@ -1,4 +1,5 @@ # coding=utf-8 +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. @@ -7,15 +8,22 @@ # -------------------------------------------------------------------------- import datetime -from typing import Any, Dict, List, Optional, Union +import sys +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union -from azure.core.exceptions import HttpResponseError -import msrest.serialization +from .. import _serialization -from ._policy_insights_client_enums import * +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -class Resource(msrest.serialization.Model): +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. @@ -31,28 +39,26 @@ class Resource(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(Resource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.name = None self.type = None -class Attestation(Resource): +class Attestation(Resource): # pylint: disable=too-many-instance-attributes """An attestation resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -70,57 +76,63 @@ class Attestation(Resource): :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. :vartype system_data: ~azure.mgmt.policyinsights.models.SystemData - :param policy_assignment_id: Required. The resource ID of the policy assignment that the - attestation is setting the state for. - :type policy_assignment_id: str - :param policy_definition_reference_id: The policy definition reference ID from a policy set + :ivar policy_assignment_id: The resource ID of the policy assignment that the attestation is + setting the state for. Required. + :vartype policy_assignment_id: str + :ivar policy_definition_reference_id: The policy definition reference ID from a policy set definition that the attestation is setting the state for. If the policy assignment assigns a policy set definition the attestation can choose a definition within the set definition with this property or omit this and set the state for the entire set definition. - :type policy_definition_reference_id: str - :param compliance_state: The compliance state that should be set on the resource. Possible - values include: "Compliant", "NonCompliant", "Unknown". - :type compliance_state: str or ~azure.mgmt.policyinsights.models.ComplianceState - :param expires_on: The time the compliance state should expire. - :type expires_on: ~datetime.datetime - :param owner: The person responsible for setting the state of the resource. This value is + :vartype policy_definition_reference_id: str + :ivar compliance_state: The compliance state that should be set on the resource. Known values + are: "Compliant", "NonCompliant", and "Unknown". + :vartype compliance_state: str or ~azure.mgmt.policyinsights.models.ComplianceState + :ivar expires_on: The time the compliance state should expire. + :vartype expires_on: ~datetime.datetime + :ivar owner: The person responsible for setting the state of the resource. This value is typically an Azure Active Directory object ID. - :type owner: str - :param comments: Comments describing why this attestation was created. - :type comments: str - :param evidence: The evidence supporting the compliance state set in this attestation. - :type evidence: list[~azure.mgmt.policyinsights.models.AttestationEvidence] + :vartype owner: str + :ivar comments: Comments describing why this attestation was created. + :vartype comments: str + :ivar evidence: The evidence supporting the compliance state set in this attestation. + :vartype evidence: list[~azure.mgmt.policyinsights.models.AttestationEvidence] :ivar provisioning_state: The status of the attestation. :vartype provisioning_state: str :ivar last_compliance_state_change_at: The time the compliance state was last changed in this attestation. :vartype last_compliance_state_change_at: ~datetime.datetime + :ivar assessment_date: The time the evidence was assessed. + :vartype assessment_date: ~datetime.datetime + :ivar metadata: Additional metadata for this attestation. + :vartype metadata: JSON """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'system_data': {'readonly': True}, - 'policy_assignment_id': {'required': True}, - 'provisioning_state': {'readonly': True}, - 'last_compliance_state_change_at': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "system_data": {"readonly": True}, + "policy_assignment_id": {"required": True}, + "provisioning_state": {"readonly": True}, + "last_compliance_state_change_at": {"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'}, - 'policy_assignment_id': {'key': 'properties.policyAssignmentId', 'type': 'str'}, - 'policy_definition_reference_id': {'key': 'properties.policyDefinitionReferenceId', 'type': 'str'}, - 'compliance_state': {'key': 'properties.complianceState', 'type': 'str'}, - 'expires_on': {'key': 'properties.expiresOn', 'type': 'iso-8601'}, - 'owner': {'key': 'properties.owner', 'type': 'str'}, - 'comments': {'key': 'properties.comments', 'type': 'str'}, - 'evidence': {'key': 'properties.evidence', 'type': '[AttestationEvidence]'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'last_compliance_state_change_at': {'key': 'properties.lastComplianceStateChangeAt', 'type': 'iso-8601'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "policy_assignment_id": {"key": "properties.policyAssignmentId", "type": "str"}, + "policy_definition_reference_id": {"key": "properties.policyDefinitionReferenceId", "type": "str"}, + "compliance_state": {"key": "properties.complianceState", "type": "str"}, + "expires_on": {"key": "properties.expiresOn", "type": "iso-8601"}, + "owner": {"key": "properties.owner", "type": "str"}, + "comments": {"key": "properties.comments", "type": "str"}, + "evidence": {"key": "properties.evidence", "type": "[AttestationEvidence]"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "last_compliance_state_change_at": {"key": "properties.lastComplianceStateChangeAt", "type": "iso-8601"}, + "assessment_date": {"key": "properties.assessmentDate", "type": "iso-8601"}, + "metadata": {"key": "properties.metadata", "type": "object"}, } def __init__( @@ -128,14 +140,42 @@ def __init__( *, policy_assignment_id: str, policy_definition_reference_id: Optional[str] = None, - compliance_state: Optional[Union[str, "ComplianceState"]] = None, + compliance_state: Optional[Union[str, "_models.ComplianceState"]] = None, expires_on: Optional[datetime.datetime] = None, owner: Optional[str] = None, comments: Optional[str] = None, - evidence: Optional[List["AttestationEvidence"]] = None, + evidence: Optional[List["_models.AttestationEvidence"]] = None, + assessment_date: Optional[datetime.datetime] = None, + metadata: Optional[JSON] = None, **kwargs ): - super(Attestation, self).__init__(**kwargs) + """ + :keyword policy_assignment_id: The resource ID of the policy assignment that the attestation is + setting the state for. Required. + :paramtype policy_assignment_id: str + :keyword policy_definition_reference_id: The policy definition reference ID from a policy set + definition that the attestation is setting the state for. If the policy assignment assigns a + policy set definition the attestation can choose a definition within the set definition with + this property or omit this and set the state for the entire set definition. + :paramtype policy_definition_reference_id: str + :keyword compliance_state: The compliance state that should be set on the resource. Known + values are: "Compliant", "NonCompliant", and "Unknown". + :paramtype compliance_state: str or ~azure.mgmt.policyinsights.models.ComplianceState + :keyword expires_on: The time the compliance state should expire. + :paramtype expires_on: ~datetime.datetime + :keyword owner: The person responsible for setting the state of the resource. This value is + typically an Azure Active Directory object ID. + :paramtype owner: str + :keyword comments: Comments describing why this attestation was created. + :paramtype comments: str + :keyword evidence: The evidence supporting the compliance state set in this attestation. + :paramtype evidence: list[~azure.mgmt.policyinsights.models.AttestationEvidence] + :keyword assessment_date: The time the evidence was assessed. + :paramtype assessment_date: ~datetime.datetime + :keyword metadata: Additional metadata for this attestation. + :paramtype metadata: JSON + """ + super().__init__(**kwargs) self.system_data = None self.policy_assignment_id = policy_assignment_id self.policy_definition_reference_id = policy_definition_reference_id @@ -146,35 +186,37 @@ def __init__( self.evidence = evidence self.provisioning_state = None self.last_compliance_state_change_at = None + self.assessment_date = assessment_date + self.metadata = metadata -class AttestationEvidence(msrest.serialization.Model): +class AttestationEvidence(_serialization.Model): """A piece of evidence supporting the compliance state set in the attestation. - :param description: The description for this piece of evidence. - :type description: str - :param source_uri: The URI location of the evidence. - :type source_uri: str + :ivar description: The description for this piece of evidence. + :vartype description: str + :ivar source_uri: The URI location of the evidence. + :vartype source_uri: str """ _attribute_map = { - 'description': {'key': 'description', 'type': 'str'}, - 'source_uri': {'key': 'sourceUri', 'type': 'str'}, - } - - def __init__( - self, - *, - description: Optional[str] = None, - source_uri: Optional[str] = None, - **kwargs - ): - super(AttestationEvidence, self).__init__(**kwargs) + "description": {"key": "description", "type": "str"}, + "source_uri": {"key": "sourceUri", "type": "str"}, + } + + def __init__(self, *, description: Optional[str] = None, source_uri: Optional[str] = None, **kwargs): + """ + :keyword description: The description for this piece of evidence. + :paramtype description: str + :keyword source_uri: The URI location of the evidence. + :paramtype source_uri: str + """ + super().__init__(**kwargs) self.description = description self.source_uri = source_uri -class AttestationListResult(msrest.serialization.Model): +class AttestationListResult(_serialization.Model): """List of attestations. Variables are only populated by the server, and will be ignored when sending a request. @@ -186,97 +228,141 @@ class AttestationListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Attestation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Attestation]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) + self.value = None + self.next_link = None + + +class CheckManagementGroupRestrictionsRequest(_serialization.Model): + """The check policy restrictions parameters describing the resource that is being evaluated. + + :ivar resource_details: The information about the resource that will be evaluated. + :vartype resource_details: ~azure.mgmt.policyinsights.models.CheckRestrictionsResourceDetails + :ivar pending_fields: The list of fields and values that should be evaluated for potential + restrictions. + :vartype pending_fields: list[~azure.mgmt.policyinsights.models.PendingField] + """ + + _attribute_map = { + "resource_details": {"key": "resourceDetails", "type": "CheckRestrictionsResourceDetails"}, + "pending_fields": {"key": "pendingFields", "type": "[PendingField]"}, } def __init__( self, + *, + resource_details: Optional["_models.CheckRestrictionsResourceDetails"] = None, + pending_fields: Optional[List["_models.PendingField"]] = None, **kwargs ): - super(AttestationListResult, self).__init__(**kwargs) - self.value = None - self.next_link = None + """ + :keyword resource_details: The information about the resource that will be evaluated. + :paramtype resource_details: ~azure.mgmt.policyinsights.models.CheckRestrictionsResourceDetails + :keyword pending_fields: The list of fields and values that should be evaluated for potential + restrictions. + :paramtype pending_fields: list[~azure.mgmt.policyinsights.models.PendingField] + """ + super().__init__(**kwargs) + self.resource_details = resource_details + self.pending_fields = pending_fields -class CheckRestrictionsRequest(msrest.serialization.Model): +class CheckRestrictionsRequest(_serialization.Model): """The check policy restrictions parameters describing the resource that is being evaluated. All required parameters must be populated in order to send to Azure. - :param resource_details: Required. The information about the resource that will be evaluated. - :type resource_details: ~azure.mgmt.policyinsights.models.CheckRestrictionsResourceDetails - :param pending_fields: The list of fields and values that should be evaluated for potential + :ivar resource_details: The information about the resource that will be evaluated. Required. + :vartype resource_details: ~azure.mgmt.policyinsights.models.CheckRestrictionsResourceDetails + :ivar pending_fields: The list of fields and values that should be evaluated for potential restrictions. - :type pending_fields: list[~azure.mgmt.policyinsights.models.PendingField] + :vartype pending_fields: list[~azure.mgmt.policyinsights.models.PendingField] """ _validation = { - 'resource_details': {'required': True}, + "resource_details": {"required": True}, } _attribute_map = { - 'resource_details': {'key': 'resourceDetails', 'type': 'CheckRestrictionsResourceDetails'}, - 'pending_fields': {'key': 'pendingFields', 'type': '[PendingField]'}, + "resource_details": {"key": "resourceDetails", "type": "CheckRestrictionsResourceDetails"}, + "pending_fields": {"key": "pendingFields", "type": "[PendingField]"}, } def __init__( self, *, - resource_details: "CheckRestrictionsResourceDetails", - pending_fields: Optional[List["PendingField"]] = None, + resource_details: "_models.CheckRestrictionsResourceDetails", + pending_fields: Optional[List["_models.PendingField"]] = None, **kwargs ): - super(CheckRestrictionsRequest, self).__init__(**kwargs) + """ + :keyword resource_details: The information about the resource that will be evaluated. Required. + :paramtype resource_details: ~azure.mgmt.policyinsights.models.CheckRestrictionsResourceDetails + :keyword pending_fields: The list of fields and values that should be evaluated for potential + restrictions. + :paramtype pending_fields: list[~azure.mgmt.policyinsights.models.PendingField] + """ + super().__init__(**kwargs) self.resource_details = resource_details self.pending_fields = pending_fields -class CheckRestrictionsResourceDetails(msrest.serialization.Model): +class CheckRestrictionsResourceDetails(_serialization.Model): """The information about the resource that will be evaluated. All required parameters must be populated in order to send to Azure. - :param resource_content: Required. The resource content. This should include whatever - properties are already known and can be a partial set of all resource properties. - :type resource_content: any - :param api_version: The api-version of the resource content. - :type api_version: str - :param scope: The scope where the resource is being created. For example, if the resource is a + :ivar resource_content: The resource content. This should include whatever properties are + already known and can be a partial set of all resource properties. Required. + :vartype resource_content: JSON + :ivar api_version: The api-version of the resource content. + :vartype api_version: str + :ivar scope: The scope where the resource is being created. For example, if the resource is a child resource this would be the parent resource's resource ID. - :type scope: str + :vartype scope: str """ _validation = { - 'resource_content': {'required': True}, + "resource_content": {"required": True}, } _attribute_map = { - 'resource_content': {'key': 'resourceContent', 'type': 'object'}, - 'api_version': {'key': 'apiVersion', 'type': 'str'}, - 'scope': {'key': 'scope', 'type': 'str'}, + "resource_content": {"key": "resourceContent", "type": "object"}, + "api_version": {"key": "apiVersion", "type": "str"}, + "scope": {"key": "scope", "type": "str"}, } def __init__( - self, - *, - resource_content: Any, - api_version: Optional[str] = None, - scope: Optional[str] = None, - **kwargs + self, *, resource_content: JSON, api_version: Optional[str] = None, scope: Optional[str] = None, **kwargs ): - super(CheckRestrictionsResourceDetails, self).__init__(**kwargs) + """ + :keyword resource_content: The resource content. This should include whatever properties are + already known and can be a partial set of all resource properties. Required. + :paramtype resource_content: JSON + :keyword api_version: The api-version of the resource content. + :paramtype api_version: str + :keyword scope: The scope where the resource is being created. For example, if the resource is + a child resource this would be the parent resource's resource ID. + :paramtype scope: str + """ + super().__init__(**kwargs) self.resource_content = resource_content self.api_version = api_version self.scope = scope -class CheckRestrictionsResult(msrest.serialization.Model): +class CheckRestrictionsResult(_serialization.Model): """The result of a check policy restrictions evaluation on a resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -290,111 +376,112 @@ class CheckRestrictionsResult(msrest.serialization.Model): """ _validation = { - 'field_restrictions': {'readonly': True}, - 'content_evaluation_result': {'readonly': True}, + "field_restrictions": {"readonly": True}, + "content_evaluation_result": {"readonly": True}, } _attribute_map = { - 'field_restrictions': {'key': 'fieldRestrictions', 'type': '[FieldRestrictions]'}, - 'content_evaluation_result': {'key': 'contentEvaluationResult', 'type': 'CheckRestrictionsResultContentEvaluationResult'}, + "field_restrictions": {"key": "fieldRestrictions", "type": "[FieldRestrictions]"}, + "content_evaluation_result": { + "key": "contentEvaluationResult", + "type": "CheckRestrictionsResultContentEvaluationResult", + }, } - def __init__( - self, - **kwargs - ): - super(CheckRestrictionsResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.field_restrictions = None self.content_evaluation_result = None -class CheckRestrictionsResultContentEvaluationResult(msrest.serialization.Model): +class CheckRestrictionsResultContentEvaluationResult(_serialization.Model): """Evaluation results for the provided partial resource content. - :param policy_evaluations: Policy evaluation results against the given resource content. This + :ivar policy_evaluations: Policy evaluation results against the given resource content. This will indicate if the partial content that was provided will be denied as-is. - :type policy_evaluations: list[~azure.mgmt.policyinsights.models.PolicyEvaluationResult] + :vartype policy_evaluations: list[~azure.mgmt.policyinsights.models.PolicyEvaluationResult] """ _attribute_map = { - 'policy_evaluations': {'key': 'policyEvaluations', 'type': '[PolicyEvaluationResult]'}, + "policy_evaluations": {"key": "policyEvaluations", "type": "[PolicyEvaluationResult]"}, } - def __init__( - self, - *, - policy_evaluations: Optional[List["PolicyEvaluationResult"]] = None, - **kwargs - ): - super(CheckRestrictionsResultContentEvaluationResult, self).__init__(**kwargs) + def __init__(self, *, policy_evaluations: Optional[List["_models.PolicyEvaluationResult"]] = None, **kwargs): + """ + :keyword policy_evaluations: Policy evaluation results against the given resource content. This + will indicate if the partial content that was provided will be denied as-is. + :paramtype policy_evaluations: list[~azure.mgmt.policyinsights.models.PolicyEvaluationResult] + """ + super().__init__(**kwargs) self.policy_evaluations = policy_evaluations -class ComplianceDetail(msrest.serialization.Model): +class ComplianceDetail(_serialization.Model): """The compliance state rollup. - :param compliance_state: The compliance state. - :type compliance_state: str - :param count: Summarized count value for this compliance state. - :type count: int + :ivar compliance_state: The compliance state. + :vartype compliance_state: str + :ivar count: Summarized count value for this compliance state. + :vartype count: int """ _attribute_map = { - 'compliance_state': {'key': 'complianceState', 'type': 'str'}, - 'count': {'key': 'count', 'type': 'int'}, - } - - def __init__( - self, - *, - compliance_state: Optional[str] = None, - count: Optional[int] = None, - **kwargs - ): - super(ComplianceDetail, self).__init__(**kwargs) + "compliance_state": {"key": "complianceState", "type": "str"}, + "count": {"key": "count", "type": "int"}, + } + + def __init__(self, *, compliance_state: Optional[str] = None, count: Optional[int] = None, **kwargs): + """ + :keyword compliance_state: The compliance state. + :paramtype compliance_state: str + :keyword count: Summarized count value for this compliance state. + :paramtype count: int + """ + super().__init__(**kwargs) self.compliance_state = compliance_state self.count = count -class ComponentEventDetails(msrest.serialization.Model): +class ComponentEventDetails(_serialization.Model): """Component event details. - :param additional_properties: Unmatched properties from the message are deserialized to this + :ivar additional_properties: Unmatched properties from the message are deserialized to this collection. - :type additional_properties: dict[str, any] - :param id: Component Id. - :type id: str - :param type: Component type. - :type type: str - :param name: Component name. - :type name: str - :param timestamp: Timestamp for component policy event record. - :type timestamp: ~datetime.datetime - :param tenant_id: Tenant ID for the policy event record. - :type tenant_id: str - :param principal_oid: Principal object ID for the user who initiated the resource component + :vartype additional_properties: dict[str, any] + :ivar id: Component Id. + :vartype id: str + :ivar type: Component type. + :vartype type: str + :ivar name: Component name. + :vartype name: str + :ivar timestamp: Timestamp for component policy event record. + :vartype timestamp: ~datetime.datetime + :ivar tenant_id: Tenant ID for the policy event record. + :vartype tenant_id: str + :ivar principal_oid: Principal object ID for the user who initiated the resource component operation that triggered the policy event. - :type principal_oid: str - :param policy_definition_action: Policy definition action, i.e. effect. - :type policy_definition_action: str + :vartype principal_oid: str + :ivar policy_definition_action: Policy definition action, i.e. effect. + :vartype policy_definition_action: str """ _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'timestamp': {'key': 'timestamp', 'type': 'iso-8601'}, - 'tenant_id': {'key': 'tenantId', 'type': 'str'}, - 'principal_oid': {'key': 'principalOid', 'type': 'str'}, - 'policy_definition_action': {'key': 'policyDefinitionAction', 'type': 'str'}, + "additional_properties": {"key": "", "type": "{object}"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "timestamp": {"key": "timestamp", "type": "iso-8601"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "principal_oid": {"key": "principalOid", "type": "str"}, + "policy_definition_action": {"key": "policyDefinitionAction", "type": "str"}, } def __init__( self, *, additional_properties: Optional[Dict[str, Any]] = None, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin type: Optional[str] = None, name: Optional[str] = None, timestamp: Optional[datetime.datetime] = None, @@ -403,7 +490,27 @@ def __init__( policy_definition_action: Optional[str] = None, **kwargs ): - super(ComponentEventDetails, self).__init__(**kwargs) + """ + :keyword additional_properties: Unmatched properties from the message are deserialized to this + collection. + :paramtype additional_properties: dict[str, any] + :keyword id: Component Id. + :paramtype id: str + :keyword type: Component type. + :paramtype type: str + :keyword name: Component name. + :paramtype name: str + :keyword timestamp: Timestamp for component policy event record. + :paramtype timestamp: ~datetime.datetime + :keyword tenant_id: Tenant ID for the policy event record. + :paramtype tenant_id: str + :keyword principal_oid: Principal object ID for the user who initiated the resource component + operation that triggered the policy event. + :paramtype principal_oid: str + :keyword policy_definition_action: Policy definition action, i.e. effect. + :paramtype policy_definition_action: str + """ + super().__init__(**kwargs) self.additional_properties = additional_properties self.id = id self.type = type @@ -414,45 +521,60 @@ def __init__( self.policy_definition_action = policy_definition_action -class ComponentStateDetails(msrest.serialization.Model): +class ComponentStateDetails(_serialization.Model): """Component state details. - :param additional_properties: Unmatched properties from the message are deserialized to this + :ivar additional_properties: Unmatched properties from the message are deserialized to this collection. - :type additional_properties: dict[str, any] - :param id: Component Id. - :type id: str - :param type: Component type. - :type type: str - :param name: Component name. - :type name: str - :param timestamp: Component compliance evaluation timestamp. - :type timestamp: ~datetime.datetime - :param compliance_state: Component compliance state. - :type compliance_state: str + :vartype additional_properties: dict[str, any] + :ivar id: Component Id. + :vartype id: str + :ivar type: Component type. + :vartype type: str + :ivar name: Component name. + :vartype name: str + :ivar timestamp: Component compliance evaluation timestamp. + :vartype timestamp: ~datetime.datetime + :ivar compliance_state: Component compliance state. + :vartype compliance_state: str """ _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'timestamp': {'key': 'timestamp', 'type': 'iso-8601'}, - 'compliance_state': {'key': 'complianceState', 'type': 'str'}, + "additional_properties": {"key": "", "type": "{object}"}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "timestamp": {"key": "timestamp", "type": "iso-8601"}, + "compliance_state": {"key": "complianceState", "type": "str"}, } def __init__( self, *, additional_properties: Optional[Dict[str, Any]] = None, - id: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin type: Optional[str] = None, name: Optional[str] = None, timestamp: Optional[datetime.datetime] = None, compliance_state: Optional[str] = None, **kwargs ): - super(ComponentStateDetails, self).__init__(**kwargs) + """ + :keyword additional_properties: Unmatched properties from the message are deserialized to this + collection. + :paramtype additional_properties: dict[str, any] + :keyword id: Component Id. + :paramtype id: str + :keyword type: Component type. + :paramtype type: str + :keyword name: Component name. + :paramtype name: str + :keyword timestamp: Component compliance evaluation timestamp. + :paramtype timestamp: ~datetime.datetime + :keyword compliance_state: Component compliance state. + :paramtype compliance_state: str + """ + super().__init__(**kwargs) self.additional_properties = additional_properties self.id = id self.type = type @@ -461,7 +583,7 @@ def __init__( self.compliance_state = compliance_state -class ErrorDefinition(msrest.serialization.Model): +class ErrorDefinition(_serialization.Model): """Error definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -479,26 +601,24 @@ class ErrorDefinition(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, + "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': '[ErrorDefinition]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[TypedErrorInfo]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDefinition]"}, + "additional_info": {"key": "additionalInfo", "type": "[TypedErrorInfo]"}, } - def __init__( - self, - **kwargs - ): - super(ErrorDefinition, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -506,7 +626,7 @@ def __init__( self.additional_info = None -class ErrorDefinitionAutoGenerated(msrest.serialization.Model): +class ErrorDefinitionAutoGenerated(_serialization.Model): """Error definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -524,26 +644,24 @@ class ErrorDefinitionAutoGenerated(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, + "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': '[ErrorDefinitionAutoGenerated]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[TypedErrorInfo]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDefinitionAutoGenerated]"}, + "additional_info": {"key": "additionalInfo", "type": "[TypedErrorInfo]"}, } - def __init__( - self, - **kwargs - ): - super(ErrorDefinitionAutoGenerated, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -551,7 +669,7 @@ def __init__( self.additional_info = None -class ErrorDefinitionAutoGenerated2(msrest.serialization.Model): +class ErrorDefinitionAutoGenerated2(_serialization.Model): """Error definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -569,26 +687,24 @@ class ErrorDefinitionAutoGenerated2(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, - 'target': {'readonly': True}, - 'details': {'readonly': True}, - 'additional_info': {'readonly': True}, + "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': '[ErrorDefinitionAutoGenerated2]'}, - 'additional_info': {'key': 'additionalInfo', 'type': '[TypedErrorInfo]'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[ErrorDefinitionAutoGenerated2]"}, + "additional_info": {"key": "additionalInfo", "type": "[TypedErrorInfo]"}, } - def __init__( - self, - **kwargs - ): - super(ErrorDefinitionAutoGenerated2, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None self.target = None @@ -596,102 +712,99 @@ def __init__( self.additional_info = None -class ErrorResponse(msrest.serialization.Model): +class ErrorResponse(_serialization.Model): """Error response. - :param error: The error details. - :type error: ~azure.mgmt.policyinsights.models.ErrorDefinition + :ivar error: The error details. + :vartype error: ~azure.mgmt.policyinsights.models.ErrorDefinition """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinition'}, + "error": {"key": "error", "type": "ErrorDefinition"}, } - def __init__( - self, - *, - error: Optional["ErrorDefinition"] = None, - **kwargs - ): - super(ErrorResponse, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDefinition"] = None, **kwargs): + """ + :keyword error: The error details. + :paramtype error: ~azure.mgmt.policyinsights.models.ErrorDefinition + """ + super().__init__(**kwargs) self.error = error -class ErrorResponseAutoGenerated(msrest.serialization.Model): +class ErrorResponseAutoGenerated(_serialization.Model): """Error response. - :param error: The error details. - :type error: ~azure.mgmt.policyinsights.models.ErrorDefinitionAutoGenerated + :ivar error: The error details. + :vartype error: ~azure.mgmt.policyinsights.models.ErrorDefinitionAutoGenerated """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinitionAutoGenerated'}, + "error": {"key": "error", "type": "ErrorDefinitionAutoGenerated"}, } - def __init__( - self, - *, - error: Optional["ErrorDefinitionAutoGenerated"] = None, - **kwargs - ): - super(ErrorResponseAutoGenerated, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDefinitionAutoGenerated"] = None, **kwargs): + """ + :keyword error: The error details. + :paramtype error: ~azure.mgmt.policyinsights.models.ErrorDefinitionAutoGenerated + """ + super().__init__(**kwargs) self.error = error -class ErrorResponseAutoGenerated2(msrest.serialization.Model): +class ErrorResponseAutoGenerated2(_serialization.Model): """Error response. - :param error: The error details. - :type error: ~azure.mgmt.policyinsights.models.ErrorDefinitionAutoGenerated2 + :ivar error: The error details. + :vartype error: ~azure.mgmt.policyinsights.models.ErrorDefinitionAutoGenerated2 """ _attribute_map = { - 'error': {'key': 'error', 'type': 'ErrorDefinitionAutoGenerated2'}, + "error": {"key": "error", "type": "ErrorDefinitionAutoGenerated2"}, } - def __init__( - self, - *, - error: Optional["ErrorDefinitionAutoGenerated2"] = None, - **kwargs - ): - super(ErrorResponseAutoGenerated2, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.ErrorDefinitionAutoGenerated2"] = None, **kwargs): + """ + :keyword error: The error details. + :paramtype error: ~azure.mgmt.policyinsights.models.ErrorDefinitionAutoGenerated2 + """ + super().__init__(**kwargs) self.error = error -class ExpressionEvaluationDetails(msrest.serialization.Model): +class ExpressionEvaluationDetails(_serialization.Model): """Evaluation details of policy language expressions. Variables are only populated by the server, and will be ignored when sending a request. - :param result: Evaluation result. - :type result: str - :param expression: Expression evaluated. - :type expression: str + :ivar result: Evaluation result. + :vartype result: str + :ivar expression: Expression evaluated. + :vartype expression: str :ivar expression_kind: The kind of expression that was evaluated. :vartype expression_kind: str - :param path: Property path if the expression is a field or an alias. - :type path: str - :param expression_value: Value of the expression. - :type expression_value: any - :param target_value: Target value to be compared with the expression value. - :type target_value: any - :param operator: Operator to compare the expression value and the target value. - :type operator: str + :ivar path: Property path if the expression is a field or an alias. + :vartype path: str + :ivar expression_value: Value of the expression. + :vartype expression_value: JSON + :ivar target_value: Target value to be compared with the expression value. + :vartype target_value: JSON + :ivar operator: Operator to compare the expression value and the target value. + :vartype operator: str """ _validation = { - 'expression_kind': {'readonly': True}, + "expression_kind": {"readonly": True}, } _attribute_map = { - 'result': {'key': 'result', 'type': 'str'}, - 'expression': {'key': 'expression', 'type': 'str'}, - 'expression_kind': {'key': 'expressionKind', 'type': 'str'}, - 'path': {'key': 'path', 'type': 'str'}, - 'expression_value': {'key': 'expressionValue', 'type': 'object'}, - 'target_value': {'key': 'targetValue', 'type': 'object'}, - 'operator': {'key': 'operator', 'type': 'str'}, + "result": {"key": "result", "type": "str"}, + "expression": {"key": "expression", "type": "str"}, + "expression_kind": {"key": "expressionKind", "type": "str"}, + "path": {"key": "path", "type": "str"}, + "expression_value": {"key": "expressionValue", "type": "object"}, + "target_value": {"key": "targetValue", "type": "object"}, + "operator": {"key": "operator", "type": "str"}, } def __init__( @@ -700,12 +813,26 @@ def __init__( result: Optional[str] = None, expression: Optional[str] = None, path: Optional[str] = None, - expression_value: Optional[Any] = None, - target_value: Optional[Any] = None, + expression_value: Optional[JSON] = None, + target_value: Optional[JSON] = None, operator: Optional[str] = None, **kwargs ): - super(ExpressionEvaluationDetails, self).__init__(**kwargs) + """ + :keyword result: Evaluation result. + :paramtype result: str + :keyword expression: Expression evaluated. + :paramtype expression: str + :keyword path: Property path if the expression is a field or an alias. + :paramtype path: str + :keyword expression_value: Value of the expression. + :paramtype expression_value: JSON + :keyword target_value: Target value to be compared with the expression value. + :paramtype target_value: JSON + :keyword operator: Operator to compare the expression value and the target value. + :paramtype operator: str + """ + super().__init__(**kwargs) self.result = result self.expression = expression self.expression_kind = None @@ -715,13 +842,13 @@ def __init__( self.operator = operator -class FieldRestriction(msrest.serialization.Model): +class FieldRestriction(_serialization.Model): """The restrictions on a field imposed by a specific policy. Variables are only populated by the server, and will be ignored when sending a request. - :ivar result: The type of restriction that is imposed on the field. Possible values include: - "Required", "Removed", "Deny". + :ivar result: The type of restriction that is imposed on the field. Known values are: + "Required", "Removed", and "Deny". :vartype result: str or ~azure.mgmt.policyinsights.models.FieldRestrictionResult :ivar default_value: The value that policy will set for the field if the user does not provide a value. @@ -733,31 +860,29 @@ class FieldRestriction(msrest.serialization.Model): """ _validation = { - 'result': {'readonly': True}, - 'default_value': {'readonly': True}, - 'values': {'readonly': True}, - 'policy': {'readonly': True}, + "result": {"readonly": True}, + "default_value": {"readonly": True}, + "values": {"readonly": True}, + "policy": {"readonly": True}, } _attribute_map = { - 'result': {'key': 'result', 'type': 'str'}, - 'default_value': {'key': 'defaultValue', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, - 'policy': {'key': 'policy', 'type': 'PolicyReference'}, + "result": {"key": "result", "type": "str"}, + "default_value": {"key": "defaultValue", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, + "policy": {"key": "policy", "type": "PolicyReference"}, } - def __init__( - self, - **kwargs - ): - super(FieldRestriction, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.result = None self.default_value = None self.values = None self.policy = None -class FieldRestrictions(msrest.serialization.Model): +class FieldRestrictions(_serialization.Model): """The restrictions that will be placed on a field in the resource by policy. Variables are only populated by the server, and will be ignored when sending a request. @@ -765,101 +890,101 @@ class FieldRestrictions(msrest.serialization.Model): :ivar field: The name of the field. This can be a top-level property like 'name' or 'type' or an Azure Policy field alias. :vartype field: str - :param restrictions: The restrictions placed on that field by policy. - :type restrictions: list[~azure.mgmt.policyinsights.models.FieldRestriction] + :ivar restrictions: The restrictions placed on that field by policy. + :vartype restrictions: list[~azure.mgmt.policyinsights.models.FieldRestriction] """ _validation = { - 'field': {'readonly': True}, + "field": {"readonly": True}, } _attribute_map = { - 'field': {'key': 'field', 'type': 'str'}, - 'restrictions': {'key': 'restrictions', 'type': '[FieldRestriction]'}, + "field": {"key": "field", "type": "str"}, + "restrictions": {"key": "restrictions", "type": "[FieldRestriction]"}, } - def __init__( - self, - *, - restrictions: Optional[List["FieldRestriction"]] = None, - **kwargs - ): - super(FieldRestrictions, self).__init__(**kwargs) + def __init__(self, *, restrictions: Optional[List["_models.FieldRestriction"]] = None, **kwargs): + """ + :keyword restrictions: The restrictions placed on that field by policy. + :paramtype restrictions: list[~azure.mgmt.policyinsights.models.FieldRestriction] + """ + super().__init__(**kwargs) self.field = None self.restrictions = restrictions -class IfNotExistsEvaluationDetails(msrest.serialization.Model): +class IfNotExistsEvaluationDetails(_serialization.Model): """Evaluation details of IfNotExists effect. - :param resource_id: ID of the last evaluated resource for IfNotExists effect. - :type resource_id: str - :param total_resources: Total number of resources to which the existence condition is + :ivar resource_id: ID of the last evaluated resource for IfNotExists effect. + :vartype resource_id: str + :ivar total_resources: Total number of resources to which the existence condition is applicable. - :type total_resources: int + :vartype total_resources: int """ _attribute_map = { - 'resource_id': {'key': 'resourceId', 'type': 'str'}, - 'total_resources': {'key': 'totalResources', 'type': 'int'}, - } - - def __init__( - self, - *, - resource_id: Optional[str] = None, - total_resources: Optional[int] = None, - **kwargs - ): - super(IfNotExistsEvaluationDetails, self).__init__(**kwargs) + "resource_id": {"key": "resourceId", "type": "str"}, + "total_resources": {"key": "totalResources", "type": "int"}, + } + + def __init__(self, *, resource_id: Optional[str] = None, total_resources: Optional[int] = None, **kwargs): + """ + :keyword resource_id: ID of the last evaluated resource for IfNotExists effect. + :paramtype resource_id: str + :keyword total_resources: Total number of resources to which the existence condition is + applicable. + :paramtype total_resources: int + """ + super().__init__(**kwargs) self.resource_id = resource_id self.total_resources = total_resources -class Operation(msrest.serialization.Model): +class Operation(_serialization.Model): """Operation definition. - :param name: Operation name. - :type name: str - :param display: Display metadata associated with the operation. - :type display: ~azure.mgmt.policyinsights.models.OperationDisplay + :ivar name: Operation name. + :vartype name: str + :ivar display: Display metadata associated with the operation. + :vartype display: ~azure.mgmt.policyinsights.models.OperationDisplay """ _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'display': {'key': 'display', 'type': 'OperationDisplay'}, - } - - def __init__( - self, - *, - name: Optional[str] = None, - display: Optional["OperationDisplay"] = None, - **kwargs - ): - super(Operation, self).__init__(**kwargs) + "name": {"key": "name", "type": "str"}, + "display": {"key": "display", "type": "OperationDisplay"}, + } + + def __init__(self, *, name: Optional[str] = None, display: Optional["_models.OperationDisplay"] = None, **kwargs): + """ + :keyword name: Operation name. + :paramtype name: str + :keyword display: Display metadata associated with the operation. + :paramtype display: ~azure.mgmt.policyinsights.models.OperationDisplay + """ + super().__init__(**kwargs) self.name = name self.display = display -class OperationDisplay(msrest.serialization.Model): +class OperationDisplay(_serialization.Model): """Display metadata associated with the operation. - :param provider: Resource provider name. - :type provider: str - :param resource: Resource name on which the operation is performed. - :type resource: str - :param operation: Operation name. - :type operation: str - :param description: Operation description. - :type description: str + :ivar provider: Resource provider name. + :vartype provider: str + :ivar resource: Resource name on which the operation is performed. + :vartype resource: str + :ivar operation: Operation name. + :vartype operation: str + :ivar description: Operation description. + :vartype description: str """ _attribute_map = { - 'provider': {'key': 'provider', 'type': 'str'}, - 'resource': {'key': 'resource', 'type': 'str'}, - 'operation': {'key': 'operation', 'type': 'str'}, - 'description': {'key': 'description', 'type': 'str'}, + "provider": {"key": "provider", "type": "str"}, + "resource": {"key": "resource", "type": "str"}, + "operation": {"key": "operation", "type": "str"}, + "description": {"key": "description", "type": "str"}, } def __init__( @@ -871,99 +996,113 @@ def __init__( description: Optional[str] = None, **kwargs ): - super(OperationDisplay, self).__init__(**kwargs) + """ + :keyword provider: Resource provider name. + :paramtype provider: str + :keyword resource: Resource name on which the operation is performed. + :paramtype resource: str + :keyword operation: Operation name. + :paramtype operation: str + :keyword description: Operation description. + :paramtype description: str + """ + super().__init__(**kwargs) self.provider = provider self.resource = resource self.operation = operation self.description = description -class OperationsListResults(msrest.serialization.Model): +class OperationsListResults(_serialization.Model): """List of available operations. - :param odata_count: OData entity count; represents the number of operations returned. - :type odata_count: int - :param value: List of available operations. - :type value: list[~azure.mgmt.policyinsights.models.Operation] + :ivar odata_count: OData entity count; represents the number of operations returned. + :vartype odata_count: int + :ivar value: List of available operations. + :vartype value: list[~azure.mgmt.policyinsights.models.Operation] """ _validation = { - 'odata_count': {'minimum': 1}, + "odata_count": {"minimum": 1}, } _attribute_map = { - 'odata_count': {'key': '@odata\\.count', 'type': 'int'}, - 'value': {'key': 'value', 'type': '[Operation]'}, + "odata_count": {"key": "@odata\\.count", "type": "int"}, + "value": {"key": "value", "type": "[Operation]"}, } def __init__( - self, - *, - odata_count: Optional[int] = None, - value: Optional[List["Operation"]] = None, - **kwargs + self, *, odata_count: Optional[int] = None, value: Optional[List["_models.Operation"]] = None, **kwargs ): - super(OperationsListResults, self).__init__(**kwargs) + """ + :keyword odata_count: OData entity count; represents the number of operations returned. + :paramtype odata_count: int + :keyword value: List of available operations. + :paramtype value: list[~azure.mgmt.policyinsights.models.Operation] + """ + super().__init__(**kwargs) self.odata_count = odata_count self.value = value -class PendingField(msrest.serialization.Model): +class PendingField(_serialization.Model): """A field that should be evaluated against Azure Policy to determine restrictions. All required parameters must be populated in order to send to Azure. - :param field: Required. The name of the field. This can be a top-level property like 'name' or - 'type' or an Azure Policy field alias. - :type field: str - :param values: The list of potential values for the field that should be evaluated against - Azure Policy. - :type values: list[str] + :ivar field: The name of the field. This can be a top-level property like 'name' or 'type' or + an Azure Policy field alias. Required. + :vartype field: str + :ivar values: The list of potential values for the field that should be evaluated against Azure + Policy. + :vartype values: list[str] """ _validation = { - 'field': {'required': True}, + "field": {"required": True}, } _attribute_map = { - 'field': {'key': 'field', 'type': 'str'}, - 'values': {'key': 'values', 'type': '[str]'}, - } - - def __init__( - self, - *, - field: str, - values: Optional[List[str]] = None, - **kwargs - ): - super(PendingField, self).__init__(**kwargs) + "field": {"key": "field", "type": "str"}, + "values": {"key": "values", "type": "[str]"}, + } + + def __init__(self, *, field: str, values: Optional[List[str]] = None, **kwargs): + """ + :keyword field: The name of the field. This can be a top-level property like 'name' or 'type' + or an Azure Policy field alias. Required. + :paramtype field: str + :keyword values: The list of potential values for the field that should be evaluated against + Azure Policy. + :paramtype values: list[str] + """ + super().__init__(**kwargs) self.field = field self.values = values -class PolicyAssignmentSummary(msrest.serialization.Model): +class PolicyAssignmentSummary(_serialization.Model): """Policy assignment summary. - :param policy_assignment_id: Policy assignment ID. - :type policy_assignment_id: str - :param policy_set_definition_id: Policy set definition ID, if the policy assignment is for a + :ivar policy_assignment_id: Policy assignment ID. + :vartype policy_assignment_id: str + :ivar policy_set_definition_id: Policy set definition ID, if the policy assignment is for a policy set. - :type policy_set_definition_id: str - :param results: Compliance summary for the policy assignment. - :type results: ~azure.mgmt.policyinsights.models.SummaryResults - :param policy_definitions: Policy definitions summary. - :type policy_definitions: list[~azure.mgmt.policyinsights.models.PolicyDefinitionSummary] - :param policy_groups: Policy definition group summary. - :type policy_groups: list[~azure.mgmt.policyinsights.models.PolicyGroupSummary] + :vartype policy_set_definition_id: str + :ivar results: Compliance summary for the policy assignment. + :vartype results: ~azure.mgmt.policyinsights.models.SummaryResults + :ivar policy_definitions: Policy definitions summary. + :vartype policy_definitions: list[~azure.mgmt.policyinsights.models.PolicyDefinitionSummary] + :ivar policy_groups: Policy definition group summary. + :vartype policy_groups: list[~azure.mgmt.policyinsights.models.PolicyGroupSummary] """ _attribute_map = { - 'policy_assignment_id': {'key': 'policyAssignmentId', 'type': 'str'}, - 'policy_set_definition_id': {'key': 'policySetDefinitionId', 'type': 'str'}, - 'results': {'key': 'results', 'type': 'SummaryResults'}, - 'policy_definitions': {'key': 'policyDefinitions', 'type': '[PolicyDefinitionSummary]'}, - 'policy_groups': {'key': 'policyGroups', 'type': '[PolicyGroupSummary]'}, + "policy_assignment_id": {"key": "policyAssignmentId", "type": "str"}, + "policy_set_definition_id": {"key": "policySetDefinitionId", "type": "str"}, + "results": {"key": "results", "type": "SummaryResults"}, + "policy_definitions": {"key": "policyDefinitions", "type": "[PolicyDefinitionSummary]"}, + "policy_groups": {"key": "policyGroups", "type": "[PolicyGroupSummary]"}, } def __init__( @@ -971,12 +1110,25 @@ def __init__( *, policy_assignment_id: Optional[str] = None, policy_set_definition_id: Optional[str] = None, - results: Optional["SummaryResults"] = None, - policy_definitions: Optional[List["PolicyDefinitionSummary"]] = None, - policy_groups: Optional[List["PolicyGroupSummary"]] = None, + results: Optional["_models.SummaryResults"] = None, + policy_definitions: Optional[List["_models.PolicyDefinitionSummary"]] = None, + policy_groups: Optional[List["_models.PolicyGroupSummary"]] = None, **kwargs ): - super(PolicyAssignmentSummary, self).__init__(**kwargs) + """ + :keyword policy_assignment_id: Policy assignment ID. + :paramtype policy_assignment_id: str + :keyword policy_set_definition_id: Policy set definition ID, if the policy assignment is for a + policy set. + :paramtype policy_set_definition_id: str + :keyword results: Compliance summary for the policy assignment. + :paramtype results: ~azure.mgmt.policyinsights.models.SummaryResults + :keyword policy_definitions: Policy definitions summary. + :paramtype policy_definitions: list[~azure.mgmt.policyinsights.models.PolicyDefinitionSummary] + :keyword policy_groups: Policy definition group summary. + :paramtype policy_groups: list[~azure.mgmt.policyinsights.models.PolicyGroupSummary] + """ + super().__init__(**kwargs) self.policy_assignment_id = policy_assignment_id self.policy_set_definition_id = policy_set_definition_id self.results = results @@ -984,27 +1136,27 @@ def __init__( self.policy_groups = policy_groups -class PolicyDefinitionSummary(msrest.serialization.Model): +class PolicyDefinitionSummary(_serialization.Model): """Policy definition summary. - :param policy_definition_id: Policy definition ID. - :type policy_definition_id: str - :param policy_definition_reference_id: Policy definition reference ID. - :type policy_definition_reference_id: str - :param policy_definition_group_names: Policy definition group names. - :type policy_definition_group_names: list[str] - :param effect: Policy effect, i.e. policy definition action. - :type effect: str - :param results: Compliance summary for the policy definition. - :type results: ~azure.mgmt.policyinsights.models.SummaryResults + :ivar policy_definition_id: Policy definition ID. + :vartype policy_definition_id: str + :ivar policy_definition_reference_id: Policy definition reference ID. + :vartype policy_definition_reference_id: str + :ivar policy_definition_group_names: Policy definition group names. + :vartype policy_definition_group_names: list[str] + :ivar effect: Policy effect, i.e. policy definition action. + :vartype effect: str + :ivar results: Compliance summary for the policy definition. + :vartype results: ~azure.mgmt.policyinsights.models.SummaryResults """ _attribute_map = { - 'policy_definition_id': {'key': 'policyDefinitionId', 'type': 'str'}, - 'policy_definition_reference_id': {'key': 'policyDefinitionReferenceId', 'type': 'str'}, - 'policy_definition_group_names': {'key': 'policyDefinitionGroupNames', 'type': '[str]'}, - 'effect': {'key': 'effect', 'type': 'str'}, - 'results': {'key': 'results', 'type': 'SummaryResults'}, + "policy_definition_id": {"key": "policyDefinitionId", "type": "str"}, + "policy_definition_reference_id": {"key": "policyDefinitionReferenceId", "type": "str"}, + "policy_definition_group_names": {"key": "policyDefinitionGroupNames", "type": "[str]"}, + "effect": {"key": "effect", "type": "str"}, + "results": {"key": "results", "type": "SummaryResults"}, } def __init__( @@ -1014,10 +1166,22 @@ def __init__( policy_definition_reference_id: Optional[str] = None, policy_definition_group_names: Optional[List[str]] = None, effect: Optional[str] = None, - results: Optional["SummaryResults"] = None, + results: Optional["_models.SummaryResults"] = None, **kwargs ): - super(PolicyDefinitionSummary, self).__init__(**kwargs) + """ + :keyword policy_definition_id: Policy definition ID. + :paramtype policy_definition_id: str + :keyword policy_definition_reference_id: Policy definition reference ID. + :paramtype policy_definition_reference_id: str + :keyword policy_definition_group_names: Policy definition group names. + :paramtype policy_definition_group_names: list[str] + :keyword effect: Policy effect, i.e. policy definition action. + :paramtype effect: str + :keyword results: Compliance summary for the policy definition. + :paramtype results: ~azure.mgmt.policyinsights.models.SummaryResults + """ + super().__init__(**kwargs) self.policy_definition_id = policy_definition_id self.policy_definition_reference_id = policy_definition_reference_id self.policy_definition_group_names = policy_definition_group_names @@ -1025,7 +1189,7 @@ def __init__( self.results = results -class PolicyDetails(msrest.serialization.Model): +class PolicyDetails(_serialization.Model): """The policy details. Variables are only populated by the server, and will be ignored when sending a request. @@ -1046,28 +1210,26 @@ class PolicyDetails(msrest.serialization.Model): """ _validation = { - 'policy_definition_id': {'readonly': True}, - 'policy_assignment_id': {'readonly': True}, - 'policy_assignment_display_name': {'readonly': True}, - 'policy_assignment_scope': {'readonly': True}, - 'policy_set_definition_id': {'readonly': True}, - 'policy_definition_reference_id': {'readonly': True}, + "policy_definition_id": {"readonly": True}, + "policy_assignment_id": {"readonly": True}, + "policy_assignment_display_name": {"readonly": True}, + "policy_assignment_scope": {"readonly": True}, + "policy_set_definition_id": {"readonly": True}, + "policy_definition_reference_id": {"readonly": True}, } _attribute_map = { - 'policy_definition_id': {'key': 'policyDefinitionId', 'type': 'str'}, - 'policy_assignment_id': {'key': 'policyAssignmentId', 'type': 'str'}, - 'policy_assignment_display_name': {'key': 'policyAssignmentDisplayName', 'type': 'str'}, - 'policy_assignment_scope': {'key': 'policyAssignmentScope', 'type': 'str'}, - 'policy_set_definition_id': {'key': 'policySetDefinitionId', 'type': 'str'}, - 'policy_definition_reference_id': {'key': 'policyDefinitionReferenceId', 'type': 'str'}, + "policy_definition_id": {"key": "policyDefinitionId", "type": "str"}, + "policy_assignment_id": {"key": "policyAssignmentId", "type": "str"}, + "policy_assignment_display_name": {"key": "policyAssignmentDisplayName", "type": "str"}, + "policy_assignment_scope": {"key": "policyAssignmentScope", "type": "str"}, + "policy_set_definition_id": {"key": "policySetDefinitionId", "type": "str"}, + "policy_definition_reference_id": {"key": "policyDefinitionReferenceId", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(PolicyDetails, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.policy_definition_id = None self.policy_assignment_id = None self.policy_assignment_display_name = None @@ -1076,34 +1238,42 @@ def __init__( self.policy_definition_reference_id = None -class PolicyEvaluationDetails(msrest.serialization.Model): +class PolicyEvaluationDetails(_serialization.Model): """Policy evaluation details. - :param evaluated_expressions: Details of the evaluated expressions. - :type evaluated_expressions: + :ivar evaluated_expressions: Details of the evaluated expressions. + :vartype evaluated_expressions: list[~azure.mgmt.policyinsights.models.ExpressionEvaluationDetails] - :param if_not_exists_details: Evaluation details of IfNotExists effect. - :type if_not_exists_details: ~azure.mgmt.policyinsights.models.IfNotExistsEvaluationDetails + :ivar if_not_exists_details: Evaluation details of IfNotExists effect. + :vartype if_not_exists_details: ~azure.mgmt.policyinsights.models.IfNotExistsEvaluationDetails """ _attribute_map = { - 'evaluated_expressions': {'key': 'evaluatedExpressions', 'type': '[ExpressionEvaluationDetails]'}, - 'if_not_exists_details': {'key': 'ifNotExistsDetails', 'type': 'IfNotExistsEvaluationDetails'}, + "evaluated_expressions": {"key": "evaluatedExpressions", "type": "[ExpressionEvaluationDetails]"}, + "if_not_exists_details": {"key": "ifNotExistsDetails", "type": "IfNotExistsEvaluationDetails"}, } def __init__( self, *, - evaluated_expressions: Optional[List["ExpressionEvaluationDetails"]] = None, - if_not_exists_details: Optional["IfNotExistsEvaluationDetails"] = None, + evaluated_expressions: Optional[List["_models.ExpressionEvaluationDetails"]] = None, + if_not_exists_details: Optional["_models.IfNotExistsEvaluationDetails"] = None, **kwargs ): - super(PolicyEvaluationDetails, self).__init__(**kwargs) + """ + :keyword evaluated_expressions: Details of the evaluated expressions. + :paramtype evaluated_expressions: + list[~azure.mgmt.policyinsights.models.ExpressionEvaluationDetails] + :keyword if_not_exists_details: Evaluation details of IfNotExists effect. + :paramtype if_not_exists_details: + ~azure.mgmt.policyinsights.models.IfNotExistsEvaluationDetails + """ + super().__init__(**kwargs) self.evaluated_expressions = evaluated_expressions self.if_not_exists_details = if_not_exists_details -class PolicyEvaluationResult(msrest.serialization.Model): +class PolicyEvaluationResult(_serialization.Model): """The result of a non-compliant policy evaluation against the given resource content. Variables are only populated by the server, and will be ignored when sending a request. @@ -1119,145 +1289,143 @@ class PolicyEvaluationResult(msrest.serialization.Model): """ _validation = { - 'policy_info': {'readonly': True}, - 'evaluation_result': {'readonly': True}, - 'evaluation_details': {'readonly': True}, + "policy_info": {"readonly": True}, + "evaluation_result": {"readonly": True}, + "evaluation_details": {"readonly": True}, } _attribute_map = { - 'policy_info': {'key': 'policyInfo', 'type': 'PolicyReference'}, - 'evaluation_result': {'key': 'evaluationResult', 'type': 'str'}, - 'evaluation_details': {'key': 'evaluationDetails', 'type': 'PolicyEvaluationDetails'}, + "policy_info": {"key": "policyInfo", "type": "PolicyReference"}, + "evaluation_result": {"key": "evaluationResult", "type": "str"}, + "evaluation_details": {"key": "evaluationDetails", "type": "PolicyEvaluationDetails"}, } - def __init__( - self, - **kwargs - ): - super(PolicyEvaluationResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.policy_info = None self.evaluation_result = None self.evaluation_details = None -class PolicyEvent(msrest.serialization.Model): +class PolicyEvent(_serialization.Model): # pylint: disable=too-many-instance-attributes """Policy event record. - :param additional_properties: Unmatched properties from the message are deserialized to this + :ivar additional_properties: Unmatched properties from the message are deserialized to this collection. - :type additional_properties: dict[str, any] - :param odata_id: OData entity ID; always set to null since policy event records do not have an + :vartype additional_properties: dict[str, any] + :ivar odata_id: OData entity ID; always set to null since policy event records do not have an entity ID. - :type odata_id: str - :param odata_context: OData context string; used by OData clients to resolve type information + :vartype odata_id: str + :ivar odata_context: OData context string; used by OData clients to resolve type information based on metadata. - :type odata_context: str - :param timestamp: Timestamp for the policy event record. - :type timestamp: ~datetime.datetime - :param resource_id: Resource ID. - :type resource_id: str - :param policy_assignment_id: Policy assignment ID. - :type policy_assignment_id: str - :param policy_definition_id: Policy definition ID. - :type policy_definition_id: str - :param effective_parameters: Effective parameters for the policy assignment. - :type effective_parameters: str - :param is_compliant: Flag which states whether the resource is compliant against the policy + :vartype odata_context: str + :ivar timestamp: Timestamp for the policy event record. + :vartype timestamp: ~datetime.datetime + :ivar resource_id: Resource ID. + :vartype resource_id: str + :ivar policy_assignment_id: Policy assignment ID. + :vartype policy_assignment_id: str + :ivar policy_definition_id: Policy definition ID. + :vartype policy_definition_id: str + :ivar effective_parameters: Effective parameters for the policy assignment. + :vartype effective_parameters: str + :ivar is_compliant: Flag which states whether the resource is compliant against the policy assignment it was evaluated against. - :type is_compliant: bool - :param subscription_id: Subscription ID. - :type subscription_id: str - :param resource_type: Resource type. - :type resource_type: str - :param resource_location: Resource location. - :type resource_location: str - :param resource_group: Resource group name. - :type resource_group: str - :param resource_tags: List of resource tags. - :type resource_tags: str - :param policy_assignment_name: Policy assignment name. - :type policy_assignment_name: str - :param policy_assignment_owner: Policy assignment owner. - :type policy_assignment_owner: str - :param policy_assignment_parameters: Policy assignment parameters. - :type policy_assignment_parameters: str - :param policy_assignment_scope: Policy assignment scope. - :type policy_assignment_scope: str - :param policy_definition_name: Policy definition name. - :type policy_definition_name: str - :param policy_definition_action: Policy definition action, i.e. effect. - :type policy_definition_action: str - :param policy_definition_category: Policy definition category. - :type policy_definition_category: str - :param policy_set_definition_id: Policy set definition ID, if the policy assignment is for a + :vartype is_compliant: bool + :ivar subscription_id: Subscription ID. + :vartype subscription_id: str + :ivar resource_type: Resource type. + :vartype resource_type: str + :ivar resource_location: Resource location. + :vartype resource_location: str + :ivar resource_group: Resource group name. + :vartype resource_group: str + :ivar resource_tags: List of resource tags. + :vartype resource_tags: str + :ivar policy_assignment_name: Policy assignment name. + :vartype policy_assignment_name: str + :ivar policy_assignment_owner: Policy assignment owner. + :vartype policy_assignment_owner: str + :ivar policy_assignment_parameters: Policy assignment parameters. + :vartype policy_assignment_parameters: str + :ivar policy_assignment_scope: Policy assignment scope. + :vartype policy_assignment_scope: str + :ivar policy_definition_name: Policy definition name. + :vartype policy_definition_name: str + :ivar policy_definition_action: Policy definition action, i.e. effect. + :vartype policy_definition_action: str + :ivar policy_definition_category: Policy definition category. + :vartype policy_definition_category: str + :ivar policy_set_definition_id: Policy set definition ID, if the policy assignment is for a + policy set. + :vartype policy_set_definition_id: str + :ivar policy_set_definition_name: Policy set definition name, if the policy assignment is for a policy set. - :type policy_set_definition_id: str - :param policy_set_definition_name: Policy set definition name, if the policy assignment is for + :vartype policy_set_definition_name: str + :ivar policy_set_definition_owner: Policy set definition owner, if the policy assignment is for a policy set. - :type policy_set_definition_name: str - :param policy_set_definition_owner: Policy set definition owner, if the policy assignment is - for a policy set. - :type policy_set_definition_owner: str - :param policy_set_definition_category: Policy set definition category, if the policy assignment + :vartype policy_set_definition_owner: str + :ivar policy_set_definition_category: Policy set definition category, if the policy assignment is for a policy set. - :type policy_set_definition_category: str - :param policy_set_definition_parameters: Policy set definition parameters, if the policy + :vartype policy_set_definition_category: str + :ivar policy_set_definition_parameters: Policy set definition parameters, if the policy assignment is for a policy set. - :type policy_set_definition_parameters: str - :param management_group_ids: Comma separated list of management group IDs, which represent the + :vartype policy_set_definition_parameters: str + :ivar management_group_ids: Comma separated list of management group IDs, which represent the hierarchy of the management groups the resource is under. - :type management_group_ids: str - :param policy_definition_reference_id: Reference ID for the policy definition inside the policy + :vartype management_group_ids: str + :ivar policy_definition_reference_id: Reference ID for the policy definition inside the policy set, if the policy assignment is for a policy set. - :type policy_definition_reference_id: str - :param compliance_state: Compliance state of the resource. - :type compliance_state: str - :param tenant_id: Tenant ID for the policy event record. - :type tenant_id: str - :param principal_oid: Principal object ID for the user who initiated the resource operation - that triggered the policy event. - :type principal_oid: str - :param components: Components events records populated only when URL contains - $expand=components clause. - :type components: list[~azure.mgmt.policyinsights.models.ComponentEventDetails] + :vartype policy_definition_reference_id: str + :ivar compliance_state: Compliance state of the resource. + :vartype compliance_state: str + :ivar tenant_id: Tenant ID for the policy event record. + :vartype tenant_id: str + :ivar principal_oid: Principal object ID for the user who initiated the resource operation that + triggered the policy event. + :vartype principal_oid: str + :ivar components: Components events records populated only when URL contains $expand=components + clause. + :vartype components: list[~azure.mgmt.policyinsights.models.ComponentEventDetails] """ _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'odata_id': {'key': '@odata\\.id', 'type': 'str'}, - 'odata_context': {'key': '@odata\\.context', 'type': 'str'}, - 'timestamp': {'key': 'timestamp', 'type': 'iso-8601'}, - 'resource_id': {'key': 'resourceId', 'type': 'str'}, - 'policy_assignment_id': {'key': 'policyAssignmentId', 'type': 'str'}, - 'policy_definition_id': {'key': 'policyDefinitionId', 'type': 'str'}, - 'effective_parameters': {'key': 'effectiveParameters', 'type': 'str'}, - 'is_compliant': {'key': 'isCompliant', 'type': 'bool'}, - 'subscription_id': {'key': 'subscriptionId', 'type': 'str'}, - 'resource_type': {'key': 'resourceType', 'type': 'str'}, - 'resource_location': {'key': 'resourceLocation', 'type': 'str'}, - 'resource_group': {'key': 'resourceGroup', 'type': 'str'}, - 'resource_tags': {'key': 'resourceTags', 'type': 'str'}, - 'policy_assignment_name': {'key': 'policyAssignmentName', 'type': 'str'}, - 'policy_assignment_owner': {'key': 'policyAssignmentOwner', 'type': 'str'}, - 'policy_assignment_parameters': {'key': 'policyAssignmentParameters', 'type': 'str'}, - 'policy_assignment_scope': {'key': 'policyAssignmentScope', 'type': 'str'}, - 'policy_definition_name': {'key': 'policyDefinitionName', 'type': 'str'}, - 'policy_definition_action': {'key': 'policyDefinitionAction', 'type': 'str'}, - 'policy_definition_category': {'key': 'policyDefinitionCategory', 'type': 'str'}, - 'policy_set_definition_id': {'key': 'policySetDefinitionId', 'type': 'str'}, - 'policy_set_definition_name': {'key': 'policySetDefinitionName', 'type': 'str'}, - 'policy_set_definition_owner': {'key': 'policySetDefinitionOwner', 'type': 'str'}, - 'policy_set_definition_category': {'key': 'policySetDefinitionCategory', 'type': 'str'}, - 'policy_set_definition_parameters': {'key': 'policySetDefinitionParameters', 'type': 'str'}, - 'management_group_ids': {'key': 'managementGroupIds', 'type': 'str'}, - 'policy_definition_reference_id': {'key': 'policyDefinitionReferenceId', 'type': 'str'}, - 'compliance_state': {'key': 'complianceState', 'type': 'str'}, - 'tenant_id': {'key': 'tenantId', 'type': 'str'}, - 'principal_oid': {'key': 'principalOid', 'type': 'str'}, - 'components': {'key': 'components', 'type': '[ComponentEventDetails]'}, - } - - def __init__( + "additional_properties": {"key": "", "type": "{object}"}, + "odata_id": {"key": "@odata\\.id", "type": "str"}, + "odata_context": {"key": "@odata\\.context", "type": "str"}, + "timestamp": {"key": "timestamp", "type": "iso-8601"}, + "resource_id": {"key": "resourceId", "type": "str"}, + "policy_assignment_id": {"key": "policyAssignmentId", "type": "str"}, + "policy_definition_id": {"key": "policyDefinitionId", "type": "str"}, + "effective_parameters": {"key": "effectiveParameters", "type": "str"}, + "is_compliant": {"key": "isCompliant", "type": "bool"}, + "subscription_id": {"key": "subscriptionId", "type": "str"}, + "resource_type": {"key": "resourceType", "type": "str"}, + "resource_location": {"key": "resourceLocation", "type": "str"}, + "resource_group": {"key": "resourceGroup", "type": "str"}, + "resource_tags": {"key": "resourceTags", "type": "str"}, + "policy_assignment_name": {"key": "policyAssignmentName", "type": "str"}, + "policy_assignment_owner": {"key": "policyAssignmentOwner", "type": "str"}, + "policy_assignment_parameters": {"key": "policyAssignmentParameters", "type": "str"}, + "policy_assignment_scope": {"key": "policyAssignmentScope", "type": "str"}, + "policy_definition_name": {"key": "policyDefinitionName", "type": "str"}, + "policy_definition_action": {"key": "policyDefinitionAction", "type": "str"}, + "policy_definition_category": {"key": "policyDefinitionCategory", "type": "str"}, + "policy_set_definition_id": {"key": "policySetDefinitionId", "type": "str"}, + "policy_set_definition_name": {"key": "policySetDefinitionName", "type": "str"}, + "policy_set_definition_owner": {"key": "policySetDefinitionOwner", "type": "str"}, + "policy_set_definition_category": {"key": "policySetDefinitionCategory", "type": "str"}, + "policy_set_definition_parameters": {"key": "policySetDefinitionParameters", "type": "str"}, + "management_group_ids": {"key": "managementGroupIds", "type": "str"}, + "policy_definition_reference_id": {"key": "policyDefinitionReferenceId", "type": "str"}, + "compliance_state": {"key": "complianceState", "type": "str"}, + "tenant_id": {"key": "tenantId", "type": "str"}, + "principal_oid": {"key": "principalOid", "type": "str"}, + "components": {"key": "components", "type": "[ComponentEventDetails]"}, + } + + def __init__( # pylint: disable=too-many-locals self, *, additional_properties: Optional[Dict[str, Any]] = None, @@ -1291,10 +1459,89 @@ def __init__( compliance_state: Optional[str] = None, tenant_id: Optional[str] = None, principal_oid: Optional[str] = None, - components: Optional[List["ComponentEventDetails"]] = None, + components: Optional[List["_models.ComponentEventDetails"]] = None, **kwargs ): - super(PolicyEvent, self).__init__(**kwargs) + """ + :keyword additional_properties: Unmatched properties from the message are deserialized to this + collection. + :paramtype additional_properties: dict[str, any] + :keyword odata_id: OData entity ID; always set to null since policy event records do not have + an entity ID. + :paramtype odata_id: str + :keyword odata_context: OData context string; used by OData clients to resolve type information + based on metadata. + :paramtype odata_context: str + :keyword timestamp: Timestamp for the policy event record. + :paramtype timestamp: ~datetime.datetime + :keyword resource_id: Resource ID. + :paramtype resource_id: str + :keyword policy_assignment_id: Policy assignment ID. + :paramtype policy_assignment_id: str + :keyword policy_definition_id: Policy definition ID. + :paramtype policy_definition_id: str + :keyword effective_parameters: Effective parameters for the policy assignment. + :paramtype effective_parameters: str + :keyword is_compliant: Flag which states whether the resource is compliant against the policy + assignment it was evaluated against. + :paramtype is_compliant: bool + :keyword subscription_id: Subscription ID. + :paramtype subscription_id: str + :keyword resource_type: Resource type. + :paramtype resource_type: str + :keyword resource_location: Resource location. + :paramtype resource_location: str + :keyword resource_group: Resource group name. + :paramtype resource_group: str + :keyword resource_tags: List of resource tags. + :paramtype resource_tags: str + :keyword policy_assignment_name: Policy assignment name. + :paramtype policy_assignment_name: str + :keyword policy_assignment_owner: Policy assignment owner. + :paramtype policy_assignment_owner: str + :keyword policy_assignment_parameters: Policy assignment parameters. + :paramtype policy_assignment_parameters: str + :keyword policy_assignment_scope: Policy assignment scope. + :paramtype policy_assignment_scope: str + :keyword policy_definition_name: Policy definition name. + :paramtype policy_definition_name: str + :keyword policy_definition_action: Policy definition action, i.e. effect. + :paramtype policy_definition_action: str + :keyword policy_definition_category: Policy definition category. + :paramtype policy_definition_category: str + :keyword policy_set_definition_id: Policy set definition ID, if the policy assignment is for a + policy set. + :paramtype policy_set_definition_id: str + :keyword policy_set_definition_name: Policy set definition name, if the policy assignment is + for a policy set. + :paramtype policy_set_definition_name: str + :keyword policy_set_definition_owner: Policy set definition owner, if the policy assignment is + for a policy set. + :paramtype policy_set_definition_owner: str + :keyword policy_set_definition_category: Policy set definition category, if the policy + assignment is for a policy set. + :paramtype policy_set_definition_category: str + :keyword policy_set_definition_parameters: Policy set definition parameters, if the policy + assignment is for a policy set. + :paramtype policy_set_definition_parameters: str + :keyword management_group_ids: Comma separated list of management group IDs, which represent + the hierarchy of the management groups the resource is under. + :paramtype management_group_ids: str + :keyword policy_definition_reference_id: Reference ID for the policy definition inside the + policy set, if the policy assignment is for a policy set. + :paramtype policy_definition_reference_id: str + :keyword compliance_state: Compliance state of the resource. + :paramtype compliance_state: str + :keyword tenant_id: Tenant ID for the policy event record. + :paramtype tenant_id: str + :keyword principal_oid: Principal object ID for the user who initiated the resource operation + that triggered the policy event. + :paramtype principal_oid: str + :keyword components: Components events records populated only when URL contains + $expand=components clause. + :paramtype components: list[~azure.mgmt.policyinsights.models.ComponentEventDetails] + """ + super().__init__(**kwargs) self.additional_properties = additional_properties self.odata_id = odata_id self.odata_context = odata_context @@ -1329,29 +1576,29 @@ def __init__( self.components = components -class PolicyEventsQueryResults(msrest.serialization.Model): +class PolicyEventsQueryResults(_serialization.Model): """Query results. - :param odata_context: OData context string; used by OData clients to resolve type information + :ivar odata_context: OData context string; used by OData clients to resolve type information based on metadata. - :type odata_context: str - :param odata_count: OData entity count; represents the number of policy event records returned. - :type odata_count: int - :param odata_next_link: Odata next link; URL to get the next set of results. - :type odata_next_link: str - :param value: Query results. - :type value: list[~azure.mgmt.policyinsights.models.PolicyEvent] + :vartype odata_context: str + :ivar odata_count: OData entity count; represents the number of policy event records returned. + :vartype odata_count: int + :ivar odata_next_link: Odata next link; URL to get the next set of results. + :vartype odata_next_link: str + :ivar value: Query results. + :vartype value: list[~azure.mgmt.policyinsights.models.PolicyEvent] """ _validation = { - 'odata_count': {'minimum': 0}, + "odata_count": {"minimum": 0}, } _attribute_map = { - 'odata_context': {'key': '@odata\\.context', 'type': 'str'}, - 'odata_count': {'key': '@odata\\.count', 'type': 'int'}, - 'odata_next_link': {'key': '@odata\\.nextLink', 'type': 'str'}, - 'value': {'key': 'value', 'type': '[PolicyEvent]'}, + "odata_context": {"key": "@odata\\.context", "type": "str"}, + "odata_count": {"key": "@odata\\.count", "type": "int"}, + "odata_next_link": {"key": "@odata\\.nextLink", "type": "str"}, + "value": {"key": "value", "type": "[PolicyEvent]"}, } def __init__( @@ -1360,43 +1607,57 @@ def __init__( odata_context: Optional[str] = None, odata_count: Optional[int] = None, odata_next_link: Optional[str] = None, - value: Optional[List["PolicyEvent"]] = None, + value: Optional[List["_models.PolicyEvent"]] = None, **kwargs ): - super(PolicyEventsQueryResults, self).__init__(**kwargs) + """ + :keyword odata_context: OData context string; used by OData clients to resolve type information + based on metadata. + :paramtype odata_context: str + :keyword odata_count: OData entity count; represents the number of policy event records + returned. + :paramtype odata_count: int + :keyword odata_next_link: Odata next link; URL to get the next set of results. + :paramtype odata_next_link: str + :keyword value: Query results. + :paramtype value: list[~azure.mgmt.policyinsights.models.PolicyEvent] + """ + super().__init__(**kwargs) self.odata_context = odata_context self.odata_count = odata_count self.odata_next_link = odata_next_link self.value = value -class PolicyGroupSummary(msrest.serialization.Model): +class PolicyGroupSummary(_serialization.Model): """Policy definition group summary. - :param policy_group_name: Policy group name. - :type policy_group_name: str - :param results: Compliance summary for the policy definition group. - :type results: ~azure.mgmt.policyinsights.models.SummaryResults + :ivar policy_group_name: Policy group name. + :vartype policy_group_name: str + :ivar results: Compliance summary for the policy definition group. + :vartype results: ~azure.mgmt.policyinsights.models.SummaryResults """ _attribute_map = { - 'policy_group_name': {'key': 'policyGroupName', 'type': 'str'}, - 'results': {'key': 'results', 'type': 'SummaryResults'}, + "policy_group_name": {"key": "policyGroupName", "type": "str"}, + "results": {"key": "results", "type": "SummaryResults"}, } def __init__( - self, - *, - policy_group_name: Optional[str] = None, - results: Optional["SummaryResults"] = None, - **kwargs + self, *, policy_group_name: Optional[str] = None, results: Optional["_models.SummaryResults"] = None, **kwargs ): - super(PolicyGroupSummary, self).__init__(**kwargs) + """ + :keyword policy_group_name: Policy group name. + :paramtype policy_group_name: str + :keyword results: Compliance summary for the policy definition group. + :paramtype results: ~azure.mgmt.policyinsights.models.SummaryResults + """ + super().__init__(**kwargs) self.policy_group_name = policy_group_name self.results = results -class PolicyMetadata(msrest.serialization.Model): +class PolicyMetadata(_serialization.Model): # pylint: disable=too-many-instance-attributes """Policy metadata resource definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -1418,7 +1679,7 @@ class PolicyMetadata(msrest.serialization.Model): :ivar additional_content_url: Url for getting additional content about the resource metadata. :vartype additional_content_url: str :ivar metadata: Additional metadata. - :vartype metadata: any + :vartype metadata: JSON :ivar description: The description of the policy metadata. :vartype description: str :ivar requirements: The requirements of the policy metadata. @@ -1426,38 +1687,36 @@ class PolicyMetadata(msrest.serialization.Model): """ _validation = { - 'id': {'readonly': True}, - 'type': {'readonly': True}, - 'name': {'readonly': True}, - 'metadata_id': {'readonly': True}, - 'category': {'readonly': True}, - 'title': {'readonly': True}, - 'owner': {'readonly': True}, - 'additional_content_url': {'readonly': True}, - 'metadata': {'readonly': True}, - 'description': {'readonly': True}, - 'requirements': {'readonly': True}, + "id": {"readonly": True}, + "type": {"readonly": True}, + "name": {"readonly": True}, + "metadata_id": {"readonly": True}, + "category": {"readonly": True}, + "title": {"readonly": True}, + "owner": {"readonly": True}, + "additional_content_url": {"readonly": True}, + "metadata": {"readonly": True}, + "description": {"readonly": True}, + "requirements": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'metadata_id': {'key': 'properties.metadataId', 'type': 'str'}, - 'category': {'key': 'properties.category', 'type': 'str'}, - 'title': {'key': 'properties.title', 'type': 'str'}, - 'owner': {'key': 'properties.owner', 'type': 'str'}, - 'additional_content_url': {'key': 'properties.additionalContentUrl', 'type': 'str'}, - 'metadata': {'key': 'properties.metadata', 'type': 'object'}, - 'description': {'key': 'properties.description', 'type': 'str'}, - 'requirements': {'key': 'properties.requirements', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyMetadata, self).__init__(**kwargs) + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "metadata_id": {"key": "properties.metadataId", "type": "str"}, + "category": {"key": "properties.category", "type": "str"}, + "title": {"key": "properties.title", "type": "str"}, + "owner": {"key": "properties.owner", "type": "str"}, + "additional_content_url": {"key": "properties.additionalContentUrl", "type": "str"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + "description": {"key": "properties.description", "type": "str"}, + "requirements": {"key": "properties.requirements", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.type = None self.name = None @@ -1471,7 +1730,7 @@ def __init__( self.requirements = None -class PolicyMetadataCollection(msrest.serialization.Model): +class PolicyMetadataCollection(_serialization.Model): """Collection of policy metadata resources. Variables are only populated by the server, and will be ignored when sending a request. @@ -1483,25 +1742,23 @@ class PolicyMetadataCollection(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[SlimPolicyMetadata]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[SlimPolicyMetadata]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(PolicyMetadataCollection, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class PolicyMetadataSlimProperties(msrest.serialization.Model): +class PolicyMetadataSlimProperties(_serialization.Model): """The properties of the policy metadata, excluding properties containing large strings. Variables are only populated by the server, and will be ignored when sending a request. @@ -1517,32 +1774,30 @@ class PolicyMetadataSlimProperties(msrest.serialization.Model): :ivar additional_content_url: Url for getting additional content about the resource metadata. :vartype additional_content_url: str :ivar metadata: Additional metadata. - :vartype metadata: any + :vartype metadata: JSON """ _validation = { - 'metadata_id': {'readonly': True}, - 'category': {'readonly': True}, - 'title': {'readonly': True}, - 'owner': {'readonly': True}, - 'additional_content_url': {'readonly': True}, - 'metadata': {'readonly': True}, + "metadata_id": {"readonly": True}, + "category": {"readonly": True}, + "title": {"readonly": True}, + "owner": {"readonly": True}, + "additional_content_url": {"readonly": True}, + "metadata": {"readonly": True}, } _attribute_map = { - 'metadata_id': {'key': 'metadataId', 'type': 'str'}, - 'category': {'key': 'category', 'type': 'str'}, - 'title': {'key': 'title', 'type': 'str'}, - 'owner': {'key': 'owner', 'type': 'str'}, - 'additional_content_url': {'key': 'additionalContentUrl', 'type': 'str'}, - 'metadata': {'key': 'metadata', 'type': 'object'}, + "metadata_id": {"key": "metadataId", "type": "str"}, + "category": {"key": "category", "type": "str"}, + "title": {"key": "title", "type": "str"}, + "owner": {"key": "owner", "type": "str"}, + "additional_content_url": {"key": "additionalContentUrl", "type": "str"}, + "metadata": {"key": "metadata", "type": "object"}, } - def __init__( - self, - **kwargs - ): - super(PolicyMetadataSlimProperties, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.metadata_id = None self.category = None self.title = None @@ -1567,7 +1822,7 @@ class PolicyMetadataProperties(PolicyMetadataSlimProperties): :ivar additional_content_url: Url for getting additional content about the resource metadata. :vartype additional_content_url: str :ivar metadata: Additional metadata. - :vartype metadata: any + :vartype metadata: JSON :ivar description: The description of the policy metadata. :vartype description: str :ivar requirements: The requirements of the policy metadata. @@ -1575,37 +1830,35 @@ class PolicyMetadataProperties(PolicyMetadataSlimProperties): """ _validation = { - 'metadata_id': {'readonly': True}, - 'category': {'readonly': True}, - 'title': {'readonly': True}, - 'owner': {'readonly': True}, - 'additional_content_url': {'readonly': True}, - 'metadata': {'readonly': True}, - 'description': {'readonly': True}, - 'requirements': {'readonly': True}, + "metadata_id": {"readonly": True}, + "category": {"readonly": True}, + "title": {"readonly": True}, + "owner": {"readonly": True}, + "additional_content_url": {"readonly": True}, + "metadata": {"readonly": True}, + "description": {"readonly": True}, + "requirements": {"readonly": True}, } _attribute_map = { - 'metadata_id': {'key': 'metadataId', 'type': 'str'}, - 'category': {'key': 'category', 'type': 'str'}, - 'title': {'key': 'title', 'type': 'str'}, - 'owner': {'key': 'owner', 'type': 'str'}, - 'additional_content_url': {'key': 'additionalContentUrl', 'type': 'str'}, - 'metadata': {'key': 'metadata', 'type': 'object'}, - 'description': {'key': 'description', 'type': 'str'}, - 'requirements': {'key': 'requirements', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(PolicyMetadataProperties, self).__init__(**kwargs) + "metadata_id": {"key": "metadataId", "type": "str"}, + "category": {"key": "category", "type": "str"}, + "title": {"key": "title", "type": "str"}, + "owner": {"key": "owner", "type": "str"}, + "additional_content_url": {"key": "additionalContentUrl", "type": "str"}, + "metadata": {"key": "metadata", "type": "object"}, + "description": {"key": "description", "type": "str"}, + "requirements": {"key": "requirements", "type": "str"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.description = None self.requirements = None -class PolicyReference(msrest.serialization.Model): +class PolicyReference(_serialization.Model): """Resource identifiers for a policy. Variables are only populated by the server, and will be ignored when sending a request. @@ -1622,112 +1875,110 @@ class PolicyReference(msrest.serialization.Model): """ _validation = { - 'policy_definition_id': {'readonly': True}, - 'policy_set_definition_id': {'readonly': True}, - 'policy_definition_reference_id': {'readonly': True}, - 'policy_assignment_id': {'readonly': True}, + "policy_definition_id": {"readonly": True}, + "policy_set_definition_id": {"readonly": True}, + "policy_definition_reference_id": {"readonly": True}, + "policy_assignment_id": {"readonly": True}, } _attribute_map = { - 'policy_definition_id': {'key': 'policyDefinitionId', 'type': 'str'}, - 'policy_set_definition_id': {'key': 'policySetDefinitionId', 'type': 'str'}, - 'policy_definition_reference_id': {'key': 'policyDefinitionReferenceId', 'type': 'str'}, - 'policy_assignment_id': {'key': 'policyAssignmentId', 'type': 'str'}, + "policy_definition_id": {"key": "policyDefinitionId", "type": "str"}, + "policy_set_definition_id": {"key": "policySetDefinitionId", "type": "str"}, + "policy_definition_reference_id": {"key": "policyDefinitionReferenceId", "type": "str"}, + "policy_assignment_id": {"key": "policyAssignmentId", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(PolicyReference, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.policy_definition_id = None self.policy_set_definition_id = None self.policy_definition_reference_id = None self.policy_assignment_id = None -class PolicyState(msrest.serialization.Model): +class PolicyState(_serialization.Model): # pylint: disable=too-many-instance-attributes """Policy state record. Variables are only populated by the server, and will be ignored when sending a request. - :param additional_properties: Unmatched properties from the message are deserialized to this + :ivar additional_properties: Unmatched properties from the message are deserialized to this collection. - :type additional_properties: dict[str, any] - :param odata_id: OData entity ID; always set to null since policy state records do not have an + :vartype additional_properties: dict[str, any] + :ivar odata_id: OData entity ID; always set to null since policy state records do not have an entity ID. - :type odata_id: str - :param odata_context: OData context string; used by OData clients to resolve type information + :vartype odata_id: str + :ivar odata_context: OData context string; used by OData clients to resolve type information based on metadata. - :type odata_context: str - :param timestamp: Timestamp for the policy state record. - :type timestamp: ~datetime.datetime - :param resource_id: Resource ID. - :type resource_id: str - :param policy_assignment_id: Policy assignment ID. - :type policy_assignment_id: str - :param policy_definition_id: Policy definition ID. - :type policy_definition_id: str - :param effective_parameters: Effective parameters for the policy assignment. - :type effective_parameters: str - :param is_compliant: Flag which states whether the resource is compliant against the policy + :vartype odata_context: str + :ivar timestamp: Timestamp for the policy state record. + :vartype timestamp: ~datetime.datetime + :ivar resource_id: Resource ID. + :vartype resource_id: str + :ivar policy_assignment_id: Policy assignment ID. + :vartype policy_assignment_id: str + :ivar policy_definition_id: Policy definition ID. + :vartype policy_definition_id: str + :ivar effective_parameters: Effective parameters for the policy assignment. + :vartype effective_parameters: str + :ivar is_compliant: Flag which states whether the resource is compliant against the policy assignment it was evaluated against. This property is deprecated; please use ComplianceState instead. - :type is_compliant: bool - :param subscription_id: Subscription ID. - :type subscription_id: str - :param resource_type: Resource type. - :type resource_type: str - :param resource_location: Resource location. - :type resource_location: str - :param resource_group: Resource group name. - :type resource_group: str - :param resource_tags: List of resource tags. - :type resource_tags: str - :param policy_assignment_name: Policy assignment name. - :type policy_assignment_name: str - :param policy_assignment_owner: Policy assignment owner. - :type policy_assignment_owner: str - :param policy_assignment_parameters: Policy assignment parameters. - :type policy_assignment_parameters: str - :param policy_assignment_scope: Policy assignment scope. - :type policy_assignment_scope: str - :param policy_definition_name: Policy definition name. - :type policy_definition_name: str - :param policy_definition_action: Policy definition action, i.e. effect. - :type policy_definition_action: str - :param policy_definition_category: Policy definition category. - :type policy_definition_category: str - :param policy_set_definition_id: Policy set definition ID, if the policy assignment is for a + :vartype is_compliant: bool + :ivar subscription_id: Subscription ID. + :vartype subscription_id: str + :ivar resource_type: Resource type. + :vartype resource_type: str + :ivar resource_location: Resource location. + :vartype resource_location: str + :ivar resource_group: Resource group name. + :vartype resource_group: str + :ivar resource_tags: List of resource tags. + :vartype resource_tags: str + :ivar policy_assignment_name: Policy assignment name. + :vartype policy_assignment_name: str + :ivar policy_assignment_owner: Policy assignment owner. + :vartype policy_assignment_owner: str + :ivar policy_assignment_parameters: Policy assignment parameters. + :vartype policy_assignment_parameters: str + :ivar policy_assignment_scope: Policy assignment scope. + :vartype policy_assignment_scope: str + :ivar policy_definition_name: Policy definition name. + :vartype policy_definition_name: str + :ivar policy_definition_action: Policy definition action, i.e. effect. + :vartype policy_definition_action: str + :ivar policy_definition_category: Policy definition category. + :vartype policy_definition_category: str + :ivar policy_set_definition_id: Policy set definition ID, if the policy assignment is for a + policy set. + :vartype policy_set_definition_id: str + :ivar policy_set_definition_name: Policy set definition name, if the policy assignment is for a policy set. - :type policy_set_definition_id: str - :param policy_set_definition_name: Policy set definition name, if the policy assignment is for + :vartype policy_set_definition_name: str + :ivar policy_set_definition_owner: Policy set definition owner, if the policy assignment is for a policy set. - :type policy_set_definition_name: str - :param policy_set_definition_owner: Policy set definition owner, if the policy assignment is - for a policy set. - :type policy_set_definition_owner: str - :param policy_set_definition_category: Policy set definition category, if the policy assignment + :vartype policy_set_definition_owner: str + :ivar policy_set_definition_category: Policy set definition category, if the policy assignment is for a policy set. - :type policy_set_definition_category: str - :param policy_set_definition_parameters: Policy set definition parameters, if the policy + :vartype policy_set_definition_category: str + :ivar policy_set_definition_parameters: Policy set definition parameters, if the policy assignment is for a policy set. - :type policy_set_definition_parameters: str - :param management_group_ids: Comma separated list of management group IDs, which represent the + :vartype policy_set_definition_parameters: str + :ivar management_group_ids: Comma separated list of management group IDs, which represent the hierarchy of the management groups the resource is under. - :type management_group_ids: str - :param policy_definition_reference_id: Reference ID for the policy definition inside the policy + :vartype management_group_ids: str + :ivar policy_definition_reference_id: Reference ID for the policy definition inside the policy set, if the policy assignment is for a policy set. - :type policy_definition_reference_id: str - :param compliance_state: Compliance state of the resource. - :type compliance_state: str - :param policy_evaluation_details: Policy evaluation details. - :type policy_evaluation_details: ~azure.mgmt.policyinsights.models.PolicyEvaluationDetails - :param policy_definition_group_names: Policy definition group names. - :type policy_definition_group_names: list[str] - :param components: Components state compliance records populated only when URL contains + :vartype policy_definition_reference_id: str + :ivar compliance_state: Compliance state of the resource. + :vartype compliance_state: str + :ivar policy_evaluation_details: Policy evaluation details. + :vartype policy_evaluation_details: ~azure.mgmt.policyinsights.models.PolicyEvaluationDetails + :ivar policy_definition_group_names: Policy definition group names. + :vartype policy_definition_group_names: list[str] + :ivar components: Components state compliance records populated only when URL contains $expand=components clause. - :type components: list[~azure.mgmt.policyinsights.models.ComponentStateDetails] + :vartype components: list[~azure.mgmt.policyinsights.models.ComponentStateDetails] :ivar policy_definition_version: Evaluated policy definition version. :vartype policy_definition_version: str :ivar policy_set_definition_version: Evaluated policy set definition version. @@ -1737,50 +1988,50 @@ class PolicyState(msrest.serialization.Model): """ _validation = { - 'policy_definition_version': {'readonly': True}, - 'policy_set_definition_version': {'readonly': True}, - 'policy_assignment_version': {'readonly': True}, + "policy_definition_version": {"readonly": True}, + "policy_set_definition_version": {"readonly": True}, + "policy_assignment_version": {"readonly": True}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'odata_id': {'key': '@odata\\.id', 'type': 'str'}, - 'odata_context': {'key': '@odata\\.context', 'type': 'str'}, - 'timestamp': {'key': 'timestamp', 'type': 'iso-8601'}, - 'resource_id': {'key': 'resourceId', 'type': 'str'}, - 'policy_assignment_id': {'key': 'policyAssignmentId', 'type': 'str'}, - 'policy_definition_id': {'key': 'policyDefinitionId', 'type': 'str'}, - 'effective_parameters': {'key': 'effectiveParameters', 'type': 'str'}, - 'is_compliant': {'key': 'isCompliant', 'type': 'bool'}, - 'subscription_id': {'key': 'subscriptionId', 'type': 'str'}, - 'resource_type': {'key': 'resourceType', 'type': 'str'}, - 'resource_location': {'key': 'resourceLocation', 'type': 'str'}, - 'resource_group': {'key': 'resourceGroup', 'type': 'str'}, - 'resource_tags': {'key': 'resourceTags', 'type': 'str'}, - 'policy_assignment_name': {'key': 'policyAssignmentName', 'type': 'str'}, - 'policy_assignment_owner': {'key': 'policyAssignmentOwner', 'type': 'str'}, - 'policy_assignment_parameters': {'key': 'policyAssignmentParameters', 'type': 'str'}, - 'policy_assignment_scope': {'key': 'policyAssignmentScope', 'type': 'str'}, - 'policy_definition_name': {'key': 'policyDefinitionName', 'type': 'str'}, - 'policy_definition_action': {'key': 'policyDefinitionAction', 'type': 'str'}, - 'policy_definition_category': {'key': 'policyDefinitionCategory', 'type': 'str'}, - 'policy_set_definition_id': {'key': 'policySetDefinitionId', 'type': 'str'}, - 'policy_set_definition_name': {'key': 'policySetDefinitionName', 'type': 'str'}, - 'policy_set_definition_owner': {'key': 'policySetDefinitionOwner', 'type': 'str'}, - 'policy_set_definition_category': {'key': 'policySetDefinitionCategory', 'type': 'str'}, - 'policy_set_definition_parameters': {'key': 'policySetDefinitionParameters', 'type': 'str'}, - 'management_group_ids': {'key': 'managementGroupIds', 'type': 'str'}, - 'policy_definition_reference_id': {'key': 'policyDefinitionReferenceId', 'type': 'str'}, - 'compliance_state': {'key': 'complianceState', 'type': 'str'}, - 'policy_evaluation_details': {'key': 'policyEvaluationDetails', 'type': 'PolicyEvaluationDetails'}, - 'policy_definition_group_names': {'key': 'policyDefinitionGroupNames', 'type': '[str]'}, - 'components': {'key': 'components', 'type': '[ComponentStateDetails]'}, - 'policy_definition_version': {'key': 'policyDefinitionVersion', 'type': 'str'}, - 'policy_set_definition_version': {'key': 'policySetDefinitionVersion', 'type': 'str'}, - 'policy_assignment_version': {'key': 'policyAssignmentVersion', 'type': 'str'}, - } - - def __init__( + "additional_properties": {"key": "", "type": "{object}"}, + "odata_id": {"key": "@odata\\.id", "type": "str"}, + "odata_context": {"key": "@odata\\.context", "type": "str"}, + "timestamp": {"key": "timestamp", "type": "iso-8601"}, + "resource_id": {"key": "resourceId", "type": "str"}, + "policy_assignment_id": {"key": "policyAssignmentId", "type": "str"}, + "policy_definition_id": {"key": "policyDefinitionId", "type": "str"}, + "effective_parameters": {"key": "effectiveParameters", "type": "str"}, + "is_compliant": {"key": "isCompliant", "type": "bool"}, + "subscription_id": {"key": "subscriptionId", "type": "str"}, + "resource_type": {"key": "resourceType", "type": "str"}, + "resource_location": {"key": "resourceLocation", "type": "str"}, + "resource_group": {"key": "resourceGroup", "type": "str"}, + "resource_tags": {"key": "resourceTags", "type": "str"}, + "policy_assignment_name": {"key": "policyAssignmentName", "type": "str"}, + "policy_assignment_owner": {"key": "policyAssignmentOwner", "type": "str"}, + "policy_assignment_parameters": {"key": "policyAssignmentParameters", "type": "str"}, + "policy_assignment_scope": {"key": "policyAssignmentScope", "type": "str"}, + "policy_definition_name": {"key": "policyDefinitionName", "type": "str"}, + "policy_definition_action": {"key": "policyDefinitionAction", "type": "str"}, + "policy_definition_category": {"key": "policyDefinitionCategory", "type": "str"}, + "policy_set_definition_id": {"key": "policySetDefinitionId", "type": "str"}, + "policy_set_definition_name": {"key": "policySetDefinitionName", "type": "str"}, + "policy_set_definition_owner": {"key": "policySetDefinitionOwner", "type": "str"}, + "policy_set_definition_category": {"key": "policySetDefinitionCategory", "type": "str"}, + "policy_set_definition_parameters": {"key": "policySetDefinitionParameters", "type": "str"}, + "management_group_ids": {"key": "managementGroupIds", "type": "str"}, + "policy_definition_reference_id": {"key": "policyDefinitionReferenceId", "type": "str"}, + "compliance_state": {"key": "complianceState", "type": "str"}, + "policy_evaluation_details": {"key": "policyEvaluationDetails", "type": "PolicyEvaluationDetails"}, + "policy_definition_group_names": {"key": "policyDefinitionGroupNames", "type": "[str]"}, + "components": {"key": "components", "type": "[ComponentStateDetails]"}, + "policy_definition_version": {"key": "policyDefinitionVersion", "type": "str"}, + "policy_set_definition_version": {"key": "policySetDefinitionVersion", "type": "str"}, + "policy_assignment_version": {"key": "policyAssignmentVersion", "type": "str"}, + } + + def __init__( # pylint: disable=too-many-locals self, *, additional_properties: Optional[Dict[str, Any]] = None, @@ -1812,12 +2063,91 @@ def __init__( management_group_ids: Optional[str] = None, policy_definition_reference_id: Optional[str] = None, compliance_state: Optional[str] = None, - policy_evaluation_details: Optional["PolicyEvaluationDetails"] = None, + policy_evaluation_details: Optional["_models.PolicyEvaluationDetails"] = None, policy_definition_group_names: Optional[List[str]] = None, - components: Optional[List["ComponentStateDetails"]] = None, + components: Optional[List["_models.ComponentStateDetails"]] = None, **kwargs ): - super(PolicyState, self).__init__(**kwargs) + """ + :keyword additional_properties: Unmatched properties from the message are deserialized to this + collection. + :paramtype additional_properties: dict[str, any] + :keyword odata_id: OData entity ID; always set to null since policy state records do not have + an entity ID. + :paramtype odata_id: str + :keyword odata_context: OData context string; used by OData clients to resolve type information + based on metadata. + :paramtype odata_context: str + :keyword timestamp: Timestamp for the policy state record. + :paramtype timestamp: ~datetime.datetime + :keyword resource_id: Resource ID. + :paramtype resource_id: str + :keyword policy_assignment_id: Policy assignment ID. + :paramtype policy_assignment_id: str + :keyword policy_definition_id: Policy definition ID. + :paramtype policy_definition_id: str + :keyword effective_parameters: Effective parameters for the policy assignment. + :paramtype effective_parameters: str + :keyword is_compliant: Flag which states whether the resource is compliant against the policy + assignment it was evaluated against. This property is deprecated; please use ComplianceState + instead. + :paramtype is_compliant: bool + :keyword subscription_id: Subscription ID. + :paramtype subscription_id: str + :keyword resource_type: Resource type. + :paramtype resource_type: str + :keyword resource_location: Resource location. + :paramtype resource_location: str + :keyword resource_group: Resource group name. + :paramtype resource_group: str + :keyword resource_tags: List of resource tags. + :paramtype resource_tags: str + :keyword policy_assignment_name: Policy assignment name. + :paramtype policy_assignment_name: str + :keyword policy_assignment_owner: Policy assignment owner. + :paramtype policy_assignment_owner: str + :keyword policy_assignment_parameters: Policy assignment parameters. + :paramtype policy_assignment_parameters: str + :keyword policy_assignment_scope: Policy assignment scope. + :paramtype policy_assignment_scope: str + :keyword policy_definition_name: Policy definition name. + :paramtype policy_definition_name: str + :keyword policy_definition_action: Policy definition action, i.e. effect. + :paramtype policy_definition_action: str + :keyword policy_definition_category: Policy definition category. + :paramtype policy_definition_category: str + :keyword policy_set_definition_id: Policy set definition ID, if the policy assignment is for a + policy set. + :paramtype policy_set_definition_id: str + :keyword policy_set_definition_name: Policy set definition name, if the policy assignment is + for a policy set. + :paramtype policy_set_definition_name: str + :keyword policy_set_definition_owner: Policy set definition owner, if the policy assignment is + for a policy set. + :paramtype policy_set_definition_owner: str + :keyword policy_set_definition_category: Policy set definition category, if the policy + assignment is for a policy set. + :paramtype policy_set_definition_category: str + :keyword policy_set_definition_parameters: Policy set definition parameters, if the policy + assignment is for a policy set. + :paramtype policy_set_definition_parameters: str + :keyword management_group_ids: Comma separated list of management group IDs, which represent + the hierarchy of the management groups the resource is under. + :paramtype management_group_ids: str + :keyword policy_definition_reference_id: Reference ID for the policy definition inside the + policy set, if the policy assignment is for a policy set. + :paramtype policy_definition_reference_id: str + :keyword compliance_state: Compliance state of the resource. + :paramtype compliance_state: str + :keyword policy_evaluation_details: Policy evaluation details. + :paramtype policy_evaluation_details: ~azure.mgmt.policyinsights.models.PolicyEvaluationDetails + :keyword policy_definition_group_names: Policy definition group names. + :paramtype policy_definition_group_names: list[str] + :keyword components: Components state compliance records populated only when URL contains + $expand=components clause. + :paramtype components: list[~azure.mgmt.policyinsights.models.ComponentStateDetails] + """ + super().__init__(**kwargs) self.additional_properties = additional_properties self.odata_id = odata_id self.odata_context = odata_context @@ -1855,29 +2185,29 @@ def __init__( self.policy_assignment_version = None -class PolicyStatesQueryResults(msrest.serialization.Model): +class PolicyStatesQueryResults(_serialization.Model): """Query results. - :param odata_context: OData context string; used by OData clients to resolve type information + :ivar odata_context: OData context string; used by OData clients to resolve type information based on metadata. - :type odata_context: str - :param odata_count: OData entity count; represents the number of policy state records returned. - :type odata_count: int - :param odata_next_link: Odata next link; URL to get the next set of results. - :type odata_next_link: str - :param value: Query results. - :type value: list[~azure.mgmt.policyinsights.models.PolicyState] + :vartype odata_context: str + :ivar odata_count: OData entity count; represents the number of policy state records returned. + :vartype odata_count: int + :ivar odata_next_link: Odata next link; URL to get the next set of results. + :vartype odata_next_link: str + :ivar value: Query results. + :vartype value: list[~azure.mgmt.policyinsights.models.PolicyState] """ _validation = { - 'odata_count': {'minimum': 0}, + "odata_count": {"minimum": 0}, } _attribute_map = { - 'odata_context': {'key': '@odata\\.context', 'type': 'str'}, - 'odata_count': {'key': '@odata\\.count', 'type': 'int'}, - 'odata_next_link': {'key': '@odata\\.nextLink', 'type': 'str'}, - 'value': {'key': 'value', 'type': '[PolicyState]'}, + "odata_context": {"key": "@odata\\.context", "type": "str"}, + "odata_count": {"key": "@odata\\.count", "type": "int"}, + "odata_next_link": {"key": "@odata\\.nextLink", "type": "str"}, + "value": {"key": "value", "type": "[PolicyState]"}, } def __init__( @@ -1886,17 +2216,29 @@ def __init__( odata_context: Optional[str] = None, odata_count: Optional[int] = None, odata_next_link: Optional[str] = None, - value: Optional[List["PolicyState"]] = None, + value: Optional[List["_models.PolicyState"]] = None, **kwargs ): - super(PolicyStatesQueryResults, self).__init__(**kwargs) + """ + :keyword odata_context: OData context string; used by OData clients to resolve type information + based on metadata. + :paramtype odata_context: str + :keyword odata_count: OData entity count; represents the number of policy state records + returned. + :paramtype odata_count: int + :keyword odata_next_link: Odata next link; URL to get the next set of results. + :paramtype odata_next_link: str + :keyword value: Query results. + :paramtype value: list[~azure.mgmt.policyinsights.models.PolicyState] + """ + super().__init__(**kwargs) self.odata_context = odata_context self.odata_count = odata_count self.odata_next_link = odata_next_link self.value = value -class PolicyTrackedResource(msrest.serialization.Model): +class PolicyTrackedResource(_serialization.Model): """Policy tracked resource record. Variables are only populated by the server, and will be ignored when sending a request. @@ -1916,26 +2258,24 @@ class PolicyTrackedResource(msrest.serialization.Model): """ _validation = { - 'tracked_resource_id': {'readonly': True}, - 'policy_details': {'readonly': True}, - 'created_by': {'readonly': True}, - 'last_modified_by': {'readonly': True}, - 'last_update_utc': {'readonly': True}, + "tracked_resource_id": {"readonly": True}, + "policy_details": {"readonly": True}, + "created_by": {"readonly": True}, + "last_modified_by": {"readonly": True}, + "last_update_utc": {"readonly": True}, } _attribute_map = { - 'tracked_resource_id': {'key': 'trackedResourceId', 'type': 'str'}, - 'policy_details': {'key': 'policyDetails', 'type': 'PolicyDetails'}, - 'created_by': {'key': 'createdBy', 'type': 'TrackedResourceModificationDetails'}, - 'last_modified_by': {'key': 'lastModifiedBy', 'type': 'TrackedResourceModificationDetails'}, - 'last_update_utc': {'key': 'lastUpdateUtc', 'type': 'iso-8601'}, + "tracked_resource_id": {"key": "trackedResourceId", "type": "str"}, + "policy_details": {"key": "policyDetails", "type": "PolicyDetails"}, + "created_by": {"key": "createdBy", "type": "TrackedResourceModificationDetails"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "TrackedResourceModificationDetails"}, + "last_update_utc": {"key": "lastUpdateUtc", "type": "iso-8601"}, } - def __init__( - self, - **kwargs - ): - super(PolicyTrackedResource, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.tracked_resource_id = None self.policy_details = None self.created_by = None @@ -1943,7 +2283,7 @@ def __init__( self.last_update_utc = None -class PolicyTrackedResourcesQueryResults(msrest.serialization.Model): +class PolicyTrackedResourcesQueryResults(_serialization.Model): """Query results. Variables are only populated by the server, and will be ignored when sending a request. @@ -1955,46 +2295,43 @@ class PolicyTrackedResourcesQueryResults(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[PolicyTrackedResource]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[PolicyTrackedResource]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(PolicyTrackedResourcesQueryResults, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class QueryFailure(msrest.serialization.Model): +class QueryFailure(_serialization.Model): """Error response. - :param error: Error definition. - :type error: ~azure.mgmt.policyinsights.models.QueryFailureError + :ivar error: Error definition. + :vartype error: ~azure.mgmt.policyinsights.models.QueryFailureError """ _attribute_map = { - 'error': {'key': 'error', 'type': 'QueryFailureError'}, + "error": {"key": "error", "type": "QueryFailureError"}, } - def __init__( - self, - *, - error: Optional["QueryFailureError"] = None, - **kwargs - ): - super(QueryFailure, self).__init__(**kwargs) + def __init__(self, *, error: Optional["_models.QueryFailureError"] = None, **kwargs): + """ + :keyword error: Error definition. + :paramtype error: ~azure.mgmt.policyinsights.models.QueryFailureError + """ + super().__init__(**kwargs) self.error = error -class QueryFailureError(msrest.serialization.Model): +class QueryFailureError(_serialization.Model): """Error definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -2006,75 +2343,73 @@ class QueryFailureError(msrest.serialization.Model): """ _validation = { - 'code': {'readonly': True}, - 'message': {'readonly': True}, + "code": {"readonly": True}, + "message": {"readonly": True}, } _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(QueryFailureError, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.code = None self.message = None -class QueryOptions(msrest.serialization.Model): +class QueryOptions(_serialization.Model): """Parameter group. - :param top: Maximum number of records to return. - :type top: int - :param filter: OData filter expression. - :type filter: str - :param order_by: Ordering expression using OData notation. One or more comma-separated column + :ivar top: Maximum number of records to return. + :vartype top: int + :ivar filter: OData filter expression. + :vartype filter: str + :ivar order_by: Ordering expression using OData notation. One or more comma-separated column names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". - :type order_by: str - :param select: Select expression using OData notation. Limits the columns on each record to - just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". - :type select: str - :param from_property: ISO 8601 formatted timestamp specifying the start time of the interval to + :vartype order_by: str + :ivar select: Select expression using OData notation. Limits the columns on each record to just + those requested, e.g. "$select=PolicyAssignmentId, ResourceId". + :vartype select: str + :ivar from_property: ISO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, the service uses ($to - 1-day). - :type from_property: ~datetime.datetime - :param to: ISO 8601 formatted timestamp specifying the end time of the interval to query. When + :vartype from_property: ~datetime.datetime + :ivar to: ISO 8601 formatted timestamp specifying the end time of the interval to query. When not specified, the service uses request time. - :type to: ~datetime.datetime - :param apply: OData apply expression for aggregations. - :type apply: str - :param skip_token: Skiptoken is only provided if a previous response returned a partial result + :vartype to: ~datetime.datetime + :ivar apply: OData apply expression for aggregations. + :vartype apply: str + :ivar skip_token: Skiptoken is only provided if a previous response returned a partial result as a part of nextLink element. - :type skip_token: str - :param expand: The $expand query parameter. For example, to expand components use + :vartype skip_token: str + :ivar expand: The $expand query parameter. For example, to expand components use $expand=components. - :type expand: str + :vartype expand: str """ _validation = { - 'top': {'minimum': 0}, + "top": {"minimum": 0}, } _attribute_map = { - 'top': {'key': 'Top', 'type': 'int'}, - 'filter': {'key': 'Filter', 'type': 'str'}, - 'order_by': {'key': 'OrderBy', 'type': 'str'}, - 'select': {'key': 'Select', 'type': 'str'}, - 'from_property': {'key': 'FromProperty', 'type': 'iso-8601'}, - 'to': {'key': 'To', 'type': 'iso-8601'}, - 'apply': {'key': 'Apply', 'type': 'str'}, - 'skip_token': {'key': 'SkipToken', 'type': 'str'}, - 'expand': {'key': 'Expand', 'type': 'str'}, + "top": {"key": "Top", "type": "int"}, + "filter": {"key": "Filter", "type": "str"}, + "order_by": {"key": "OrderBy", "type": "str"}, + "select": {"key": "Select", "type": "str"}, + "from_property": {"key": "FromProperty", "type": "iso-8601"}, + "to": {"key": "To", "type": "iso-8601"}, + "apply": {"key": "Apply", "type": "str"}, + "skip_token": {"key": "SkipToken", "type": "str"}, + "expand": {"key": "Expand", "type": "str"}, } def __init__( self, *, top: Optional[int] = None, - filter: Optional[str] = None, + filter: Optional[str] = None, # pylint: disable=redefined-builtin order_by: Optional[str] = None, select: Optional[str] = None, from_property: Optional[datetime.datetime] = None, @@ -2084,7 +2419,34 @@ def __init__( expand: Optional[str] = None, **kwargs ): - super(QueryOptions, self).__init__(**kwargs) + """ + :keyword top: Maximum number of records to return. + :paramtype top: int + :keyword filter: OData filter expression. + :paramtype filter: str + :keyword order_by: Ordering expression using OData notation. One or more comma-separated column + names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, + ResourceId asc". + :paramtype order_by: str + :keyword select: Select expression using OData notation. Limits the columns on each record to + just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". + :paramtype select: str + :keyword from_property: ISO 8601 formatted timestamp specifying the start time of the interval + to query. When not specified, the service uses ($to - 1-day). + :paramtype from_property: ~datetime.datetime + :keyword to: ISO 8601 formatted timestamp specifying the end time of the interval to query. + When not specified, the service uses request time. + :paramtype to: ~datetime.datetime + :keyword apply: OData apply expression for aggregations. + :paramtype apply: str + :keyword skip_token: Skiptoken is only provided if a previous response returned a partial + result as a part of nextLink element. + :paramtype skip_token: str + :keyword expand: The $expand query parameter. For example, to expand components use + $expand=components. + :paramtype expand: str + """ + super().__init__(**kwargs) self.top = top self.filter = filter self.order_by = order_by @@ -2096,7 +2458,7 @@ def __init__( self.expand = expand -class Remediation(msrest.serialization.Model): +class Remediation(_serialization.Model): # pylint: disable=too-many-instance-attributes """The remediation definition. Variables are only populated by the server, and will be ignored when sending a request. @@ -2110,25 +2472,25 @@ class Remediation(msrest.serialization.Model): :ivar system_data: Azure Resource Manager metadata containing createdBy and modifiedBy information. :vartype system_data: ~azure.mgmt.policyinsights.models.SystemData - :param policy_assignment_id: The resource ID of the policy assignment that should be - remediated. - :type policy_assignment_id: str - :param policy_definition_reference_id: The policy definition reference ID of the individual + :ivar policy_assignment_id: The resource ID of the policy assignment that should be remediated. + :vartype policy_assignment_id: str + :ivar policy_definition_reference_id: The policy definition reference ID of the individual definition that should be remediated. Required when the policy assignment being remediated assigns a policy set definition. - :type policy_definition_reference_id: str - :param resource_discovery_mode: The way resources to remediate are discovered. Defaults to - ExistingNonCompliant if not specified. Possible values include: "ExistingNonCompliant", + :vartype policy_definition_reference_id: str + :ivar resource_discovery_mode: The way resources to remediate are discovered. Defaults to + ExistingNonCompliant if not specified. Known values are: "ExistingNonCompliant" and "ReEvaluateCompliance". - :type resource_discovery_mode: str or ~azure.mgmt.policyinsights.models.ResourceDiscoveryMode + :vartype resource_discovery_mode: str or + ~azure.mgmt.policyinsights.models.ResourceDiscoveryMode :ivar provisioning_state: The status of the remediation. :vartype provisioning_state: str :ivar created_on: The time at which the remediation was created. :vartype created_on: ~datetime.datetime :ivar last_updated_on: The time at which the remediation was last updated. :vartype last_updated_on: ~datetime.datetime - :param filters: The filters that will be applied to determine which resources to remediate. - :type filters: ~azure.mgmt.policyinsights.models.RemediationFilters + :ivar filters: The filters that will be applied to determine which resources to remediate. + :vartype filters: ~azure.mgmt.policyinsights.models.RemediationFilters :ivar deployment_status: The deployment status summary for all deployments created by the remediation. :vartype deployment_status: ~azure.mgmt.policyinsights.models.RemediationDeploymentSummary @@ -2138,49 +2500,49 @@ class Remediation(msrest.serialization.Model): :ivar correlation_id: The remediation correlation Id. Can be used to find events related to the remediation in the activity log. :vartype correlation_id: str - :param resource_count: Determines the max number of resources that can be remediated by the + :ivar resource_count: Determines the max number of resources that can be remediated by the remediation job. If not provided, the default resource count is used. - :type resource_count: int - :param parallel_deployments: Determines how many resources to remediate at any given time. Can + :vartype resource_count: int + :ivar parallel_deployments: Determines how many resources to remediate at any given time. Can be used to increase or reduce the pace of the remediation. If not provided, the default parallel deployments value is used. - :type parallel_deployments: int - :param failure_threshold: The remediation failure threshold settings. - :type failure_threshold: + :vartype parallel_deployments: int + :ivar failure_threshold: The remediation failure threshold settings. + :vartype failure_threshold: ~azure.mgmt.policyinsights.models.RemediationPropertiesFailureThreshold """ _validation = { - 'id': {'readonly': True}, - 'type': {'readonly': True}, - 'name': {'readonly': True}, - 'system_data': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'created_on': {'readonly': True}, - 'last_updated_on': {'readonly': True}, - 'deployment_status': {'readonly': True}, - 'status_message': {'readonly': True}, - 'correlation_id': {'readonly': True}, + "id": {"readonly": True}, + "type": {"readonly": True}, + "name": {"readonly": True}, + "system_data": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "created_on": {"readonly": True}, + "last_updated_on": {"readonly": True}, + "deployment_status": {"readonly": True}, + "status_message": {"readonly": True}, + "correlation_id": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'system_data': {'key': 'systemData', 'type': 'SystemData'}, - 'policy_assignment_id': {'key': 'properties.policyAssignmentId', 'type': 'str'}, - 'policy_definition_reference_id': {'key': 'properties.policyDefinitionReferenceId', 'type': 'str'}, - 'resource_discovery_mode': {'key': 'properties.resourceDiscoveryMode', 'type': 'str'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, - 'created_on': {'key': 'properties.createdOn', 'type': 'iso-8601'}, - 'last_updated_on': {'key': 'properties.lastUpdatedOn', 'type': 'iso-8601'}, - 'filters': {'key': 'properties.filters', 'type': 'RemediationFilters'}, - 'deployment_status': {'key': 'properties.deploymentStatus', 'type': 'RemediationDeploymentSummary'}, - 'status_message': {'key': 'properties.statusMessage', 'type': 'str'}, - 'correlation_id': {'key': 'properties.correlationId', 'type': 'str'}, - 'resource_count': {'key': 'properties.resourceCount', 'type': 'int'}, - 'parallel_deployments': {'key': 'properties.parallelDeployments', 'type': 'int'}, - 'failure_threshold': {'key': 'properties.failureThreshold', 'type': 'RemediationPropertiesFailureThreshold'}, + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "system_data": {"key": "systemData", "type": "SystemData"}, + "policy_assignment_id": {"key": "properties.policyAssignmentId", "type": "str"}, + "policy_definition_reference_id": {"key": "properties.policyDefinitionReferenceId", "type": "str"}, + "resource_discovery_mode": {"key": "properties.resourceDiscoveryMode", "type": "str"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "str"}, + "created_on": {"key": "properties.createdOn", "type": "iso-8601"}, + "last_updated_on": {"key": "properties.lastUpdatedOn", "type": "iso-8601"}, + "filters": {"key": "properties.filters", "type": "RemediationFilters"}, + "deployment_status": {"key": "properties.deploymentStatus", "type": "RemediationDeploymentSummary"}, + "status_message": {"key": "properties.statusMessage", "type": "str"}, + "correlation_id": {"key": "properties.correlationId", "type": "str"}, + "resource_count": {"key": "properties.resourceCount", "type": "int"}, + "parallel_deployments": {"key": "properties.parallelDeployments", "type": "int"}, + "failure_threshold": {"key": "properties.failureThreshold", "type": "RemediationPropertiesFailureThreshold"}, } def __init__( @@ -2188,14 +2550,40 @@ def __init__( *, policy_assignment_id: Optional[str] = None, policy_definition_reference_id: Optional[str] = None, - resource_discovery_mode: Optional[Union[str, "ResourceDiscoveryMode"]] = None, - filters: Optional["RemediationFilters"] = None, + resource_discovery_mode: Optional[Union[str, "_models.ResourceDiscoveryMode"]] = None, + filters: Optional["_models.RemediationFilters"] = None, resource_count: Optional[int] = None, parallel_deployments: Optional[int] = None, - failure_threshold: Optional["RemediationPropertiesFailureThreshold"] = None, + failure_threshold: Optional["_models.RemediationPropertiesFailureThreshold"] = None, **kwargs ): - super(Remediation, self).__init__(**kwargs) + """ + :keyword policy_assignment_id: The resource ID of the policy assignment that should be + remediated. + :paramtype policy_assignment_id: str + :keyword policy_definition_reference_id: The policy definition reference ID of the individual + definition that should be remediated. Required when the policy assignment being remediated + assigns a policy set definition. + :paramtype policy_definition_reference_id: str + :keyword resource_discovery_mode: The way resources to remediate are discovered. Defaults to + ExistingNonCompliant if not specified. Known values are: "ExistingNonCompliant" and + "ReEvaluateCompliance". + :paramtype resource_discovery_mode: str or + ~azure.mgmt.policyinsights.models.ResourceDiscoveryMode + :keyword filters: The filters that will be applied to determine which resources to remediate. + :paramtype filters: ~azure.mgmt.policyinsights.models.RemediationFilters + :keyword resource_count: Determines the max number of resources that can be remediated by the + remediation job. If not provided, the default resource count is used. + :paramtype resource_count: int + :keyword parallel_deployments: Determines how many resources to remediate at any given time. + Can be used to increase or reduce the pace of the remediation. If not provided, the default + parallel deployments value is used. + :paramtype parallel_deployments: int + :keyword failure_threshold: The remediation failure threshold settings. + :paramtype failure_threshold: + ~azure.mgmt.policyinsights.models.RemediationPropertiesFailureThreshold + """ + super().__init__(**kwargs) self.id = None self.type = None self.name = None @@ -2215,7 +2603,7 @@ def __init__( self.failure_threshold = failure_threshold -class RemediationDeployment(msrest.serialization.Model): +class RemediationDeployment(_serialization.Model): """Details of a single deployment created by the remediation. Variables are only populated by the server, and will be ignored when sending a request. @@ -2238,30 +2626,28 @@ class RemediationDeployment(msrest.serialization.Model): """ _validation = { - 'remediated_resource_id': {'readonly': True}, - 'deployment_id': {'readonly': True}, - 'status': {'readonly': True}, - 'resource_location': {'readonly': True}, - 'error': {'readonly': True}, - 'created_on': {'readonly': True}, - 'last_updated_on': {'readonly': True}, + "remediated_resource_id": {"readonly": True}, + "deployment_id": {"readonly": True}, + "status": {"readonly": True}, + "resource_location": {"readonly": True}, + "error": {"readonly": True}, + "created_on": {"readonly": True}, + "last_updated_on": {"readonly": True}, } _attribute_map = { - 'remediated_resource_id': {'key': 'remediatedResourceId', 'type': 'str'}, - 'deployment_id': {'key': 'deploymentId', 'type': 'str'}, - 'status': {'key': 'status', 'type': 'str'}, - 'resource_location': {'key': 'resourceLocation', 'type': 'str'}, - 'error': {'key': 'error', 'type': 'ErrorDefinition'}, - 'created_on': {'key': 'createdOn', 'type': 'iso-8601'}, - 'last_updated_on': {'key': 'lastUpdatedOn', 'type': 'iso-8601'}, - } - - def __init__( - self, - **kwargs - ): - super(RemediationDeployment, self).__init__(**kwargs) + "remediated_resource_id": {"key": "remediatedResourceId", "type": "str"}, + "deployment_id": {"key": "deploymentId", "type": "str"}, + "status": {"key": "status", "type": "str"}, + "resource_location": {"key": "resourceLocation", "type": "str"}, + "error": {"key": "error", "type": "ErrorDefinition"}, + "created_on": {"key": "createdOn", "type": "iso-8601"}, + "last_updated_on": {"key": "lastUpdatedOn", "type": "iso-8601"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.remediated_resource_id = None self.deployment_id = None self.status = None @@ -2271,7 +2657,7 @@ def __init__( self.last_updated_on = None -class RemediationDeploymentsListResult(msrest.serialization.Model): +class RemediationDeploymentsListResult(_serialization.Model): """List of deployments for a remediation. Variables are only populated by the server, and will be ignored when sending a request. @@ -2283,25 +2669,23 @@ class RemediationDeploymentsListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[RemediationDeployment]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[RemediationDeployment]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(RemediationDeploymentsListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class RemediationDeploymentSummary(msrest.serialization.Model): +class RemediationDeploymentSummary(_serialization.Model): """The deployment status summary for all deployments created by the remediation. Variables are only populated by the server, and will be ignored when sending a request. @@ -2317,49 +2701,46 @@ class RemediationDeploymentSummary(msrest.serialization.Model): """ _validation = { - 'total_deployments': {'readonly': True}, - 'successful_deployments': {'readonly': True}, - 'failed_deployments': {'readonly': True}, + "total_deployments": {"readonly": True}, + "successful_deployments": {"readonly": True}, + "failed_deployments": {"readonly": True}, } _attribute_map = { - 'total_deployments': {'key': 'totalDeployments', 'type': 'int'}, - 'successful_deployments': {'key': 'successfulDeployments', 'type': 'int'}, - 'failed_deployments': {'key': 'failedDeployments', 'type': 'int'}, + "total_deployments": {"key": "totalDeployments", "type": "int"}, + "successful_deployments": {"key": "successfulDeployments", "type": "int"}, + "failed_deployments": {"key": "failedDeployments", "type": "int"}, } - def __init__( - self, - **kwargs - ): - super(RemediationDeploymentSummary, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.total_deployments = None self.successful_deployments = None self.failed_deployments = None -class RemediationFilters(msrest.serialization.Model): +class RemediationFilters(_serialization.Model): """The filters that will be applied to determine which resources to remediate. - :param locations: The resource locations that will be remediated. - :type locations: list[str] + :ivar locations: The resource locations that will be remediated. + :vartype locations: list[str] """ _attribute_map = { - 'locations': {'key': 'locations', 'type': '[str]'}, + "locations": {"key": "locations", "type": "[str]"}, } - def __init__( - self, - *, - locations: Optional[List[str]] = None, - **kwargs - ): - super(RemediationFilters, self).__init__(**kwargs) + def __init__(self, *, locations: Optional[List[str]] = None, **kwargs): + """ + :keyword locations: The resource locations that will be remediated. + :paramtype locations: list[str] + """ + super().__init__(**kwargs) self.locations = locations -class RemediationListResult(msrest.serialization.Model): +class RemediationListResult(_serialization.Model): """List of remediations. Variables are only populated by the server, and will be ignored when sending a request. @@ -2371,48 +2752,47 @@ class RemediationListResult(msrest.serialization.Model): """ _validation = { - 'value': {'readonly': True}, - 'next_link': {'readonly': True}, + "value": {"readonly": True}, + "next_link": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': '[Remediation]'}, - 'next_link': {'key': 'nextLink', 'type': 'str'}, + "value": {"key": "value", "type": "[Remediation]"}, + "next_link": {"key": "nextLink", "type": "str"}, } - def __init__( - self, - **kwargs - ): - super(RemediationListResult, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.value = None self.next_link = None -class RemediationPropertiesFailureThreshold(msrest.serialization.Model): +class RemediationPropertiesFailureThreshold(_serialization.Model): """The remediation failure threshold settings. - :param percentage: A number between 0.0 to 1.0 representing the percentage failure threshold. + :ivar percentage: A number between 0.0 to 1.0 representing the percentage failure threshold. The remediation will fail if the percentage of failed remediation operations (i.e. failed deployments) exceeds this threshold. - :type percentage: float + :vartype percentage: float """ _attribute_map = { - 'percentage': {'key': 'percentage', 'type': 'float'}, + "percentage": {"key": "percentage", "type": "float"}, } - def __init__( - self, - *, - percentage: Optional[float] = None, - **kwargs - ): - super(RemediationPropertiesFailureThreshold, self).__init__(**kwargs) + def __init__(self, *, percentage: Optional[float] = None, **kwargs): + """ + :keyword percentage: A number between 0.0 to 1.0 representing the percentage failure threshold. + The remediation will fail if the percentage of failed remediation operations (i.e. failed + deployments) exceeds this threshold. + :paramtype percentage: float + """ + super().__init__(**kwargs) self.percentage = percentage -class SlimPolicyMetadata(msrest.serialization.Model): +class SlimPolicyMetadata(_serialization.Model): """Slim version of policy metadata resource definition, excluding properties with large strings. Variables are only populated by the server, and will be ignored when sending a request. @@ -2434,38 +2814,36 @@ class SlimPolicyMetadata(msrest.serialization.Model): :ivar additional_content_url: Url for getting additional content about the resource metadata. :vartype additional_content_url: str :ivar metadata: Additional metadata. - :vartype metadata: any + :vartype metadata: JSON """ _validation = { - 'id': {'readonly': True}, - 'type': {'readonly': True}, - 'name': {'readonly': True}, - 'metadata_id': {'readonly': True}, - 'category': {'readonly': True}, - 'title': {'readonly': True}, - 'owner': {'readonly': True}, - 'additional_content_url': {'readonly': True}, - 'metadata': {'readonly': True}, + "id": {"readonly": True}, + "type": {"readonly": True}, + "name": {"readonly": True}, + "metadata_id": {"readonly": True}, + "category": {"readonly": True}, + "title": {"readonly": True}, + "owner": {"readonly": True}, + "additional_content_url": {"readonly": True}, + "metadata": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'metadata_id': {'key': 'properties.metadataId', 'type': 'str'}, - 'category': {'key': 'properties.category', 'type': 'str'}, - 'title': {'key': 'properties.title', 'type': 'str'}, - 'owner': {'key': 'properties.owner', 'type': 'str'}, - 'additional_content_url': {'key': 'properties.additionalContentUrl', 'type': 'str'}, - 'metadata': {'key': 'properties.metadata', 'type': 'object'}, - } - - def __init__( - self, - **kwargs - ): - super(SlimPolicyMetadata, self).__init__(**kwargs) + "id": {"key": "id", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "metadata_id": {"key": "properties.metadataId", "type": "str"}, + "category": {"key": "properties.category", "type": "str"}, + "title": {"key": "properties.title", "type": "str"}, + "owner": {"key": "properties.owner", "type": "str"}, + "additional_content_url": {"key": "properties.additionalContentUrl", "type": "str"}, + "metadata": {"key": "properties.metadata", "type": "object"}, + } + + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.id = None self.type = None self.name = None @@ -2477,27 +2855,27 @@ def __init__( self.metadata = None -class SummarizeResults(msrest.serialization.Model): +class SummarizeResults(_serialization.Model): """Summarize action results. - :param odata_context: OData context string; used by OData clients to resolve type information + :ivar odata_context: OData context string; used by OData clients to resolve type information based on metadata. - :type odata_context: str - :param odata_count: OData entity count; represents the number of summaries returned; always set + :vartype odata_context: str + :ivar odata_count: OData entity count; represents the number of summaries returned; always set to 1. - :type odata_count: int - :param value: Summarize action results. - :type value: list[~azure.mgmt.policyinsights.models.Summary] + :vartype odata_count: int + :ivar value: Summarize action results. + :vartype value: list[~azure.mgmt.policyinsights.models.Summary] """ _validation = { - 'odata_count': {'maximum': 1, 'minimum': 1}, + "odata_count": {"maximum": 1, "minimum": 1}, } _attribute_map = { - 'odata_context': {'key': '@odata\\.context', 'type': 'str'}, - 'odata_count': {'key': '@odata\\.count', 'type': 'int'}, - 'value': {'key': 'value', 'type': '[Summary]'}, + "odata_context": {"key": "@odata\\.context", "type": "str"}, + "odata_count": {"key": "@odata\\.count", "type": "int"}, + "value": {"key": "value", "type": "[Summary]"}, } def __init__( @@ -2505,34 +2883,44 @@ def __init__( *, odata_context: Optional[str] = None, odata_count: Optional[int] = None, - value: Optional[List["Summary"]] = None, + value: Optional[List["_models.Summary"]] = None, **kwargs ): - super(SummarizeResults, self).__init__(**kwargs) + """ + :keyword odata_context: OData context string; used by OData clients to resolve type information + based on metadata. + :paramtype odata_context: str + :keyword odata_count: OData entity count; represents the number of summaries returned; always + set to 1. + :paramtype odata_count: int + :keyword value: Summarize action results. + :paramtype value: list[~azure.mgmt.policyinsights.models.Summary] + """ + super().__init__(**kwargs) self.odata_context = odata_context self.odata_count = odata_count self.value = value -class Summary(msrest.serialization.Model): +class Summary(_serialization.Model): """Summary results. - :param odata_id: OData entity ID; always set to null since summaries do not have an entity ID. - :type odata_id: str - :param odata_context: OData context string; used by OData clients to resolve type information + :ivar odata_id: OData entity ID; always set to null since summaries do not have an entity ID. + :vartype odata_id: str + :ivar odata_context: OData context string; used by OData clients to resolve type information based on metadata. - :type odata_context: str - :param results: Compliance summary for all policy assignments. - :type results: ~azure.mgmt.policyinsights.models.SummaryResults - :param policy_assignments: Policy assignments summary. - :type policy_assignments: list[~azure.mgmt.policyinsights.models.PolicyAssignmentSummary] + :vartype odata_context: str + :ivar results: Compliance summary for all policy assignments. + :vartype results: ~azure.mgmt.policyinsights.models.SummaryResults + :ivar policy_assignments: Policy assignments summary. + :vartype policy_assignments: list[~azure.mgmt.policyinsights.models.PolicyAssignmentSummary] """ _attribute_map = { - 'odata_id': {'key': '@odata\\.id', 'type': 'str'}, - 'odata_context': {'key': '@odata\\.context', 'type': 'str'}, - 'results': {'key': 'results', 'type': 'SummaryResults'}, - 'policy_assignments': {'key': 'policyAssignments', 'type': '[PolicyAssignmentSummary]'}, + "odata_id": {"key": "@odata\\.id", "type": "str"}, + "odata_context": {"key": "@odata\\.context", "type": "str"}, + "results": {"key": "results", "type": "SummaryResults"}, + "policy_assignments": {"key": "policyAssignments", "type": "[PolicyAssignmentSummary]"}, } def __init__( @@ -2540,50 +2928,62 @@ def __init__( *, odata_id: Optional[str] = None, odata_context: Optional[str] = None, - results: Optional["SummaryResults"] = None, - policy_assignments: Optional[List["PolicyAssignmentSummary"]] = None, + results: Optional["_models.SummaryResults"] = None, + policy_assignments: Optional[List["_models.PolicyAssignmentSummary"]] = None, **kwargs ): - super(Summary, self).__init__(**kwargs) + """ + :keyword odata_id: OData entity ID; always set to null since summaries do not have an entity + ID. + :paramtype odata_id: str + :keyword odata_context: OData context string; used by OData clients to resolve type information + based on metadata. + :paramtype odata_context: str + :keyword results: Compliance summary for all policy assignments. + :paramtype results: ~azure.mgmt.policyinsights.models.SummaryResults + :keyword policy_assignments: Policy assignments summary. + :paramtype policy_assignments: list[~azure.mgmt.policyinsights.models.PolicyAssignmentSummary] + """ + super().__init__(**kwargs) self.odata_id = odata_id self.odata_context = odata_context self.results = results self.policy_assignments = policy_assignments -class SummaryResults(msrest.serialization.Model): +class SummaryResults(_serialization.Model): """Compliance summary on a particular summary level. - :param query_results_uri: HTTP POST URI for queryResults action on Microsoft.PolicyInsights to + :ivar query_results_uri: HTTP POST URI for queryResults action on Microsoft.PolicyInsights to retrieve raw results for the compliance summary. This property will not be available by default in future API versions, but could be queried explicitly. - :type query_results_uri: str - :param non_compliant_resources: Number of non-compliant resources. - :type non_compliant_resources: int - :param non_compliant_policies: Number of non-compliant policies. - :type non_compliant_policies: int - :param resource_details: The resources summary at this level. - :type resource_details: list[~azure.mgmt.policyinsights.models.ComplianceDetail] - :param policy_details: The policy artifact summary at this level. For query scope level, it + :vartype query_results_uri: str + :ivar non_compliant_resources: Number of non-compliant resources. + :vartype non_compliant_resources: int + :ivar non_compliant_policies: Number of non-compliant policies. + :vartype non_compliant_policies: int + :ivar resource_details: The resources summary at this level. + :vartype resource_details: list[~azure.mgmt.policyinsights.models.ComplianceDetail] + :ivar policy_details: The policy artifact summary at this level. For query scope level, it represents policy assignment summary. For policy assignment level, it represents policy definitions summary. - :type policy_details: list[~azure.mgmt.policyinsights.models.ComplianceDetail] - :param policy_group_details: The policy definition group summary at this level. - :type policy_group_details: list[~azure.mgmt.policyinsights.models.ComplianceDetail] + :vartype policy_details: list[~azure.mgmt.policyinsights.models.ComplianceDetail] + :ivar policy_group_details: The policy definition group summary at this level. + :vartype policy_group_details: list[~azure.mgmt.policyinsights.models.ComplianceDetail] """ _validation = { - 'non_compliant_resources': {'minimum': 0}, - 'non_compliant_policies': {'minimum': 0}, + "non_compliant_resources": {"minimum": 0}, + "non_compliant_policies": {"minimum": 0}, } _attribute_map = { - 'query_results_uri': {'key': 'queryResultsUri', 'type': 'str'}, - 'non_compliant_resources': {'key': 'nonCompliantResources', 'type': 'int'}, - 'non_compliant_policies': {'key': 'nonCompliantPolicies', 'type': 'int'}, - 'resource_details': {'key': 'resourceDetails', 'type': '[ComplianceDetail]'}, - 'policy_details': {'key': 'policyDetails', 'type': '[ComplianceDetail]'}, - 'policy_group_details': {'key': 'policyGroupDetails', 'type': '[ComplianceDetail]'}, + "query_results_uri": {"key": "queryResultsUri", "type": "str"}, + "non_compliant_resources": {"key": "nonCompliantResources", "type": "int"}, + "non_compliant_policies": {"key": "nonCompliantPolicies", "type": "int"}, + "resource_details": {"key": "resourceDetails", "type": "[ComplianceDetail]"}, + "policy_details": {"key": "policyDetails", "type": "[ComplianceDetail]"}, + "policy_group_details": {"key": "policyGroupDetails", "type": "[ComplianceDetail]"}, } def __init__( @@ -2592,12 +2992,30 @@ def __init__( query_results_uri: Optional[str] = None, non_compliant_resources: Optional[int] = None, non_compliant_policies: Optional[int] = None, - resource_details: Optional[List["ComplianceDetail"]] = None, - policy_details: Optional[List["ComplianceDetail"]] = None, - policy_group_details: Optional[List["ComplianceDetail"]] = None, + resource_details: Optional[List["_models.ComplianceDetail"]] = None, + policy_details: Optional[List["_models.ComplianceDetail"]] = None, + policy_group_details: Optional[List["_models.ComplianceDetail"]] = None, **kwargs ): - super(SummaryResults, self).__init__(**kwargs) + """ + :keyword query_results_uri: HTTP POST URI for queryResults action on Microsoft.PolicyInsights + to retrieve raw results for the compliance summary. This property will not be available by + default in future API versions, but could be queried explicitly. + :paramtype query_results_uri: str + :keyword non_compliant_resources: Number of non-compliant resources. + :paramtype non_compliant_resources: int + :keyword non_compliant_policies: Number of non-compliant policies. + :paramtype non_compliant_policies: int + :keyword resource_details: The resources summary at this level. + :paramtype resource_details: list[~azure.mgmt.policyinsights.models.ComplianceDetail] + :keyword policy_details: The policy artifact summary at this level. For query scope level, it + represents policy assignment summary. For policy assignment level, it represents policy + definitions summary. + :paramtype policy_details: list[~azure.mgmt.policyinsights.models.ComplianceDetail] + :keyword policy_group_details: The policy definition group summary at this level. + :paramtype policy_group_details: list[~azure.mgmt.policyinsights.models.ComplianceDetail] + """ + super().__init__(**kwargs) self.query_results_uri = query_results_uri self.non_compliant_resources = non_compliant_resources self.non_compliant_policies = non_compliant_policies @@ -2606,46 +3024,62 @@ def __init__( self.policy_group_details = policy_group_details -class SystemData(msrest.serialization.Model): +class SystemData(_serialization.Model): """Metadata pertaining to creation and last modification of the resource. - :param created_by: The identity that created the resource. - :type created_by: str - :param created_by_type: The type of identity that created the resource. Possible values - include: "User", "Application", "ManagedIdentity", "Key". - :type created_by_type: str or ~azure.mgmt.policyinsights.models.CreatedByType - :param created_at: The timestamp of resource creation (UTC). - :type created_at: ~datetime.datetime - :param last_modified_by: The identity that last modified the resource. - :type last_modified_by: str - :param last_modified_by_type: The type of identity that last modified the resource. Possible - values include: "User", "Application", "ManagedIdentity", "Key". - :type last_modified_by_type: str or ~azure.mgmt.policyinsights.models.CreatedByType - :param last_modified_at: The timestamp of resource last modification (UTC). - :type last_modified_at: ~datetime.datetime + :ivar created_by: The identity that created the resource. + :vartype created_by: str + :ivar created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :vartype created_by_type: str or ~azure.mgmt.policyinsights.models.CreatedByType + :ivar created_at: The timestamp of resource creation (UTC). + :vartype created_at: ~datetime.datetime + :ivar last_modified_by: The identity that last modified the resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of identity that last modified the resource. Known values + are: "User", "Application", "ManagedIdentity", and "Key". + :vartype last_modified_by_type: str or ~azure.mgmt.policyinsights.models.CreatedByType + :ivar last_modified_at: The timestamp of resource last modification (UTC). + :vartype last_modified_at: ~datetime.datetime """ _attribute_map = { - 'created_by': {'key': 'createdBy', 'type': 'str'}, - 'created_by_type': {'key': 'createdByType', 'type': 'str'}, - 'created_at': {'key': 'createdAt', 'type': 'iso-8601'}, - 'last_modified_by': {'key': 'lastModifiedBy', 'type': 'str'}, - 'last_modified_by_type': {'key': 'lastModifiedByType', 'type': 'str'}, - 'last_modified_at': {'key': 'lastModifiedAt', 'type': 'iso-8601'}, + "created_by": {"key": "createdBy", "type": "str"}, + "created_by_type": {"key": "createdByType", "type": "str"}, + "created_at": {"key": "createdAt", "type": "iso-8601"}, + "last_modified_by": {"key": "lastModifiedBy", "type": "str"}, + "last_modified_by_type": {"key": "lastModifiedByType", "type": "str"}, + "last_modified_at": {"key": "lastModifiedAt", "type": "iso-8601"}, } def __init__( self, *, created_by: Optional[str] = None, - created_by_type: Optional[Union[str, "CreatedByType"]] = None, + created_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, created_at: Optional[datetime.datetime] = None, last_modified_by: Optional[str] = None, - last_modified_by_type: Optional[Union[str, "CreatedByType"]] = None, + last_modified_by_type: Optional[Union[str, "_models.CreatedByType"]] = None, last_modified_at: Optional[datetime.datetime] = None, **kwargs ): - super(SystemData, self).__init__(**kwargs) + """ + :keyword created_by: The identity that created the resource. + :paramtype created_by: str + :keyword created_by_type: The type of identity that created the resource. Known values are: + "User", "Application", "ManagedIdentity", and "Key". + :paramtype created_by_type: str or ~azure.mgmt.policyinsights.models.CreatedByType + :keyword created_at: The timestamp of resource creation (UTC). + :paramtype created_at: ~datetime.datetime + :keyword last_modified_by: The identity that last modified the resource. + :paramtype last_modified_by: str + :keyword last_modified_by_type: The type of identity that last modified the resource. Known + values are: "User", "Application", "ManagedIdentity", and "Key". + :paramtype last_modified_by_type: str or ~azure.mgmt.policyinsights.models.CreatedByType + :keyword last_modified_at: The timestamp of resource last modification (UTC). + :paramtype last_modified_at: ~datetime.datetime + """ + super().__init__(**kwargs) self.created_by = created_by self.created_by_type = created_by_type self.created_at = created_at @@ -2654,7 +3088,7 @@ def __init__( self.last_modified_at = last_modified_at -class TrackedResourceModificationDetails(msrest.serialization.Model): +class TrackedResourceModificationDetails(_serialization.Model): """The details of the policy triggered deployment that created or modified the tracked resource. Variables are only populated by the server, and will be ignored when sending a request. @@ -2669,28 +3103,26 @@ class TrackedResourceModificationDetails(msrest.serialization.Model): """ _validation = { - 'policy_details': {'readonly': True}, - 'deployment_id': {'readonly': True}, - 'deployment_time': {'readonly': True}, + "policy_details": {"readonly": True}, + "deployment_id": {"readonly": True}, + "deployment_time": {"readonly": True}, } _attribute_map = { - 'policy_details': {'key': 'policyDetails', 'type': 'PolicyDetails'}, - 'deployment_id': {'key': 'deploymentId', 'type': 'str'}, - 'deployment_time': {'key': 'deploymentTime', 'type': 'iso-8601'}, + "policy_details": {"key": "policyDetails", "type": "PolicyDetails"}, + "deployment_id": {"key": "deploymentId", "type": "str"}, + "deployment_time": {"key": "deploymentTime", "type": "iso-8601"}, } - def __init__( - self, - **kwargs - ): - super(TrackedResourceModificationDetails, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.policy_details = None self.deployment_id = None self.deployment_time = None -class TypedErrorInfo(msrest.serialization.Model): +class TypedErrorInfo(_serialization.Model): """Scenario specific error details. Variables are only populated by the server, and will be ignored when sending a request. @@ -2702,19 +3134,17 @@ class TypedErrorInfo(msrest.serialization.Model): """ _validation = { - 'type': {'readonly': True}, - 'info': {'readonly': True}, + "type": {"readonly": True}, + "info": {"readonly": True}, } _attribute_map = { - 'type': {'key': 'type', 'type': 'str'}, - 'info': {'key': 'info', 'type': 'object'}, + "type": {"key": "type", "type": "str"}, + "info": {"key": "info", "type": "object"}, } - def __init__( - self, - **kwargs - ): - super(TypedErrorInfo, self).__init__(**kwargs) + def __init__(self, **kwargs): + """ """ + super().__init__(**kwargs) self.type = None self.info = None diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/_patch.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/_policy_insights_client_enums.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/_policy_insights_client_enums.py index ada9f0a6b76a..df9c0822f56e 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/_policy_insights_client_enums.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/models/_policy_insights_client_enums.py @@ -6,29 +6,12 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta -from six import with_metaclass - -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) - - -class ComplianceState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The compliance state that should be set on the resource. - """ +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ComplianceState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The compliance state that should be set on the resource.""" #: The resource is in compliance with the policy. COMPLIANT = "Compliant" @@ -37,18 +20,18 @@ class ComplianceState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): #: The compliance state of the resource is not known. UNKNOWN = "Unknown" -class CreatedByType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of identity that created the resource. - """ + +class CreatedByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of identity that created the resource.""" USER = "User" APPLICATION = "Application" MANAGED_IDENTITY = "ManagedIdentity" KEY = "Key" -class FieldRestrictionResult(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """The type of restriction that is imposed on the field. - """ + +class FieldRestrictionResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of restriction that is imposed on the field.""" #: The field and/or values are required by policy. REQUIRED = "Required" @@ -57,12 +40,33 @@ class FieldRestrictionResult(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum) #: The field and/or values will be denied by policy. DENY = "Deny" -class PolicyStatesResource(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class PolicyEventsResourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """PolicyEventsResourceType.""" DEFAULT = "default" + + +class PolicyStatesResource(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """PolicyStatesResource.""" + + DEFAULT = "default" + LATEST = "latest" + + +class PolicyStatesSummaryResourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """PolicyStatesSummaryResourceType.""" + LATEST = "latest" -class ResourceDiscoveryMode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + +class PolicyTrackedResourcesResourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """PolicyTrackedResourcesResourceType.""" + + DEFAULT = "default" + + +class ResourceDiscoveryMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The way resources to remediate are discovered. Defaults to ExistingNonCompliant if not specified. """ diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/__init__.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/__init__.py index 91acca23d156..6e81e19fe418 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/__init__.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/__init__.py @@ -15,13 +15,19 @@ from ._policy_restrictions_operations import PolicyRestrictionsOperations from ._attestations_operations import AttestationsOperations +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'PolicyTrackedResourcesOperations', - 'RemediationsOperations', - 'PolicyEventsOperations', - 'PolicyStatesOperations', - 'Operations', - 'PolicyMetadataOperations', - 'PolicyRestrictionsOperations', - 'AttestationsOperations', + "PolicyTrackedResourcesOperations", + "RemediationsOperations", + "PolicyEventsOperations", + "PolicyStatesOperations", + "Operations", + "PolicyMetadataOperations", + "PolicyRestrictionsOperations", + "AttestationsOperations", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_attestations_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_attestations_operations.py index f4644b6556b8..f962c688f94b 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_attestations_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_attestations_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,106 +6,482 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload + +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.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import 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 azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_for_subscription_request( + subscription_id: str, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_at_subscription_request( + attestation_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 = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "attestationName": _SERIALIZER.url("attestation_name", attestation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_at_subscription_request(attestation_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 = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "attestationName": _SERIALIZER.url("attestation_name", attestation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # 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_delete_at_subscription_request(attestation_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 = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "attestationName": _SERIALIZER.url("attestation_name", attestation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_group_request( + resource_group_name: str, + subscription_id: str, + *, + top: Optional[int] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_at_resource_group_request( + resource_group_name: str, attestation_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 = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "attestationName": _SERIALIZER.url("attestation_name", attestation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_at_resource_group_request( + resource_group_name: str, attestation_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 = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "attestationName": _SERIALIZER.url("attestation_name", attestation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # 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_delete_at_resource_group_request( + resource_group_name: str, attestation_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 = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + "attestationName": _SERIALIZER.url("attestation_name", attestation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +def build_list_for_resource_request( + resource_id: str, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -class AttestationsOperations(object): - """AttestationsOperations operations. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + accept = _headers.pop("Accept", "application/json") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct URL + _url = kwargs.pop("template_url", "/{resourceId}/providers/Microsoft.PolicyInsights/attestations") + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + } - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_at_resource_request(resource_id: str, attestation_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}") + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + "attestationName": _SERIALIZER.url("attestation_name", attestation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_at_resource_request(resource_id: str, attestation_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}") + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + "attestationName": _SERIALIZER.url("attestation_name", attestation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # 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_delete_at_resource_request(resource_id: str, attestation_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}") + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + "attestationName": _SERIALIZER.url("attestation_name", attestation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class AttestationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.PolicyInsightsClient`'s + :attr:`attestations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_for_subscription( - self, - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AttestationListResult"] + self, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> Iterable["_models.Attestation"]: """Gets all attestations for the subscription. - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AttestationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.AttestationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Attestation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AttestationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AttestationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - api_version = "2021-01-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_for_subscription_request( + subscription_id=self._config.subscription_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AttestationListResult', pipeline_response) + deserialized = self._deserialize("AttestationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -113,316 +490,386 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, response) 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 ItemPaged( - get_next, extract_data - ) - list_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations"} # type: ignore def _create_or_update_at_subscription_initial( - self, - attestation_name, # type: str - parameters, # type: "_models.Attestation" - **kwargs # type: Any - ): - # type: (...) -> "_models.Attestation" - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] + self, attestation_name: str, parameters: Union[_models.Attestation, IO], **kwargs: Any + ) -> _models.Attestation: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._create_or_update_at_subscription_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Attestation') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Attestation") + + request = build_create_or_update_at_subscription_request( + attestation_name=attestation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_at_subscription_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_at_subscription_initial.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + _create_or_update_at_subscription_initial.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @overload def begin_create_or_update_at_subscription( self, - attestation_name, # type: str - parameters, # type: "_models.Attestation" - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.Attestation"] + attestation_name: str, + parameters: _models.Attestation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Attestation]: """Creates or updates an attestation at subscription scope. - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_name: str - :param parameters: The attestation parameters. + :param parameters: The attestation parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.Attestation + :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 :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of LROPoller that returns either Attestation or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Attestation or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.policyinsights.models.Attestation] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_create_or_update_at_subscription( + self, attestation_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.Attestation]: + """Creates or updates an attestation at subscription scope. + + :param attestation_name: The name of the attestation. Required. + :type attestation_name: str + :param parameters: The attestation parameters. Required. + :type parameters: IO + :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 + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Attestation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update_at_subscription( + self, attestation_name: str, parameters: Union[_models.Attestation, IO], **kwargs: Any + ) -> LROPoller[_models.Attestation]: + """Creates or updates an attestation at subscription scope. + + :param attestation_name: The name of the attestation. Required. + :type attestation_name: str + :param parameters: The attestation parameters. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.Attestation 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 + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Attestation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._create_or_update_at_subscription_initial( + raw_result = self._create_or_update_at_subscription_initial( # type: ignore attestation_name=attestation_name, parameters=parameters, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Attestation', pipeline_response) - + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - def get_at_subscription( - self, - attestation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Attestation" + begin_create_or_update_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @distributed_trace + def get_at_subscription(self, attestation_name: str, **kwargs: Any) -> _models.Attestation: """Gets an existing attestation at subscription scope. - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Attestation, or the result of cls(response) + :return: Attestation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Attestation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - accept = "application/json" - - # Construct URL - url = self.get_at_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + + request = build_get_at_subscription_request( + attestation_name=attestation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore - def delete_at_subscription( - self, - attestation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + get_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @distributed_trace + def delete_at_subscription( # pylint: disable=inconsistent-return-statements + self, attestation_name: str, **kwargs: Any + ) -> None: """Deletes an existing attestation at subscription scope. - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_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) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - accept = "application/json" - - # Construct URL - url = self.delete_at_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_at_subscription_request( + attestation_name=attestation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + delete_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + @distributed_trace def list_for_resource_group( - self, - resource_group_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AttestationListResult"] + self, resource_group_name: str, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> Iterable["_models.Attestation"]: """Gets all attestations for the resource group. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AttestationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.AttestationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Attestation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AttestationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AttestationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - api_version = "2021-01-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AttestationListResult', pipeline_response) + deserialized = self._deserialize("AttestationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -431,330 +878,412 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, response) 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 ItemPaged( - get_next, extract_data - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations"} # type: ignore def _create_or_update_at_resource_group_initial( - self, - resource_group_name, # type: str - attestation_name, # type: str - parameters, # type: "_models.Attestation" - **kwargs # type: Any - ): - # type: (...) -> "_models.Attestation" - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] + self, resource_group_name: str, attestation_name: str, parameters: Union[_models.Attestation, IO], **kwargs: Any + ) -> _models.Attestation: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._create_or_update_at_resource_group_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Attestation') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Attestation") + + request = build_create_or_update_at_resource_group_request( + resource_group_name=resource_group_name, + attestation_name=attestation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_at_resource_group_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_at_resource_group_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + _create_or_update_at_resource_group_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @overload def begin_create_or_update_at_resource_group( self, - resource_group_name, # type: str - attestation_name, # type: str - parameters, # type: "_models.Attestation" - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.Attestation"] + resource_group_name: str, + attestation_name: str, + parameters: _models.Attestation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Attestation]: """Creates or updates an attestation at resource group scope. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_name: str - :param parameters: The attestation parameters. + :param parameters: The attestation parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.Attestation + :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 :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of LROPoller that returns either Attestation or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Attestation or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.policyinsights.models.Attestation] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_create_or_update_at_resource_group( + self, + resource_group_name: str, + attestation_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Attestation]: + """Creates or updates an attestation at resource group scope. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param attestation_name: The name of the attestation. Required. + :type attestation_name: str + :param parameters: The attestation parameters. Required. + :type parameters: IO + :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 + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Attestation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update_at_resource_group( + self, resource_group_name: str, attestation_name: str, parameters: Union[_models.Attestation, IO], **kwargs: Any + ) -> LROPoller[_models.Attestation]: + """Creates or updates an attestation at resource group scope. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param attestation_name: The name of the attestation. Required. + :type attestation_name: str + :param parameters: The attestation parameters. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.Attestation 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 + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Attestation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._create_or_update_at_resource_group_initial( + raw_result = self._create_or_update_at_resource_group_initial( # type: ignore resource_group_name=resource_group_name, attestation_name=attestation_name, parameters=parameters, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Attestation', pipeline_response) - + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + begin_create_or_update_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @distributed_trace def get_at_resource_group( - self, - resource_group_name, # type: str - attestation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Attestation" + self, resource_group_name: str, attestation_name: str, **kwargs: Any + ) -> _models.Attestation: """Gets an existing attestation at resource group scope. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Attestation, or the result of cls(response) + :return: Attestation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Attestation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - accept = "application/json" - - # Construct URL - url = self.get_at_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + + request = build_get_at_resource_group_request( + resource_group_name=resource_group_name, + attestation_name=attestation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore - def delete_at_resource_group( - self, - resource_group_name, # type: str - attestation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + get_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @distributed_trace + def delete_at_resource_group( # pylint: disable=inconsistent-return-statements + self, resource_group_name: str, attestation_name: str, **kwargs: Any + ) -> None: """Deletes an existing attestation at resource group scope. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_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) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - accept = "application/json" - - # Construct URL - url = self.delete_at_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_at_resource_group_request( + resource_group_name=resource_group_name, + attestation_name=attestation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + delete_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + @distributed_trace def list_for_resource( - self, - resource_id, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.AttestationListResult"] + self, resource_id: str, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> Iterable["_models.Attestation"]: """Gets all attestations for a resource. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either AttestationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.AttestationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Attestation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.AttestationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.AttestationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - api_version = "2021-01-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_for_resource_request( + resource_id=resource_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('AttestationListResult', pipeline_response) + deserialized = self._deserialize("AttestationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -763,261 +1292,340 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, response) 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 ItemPaged( - get_next, extract_data - ) - list_for_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/attestations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/attestations"} # type: ignore def _create_or_update_at_resource_initial( - self, - resource_id, # type: str - attestation_name, # type: str - parameters, # type: "_models.Attestation" - **kwargs # type: Any - ): - # type: (...) -> "_models.Attestation" - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] + self, resource_id: str, attestation_name: str, parameters: Union[_models.Attestation, IO], **kwargs: Any + ) -> _models.Attestation: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self._create_or_update_at_resource_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Attestation') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Attestation") + + request = build_create_or_update_at_resource_request( + resource_id=resource_id, + attestation_name=attestation_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self._create_or_update_at_resource_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - _create_or_update_at_resource_initial.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + _create_or_update_at_resource_initial.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @overload def begin_create_or_update_at_resource( self, - resource_id, # type: str - attestation_name, # type: str - parameters, # type: "_models.Attestation" - **kwargs # type: Any - ): - # type: (...) -> LROPoller["_models.Attestation"] + resource_id: str, + attestation_name: str, + parameters: _models.Attestation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Attestation]: """Creates or updates an attestation at resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_name: str - :param parameters: The attestation parameters. + :param parameters: The attestation parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.Attestation + :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 :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of LROPoller that returns either Attestation or the result of cls(response) + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Attestation or the result of + cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.policyinsights.models.Attestation] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + + @overload + def begin_create_or_update_at_resource( + self, + resource_id: str, + attestation_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[_models.Attestation]: + """Creates or updates an attestation at resource scope. + + :param resource_id: Resource ID. Required. + :type resource_id: str + :param attestation_name: The name of the attestation. Required. + :type attestation_name: str + :param parameters: The attestation parameters. Required. + :type parameters: IO + :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 + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Attestation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def begin_create_or_update_at_resource( + self, resource_id: str, attestation_name: str, parameters: Union[_models.Attestation, IO], **kwargs: Any + ) -> LROPoller[_models.Attestation]: + """Creates or updates an attestation at resource scope. + + :param resource_id: Resource ID. Required. + :type resource_id: str + :param attestation_name: The name of the attestation. Required. + :type attestation_name: str + :param parameters: The attestation parameters. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.Attestation 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 + :keyword str continuation_token: A continuation token to restart a poller from a saved state. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. + :paramtype polling: bool or ~azure.core.polling.PollingMethod + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + :return: An instance of LROPoller that returns either Attestation or the result of + cls(response) + :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.policyinsights.models.Attestation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._create_or_update_at_resource_initial( + raw_result = self._create_or_update_at_resource_initial( # type: ignore resource_id=resource_id, attestation_name=attestation_name, parameters=parameters, - cls=lambda x,y,z: x, + api_version=api_version, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) - - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) + kwargs.pop("error_map", None) def get_long_running_output(pipeline_response): - deserialized = self._deserialize('Attestation', pipeline_response) - + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast(PollingMethod, ARMPolling(lro_delay, **kwargs)) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_create_or_update_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - def get_at_resource( - self, - resource_id, # type: str - attestation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Attestation" + begin_create_or_update_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @distributed_trace + def get_at_resource(self, resource_id: str, attestation_name: str, **kwargs: Any) -> _models.Attestation: """Gets an existing attestation at resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Attestation, or the result of cls(response) + :return: Attestation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Attestation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Attestation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - accept = "application/json" - - # Construct URL - url = self.get_at_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Attestation] + + request = build_get_at_resource_request( + resource_id=resource_id, + attestation_name=attestation_name, + api_version=api_version, + template_url=self.get_at_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Attestation', pipeline_response) + deserialized = self._deserialize("Attestation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore - def delete_at_resource( - self, - resource_id, # type: str - attestation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + get_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore + + @distributed_trace + def delete_at_resource( # pylint: disable=inconsistent-return-statements + self, resource_id: str, attestation_name: str, **kwargs: Any + ) -> None: """Deletes an existing attestation at individual resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param attestation_name: The name of the attestation. + :param attestation_name: The name of the attestation. Required. :type attestation_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) + :return: None or the result of cls(response) :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-01-01" - accept = "application/json" - - # Construct URL - url = self.delete_at_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'attestationName': self._serialize.url("attestation_name", attestation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_delete_at_resource_request( + resource_id=resource_id, + attestation_name=attestation_name, + api_version=api_version, + template_url=self.delete_at_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **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.ErrorResponseAutoGenerated2, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated2, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - delete_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}'} # type: ignore + delete_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/attestations/{attestationName}"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_operations.py index 1a9cecc21a3c..73da2e683def 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,89 +6,120 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Optional, TypeVar + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import 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 .._serialization import Serializer +from .._vendor import _convert_request + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.PolicyInsights/operations") - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") -class Operations(object): - """Operations operations. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + +class Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.PolicyInsightsClient`'s + :attr:`operations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def list( - self, - **kwargs # type: Any - ): - # type: (...) -> "_models.OperationsListResults" + 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(self, **kwargs: Any) -> _models.OperationsListResults: """Lists available operations. :keyword callable cls: A custom type or function that will be passed the direct response - :return: OperationsListResults, or the result of cls(response) + :return: OperationsListResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.OperationsListResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationsListResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct URL - url = self.list.metadata['url'] # type: ignore + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.OperationsListResults] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + 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) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('OperationsListResults', pipeline_response) + deserialized = self._deserialize("OperationsListResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - list.metadata = {'url': '/providers/Microsoft.PolicyInsights/operations'} # type: ignore + + list.metadata = {"url": "/providers/Microsoft.PolicyInsights/operations"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_patch.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_events_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_events_operations.py index 3a31b9099118..0ec527e90f75 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_events_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_events_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,144 +7,858 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union + +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.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import 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 .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_query_results_for_management_group_request( + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + management_group_name: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyEventsResource": _SERIALIZER.url("policy_events_resource", policy_events_resource, "str"), + "managementGroupsNamespace": _SERIALIZER.url("management_groups_namespace", management_groups_namespace, "str"), + "managementGroupName": _SERIALIZER.url("management_group_name", management_group_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_subscription_request( + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + subscription_id: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyEventsResource": _SERIALIZER.url("policy_events_resource", policy_events_resource, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_resource_group_request( + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + subscription_id: str, + resource_group_name: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyEventsResource": _SERIALIZER.url("policy_events_resource", policy_events_resource, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_resource_request( + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + resource_id: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + expand: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{resourceId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyEventsResource": _SERIALIZER.url("policy_events_resource", policy_events_resource, "str"), + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_policy_set_definition_request( + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + subscription_id: str, + policy_set_definition_name: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyEventsResource": _SERIALIZER.url("policy_events_resource", policy_events_resource, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "authorizationNamespace": _SERIALIZER.url("authorization_namespace", authorization_namespace, "str"), + "policySetDefinitionName": _SERIALIZER.url("policy_set_definition_name", policy_set_definition_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_policy_definition_request( + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + subscription_id: str, + policy_definition_name: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyEventsResource": _SERIALIZER.url("policy_events_resource", policy_events_resource, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "authorizationNamespace": _SERIALIZER.url("authorization_namespace", authorization_namespace, "str"), + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_subscription_level_policy_assignment_request( + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + subscription_id: str, + policy_assignment_name: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyEventsResource": _SERIALIZER.url("policy_events_resource", policy_events_resource, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "authorizationNamespace": _SERIALIZER.url("authorization_namespace", authorization_namespace, "str"), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_resource_group_level_policy_assignment_request( + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + subscription_id: str, + resource_group_name: str, + policy_assignment_name: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyEventsResource": _SERIALIZER.url("policy_events_resource", policy_events_resource, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "authorizationNamespace": _SERIALIZER.url("authorization_namespace", authorization_namespace, "str"), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class PolicyEventsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -class PolicyEventsOperations(object): - """PolicyEventsOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.PolicyInsightsClient`'s + :attr:`policy_events` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_query_results_for_management_group( self, - management_group_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyEventsQueryResults"] + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + management_group_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyEvent"]: """Queries policy events for the resources under the management group. - :param management_group_name: Management group name. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param management_group_name: Management group name. Required. :type management_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - policy_events_resource = "default" - management_groups_namespace = "Microsoft.Management" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupName': self._serialize.url("management_group_name", management_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_management_group_request( + policy_events_resource=policy_events_resource, + management_group_name=management_group_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.list_query_results_for_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -152,117 +867,131 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + list_query_results_for_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore + + @distributed_trace def list_query_results_for_subscription( self, - subscription_id, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyEventsQueryResults"] + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + subscription_id: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyEvent"]: """Queries policy events for the resources under the subscription. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - policy_events_resource = "default" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_subscription_request( + policy_events_resource=policy_events_resource, + subscription_id=subscription_id, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + api_version=api_version, + template_url=self.list_query_results_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -271,121 +1000,135 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_query_results_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore + @distributed_trace def list_query_results_for_resource_group( self, - subscription_id, # type: str - resource_group_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyEventsQueryResults"] + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + subscription_id: str, + resource_group_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyEvent"]: """Queries policy events for the resources under the resource group. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - policy_events_resource = "default" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_resource_group_request( + policy_events_resource=policy_events_resource, + subscription_id=subscription_id, + resource_group_name=resource_group_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + api_version=api_version, + template_url=self.list_query_results_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -394,121 +1137,136 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_query_results_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore + @distributed_trace def list_query_results_for_resource( self, - resource_id, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyEventsQueryResults"] + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + resource_id: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyEvent"]: """Queries policy events for the resource. - :param resource_id: Resource ID. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param resource_id: Resource ID. Required. :type resource_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _expand = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _expand = query_options.expand - _skip_token = query_options.skip_token - policy_events_resource = "default" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", _expand, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _expand = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _expand = query_options.expand + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_resource_request( + policy_events_resource=policy_events_resource, + resource_id=resource_id, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + expand=_expand, + skip_token=_skip_token, + api_version=api_version, + template_url=self.list_query_results_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _expand = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _expand = query_options.expand + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -517,123 +1275,141 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + list_query_results_for_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore + + @distributed_trace def list_query_results_for_policy_set_definition( self, - subscription_id, # type: str - policy_set_definition_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyEventsQueryResults"] + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + subscription_id: str, + policy_set_definition_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyEvent"]: """Queries policy events for the subscription level policy set definition. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_set_definition_name: Policy set definition name. + :param policy_set_definition_name: Policy set definition name. Required. :type policy_set_definition_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - policy_events_resource = "default" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_policy_set_definition.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policySetDefinitionName': self._serialize.url("policy_set_definition_name", policy_set_definition_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_policy_set_definition_request( + policy_events_resource=policy_events_resource, + subscription_id=subscription_id, + policy_set_definition_name=policy_set_definition_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_policy_set_definition.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -642,123 +1418,141 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_policy_set_definition.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_query_results_for_policy_set_definition.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore + @distributed_trace def list_query_results_for_policy_definition( self, - subscription_id, # type: str - policy_definition_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyEventsQueryResults"] + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + subscription_id: str, + policy_definition_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyEvent"]: """Queries policy events for the subscription level policy definition. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_definition_name: Policy definition name. + :param policy_definition_name: Policy definition name. Required. :type policy_definition_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - policy_events_resource = "default" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_policy_definition.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyDefinitionName': self._serialize.url("policy_definition_name", policy_definition_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_policy_definition_request( + policy_events_resource=policy_events_resource, + subscription_id=subscription_id, + policy_definition_name=policy_definition_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_policy_definition.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -767,123 +1561,141 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_policy_definition.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + list_query_results_for_policy_definition.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore + + @distributed_trace def list_query_results_for_subscription_level_policy_assignment( self, - subscription_id, # type: str - policy_assignment_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyEventsQueryResults"] + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + subscription_id: str, + policy_assignment_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyEvent"]: """Queries policy events for the subscription level policy assignment. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_assignment_name: Policy assignment name. + :param policy_assignment_name: Policy assignment name. Required. :type policy_assignment_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - policy_events_resource = "default" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_subscription_level_policy_assignment.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyAssignmentName': self._serialize.url("policy_assignment_name", policy_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_subscription_level_policy_assignment_request( + policy_events_resource=policy_events_resource, + subscription_id=subscription_id, + policy_assignment_name=policy_assignment_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_subscription_level_policy_assignment.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -892,127 +1704,145 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_subscription_level_policy_assignment.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_query_results_for_subscription_level_policy_assignment.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore + @distributed_trace def list_query_results_for_resource_group_level_policy_assignment( self, - subscription_id, # type: str - resource_group_name, # type: str - policy_assignment_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyEventsQueryResults"] + policy_events_resource: Union[str, "_models.PolicyEventsResourceType"], + subscription_id: str, + resource_group_name: str, + policy_assignment_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyEvent"]: """Queries policy events for the resource group level policy assignment. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_events_resource: The name of the virtual resource under PolicyEvents resource + type; only "default" is allowed. "default" Required. + :type policy_events_resource: str or ~azure.mgmt.policyinsights.models.PolicyEventsResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param policy_assignment_name: Policy assignment name. + :param policy_assignment_name: Policy assignment name. Required. :type policy_assignment_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyEventsQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEventsQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyEvent or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyEvent] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyEventsQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyEventsQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - policy_events_resource = "default" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource_group_level_policy_assignment.metadata['url'] # type: ignore - path_format_arguments = { - 'policyEventsResource': self._serialize.url("policy_events_resource", policy_events_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyAssignmentName': self._serialize.url("policy_assignment_name", policy_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_resource_group_level_policy_assignment_request( + policy_events_resource=policy_events_resource, + subscription_id=subscription_id, + resource_group_name=resource_group_name, + policy_assignment_name=policy_assignment_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_resource_group_level_policy_assignment.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyEventsQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyEventsQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1021,17 +1851,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_resource_group_level_policy_assignment.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_query_results_for_resource_group_level_policy_assignment.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_metadata_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_metadata_operations.py index de341b26ca16..a1999f5c12f5 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_metadata_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_metadata_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,151 +6,206 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, 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.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import 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 .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_get_resource_request(resource_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.PolicyInsights/policyMetadata/{resourceName}") + path_format_arguments = { + "resourceName": _SERIALIZER.url("resource_name", resource_name, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # 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_request(*, top: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/providers/Microsoft.PolicyInsights/policyMetadata") -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") -class PolicyMetadataOperations(object): - """PolicyMetadataOperations operations. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. +class PolicyMetadataOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.PolicyInsightsClient`'s + :attr:`policy_metadata` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config - - def get_resource( - self, - resource_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.PolicyMetadata" + 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 get_resource(self, resource_name: str, **kwargs: Any) -> _models.PolicyMetadata: """Get policy metadata resource. - :param resource_name: The name of the policy metadata resource. + :param resource_name: The name of the policy metadata resource. Required. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: PolicyMetadata, or the result of cls(response) + :return: PolicyMetadata or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.PolicyMetadata - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyMetadata"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.get_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceName': self._serialize.url("resource_name", resource_name, 'str', skip_quote=True), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyMetadata] + + request = build_get_resource_request( + resource_name=resource_name, + api_version=api_version, + template_url=self.get_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(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, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('PolicyMetadata', pipeline_response) + deserialized = self._deserialize("PolicyMetadata", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_resource.metadata = {'url': '/providers/Microsoft.PolicyInsights/policyMetadata/{resourceName}'} # type: ignore + get_resource.metadata = {"url": "/providers/Microsoft.PolicyInsights/policyMetadata/{resourceName}"} # type: ignore + + @distributed_trace def list( - self, - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyMetadataCollection"] + self, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> Iterable["_models.SlimPolicyMetadata"]: """Get a list of the policy metadata resources. - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyMetadataCollection or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyMetadataCollection] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either SlimPolicyMetadata or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.SlimPolicyMetadata] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyMetadataCollection"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyMetadataCollection] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - if query_options is not None: - _top = query_options.top - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list.metadata['url'] # type: ignore - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + if query_options is not None: + _top = query_options.top + + request = build_list_request( + top=_top, + 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) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyMetadataCollection', pipeline_response) + deserialized = self._deserialize("PolicyMetadataCollection", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -158,17 +214,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, response) 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.metadata = {'url': '/providers/Microsoft.PolicyInsights/policyMetadata'} # type: ignore + return ItemPaged(get_next, extract_data) + + list.metadata = {"url": "/providers/Microsoft.PolicyInsights/policyMetadata"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_restrictions_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_restrictions_operations.py index fc1b7cfaf4cf..b95320c14956 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_restrictions_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_restrictions_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,166 +6,513 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import 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 .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Optional, TypeVar +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False -class PolicyRestrictionsOperations(object): - """PolicyRestrictionsOperations operations. - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. +def build_check_at_subscription_scope_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions" + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_check_at_resource_group_scope_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 = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url( + "resource_group_name", resource_group_name, "str", max_length=90, min_length=1 + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_check_at_management_group_scope_request(management_group_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions", + ) # pylint: disable=line-too-long + path_format_arguments = { + "managementGroupsNamespace": _SERIALIZER.url("management_groups_namespace", management_groups_namespace, "str"), + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class PolicyRestrictionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.PolicyInsightsClient`'s + :attr:`policy_restrictions` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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") + @overload def check_at_subscription_scope( - self, - parameters, # type: "_models.CheckRestrictionsRequest" - **kwargs # type: Any - ): - # type: (...) -> "_models.CheckRestrictionsResult" + self, parameters: _models.CheckRestrictionsRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckRestrictionsResult: """Checks what restrictions Azure Policy will place on a resource within a subscription. - :param parameters: The check policy restrictions parameters. + :param parameters: The check policy restrictions parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.CheckRestrictionsRequest + :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: CheckRestrictionsResult or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_at_subscription_scope( + self, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckRestrictionsResult: + """Checks what restrictions Azure Policy will place on a resource within a subscription. + + :param parameters: The check policy restrictions parameters. Required. + :type parameters: IO + :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: CheckRestrictionsResult or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_at_subscription_scope( + self, parameters: Union[_models.CheckRestrictionsRequest, IO], **kwargs: Any + ) -> _models.CheckRestrictionsResult: + """Checks what restrictions Azure Policy will place on a resource within a subscription. + + :param parameters: The check policy restrictions parameters. Is either a model type or a IO + type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.CheckRestrictionsRequest 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 - :return: CheckRestrictionsResult, or the result of cls(response) + :return: CheckRestrictionsResult or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckRestrictionsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-07-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.check_at_subscription_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'CheckRestrictionsRequest') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckRestrictionsResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CheckRestrictionsRequest") + + request = build_check_at_subscription_scope_request( + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.check_at_subscription_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # 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, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckRestrictionsResult', pipeline_response) + deserialized = self._deserialize("CheckRestrictionsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_at_subscription_scope.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions'} # type: ignore + check_at_subscription_scope.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions"} # type: ignore + + @overload def check_at_resource_group_scope( self, - resource_group_name, # type: str - parameters, # type: "_models.CheckRestrictionsRequest" - **kwargs # type: Any - ): - # type: (...) -> "_models.CheckRestrictionsResult" + resource_group_name: str, + parameters: _models.CheckRestrictionsRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckRestrictionsResult: """Checks what restrictions Azure Policy will place on a resource within a resource group. Use this when the resource group the resource will be created in is already known. :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. :type resource_group_name: str - :param parameters: The check policy restrictions parameters. + :param parameters: The check policy restrictions parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.CheckRestrictionsRequest + :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: CheckRestrictionsResult, or the result of cls(response) + :return: CheckRestrictionsResult or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_at_resource_group_scope( + self, resource_group_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckRestrictionsResult: + """Checks what restrictions Azure Policy will place on a resource within a resource group. Use + this when the resource group the resource will be created in is already known. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param parameters: The check policy restrictions parameters. Required. + :type parameters: IO + :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: CheckRestrictionsResult or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_at_resource_group_scope( + self, resource_group_name: str, parameters: Union[_models.CheckRestrictionsRequest, IO], **kwargs: Any + ) -> _models.CheckRestrictionsResult: + """Checks what restrictions Azure Policy will place on a resource within a resource group. Use + this when the resource group the resource will be created in is already known. + + :param resource_group_name: The name of the resource group. The name is case insensitive. + Required. + :type resource_group_name: str + :param parameters: The check policy restrictions parameters. Is either a model type or a IO + type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.CheckRestrictionsRequest 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 + :return: CheckRestrictionsResult or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckRestrictionsResult"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2020-07-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.check_at_resource_group_scope.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1), + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckRestrictionsResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CheckRestrictionsRequest") + + request = build_check_at_resource_group_scope_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.check_at_resource_group_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # 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) + + deserialized = self._deserialize("CheckRestrictionsResult", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + check_at_resource_group_scope.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions"} # type: ignore + + @overload + def check_at_management_group_scope( + self, + management_group_id: str, + parameters: _models.CheckManagementGroupRestrictionsRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CheckRestrictionsResult: + """Checks what restrictions Azure Policy will place on resources within a management group. + + :param management_group_id: Management group ID. Required. + :type management_group_id: str + :param parameters: The check policy restrictions parameters. Required. + :type parameters: ~azure.mgmt.policyinsights.models.CheckManagementGroupRestrictionsRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckRestrictionsResult or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def check_at_management_group_scope( + self, management_group_id: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CheckRestrictionsResult: + """Checks what restrictions Azure Policy will place on resources within a management group. + + :param management_group_id: Management group ID. Required. + :type management_group_id: str + :param parameters: The check policy restrictions parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: CheckRestrictionsResult or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def check_at_management_group_scope( + self, + management_group_id: str, + parameters: Union[_models.CheckManagementGroupRestrictionsRequest, IO], + **kwargs: Any + ) -> _models.CheckRestrictionsResult: + """Checks what restrictions Azure Policy will place on resources within a management group. + + :param management_group_id: Management group ID. Required. + :type management_group_id: str + :param parameters: The check policy restrictions parameters. Is either a model type or a IO + type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.CheckManagementGroupRestrictionsRequest or + IO + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str + :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 + :return: CheckRestrictionsResult or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.CheckRestrictionsResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'CheckRestrictionsRequest') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-03-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.CheckRestrictionsResult] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "CheckManagementGroupRestrictionsRequest") + + request = build_check_at_management_group_scope_request( + management_group_id=management_group_id, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.check_at_management_group_scope.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # 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, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('CheckRestrictionsResult', pipeline_response) + deserialized = self._deserialize("CheckRestrictionsResult", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - check_at_resource_group_scope.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions'} # type: ignore + + check_at_management_group_scope.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_states_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_states_operations.py index 31ce121ac6b2..d377edb07982 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_states_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_states_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,150 +7,1316 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union, cast + +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.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod +from azure.core.rest import 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 azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models +from .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_query_results_for_management_group_request( + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + management_group_name: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesResource": _SERIALIZER.url("policy_states_resource", policy_states_resource, "str"), + "managementGroupsNamespace": _SERIALIZER.url("management_groups_namespace", management_groups_namespace, "str"), + "managementGroupName": _SERIALIZER.url("management_group_name", management_group_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_summarize_for_management_group_request( + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + management_group_name: str, + *, + top: Optional[int] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesSummaryResource": _SERIALIZER.url( + "policy_states_summary_resource", policy_states_summary_resource, "str" + ), + "managementGroupsNamespace": _SERIALIZER.url("management_groups_namespace", management_groups_namespace, "str"), + "managementGroupName": _SERIALIZER.url("management_group_name", management_group_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_subscription_request( + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + subscription_id: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesResource": _SERIALIZER.url("policy_states_resource", policy_states_resource, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_summarize_for_subscription_request( + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + subscription_id: str, + *, + top: Optional[int] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesSummaryResource": _SERIALIZER.url( + "policy_states_summary_resource", policy_states_summary_resource, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_resource_group_request( + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + subscription_id: str, + resource_group_name: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesResource": _SERIALIZER.url("policy_states_resource", policy_states_resource, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_summarize_for_resource_group_request( + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + subscription_id: str, + resource_group_name: str, + *, + top: Optional[int] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesSummaryResource": _SERIALIZER.url( + "policy_states_summary_resource", policy_states_summary_resource, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_resource_request( + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + resource_id: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + expand: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesResource": _SERIALIZER.url("policy_states_resource", policy_states_resource, "str"), + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if expand is not None: + _params["$expand"] = _SERIALIZER.query("expand", expand, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_summarize_for_resource_request( + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + resource_id: str, + *, + top: Optional[int] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesSummaryResource": _SERIALIZER.url( + "policy_states_summary_resource", policy_states_summary_resource, "str" + ), + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_trigger_subscription_evaluation_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_trigger_resource_group_evaluation_request( + subscription_id: str, resource_group_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_policy_set_definition_request( + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + subscription_id: str, + policy_set_definition_name: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesResource": _SERIALIZER.url("policy_states_resource", policy_states_resource, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "authorizationNamespace": _SERIALIZER.url("authorization_namespace", authorization_namespace, "str"), + "policySetDefinitionName": _SERIALIZER.url("policy_set_definition_name", policy_set_definition_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_summarize_for_policy_set_definition_request( + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + subscription_id: str, + policy_set_definition_name: str, + *, + top: Optional[int] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesSummaryResource": _SERIALIZER.url( + "policy_states_summary_resource", policy_states_summary_resource, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "authorizationNamespace": _SERIALIZER.url("authorization_namespace", authorization_namespace, "str"), + "policySetDefinitionName": _SERIALIZER.url("policy_set_definition_name", policy_set_definition_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_policy_definition_request( + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + subscription_id: str, + policy_definition_name: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesResource": _SERIALIZER.url("policy_states_resource", policy_states_resource, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "authorizationNamespace": _SERIALIZER.url("authorization_namespace", authorization_namespace, "str"), + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_summarize_for_policy_definition_request( + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + subscription_id: str, + policy_definition_name: str, + *, + top: Optional[int] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesSummaryResource": _SERIALIZER.url( + "policy_states_summary_resource", policy_states_summary_resource, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "authorizationNamespace": _SERIALIZER.url("authorization_namespace", authorization_namespace, "str"), + "policyDefinitionName": _SERIALIZER.url("policy_definition_name", policy_definition_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_subscription_level_policy_assignment_request( + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + subscription_id: str, + policy_assignment_name: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesResource": _SERIALIZER.url("policy_states_resource", policy_states_resource, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "authorizationNamespace": _SERIALIZER.url("authorization_namespace", authorization_namespace, "str"), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_summarize_for_subscription_level_policy_assignment_request( + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + subscription_id: str, + policy_assignment_name: str, + *, + top: Optional[int] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesSummaryResource": _SERIALIZER.url( + "policy_states_summary_resource", policy_states_summary_resource, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "authorizationNamespace": _SERIALIZER.url("authorization_namespace", authorization_namespace, "str"), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_resource_group_level_policy_assignment_request( + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + subscription_id: str, + resource_group_name: str, + policy_assignment_name: str, + *, + top: Optional[int] = None, + order_by: Optional[str] = None, + select: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + apply: Optional[str] = None, + skip_token: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesResource": _SERIALIZER.url("policy_states_resource", policy_states_resource, "str"), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "authorizationNamespace": _SERIALIZER.url("authorization_namespace", authorization_namespace, "str"), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if order_by is not None: + _params["$orderby"] = _SERIALIZER.query("order_by", order_by, "str") + if select is not None: + _params["$select"] = _SERIALIZER.query("select", select, "str") + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + if apply is not None: + _params["$apply"] = _SERIALIZER.query("apply", apply, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_next_link_request(next_link: str, *, skip_token: Optional[str] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "{nextLink}") + path_format_arguments = { + "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if skip_token is not None: + _params["$skiptoken"] = _SERIALIZER.query("skip_token", skip_token, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_summarize_for_resource_group_level_policy_assignment_request( + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + subscription_id: str, + resource_group_name: str, + policy_assignment_name: str, + *, + top: Optional[int] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyStatesSummaryResource": _SERIALIZER.url( + "policy_states_summary_resource", policy_states_summary_resource, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "authorizationNamespace": _SERIALIZER.url("authorization_namespace", authorization_namespace, "str"), + "policyAssignmentName": _SERIALIZER.url("policy_assignment_name", policy_assignment_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if from_property is not None: + _params["$from"] = _SERIALIZER.query("from_property", from_property, "iso-8601") + if to is not None: + _params["$to"] = _SERIALIZER.query("to", to, "iso-8601") + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class PolicyStatesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -class PolicyStatesOperations(object): - """PolicyStatesOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.PolicyInsightsClient`'s + :attr:`policy_states` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_query_results_for_management_group( self, - policy_states_resource, # type: Union[str, "_models.PolicyStatesResource"] - management_group_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyStatesQueryResults"] + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + management_group_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyState"]: """Queries policy states for the resources under the management group. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param management_group_name: Management group name. + :param management_group_name: Management group name. Required. :type management_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - management_groups_namespace = "Microsoft.Management" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupName': self._serialize.url("management_group_name", management_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_management_group_request( + policy_states_resource=policy_states_resource, + management_group_name=management_group_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.list_query_results_for_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -158,201 +1325,221 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_query_results_for_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + @distributed_trace def summarize_for_management_group( self, - management_group_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> "_models.SummarizeResults" + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + management_group_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> _models.SummarizeResults: """Summarizes policy states for the resources under the management group. - :param management_group_name: Management group name. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param management_group_name: Management group name. Required. :type management_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - management_groups_namespace = "Microsoft.Management" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupName': self._serialize.url("management_group_name", management_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_management_group_request( + policy_states_summary_resource=policy_states_summary_resource, + management_group_name=management_group_name, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.summarize_for_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore + summarize_for_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore + + @distributed_trace def list_query_results_for_subscription( self, - policy_states_resource, # type: Union[str, "_models.PolicyStatesResource"] - subscription_id, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyStatesQueryResults"] + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + subscription_id: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyState"]: """Queries policy states for the resources under the subscription. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_subscription_request( + policy_states_resource=policy_states_resource, + subscription_id=subscription_id, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + api_version=api_version, + template_url=self.list_query_results_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -361,203 +1548,219 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_query_results_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + @distributed_trace def summarize_for_subscription( self, - subscription_id, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> "_models.SummarizeResults" + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + subscription_id: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> _models.SummarizeResults: """Summarizes policy states for the resources under the subscription. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_subscription_request( + policy_states_summary_resource=policy_states_summary_resource, + subscription_id=subscription_id, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + api_version=api_version, + template_url=self.summarize_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore + summarize_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore + + @distributed_trace def list_query_results_for_resource_group( self, - policy_states_resource, # type: Union[str, "_models.PolicyStatesResource"] - subscription_id, # type: str - resource_group_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyStatesQueryResults"] + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + subscription_id: str, + resource_group_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyState"]: """Queries policy states for the resources under the resource group. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_resource_group_request( + policy_states_resource=policy_states_resource, + subscription_id=subscription_id, + resource_group_name=resource_group_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + api_version=api_version, + template_url=self.list_query_results_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -566,207 +1769,224 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_query_results_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + @distributed_trace def summarize_for_resource_group( self, - subscription_id, # type: str - resource_group_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> "_models.SummarizeResults" + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + subscription_id: str, + resource_group_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> _models.SummarizeResults: """Summarizes policy states for the resources under the resource group. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_resource_group_request( + policy_states_summary_resource=policy_states_summary_resource, + subscription_id=subscription_id, + resource_group_name=resource_group_name, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + api_version=api_version, + template_url=self.summarize_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore + summarize_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore + + @distributed_trace def list_query_results_for_resource( self, - policy_states_resource, # type: Union[str, "_models.PolicyStatesResource"] - resource_id, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyStatesQueryResults"] + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + resource_id: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyState"]: """Queries policy states for the resource. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _expand = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _expand = query_options.expand - _skip_token = query_options.skip_token - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _expand is not None: - query_parameters['$expand'] = self._serialize.query("expand", _expand, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _expand = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _expand = query_options.expand + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_resource_request( + policy_states_resource=policy_states_resource, + resource_id=resource_id, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + expand=_expand, + skip_token=_skip_token, + api_version=api_version, + template_url=self.list_query_results_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _expand = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _expand = query_options.expand + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -775,416 +1995,437 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + list_query_results_for_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + + @distributed_trace def summarize_for_resource( self, - resource_id, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> "_models.SummarizeResults" + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + resource_id: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> _models.SummarizeResults: """Summarizes policy states for the resource. - :param resource_id: Resource ID. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param resource_id: Resource ID. Required. :type resource_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_resource_request( + policy_states_summary_resource=policy_states_summary_resource, + resource_id=resource_id, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + api_version=api_version, + template_url=self.summarize_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore - def _trigger_subscription_evaluation_initial( - self, - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None - cls = kwargs.pop('cls', None) # type: ClsType[None] + summarize_for_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore + + def _trigger_subscription_evaluation_initial( # pylint: disable=inconsistent-return-statements + self, subscription_id: str, **kwargs: Any + ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self._trigger_subscription_evaluation_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_trigger_subscription_evaluation_request( + subscription_id=subscription_id, + api_version=api_version, + template_url=self._trigger_subscription_evaluation_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _trigger_subscription_evaluation_initial.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation'} # type: ignore + _trigger_subscription_evaluation_initial.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation"} # type: ignore - def begin_trigger_subscription_evaluation( - self, - subscription_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> LROPoller[None] + @distributed_trace + def begin_trigger_subscription_evaluation(self, subscription_id: str, **kwargs: Any) -> LROPoller[None]: """Triggers a policy evaluation scan for all the resources under the subscription. - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._trigger_subscription_evaluation_initial( + raw_result = self._trigger_subscription_evaluation_initial( # type: ignore subscription_id=subscription_id, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) + kwargs.pop("error_map", None) - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) - - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - path_format_arguments = { - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_trigger_subscription_evaluation.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - def _trigger_resource_group_evaluation_initial( - self, - subscription_id, # type: str - resource_group_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> None - cls = kwargs.pop('cls', None) # type: ClsType[None] + begin_trigger_subscription_evaluation.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation"} # type: ignore + + def _trigger_resource_group_evaluation_initial( # pylint: disable=inconsistent-return-statements + self, subscription_id: str, resource_group_name: str, **kwargs: Any + ) -> None: error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self._trigger_resource_group_evaluation_initial.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + request = build_trigger_resource_group_evaluation_request( + subscription_id=subscription_id, + resource_group_name=resource_group_name, + api_version=api_version, + template_url=self._trigger_resource_group_evaluation_initial.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) - _trigger_resource_group_evaluation_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation'} # type: ignore + _trigger_resource_group_evaluation_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation"} # type: ignore + @distributed_trace def begin_trigger_resource_group_evaluation( - self, - subscription_id, # type: str - resource_group_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> LROPoller[None] + self, subscription_id: str, resource_group_name: str, **kwargs: Any + ) -> LROPoller[None]: """Triggers a policy evaluation scan for all the resources under the resource group. - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be ARMPolling. - Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. + :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this + operation to not poll, or pass in your own initialized polling object for a personal polling + strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ - polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] - cls = kwargs.pop('cls', None) # type: ClsType[None] - lro_delay = kwargs.pop( - 'polling_interval', - self._config.polling_interval - ) - cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token = kwargs.pop("continuation_token", None) # type: Optional[str] if cont_token is None: - raw_result = self._trigger_resource_group_evaluation_initial( + raw_result = self._trigger_resource_group_evaluation_initial( # type: ignore subscription_id=subscription_id, resource_group_name=resource_group_name, - cls=lambda x,y,z: x, + api_version=api_version, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, **kwargs ) + kwargs.pop("error_map", None) - kwargs.pop('error_map', None) - kwargs.pop('content_type', None) - - def get_long_running_output(pipeline_response): + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, {}) - path_format_arguments = { - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - } - - if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) - elif polling is False: polling_method = NoPolling() - else: polling_method = polling + if polling is True: + polling_method = cast( + PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs) + ) # type: PollingMethod + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, - deserialization_callback=get_long_running_output + deserialization_callback=get_long_running_output, ) - else: - return LROPoller(self._client, raw_result, get_long_running_output, polling_method) - begin_trigger_resource_group_evaluation.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation'} # type: ignore + return LROPoller(self._client, raw_result, get_long_running_output, polling_method) + + begin_trigger_resource_group_evaluation.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation"} # type: ignore + @distributed_trace def list_query_results_for_policy_set_definition( self, - policy_states_resource, # type: Union[str, "_models.PolicyStatesResource"] - subscription_id, # type: str - policy_set_definition_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyStatesQueryResults"] + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + subscription_id: str, + policy_set_definition_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyState"]: """Queries policy states for the subscription level policy set definition. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_set_definition_name: Policy set definition name. + :param policy_set_definition_name: Policy set definition name. Required. :type policy_set_definition_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_policy_set_definition.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policySetDefinitionName': self._serialize.url("policy_set_definition_name", policy_set_definition_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_policy_set_definition_request( + policy_states_resource=policy_states_resource, + subscription_id=subscription_id, + policy_set_definition_name=policy_set_definition_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_policy_set_definition.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1193,211 +2434,235 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_policy_set_definition.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + list_query_results_for_policy_set_definition.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + + @distributed_trace def summarize_for_policy_set_definition( self, - subscription_id, # type: str - policy_set_definition_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> "_models.SummarizeResults" + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + subscription_id: str, + policy_set_definition_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> _models.SummarizeResults: """Summarizes policy states for the subscription level policy set definition. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_set_definition_name: Policy set definition name. + :param policy_set_definition_name: Policy set definition name. Required. :type policy_set_definition_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_policy_set_definition.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policySetDefinitionName': self._serialize.url("policy_set_definition_name", policy_set_definition_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_policy_set_definition_request( + policy_states_summary_resource=policy_states_summary_resource, + subscription_id=subscription_id, + policy_set_definition_name=policy_set_definition_name, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.summarize_for_policy_set_definition.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_policy_set_definition.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore + summarize_for_policy_set_definition.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore + + @distributed_trace def list_query_results_for_policy_definition( self, - policy_states_resource, # type: Union[str, "_models.PolicyStatesResource"] - subscription_id, # type: str - policy_definition_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyStatesQueryResults"] + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + subscription_id: str, + policy_definition_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyState"]: """Queries policy states for the subscription level policy definition. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_definition_name: Policy definition name. + :param policy_definition_name: Policy definition name. Required. :type policy_definition_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_policy_definition.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyDefinitionName': self._serialize.url("policy_definition_name", policy_definition_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_policy_definition_request( + policy_states_resource=policy_states_resource, + subscription_id=subscription_id, + policy_definition_name=policy_definition_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_policy_definition.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1406,211 +2671,235 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_policy_definition.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_query_results_for_policy_definition.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + @distributed_trace def summarize_for_policy_definition( self, - subscription_id, # type: str - policy_definition_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> "_models.SummarizeResults" + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + subscription_id: str, + policy_definition_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> _models.SummarizeResults: """Summarizes policy states for the subscription level policy definition. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_definition_name: Policy definition name. + :param policy_definition_name: Policy definition name. Required. :type policy_definition_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_policy_definition.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyDefinitionName': self._serialize.url("policy_definition_name", policy_definition_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_policy_definition_request( + policy_states_summary_resource=policy_states_summary_resource, + subscription_id=subscription_id, + policy_definition_name=policy_definition_name, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.summarize_for_policy_definition.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_policy_definition.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore + summarize_for_policy_definition.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore + + @distributed_trace def list_query_results_for_subscription_level_policy_assignment( self, - policy_states_resource, # type: Union[str, "_models.PolicyStatesResource"] - subscription_id, # type: str - policy_assignment_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyStatesQueryResults"] + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + subscription_id: str, + policy_assignment_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyState"]: """Queries policy states for the subscription level policy assignment. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_assignment_name: Policy assignment name. + :param policy_assignment_name: Policy assignment name. Required. :type policy_assignment_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_subscription_level_policy_assignment.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyAssignmentName': self._serialize.url("policy_assignment_name", policy_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_subscription_level_policy_assignment_request( + policy_states_resource=policy_states_resource, + subscription_id=subscription_id, + policy_assignment_name=policy_assignment_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_subscription_level_policy_assignment.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1619,215 +2908,239 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_subscription_level_policy_assignment.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_query_results_for_subscription_level_policy_assignment.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + @distributed_trace def summarize_for_subscription_level_policy_assignment( self, - subscription_id, # type: str - policy_assignment_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> "_models.SummarizeResults" + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + subscription_id: str, + policy_assignment_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> _models.SummarizeResults: """Summarizes policy states for the subscription level policy assignment. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param policy_assignment_name: Policy assignment name. + :param policy_assignment_name: Policy assignment name. Required. :type policy_assignment_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_subscription_level_policy_assignment.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyAssignmentName': self._serialize.url("policy_assignment_name", policy_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_subscription_level_policy_assignment_request( + policy_states_summary_resource=policy_states_summary_resource, + subscription_id=subscription_id, + policy_assignment_name=policy_assignment_name, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.summarize_for_subscription_level_policy_assignment.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_subscription_level_policy_assignment.metadata = {'url': '/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore + summarize_for_subscription_level_policy_assignment.metadata = {"url": "/subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore + + @distributed_trace def list_query_results_for_resource_group_level_policy_assignment( self, - policy_states_resource, # type: Union[str, "_models.PolicyStatesResource"] - subscription_id, # type: str - resource_group_name, # type: str - policy_assignment_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyStatesQueryResults"] + policy_states_resource: Union[str, "_models.PolicyStatesResource"], + subscription_id: str, + resource_group_name: str, + policy_assignment_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyState"]: """Queries policy states for the resource group level policy assignment. :param policy_states_resource: The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents - all policy state(s). + all policy state(s). Known values are: "default" and "latest". Required. :type policy_states_resource: str or ~azure.mgmt.policyinsights.models.PolicyStatesResource - :param subscription_id: Microsoft Azure subscription ID. + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param policy_assignment_name: Policy assignment name. + :param policy_assignment_name: Policy assignment name. Required. :type policy_assignment_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyStatesQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyStatesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyState or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyState] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyStatesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyStatesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _order_by = None - _select = None - _from_property = None - _to = None - _filter = None - _apply = None - _skip_token = None - if query_options is not None: - _top = query_options.top - _order_by = query_options.order_by - _select = query_options.select - _from_property = query_options.from_property - _to = query_options.to - _filter = query_options.filter - _apply = query_options.apply - _skip_token = query_options.skip_token - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource_group_level_policy_assignment.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesResource': self._serialize.url("policy_states_resource", policy_states_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyAssignmentName': self._serialize.url("policy_assignment_name", policy_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _order_by is not None: - query_parameters['$orderby'] = self._serialize.query("order_by", _order_by, 'str') - if _select is not None: - query_parameters['$select'] = self._serialize.query("select", _select, 'str') - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - if _apply is not None: - query_parameters['$apply'] = self._serialize.query("apply", _apply, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_list_query_results_for_resource_group_level_policy_assignment_request( + policy_states_resource=policy_states_resource, + subscription_id=subscription_id, + resource_group_name=resource_group_name, + policy_assignment_name=policy_assignment_name, + top=_top, + order_by=_order_by, + select=_select, + from_property=_from_property, + to=_to, + filter=_filter, + apply=_apply, + skip_token=_skip_token, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.list_query_results_for_resource_group_level_policy_assignment.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = '{nextLink}' - path_format_arguments = { - 'nextLink': self._serialize.url("next_link", next_link, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _skip_token is not None: - query_parameters['$skiptoken'] = self._serialize.query("skip_token", _skip_token, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _order_by = None + _select = None + _from_property = None + _to = None + _filter = None + _apply = None + _skip_token = None + if query_options is not None: + _apply = query_options.apply + _filter = query_options.filter + _from_property = query_options.from_property + _order_by = query_options.order_by + _select = query_options.select + _skip_token = query_options.skip_token + _to = query_options.to + _top = query_options.top + + request = build_next_link_request( + next_link=next_link, + skip_token=_skip_token, + api_version=api_version, + template_url="{nextLink}", + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyStatesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyStatesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1836,105 +3149,115 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_resource_group_level_policy_assignment.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_query_results_for_resource_group_level_policy_assignment.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults"} # type: ignore + @distributed_trace def summarize_for_resource_group_level_policy_assignment( self, - subscription_id, # type: str - resource_group_name, # type: str - policy_assignment_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> "_models.SummarizeResults" + policy_states_summary_resource: Union[str, "_models.PolicyStatesSummaryResourceType"], + subscription_id: str, + resource_group_name: str, + policy_assignment_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> _models.SummarizeResults: """Summarizes policy states for the resource group level policy assignment. - :param subscription_id: Microsoft Azure subscription ID. + :param policy_states_summary_resource: The virtual resource under PolicyStates resource type + for summarize action. In a given time range, 'latest' represents the latest policy state(s) and + is the only allowed value. "latest" Required. + :type policy_states_summary_resource: str or + ~azure.mgmt.policyinsights.models.PolicyStatesSummaryResourceType + :param subscription_id: Microsoft Azure subscription ID. Required. :type subscription_id: str - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param policy_assignment_name: Policy assignment name. + :param policy_assignment_name: Policy assignment name. Required. :type policy_assignment_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword authorization_namespace: The namespace for Microsoft Authorization resource provider; + only "Microsoft.Authorization" is allowed. Default value is "Microsoft.Authorization". Note + that overriding this default value may result in unsupported behavior. + :paramtype authorization_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: SummarizeResults, or the result of cls(response) + :return: SummarizeResults or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.SummarizeResults"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + authorization_namespace = kwargs.pop("authorization_namespace", "Microsoft.Authorization") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2019-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.SummarizeResults] + _top = None _from_property = None _to = None _filter = None if query_options is not None: - _top = query_options.top + _filter = query_options.filter _from_property = query_options.from_property _to = query_options.to - _filter = query_options.filter - policy_states_summary_resource = "latest" - authorization_namespace = "Microsoft.Authorization" - api_version = "2019-10-01" - accept = "application/json" - - # Construct URL - url = self.summarize_for_resource_group_level_policy_assignment.metadata['url'] # type: ignore - path_format_arguments = { - 'policyStatesSummaryResource': self._serialize.url("policy_states_summary_resource", policy_states_summary_resource, 'str'), - 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'authorizationNamespace': self._serialize.url("authorization_namespace", authorization_namespace, 'str'), - 'policyAssignmentName': self._serialize.url("policy_assignment_name", policy_assignment_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _from_property is not None: - query_parameters['$from'] = self._serialize.query("from_property", _from_property, 'iso-8601') - if _to is not None: - query_parameters['$to'] = self._serialize.query("to", _to, 'iso-8601') - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + _top = query_options.top + + request = build_summarize_for_resource_group_level_policy_assignment_request( + policy_states_summary_resource=policy_states_summary_resource, + subscription_id=subscription_id, + resource_group_name=resource_group_name, + policy_assignment_name=policy_assignment_name, + top=_top, + from_property=_from_property, + to=_to, + filter=_filter, + authorization_namespace=authorization_namespace, + api_version=api_version, + template_url=self.summarize_for_resource_group_level_policy_assignment.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # 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.QueryFailure, response) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('SummarizeResults', pipeline_response) + deserialized = self._deserialize("SummarizeResults", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - summarize_for_resource_group_level_policy_assignment.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize'} # type: ignore + + summarize_for_resource_group_level_policy_assignment.metadata = {"url": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_tracked_resources_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_tracked_resources_operations.py index d11fa8ce319c..cb04fd77ad14 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_tracked_resources_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_policy_tracked_resources_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,111 +6,296 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union + +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.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import 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 .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_query_results_for_management_group_request( + management_group_name: str, + policy_tracked_resources_resource: Union[str, "_models.PolicyTrackedResourcesResourceType"], + *, + top: Optional[int] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "managementGroupsNamespace": _SERIALIZER.url("management_groups_namespace", management_groups_namespace, "str"), + "managementGroupName": _SERIALIZER.url("management_group_name", management_group_name, "str"), + "policyTrackedResourcesResource": _SERIALIZER.url( + "policy_tracked_resources_resource", policy_tracked_resources_resource, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_subscription_request( + policy_tracked_resources_resource: Union[str, "_models.PolicyTrackedResourcesResourceType"], + subscription_id: str, + *, + top: Optional[int] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "policyTrackedResourcesResource": _SERIALIZER.url( + "policy_tracked_resources_resource", policy_tracked_resources_resource, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_resource_group_request( + resource_group_name: str, + policy_tracked_resources_resource: Union[str, "_models.PolicyTrackedResourcesResourceType"], + subscription_id: str, + *, + top: Optional[int] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "policyTrackedResourcesResource": _SERIALIZER.url( + "policy_tracked_resources_resource", policy_tracked_resources_resource, "str" + ), + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_query_results_for_resource_request( + resource_id: str, + policy_tracked_resources_resource: Union[str, "_models.PolicyTrackedResourcesResourceType"], + *, + top: Optional[int] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{resourceId}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + "policyTrackedResourcesResource": _SERIALIZER.url( + "policy_tracked_resources_resource", policy_tracked_resources_resource, "str" + ), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +class PolicyTrackedResourcesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -class PolicyTrackedResourcesOperations(object): - """PolicyTrackedResourcesOperations operations. - - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. - - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.PolicyInsightsClient`'s + :attr:`policy_tracked_resources` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_query_results_for_management_group( self, - management_group_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyTrackedResourcesQueryResults"] + management_group_name: str, + policy_tracked_resources_resource: Union[str, "_models.PolicyTrackedResourcesResourceType"], + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyTrackedResource"]: """Queries policy tracked resources under the management group. - :param management_group_name: Management group name. + :param management_group_name: Management group name. Required. :type management_group_name: str - :param query_options: Parameter group. + :param policy_tracked_resources_resource: The name of the virtual resource under + PolicyTrackedResources resource type; only "default" is allowed. "default" Required. + :type policy_tracked_resources_resource: str or + ~azure.mgmt.policyinsights.models.PolicyTrackedResourcesResourceType + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyTrackedResourcesQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResourcesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyTrackedResource or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyTrackedResourcesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyTrackedResourcesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - management_groups_namespace = "Microsoft.Management" - policy_tracked_resources_resource = "default" - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupName': self._serialize.url("management_group_name", management_group_name, 'str'), - 'policyTrackedResourcesResource': self._serialize.url("policy_tracked_resources_resource", policy_tracked_resources_resource, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_query_results_for_management_group_request( + management_group_name=management_group_name, + policy_tracked_resources_resource=policy_tracked_resources_resource, + top=_top, + filter=_filter, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.list_query_results_for_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyTrackedResourcesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyTrackedResourcesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -118,81 +304,87 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + list_query_results_for_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults"} # type: ignore + + @distributed_trace def list_query_results_for_subscription( self, - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyTrackedResourcesQueryResults"] + policy_tracked_resources_resource: Union[str, "_models.PolicyTrackedResourcesResourceType"], + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyTrackedResource"]: """Queries policy tracked resources under the subscription. - :param query_options: Parameter group. + :param policy_tracked_resources_resource: The name of the virtual resource under + PolicyTrackedResources resource type; only "default" is allowed. "default" Required. + :type policy_tracked_resources_resource: str or + ~azure.mgmt.policyinsights.models.PolicyTrackedResourcesResourceType + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyTrackedResourcesQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResourcesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyTrackedResource or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyTrackedResourcesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyTrackedResourcesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - policy_tracked_resources_resource = "default" - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'policyTrackedResourcesResource': self._serialize.url("policy_tracked_resources_resource", policy_tracked_resources_resource, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_query_results_for_subscription_request( + policy_tracked_resources_resource=policy_tracked_resources_resource, + subscription_id=self._config.subscription_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_query_results_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyTrackedResourcesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyTrackedResourcesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -201,85 +393,91 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + list_query_results_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults"} # type: ignore + + @distributed_trace def list_query_results_for_resource_group( self, - resource_group_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyTrackedResourcesQueryResults"] + resource_group_name: str, + policy_tracked_resources_resource: Union[str, "_models.PolicyTrackedResourcesResourceType"], + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyTrackedResource"]: """Queries policy tracked resources under the resource group. - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param query_options: Parameter group. + :param policy_tracked_resources_resource: The name of the virtual resource under + PolicyTrackedResources resource type; only "default" is allowed. "default" Required. + :type policy_tracked_resources_resource: str or + ~azure.mgmt.policyinsights.models.PolicyTrackedResourcesResourceType + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyTrackedResourcesQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResourcesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyTrackedResource or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyTrackedResourcesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyTrackedResourcesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - policy_tracked_resources_resource = "default" - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'policyTrackedResourcesResource': self._serialize.url("policy_tracked_resources_resource", policy_tracked_resources_resource, 'str'), - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_query_results_for_resource_group_request( + resource_group_name=resource_group_name, + policy_tracked_resources_resource=policy_tracked_resources_resource, + subscription_id=self._config.subscription_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_query_results_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyTrackedResourcesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyTrackedResourcesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -288,84 +486,90 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + list_query_results_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults"} # type: ignore + + @distributed_trace def list_query_results_for_resource( self, - resource_id, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.PolicyTrackedResourcesQueryResults"] + resource_id: str, + policy_tracked_resources_resource: Union[str, "_models.PolicyTrackedResourcesResourceType"], + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.PolicyTrackedResource"]: """Queries policy tracked resources under the resource. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param query_options: Parameter group. + :param policy_tracked_resources_resource: The name of the virtual resource under + PolicyTrackedResources resource type; only "default" is allowed. "default" Required. + :type policy_tracked_resources_resource: str or + ~azure.mgmt.policyinsights.models.PolicyTrackedResourcesResourceType + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either PolicyTrackedResourcesQueryResults or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResourcesQueryResults] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either PolicyTrackedResource or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResource] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyTrackedResourcesQueryResults"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2018-07-01-preview")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.PolicyTrackedResourcesQueryResults] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - policy_tracked_resources_resource = "default" - api_version = "2018-07-01-preview" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_query_results_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'policyTrackedResourcesResource': self._serialize.url("policy_tracked_resources_resource", policy_tracked_resources_resource, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_query_results_for_resource_request( + resource_id=resource_id, + policy_tracked_resources_resource=policy_tracked_resources_resource, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_query_results_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('PolicyTrackedResourcesQueryResults', pipeline_response) + deserialized = self._deserialize("PolicyTrackedResourcesQueryResults", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -374,17 +578,18 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response) map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.QueryFailure, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response - return ItemPaged( - get_next, extract_data - ) - list_query_results_for_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_query_results_for_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults"} # type: ignore diff --git a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_remediations_operations.py b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_remediations_operations.py index 6535a60b01bb..0c226c7140c0 100644 --- a/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_remediations_operations.py +++ b/sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/operations/_remediations_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,109 +6,868 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, overload + +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.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import 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 .._serialization import Serializer +from .._vendor import _convert_request, _format_url_section + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_list_deployments_at_management_group_request( + management_group_id: str, remediation_name: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "managementGroupsNamespace": _SERIALIZER.url("management_groups_namespace", management_groups_namespace, "str"), + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_cancel_at_management_group_request( + management_group_id: str, remediation_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel", + ) # pylint: disable=line-too-long + path_format_arguments = { + "managementGroupsNamespace": _SERIALIZER.url("management_groups_namespace", management_groups_namespace, "str"), + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_management_group_request( + management_group_id: str, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations", + ) # pylint: disable=line-too-long + path_format_arguments = { + "managementGroupsNamespace": _SERIALIZER.url("management_groups_namespace", management_groups_namespace, "str"), + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_at_management_group_request( + management_group_id: str, remediation_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "managementGroupsNamespace": _SERIALIZER.url("management_groups_namespace", management_groups_namespace, "str"), + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_at_management_group_request( + management_group_id: str, remediation_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "managementGroupsNamespace": _SERIALIZER.url("management_groups_namespace", management_groups_namespace, "str"), + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # 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_delete_at_management_group_request( + management_group_id: str, remediation_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "managementGroupsNamespace": _SERIALIZER.url("management_groups_namespace", management_groups_namespace, "str"), + "managementGroupId": _SERIALIZER.url("management_group_id", management_group_id, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_deployments_at_subscription_request( + remediation_name: str, subscription_id: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_cancel_at_subscription_request(remediation_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 = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_subscription_request( + subscription_id: str, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations") + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_at_subscription_request( + remediation_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 = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_at_subscription_request(remediation_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 = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # 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_delete_at_subscription_request(remediation_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 = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_deployments_at_resource_group_request( + resource_group_name: str, remediation_name: str, subscription_id: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_cancel_at_resource_group_request( + resource_group_name: str, remediation_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 = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_group_request( + resource_group_name: str, + subscription_id: str, + *, + top: Optional[int] = None, + filter: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_at_resource_group_request( + resource_group_name: str, remediation_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 = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_at_resource_group_request( + resource_group_name: str, remediation_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 = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # 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_delete_at_resource_group_request( + resource_group_name: str, remediation_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 = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", + ) # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_deployments_at_resource_request( + resource_id: str, remediation_name: str, *, top: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop( + "template_url", + "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments", + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +def build_cancel_at_resource_request(resource_id: str, remediation_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) -class RemediationsOperations(object): - """RemediationsOperations operations. + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") - You should not instantiate this class directly. Instead, you should create a Client instance that - instantiates it for you and attaches it as an attribute. + # Construct URL + _url = kwargs.pop( + "template_url", "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel" + ) # pylint: disable=line-too-long + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } - :ivar models: Alias to model classes used in this operation group. - :type models: ~azure.mgmt.policyinsights.models - :param client: Client for service requests. - :param config: Configuration of service client. - :param serializer: An object model serializer. - :param deserializer: An object model deserializer. + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_list_for_resource_request( + resource_id: str, *, top: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{resourceId}/providers/Microsoft.PolicyInsights/remediations") + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + if top is not None: + _params["$top"] = _SERIALIZER.query("top", top, "int", minimum=0) + if filter is not None: + _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_create_or_update_at_resource_request(resource_id: str, remediation_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}") + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_get_at_resource_request(resource_id: str, remediation_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}") + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # 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_delete_at_resource_request(resource_id: str, remediation_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = kwargs.pop("template_url", "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}") + path_format_arguments = { + "resourceId": _SERIALIZER.url("resource_id", resource_id, "str", skip_quote=True), + "remediationName": _SERIALIZER.url("remediation_name", remediation_name, "str"), + } + + _url = _format_url_section(_url, **path_format_arguments) + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class RemediationsOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.mgmt.policyinsights.PolicyInsightsClient`'s + :attr:`remediations` attribute. """ models = _models - def __init__(self, client, config, serializer, deserializer): - self._client = client - self._serialize = serializer - self._deserialize = deserializer - self._config = config + 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_deployments_at_management_group( self, - management_group_id, # type: str - remediation_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RemediationDeploymentsListResult"] + management_group_id: str, + remediation_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.RemediationDeployment"]: """Gets all deployments for a remediation at management group scope. - :param management_group_id: Management group ID. + :param management_group_id: Management group ID. Required. :type management_group_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationDeploymentsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.RemediationDeploymentsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RemediationDeployment or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.RemediationDeployment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationDeploymentsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationDeploymentsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - if query_options is not None: - _top = query_options.top - management_groups_namespace = "Microsoft.Management" - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_deployments_at_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupId': self._serialize.url("management_group_id", management_group_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + if query_options is not None: + _top = query_options.top + + request = build_list_deployments_at_management_group_request( + management_group_id=management_group_id, + remediation_name=remediation_name, + top=_top, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.list_deployments_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationDeploymentsListResult', pipeline_response) + deserialized = self._deserialize("RemediationDeploymentsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -116,145 +876,152 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_deployments_at_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_deployments_at_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments"} # type: ignore + @distributed_trace def cancel_at_management_group( - self, - management_group_id, # type: str - remediation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Remediation" + self, management_group_id: str, remediation_name: str, **kwargs: Any + ) -> _models.Remediation: """Cancels a remediation at management group scope. - :param management_group_id: Management group ID. + :param management_group_id: Management group ID. Required. :type management_group_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - management_groups_namespace = "Microsoft.Management" - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.cancel_at_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupId': self._serialize.url("management_group_id", management_group_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + request = build_cancel_at_management_group_request( + management_group_id=management_group_id, + remediation_name=remediation_name, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.cancel_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - cancel_at_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel'} # type: ignore + cancel_at_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel"} # type: ignore + + @distributed_trace def list_for_management_group( - self, - management_group_id, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RemediationListResult"] + self, management_group_id: str, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> Iterable["_models.Remediation"]: """Gets all remediations for the management group. - :param management_group_id: Management group ID. + :param management_group_id: Management group ID. Required. :type management_group_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.RemediationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Remediation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.Remediation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - management_groups_namespace = "Microsoft.Management" - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupId': self._serialize.url("management_group_id", management_group_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_for_management_group_request( + management_group_id=management_group_id, + top=_top, + filter=_filter, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.list_for_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationListResult', pipeline_response) + deserialized = self._deserialize("RemediationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -263,276 +1030,362 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_for_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations"} # type: ignore + @overload def create_or_update_at_management_group( self, - management_group_id, # type: str - remediation_name, # type: str - parameters, # type: "_models.Remediation" - **kwargs # type: Any - ): - # type: (...) -> "_models.Remediation" + management_group_id: str, + remediation_name: str, + parameters: _models.Remediation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Remediation: """Creates or updates a remediation at management group scope. - :param management_group_id: Management group ID. + :param management_group_id: Management group ID. Required. :type management_group_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param parameters: The remediation parameters. + :param parameters: The remediation parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.Remediation + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_management_group( + self, + management_group_id: str, + remediation_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at management group scope. + + :param management_group_id: Management group ID. Required. + :type management_group_id: str + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Required. + :type parameters: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_management_group( + self, management_group_id: str, remediation_name: str, parameters: Union[_models.Remediation, IO], **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at management group scope. + + :param management_group_id: Management group ID. Required. + :type management_group_id: str + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.Remediation or IO + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str + :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 + :return: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - management_groups_namespace = "Microsoft.Management" - api_version = "2021-10-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_at_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupId': self._serialize.url("management_group_id", management_group_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Remediation') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Remediation") + + request = build_create_or_update_at_management_group_request( + management_group_id=management_group_id, + remediation_name=remediation_name, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **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, 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('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_at_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + create_or_update_at_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace def get_at_management_group( - self, - management_group_id, # type: str - remediation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Remediation" + self, management_group_id: str, remediation_name: str, **kwargs: Any + ) -> _models.Remediation: """Gets an existing remediation at management group scope. - :param management_group_id: Management group ID. + :param management_group_id: Management group ID. Required. :type management_group_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - management_groups_namespace = "Microsoft.Management" - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.get_at_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupId': self._serialize.url("management_group_id", management_group_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + request = build_get_at_management_group_request( + management_group_id=management_group_id, + remediation_name=remediation_name, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.get_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_at_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + get_at_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace def delete_at_management_group( - self, - management_group_id, # type: str - remediation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.Remediation"] + self, management_group_id: str, remediation_name: str, **kwargs: Any + ) -> Optional[_models.Remediation]: """Deletes an existing remediation at management group scope. - :param management_group_id: Management group ID. + :param management_group_id: Management group ID. Required. :type management_group_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str + :keyword management_groups_namespace: The namespace for Microsoft Management RP; only + "Microsoft.Management" is allowed. Default value is "Microsoft.Management". Note that + overriding this default value may result in unsupported behavior. + :paramtype management_groups_namespace: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or None or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Remediation"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - management_groups_namespace = "Microsoft.Management" - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.delete_at_management_group.metadata['url'] # type: ignore - path_format_arguments = { - 'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'), - 'managementGroupId': self._serialize.url("management_group_id", management_group_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + management_groups_namespace = kwargs.pop("management_groups_namespace", "Microsoft.Management") # type: str + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Remediation]] + + request = build_delete_at_management_group_request( + management_group_id=management_group_id, + remediation_name=remediation_name, + management_groups_namespace=management_groups_namespace, + api_version=api_version, + template_url=self.delete_at_management_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **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, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_at_management_group.metadata = {'url': '/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + delete_at_management_group.metadata = {"url": "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace def list_deployments_at_subscription( - self, - remediation_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RemediationDeploymentsListResult"] + self, remediation_name: str, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> Iterable["_models.RemediationDeployment"]: """Gets all deployments for a remediation at subscription scope. - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationDeploymentsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.RemediationDeploymentsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RemediationDeployment or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.RemediationDeployment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationDeploymentsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationDeploymentsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - if query_options is not None: - _top = query_options.top - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_deployments_at_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + if query_options is not None: + _top = query_options.top + + request = build_list_deployments_at_subscription_request( + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + top=_top, + api_version=api_version, + template_url=self.list_deployments_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationDeploymentsListResult', pipeline_response) + deserialized = self._deserialize("RemediationDeploymentsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -541,135 +1394,134 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_deployments_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments'} # type: ignore + return ItemPaged(get_next, extract_data) - def cancel_at_subscription( - self, - remediation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Remediation" + list_deployments_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments"} # type: ignore + + @distributed_trace + def cancel_at_subscription(self, remediation_name: str, **kwargs: Any) -> _models.Remediation: """Cancels a remediation at subscription scope. - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.cancel_at_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + request = build_cancel_at_subscription_request( + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.cancel_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - cancel_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel'} # type: ignore + cancel_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel"} # type: ignore + + @distributed_trace def list_for_subscription( - self, - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RemediationListResult"] + self, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> Iterable["_models.Remediation"]: """Gets all remediations for the subscription. - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.RemediationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Remediation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.Remediation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_for_subscription_request( + subscription_id=self._config.subscription_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_for_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationListResult', pipeline_response) + deserialized = self._deserialize("RemediationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -678,265 +1530,322 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_for_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations'} # type: ignore + return ItemPaged(get_next, extract_data) + list_for_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations"} # type: ignore + + @overload def create_or_update_at_subscription( self, - remediation_name, # type: str - parameters, # type: "_models.Remediation" - **kwargs # type: Any - ): - # type: (...) -> "_models.Remediation" + remediation_name: str, + parameters: _models.Remediation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Remediation: """Creates or updates a remediation at subscription scope. - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param parameters: The remediation parameters. + :param parameters: The remediation parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.Remediation + :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: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_subscription( + self, remediation_name: str, parameters: IO, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at subscription scope. + + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Required. + :type parameters: IO + :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: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_subscription( + self, remediation_name: str, parameters: Union[_models.Remediation, IO], **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at subscription scope. + + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.Remediation 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 + :return: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_at_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Remediation') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Remediation") + + request = build_create_or_update_at_subscription_request( + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **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, 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('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore - def get_at_subscription( - self, - remediation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Remediation" + create_or_update_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace + def get_at_subscription(self, remediation_name: str, **kwargs: Any) -> _models.Remediation: """Gets an existing remediation at subscription scope. - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.get_at_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + request = build_get_at_subscription_request( + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore - def delete_at_subscription( - self, - remediation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.Remediation"] + get_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace + def delete_at_subscription(self, remediation_name: str, **kwargs: Any) -> Optional[_models.Remediation]: """Deletes an existing remediation at subscription scope. - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or None or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Remediation"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.delete_at_subscription.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Remediation]] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_delete_at_subscription_request( + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_subscription.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **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, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_at_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + delete_at_subscription.metadata = {"url": "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace def list_deployments_at_resource_group( self, - resource_group_name, # type: str - remediation_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RemediationDeploymentsListResult"] + resource_group_name: str, + remediation_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.RemediationDeployment"]: """Gets all deployments for a remediation at resource group scope. - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationDeploymentsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.RemediationDeploymentsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RemediationDeployment or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.RemediationDeployment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationDeploymentsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationDeploymentsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - if query_options is not None: - _top = query_options.top - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_deployments_at_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + if query_options is not None: + _top = query_options.top + + request = build_list_deployments_at_resource_group_request( + resource_group_name=resource_group_name, + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + top=_top, + api_version=api_version, + template_url=self.list_deployments_at_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationDeploymentsListResult', pipeline_response) + deserialized = self._deserialize("RemediationDeploymentsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -945,143 +1854,142 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_deployments_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_deployments_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments"} # type: ignore + @distributed_trace def cancel_at_resource_group( - self, - resource_group_name, # type: str - remediation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Remediation" + self, resource_group_name: str, remediation_name: str, **kwargs: Any + ) -> _models.Remediation: """Cancels a remediation at resource group scope. - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.cancel_at_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + request = build_cancel_at_resource_group_request( + resource_group_name=resource_group_name, + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.cancel_at_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - cancel_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel'} # type: ignore + cancel_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel"} # type: ignore + + @distributed_trace def list_for_resource_group( - self, - resource_group_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RemediationListResult"] + self, resource_group_name: str, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> Iterable["_models.Remediation"]: """Gets all remediations for the subscription. - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.RemediationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Remediation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.Remediation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_for_resource_group_request( + resource_group_name=resource_group_name, + subscription_id=self._config.subscription_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_for_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationListResult', pipeline_response) + deserialized = self._deserialize("RemediationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1090,276 +1998,345 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_for_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations'} # type: ignore + return ItemPaged(get_next, extract_data) + list_for_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations"} # type: ignore + + @overload def create_or_update_at_resource_group( self, - resource_group_name, # type: str - remediation_name, # type: str - parameters, # type: "_models.Remediation" - **kwargs # type: Any - ): - # type: (...) -> "_models.Remediation" + resource_group_name: str, + remediation_name: str, + parameters: _models.Remediation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Remediation: """Creates or updates a remediation at resource group scope. - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param parameters: The remediation parameters. + :param parameters: The remediation parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.Remediation + :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: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_resource_group( + self, + resource_group_name: str, + remediation_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at resource group scope. + + :param resource_group_name: Resource group name. Required. + :type resource_group_name: str + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Required. + :type parameters: IO + :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: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_resource_group( + self, resource_group_name: str, remediation_name: str, parameters: Union[_models.Remediation, IO], **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at resource group scope. + + :param resource_group_name: Resource group name. Required. + :type resource_group_name: str + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.Remediation 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 - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_at_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Remediation') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Remediation") + + request = build_create_or_update_at_resource_group_request( + resource_group_name=resource_group_name, + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **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, 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('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + create_or_update_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace def get_at_resource_group( - self, - resource_group_name, # type: str - remediation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Remediation" + self, resource_group_name: str, remediation_name: str, **kwargs: Any + ) -> _models.Remediation: """Gets an existing remediation at resource group scope. - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.get_at_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + request = build_get_at_resource_group_request( + resource_group_name=resource_group_name, + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.get_at_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + get_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace def delete_at_resource_group( - self, - resource_group_name, # type: str - remediation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.Remediation"] + self, resource_group_name: str, remediation_name: str, **kwargs: Any + ) -> Optional[_models.Remediation]: """Deletes an existing remediation at resource group scope. - :param resource_group_name: Resource group name. + :param resource_group_name: Resource group name. Required. :type resource_group_name: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or None or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Remediation"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.delete_at_resource_group.metadata['url'] # type: ignore - path_format_arguments = { - 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), - 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Remediation]] + + request = build_delete_at_resource_group_request( + resource_group_name=resource_group_name, + remediation_name=remediation_name, + subscription_id=self._config.subscription_id, + api_version=api_version, + template_url=self.delete_at_resource_group.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **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, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_at_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + delete_at_resource_group.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace def list_deployments_at_resource( self, - resource_id, # type: str - remediation_name, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RemediationDeploymentsListResult"] + resource_id: str, + remediation_name: str, + query_options: Optional[_models.QueryOptions] = None, + **kwargs: Any + ) -> Iterable["_models.RemediationDeployment"]: """Gets all deployments for a remediation at resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationDeploymentsListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.RemediationDeploymentsListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either RemediationDeployment or the result of + cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.RemediationDeployment] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationDeploymentsListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationDeploymentsListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - if query_options is not None: - _top = query_options.top - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_deployments_at_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.post(url, query_parameters, header_parameters) + _top = None + if query_options is not None: + _top = query_options.top + + request = build_list_deployments_at_resource_request( + resource_id=resource_id, + remediation_name=remediation_name, + top=_top, + api_version=api_version, + template_url=self.list_deployments_at_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationDeploymentsListResult', pipeline_response) + deserialized = self._deserialize("RemediationDeploymentsListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1368,141 +2345,138 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_deployments_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments'} # type: ignore + return ItemPaged(get_next, extract_data) - def cancel_at_resource( - self, - resource_id, # type: str - remediation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Remediation" + list_deployments_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments"} # type: ignore + + @distributed_trace + def cancel_at_resource(self, resource_id: str, remediation_name: str, **kwargs: Any) -> _models.Remediation: """Cancel a remediation at resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.cancel_at_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_cancel_at_resource_request( + resource_id=resource_id, + remediation_name=remediation_name, + api_version=api_version, + template_url=self.cancel_at_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.post(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - cancel_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel'} # type: ignore + cancel_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel"} # type: ignore + + @distributed_trace def list_for_resource( - self, - resource_id, # type: str - query_options=None, # type: Optional["_models.QueryOptions"] - **kwargs # type: Any - ): - # type: (...) -> Iterable["_models.RemediationListResult"] + self, resource_id: str, query_options: Optional[_models.QueryOptions] = None, **kwargs: Any + ) -> Iterable["_models.Remediation"]: """Gets all remediations for a resource. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param query_options: Parameter group. + :param query_options: Parameter group. Default value is None. :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either RemediationListResult or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.RemediationListResult] - :raises: ~azure.core.exceptions.HttpResponseError + :return: An iterator like instance of either Remediation or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.policyinsights.models.Remediation] + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.RemediationListResult"] + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.RemediationListResult] + error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - - _top = None - _filter = None - if query_options is not None: - _top = query_options.top - _filter = query_options.filter - api_version = "2021-10-01" - accept = "application/json" + error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - if not next_link: - # Construct URL - url = self.list_for_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if _top is not None: - query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0) - if _filter is not None: - query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str') - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - request = self._client.get(url, query_parameters, header_parameters) + _top = None + _filter = None + if query_options is not None: + _filter = query_options.filter + _top = query_options.top + + request = build_list_for_resource_request( + resource_id=resource_id, + top=_top, + filter=_filter, + api_version=api_version, + template_url=self.list_for_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - request = self._client.get(url, query_parameters, header_parameters) + request = HttpRequest("GET", next_link) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + request.method = "GET" return request def extract_data(pipeline_response): - deserialized = self._deserialize('RemediationListResult', pipeline_response) + deserialized = self._deserialize("RemediationListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) @@ -1511,208 +2485,273 @@ def extract_data(pipeline_response): def get_next(next_link=None): request = prepare_request(next_link) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) 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 - ) - list_for_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/remediations'} # type: ignore + return ItemPaged(get_next, extract_data) + + list_for_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/remediations"} # type: ignore + @overload def create_or_update_at_resource( self, - resource_id, # type: str - remediation_name, # type: str - parameters, # type: "_models.Remediation" - **kwargs # type: Any - ): - # type: (...) -> "_models.Remediation" + resource_id: str, + remediation_name: str, + parameters: _models.Remediation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Remediation: """Creates or updates a remediation at resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str - :param parameters: The remediation parameters. + :param parameters: The remediation parameters. Required. :type parameters: ~azure.mgmt.policyinsights.models.Remediation + :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: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update_at_resource( + self, + resource_id: str, + remediation_name: str, + parameters: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at resource scope. + + :param resource_id: Resource ID. Required. + :type resource_id: str + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Required. + :type parameters: IO + :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: Remediation or the result of cls(response) + :rtype: ~azure.mgmt.policyinsights.models.Remediation + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update_at_resource( + self, resource_id: str, remediation_name: str, parameters: Union[_models.Remediation, IO], **kwargs: Any + ) -> _models.Remediation: + """Creates or updates a remediation at resource scope. + + :param resource_id: Resource ID. Required. + :type resource_id: str + :param remediation_name: The name of the remediation. Required. + :type remediation_name: str + :param parameters: The remediation parameters. Is either a model type or a IO type. Required. + :type parameters: ~azure.mgmt.policyinsights.models.Remediation 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 - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - - # Construct URL - url = self.create_or_update_at_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(parameters, 'Remediation') - body_content_kwargs['content'] = body_content - request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(parameters, (IO, bytes)): + _content = parameters + else: + _json = self._serialize.body(parameters, "Remediation") + + request = build_create_or_update_at_resource_request( + resource_id=resource_id, + remediation_name=remediation_name, + api_version=api_version, + content_type=content_type, + json=_json, + content=_content, + template_url=self.create_or_update_at_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **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, 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('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if response.status_code == 201: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - create_or_update_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore - def get_at_resource( - self, - resource_id, # type: str - remediation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> "_models.Remediation" + create_or_update_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace + def get_at_resource(self, resource_id: str, remediation_name: str, **kwargs: Any) -> _models.Remediation: """Gets an existing remediation at resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.Remediation"] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.get_at_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[_models.Remediation] - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_get_at_resource_request( + resource_id=resource_id, + remediation_name=remediation_name, + api_version=api_version, + template_url=self.get_at_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.get(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(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.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - get_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + get_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore + + @distributed_trace def delete_at_resource( - self, - resource_id, # type: str - remediation_name, # type: str - **kwargs # type: Any - ): - # type: (...) -> Optional["_models.Remediation"] + self, resource_id: str, remediation_name: str, **kwargs: Any + ) -> Optional[_models.Remediation]: """Deletes an existing remediation at individual resource scope. - :param resource_id: Resource ID. + :param resource_id: Resource ID. Required. :type resource_id: str - :param remediation_name: The name of the remediation. + :param remediation_name: The name of the remediation. Required. :type remediation_name: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: Remediation, or the result of cls(response) + :return: Remediation or None or the result of cls(response) :rtype: ~azure.mgmt.policyinsights.models.Remediation or None - :raises: ~azure.core.exceptions.HttpResponseError + :raises ~azure.core.exceptions.HttpResponseError: """ - cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.Remediation"]] error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - api_version = "2021-10-01" - accept = "application/json" - - # Construct URL - url = self.delete_at_resource.metadata['url'] # type: ignore - path_format_arguments = { - 'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True), - 'remediationName': self._serialize.url("remediation_name", remediation_name, 'str'), + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - url = self._client.format_url(url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + _headers = kwargs.pop("headers", {}) or {} + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop("api_version", _params.pop("api-version", "2021-10-01")) # type: str + cls = kwargs.pop("cls", None) # type: ClsType[Optional[_models.Remediation]] + + request = build_delete_at_resource_request( + resource_id=resource_id, + remediation_name=remediation_name, + api_version=api_version, + template_url=self.delete_at_resource.metadata["url"], + headers=_headers, + params=_params, + ) + request = _convert_request(request) + request.url = self._client.format_url(request.url) # type: ignore + + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) - request = self._client.delete(url, query_parameters, header_parameters) - pipeline_response = self._client._pipeline.run(request, stream=False, **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, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: - deserialized = self._deserialize('Remediation', pipeline_response) + deserialized = self._deserialize("Remediation", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - delete_at_resource.metadata = {'url': '/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}'} # type: ignore + + delete_at_resource.metadata = {"url": "/{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}"} # type: ignore