1# coding=utf-8
2# --------------------------------------------------------------------------
3# Copyright (c) Microsoft Corporation. All rights reserved.
4# Licensed under the MIT License. See License.txt in the project root for license information.
5# Code generated by Microsoft (R) AutoRest Code Generator.
6# Changes may cause incorrect behavior and will be lost if the code is regenerated.
7# --------------------------------------------------------------------------
8from typing import TYPE_CHECKING
9import warnings
10
11from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
12from azure.core.paging import ItemPaged
13from azure.core.pipeline import PipelineResponse
14from azure.core.pipeline.transport import HttpRequest, HttpResponse
15from azure.core.polling import LROPoller, NoPolling, PollingMethod
16from azure.mgmt.core.exceptions import ARMErrorFormat
17from azure.mgmt.core.polling.arm_polling import ARMPolling
18
19from .. import models as _models
20
21if TYPE_CHECKING:
22    # pylint: disable=unused-import,ungrouped-imports
23    from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
24
25    T = TypeVar('T')
26    ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
27
28class BastionHostsOperations(object):
29    """BastionHostsOperations operations.
30
31    You should not instantiate this class directly. Instead, you should create a Client instance that
32    instantiates it for you and attaches it as an attribute.
33
34    :ivar models: Alias to model classes used in this operation group.
35    :type models: ~azure.mgmt.network.v2019_11_01.models
36    :param client: Client for service requests.
37    :param config: Configuration of service client.
38    :param serializer: An object model serializer.
39    :param deserializer: An object model deserializer.
40    """
41
42    models = _models
43
44    def __init__(self, client, config, serializer, deserializer):
45        self._client = client
46        self._serialize = serializer
47        self._deserialize = deserializer
48        self._config = config
49
50    def _delete_initial(
51        self,
52        resource_group_name,  # type: str
53        bastion_host_name,  # type: str
54        **kwargs  # type: Any
55    ):
56        # type: (...) -> None
57        cls = kwargs.pop('cls', None)  # type: ClsType[None]
58        error_map = {
59            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
60        }
61        error_map.update(kwargs.pop('error_map', {}))
62        api_version = "2019-11-01"
63        accept = "application/json"
64
65        # Construct URL
66        url = self._delete_initial.metadata['url']  # type: ignore
67        path_format_arguments = {
68            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
69            'bastionHostName': self._serialize.url("bastion_host_name", bastion_host_name, 'str'),
70            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
71        }
72        url = self._client.format_url(url, **path_format_arguments)
73
74        # Construct parameters
75        query_parameters = {}  # type: Dict[str, Any]
76        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
77
78        # Construct headers
79        header_parameters = {}  # type: Dict[str, Any]
80        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
81
82        request = self._client.delete(url, query_parameters, header_parameters)
83        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
84        response = pipeline_response.http_response
85
86        if response.status_code not in [200, 202, 204]:
87            map_error(status_code=response.status_code, response=response, error_map=error_map)
88            raise HttpResponseError(response=response, error_format=ARMErrorFormat)
89
90        if cls:
91            return cls(pipeline_response, None, {})
92
93    _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}'}  # type: ignore
94
95    def begin_delete(
96        self,
97        resource_group_name,  # type: str
98        bastion_host_name,  # type: str
99        **kwargs  # type: Any
100    ):
101        # type: (...) -> LROPoller[None]
102        """Deletes the specified Bastion Host.
103
104        :param resource_group_name: The name of the resource group.
105        :type resource_group_name: str
106        :param bastion_host_name: The name of the Bastion Host.
107        :type bastion_host_name: str
108        :keyword callable cls: A custom type or function that will be passed the direct response
109        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
110        :keyword polling: Pass in True if you'd like the ARMPolling polling method,
111         False for no polling, or your own initialized polling object for a personal polling strategy.
112        :paramtype polling: bool or ~azure.core.polling.PollingMethod
113        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
114        :return: An instance of LROPoller that returns either None or the result of cls(response)
115        :rtype: ~azure.core.polling.LROPoller[None]
116        :raises ~azure.core.exceptions.HttpResponseError:
117        """
118        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
119        cls = kwargs.pop('cls', None)  # type: ClsType[None]
120        lro_delay = kwargs.pop(
121            'polling_interval',
122            self._config.polling_interval
123        )
124        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
125        if cont_token is None:
126            raw_result = self._delete_initial(
127                resource_group_name=resource_group_name,
128                bastion_host_name=bastion_host_name,
129                cls=lambda x,y,z: x,
130                **kwargs
131            )
132
133        kwargs.pop('error_map', None)
134        kwargs.pop('content_type', None)
135
136        def get_long_running_output(pipeline_response):
137            if cls:
138                return cls(pipeline_response, None, {})
139
140        path_format_arguments = {
141            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
142            'bastionHostName': self._serialize.url("bastion_host_name", bastion_host_name, 'str'),
143            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
144        }
145
146        if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments,  **kwargs)
147        elif polling is False: polling_method = NoPolling()
148        else: polling_method = polling
149        if cont_token:
150            return LROPoller.from_continuation_token(
151                polling_method=polling_method,
152                continuation_token=cont_token,
153                client=self._client,
154                deserialization_callback=get_long_running_output
155            )
156        else:
157            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
158    begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}'}  # type: ignore
159
160    def get(
161        self,
162        resource_group_name,  # type: str
163        bastion_host_name,  # type: str
164        **kwargs  # type: Any
165    ):
166        # type: (...) -> "_models.BastionHost"
167        """Gets the specified Bastion Host.
168
169        :param resource_group_name: The name of the resource group.
170        :type resource_group_name: str
171        :param bastion_host_name: The name of the Bastion Host.
172        :type bastion_host_name: str
173        :keyword callable cls: A custom type or function that will be passed the direct response
174        :return: BastionHost, or the result of cls(response)
175        :rtype: ~azure.mgmt.network.v2019_11_01.models.BastionHost
176        :raises: ~azure.core.exceptions.HttpResponseError
177        """
178        cls = kwargs.pop('cls', None)  # type: ClsType["_models.BastionHost"]
179        error_map = {
180            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
181        }
182        error_map.update(kwargs.pop('error_map', {}))
183        api_version = "2019-11-01"
184        accept = "application/json"
185
186        # Construct URL
187        url = self.get.metadata['url']  # type: ignore
188        path_format_arguments = {
189            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
190            'bastionHostName': self._serialize.url("bastion_host_name", bastion_host_name, 'str'),
191            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
192        }
193        url = self._client.format_url(url, **path_format_arguments)
194
195        # Construct parameters
196        query_parameters = {}  # type: Dict[str, Any]
197        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
198
199        # Construct headers
200        header_parameters = {}  # type: Dict[str, Any]
201        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
202
203        request = self._client.get(url, query_parameters, header_parameters)
204        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
205        response = pipeline_response.http_response
206
207        if response.status_code not in [200]:
208            map_error(status_code=response.status_code, response=response, error_map=error_map)
209            raise HttpResponseError(response=response, error_format=ARMErrorFormat)
210
211        deserialized = self._deserialize('BastionHost', pipeline_response)
212
213        if cls:
214            return cls(pipeline_response, deserialized, {})
215
216        return deserialized
217    get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}'}  # type: ignore
218
219    def _create_or_update_initial(
220        self,
221        resource_group_name,  # type: str
222        bastion_host_name,  # type: str
223        parameters,  # type: "_models.BastionHost"
224        **kwargs  # type: Any
225    ):
226        # type: (...) -> "_models.BastionHost"
227        cls = kwargs.pop('cls', None)  # type: ClsType["_models.BastionHost"]
228        error_map = {
229            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
230        }
231        error_map.update(kwargs.pop('error_map', {}))
232        api_version = "2019-11-01"
233        content_type = kwargs.pop("content_type", "application/json")
234        accept = "application/json"
235
236        # Construct URL
237        url = self._create_or_update_initial.metadata['url']  # type: ignore
238        path_format_arguments = {
239            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
240            'bastionHostName': self._serialize.url("bastion_host_name", bastion_host_name, 'str'),
241            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
242        }
243        url = self._client.format_url(url, **path_format_arguments)
244
245        # Construct parameters
246        query_parameters = {}  # type: Dict[str, Any]
247        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
248
249        # Construct headers
250        header_parameters = {}  # type: Dict[str, Any]
251        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
252        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
253
254        body_content_kwargs = {}  # type: Dict[str, Any]
255        body_content = self._serialize.body(parameters, 'BastionHost')
256        body_content_kwargs['content'] = body_content
257        request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
258        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
259        response = pipeline_response.http_response
260
261        if response.status_code not in [200, 201]:
262            map_error(status_code=response.status_code, response=response, error_map=error_map)
263            raise HttpResponseError(response=response, error_format=ARMErrorFormat)
264
265        if response.status_code == 200:
266            deserialized = self._deserialize('BastionHost', pipeline_response)
267
268        if response.status_code == 201:
269            deserialized = self._deserialize('BastionHost', pipeline_response)
270
271        if cls:
272            return cls(pipeline_response, deserialized, {})
273
274        return deserialized
275    _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}'}  # type: ignore
276
277    def begin_create_or_update(
278        self,
279        resource_group_name,  # type: str
280        bastion_host_name,  # type: str
281        parameters,  # type: "_models.BastionHost"
282        **kwargs  # type: Any
283    ):
284        # type: (...) -> LROPoller["_models.BastionHost"]
285        """Creates or updates the specified Bastion Host.
286
287        :param resource_group_name: The name of the resource group.
288        :type resource_group_name: str
289        :param bastion_host_name: The name of the Bastion Host.
290        :type bastion_host_name: str
291        :param parameters: Parameters supplied to the create or update Bastion Host operation.
292        :type parameters: ~azure.mgmt.network.v2019_11_01.models.BastionHost
293        :keyword callable cls: A custom type or function that will be passed the direct response
294        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
295        :keyword polling: Pass in True if you'd like the ARMPolling polling method,
296         False for no polling, or your own initialized polling object for a personal polling strategy.
297        :paramtype polling: bool or ~azure.core.polling.PollingMethod
298        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
299        :return: An instance of LROPoller that returns either BastionHost or the result of cls(response)
300        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2019_11_01.models.BastionHost]
301        :raises ~azure.core.exceptions.HttpResponseError:
302        """
303        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
304        cls = kwargs.pop('cls', None)  # type: ClsType["_models.BastionHost"]
305        lro_delay = kwargs.pop(
306            'polling_interval',
307            self._config.polling_interval
308        )
309        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
310        if cont_token is None:
311            raw_result = self._create_or_update_initial(
312                resource_group_name=resource_group_name,
313                bastion_host_name=bastion_host_name,
314                parameters=parameters,
315                cls=lambda x,y,z: x,
316                **kwargs
317            )
318
319        kwargs.pop('error_map', None)
320        kwargs.pop('content_type', None)
321
322        def get_long_running_output(pipeline_response):
323            deserialized = self._deserialize('BastionHost', pipeline_response)
324
325            if cls:
326                return cls(pipeline_response, deserialized, {})
327            return deserialized
328
329        path_format_arguments = {
330            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
331            'bastionHostName': self._serialize.url("bastion_host_name", bastion_host_name, 'str'),
332            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
333        }
334
335        if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments,  **kwargs)
336        elif polling is False: polling_method = NoPolling()
337        else: polling_method = polling
338        if cont_token:
339            return LROPoller.from_continuation_token(
340                polling_method=polling_method,
341                continuation_token=cont_token,
342                client=self._client,
343                deserialization_callback=get_long_running_output
344            )
345        else:
346            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
347    begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}'}  # type: ignore
348
349    def list(
350        self,
351        **kwargs  # type: Any
352    ):
353        # type: (...) -> Iterable["_models.BastionHostListResult"]
354        """Lists all Bastion Hosts in a subscription.
355
356        :keyword callable cls: A custom type or function that will be passed the direct response
357        :return: An iterator like instance of either BastionHostListResult or the result of cls(response)
358        :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2019_11_01.models.BastionHostListResult]
359        :raises: ~azure.core.exceptions.HttpResponseError
360        """
361        cls = kwargs.pop('cls', None)  # type: ClsType["_models.BastionHostListResult"]
362        error_map = {
363            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
364        }
365        error_map.update(kwargs.pop('error_map', {}))
366        api_version = "2019-11-01"
367        accept = "application/json"
368
369        def prepare_request(next_link=None):
370            # Construct headers
371            header_parameters = {}  # type: Dict[str, Any]
372            header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
373
374            if not next_link:
375                # Construct URL
376                url = self.list.metadata['url']  # type: ignore
377                path_format_arguments = {
378                    'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
379                }
380                url = self._client.format_url(url, **path_format_arguments)
381                # Construct parameters
382                query_parameters = {}  # type: Dict[str, Any]
383                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
384
385                request = self._client.get(url, query_parameters, header_parameters)
386            else:
387                url = next_link
388                query_parameters = {}  # type: Dict[str, Any]
389                request = self._client.get(url, query_parameters, header_parameters)
390            return request
391
392        def extract_data(pipeline_response):
393            deserialized = self._deserialize('BastionHostListResult', pipeline_response)
394            list_of_elem = deserialized.value
395            if cls:
396                list_of_elem = cls(list_of_elem)
397            return deserialized.next_link or None, iter(list_of_elem)
398
399        def get_next(next_link=None):
400            request = prepare_request(next_link)
401
402            pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
403            response = pipeline_response.http_response
404
405            if response.status_code not in [200]:
406                map_error(status_code=response.status_code, response=response, error_map=error_map)
407                raise HttpResponseError(response=response, error_format=ARMErrorFormat)
408
409            return pipeline_response
410
411        return ItemPaged(
412            get_next, extract_data
413        )
414    list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/bastionHosts'}  # type: ignore
415
416    def list_by_resource_group(
417        self,
418        resource_group_name,  # type: str
419        **kwargs  # type: Any
420    ):
421        # type: (...) -> Iterable["_models.BastionHostListResult"]
422        """Lists all Bastion Hosts in a resource group.
423
424        :param resource_group_name: The name of the resource group.
425        :type resource_group_name: str
426        :keyword callable cls: A custom type or function that will be passed the direct response
427        :return: An iterator like instance of either BastionHostListResult or the result of cls(response)
428        :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2019_11_01.models.BastionHostListResult]
429        :raises: ~azure.core.exceptions.HttpResponseError
430        """
431        cls = kwargs.pop('cls', None)  # type: ClsType["_models.BastionHostListResult"]
432        error_map = {
433            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
434        }
435        error_map.update(kwargs.pop('error_map', {}))
436        api_version = "2019-11-01"
437        accept = "application/json"
438
439        def prepare_request(next_link=None):
440            # Construct headers
441            header_parameters = {}  # type: Dict[str, Any]
442            header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
443
444            if not next_link:
445                # Construct URL
446                url = self.list_by_resource_group.metadata['url']  # type: ignore
447                path_format_arguments = {
448                    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
449                    'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
450                }
451                url = self._client.format_url(url, **path_format_arguments)
452                # Construct parameters
453                query_parameters = {}  # type: Dict[str, Any]
454                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
455
456                request = self._client.get(url, query_parameters, header_parameters)
457            else:
458                url = next_link
459                query_parameters = {}  # type: Dict[str, Any]
460                request = self._client.get(url, query_parameters, header_parameters)
461            return request
462
463        def extract_data(pipeline_response):
464            deserialized = self._deserialize('BastionHostListResult', pipeline_response)
465            list_of_elem = deserialized.value
466            if cls:
467                list_of_elem = cls(list_of_elem)
468            return deserialized.next_link or None, iter(list_of_elem)
469
470        def get_next(next_link=None):
471            request = prepare_request(next_link)
472
473            pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
474            response = pipeline_response.http_response
475
476            if response.status_code not in [200]:
477                map_error(status_code=response.status_code, response=response, error_map=error_map)
478                raise HttpResponseError(response=response, error_format=ARMErrorFormat)
479
480            return pipeline_response
481
482        return ItemPaged(
483            get_next, extract_data
484        )
485    list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts'}  # type: ignore
486