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.pipeline import PipelineResponse
13from azure.core.pipeline.transport import HttpRequest, HttpResponse
14from azure.core.polling import LROPoller, NoPolling, PollingMethod
15from azure.mgmt.core.exceptions import ARMErrorFormat
16from azure.mgmt.core.polling.arm_polling import ARMPolling
17
18from .. import models as _models
19
20if TYPE_CHECKING:
21    # pylint: disable=unused-import,ungrouped-imports
22    from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar, Union
23
24    T = TypeVar('T')
25    ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
26
27class VirtualMachinesOperations(object):
28    """VirtualMachinesOperations operations.
29
30    You should not instantiate this class directly. Instead, you should create a Client instance that
31    instantiates it for you and attaches it as an attribute.
32
33    :ivar models: Alias to model classes used in this operation group.
34    :type models: ~azure.mgmt.hdinsight.models
35    :param client: Client for service requests.
36    :param config: Configuration of service client.
37    :param serializer: An object model serializer.
38    :param deserializer: An object model deserializer.
39    """
40
41    models = _models
42
43    def __init__(self, client, config, serializer, deserializer):
44        self._client = client
45        self._serialize = serializer
46        self._deserialize = deserializer
47        self._config = config
48
49    def list_hosts(
50        self,
51        resource_group_name,  # type: str
52        cluster_name,  # type: str
53        **kwargs  # type: Any
54    ):
55        # type: (...) -> List["_models.HostInfo"]
56        """Lists the HDInsight clusters hosts.
57
58        :param resource_group_name: The name of the resource group.
59        :type resource_group_name: str
60        :param cluster_name: The name of the cluster.
61        :type cluster_name: str
62        :keyword callable cls: A custom type or function that will be passed the direct response
63        :return: list of HostInfo, or the result of cls(response)
64        :rtype: list[~azure.mgmt.hdinsight.models.HostInfo]
65        :raises: ~azure.core.exceptions.HttpResponseError
66        """
67        cls = kwargs.pop('cls', None)  # type: ClsType[List["_models.HostInfo"]]
68        error_map = {
69            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
70        }
71        error_map.update(kwargs.pop('error_map', {}))
72        api_version = "2018-06-01-preview"
73        accept = "application/json"
74
75        # Construct URL
76        url = self.list_hosts.metadata['url']  # type: ignore
77        path_format_arguments = {
78            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
79            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
80            'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'),
81        }
82        url = self._client.format_url(url, **path_format_arguments)
83
84        # Construct parameters
85        query_parameters = {}  # type: Dict[str, Any]
86        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
87
88        # Construct headers
89        header_parameters = {}  # type: Dict[str, Any]
90        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
91
92        request = self._client.post(url, query_parameters, header_parameters)
93        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
94        response = pipeline_response.http_response
95
96        if response.status_code not in [200]:
97            map_error(status_code=response.status_code, response=response, error_map=error_map)
98            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
99            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
100
101        deserialized = self._deserialize('[HostInfo]', pipeline_response)
102
103        if cls:
104            return cls(pipeline_response, deserialized, {})
105
106        return deserialized
107    list_hosts.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/listHosts'}  # type: ignore
108
109    def _restart_hosts_initial(
110        self,
111        resource_group_name,  # type: str
112        cluster_name,  # type: str
113        hosts,  # type: List[str]
114        **kwargs  # type: Any
115    ):
116        # type: (...) -> None
117        cls = kwargs.pop('cls', None)  # type: ClsType[None]
118        error_map = {
119            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
120        }
121        error_map.update(kwargs.pop('error_map', {}))
122        api_version = "2018-06-01-preview"
123        content_type = kwargs.pop("content_type", "application/json")
124        accept = "application/json"
125
126        # Construct URL
127        url = self._restart_hosts_initial.metadata['url']  # type: ignore
128        path_format_arguments = {
129            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
130            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
131            'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'),
132        }
133        url = self._client.format_url(url, **path_format_arguments)
134
135        # Construct parameters
136        query_parameters = {}  # type: Dict[str, Any]
137        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
138
139        # Construct headers
140        header_parameters = {}  # type: Dict[str, Any]
141        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
142        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
143
144        body_content_kwargs = {}  # type: Dict[str, Any]
145        body_content = self._serialize.body(hosts, '[str]')
146        body_content_kwargs['content'] = body_content
147        request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
148        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
149        response = pipeline_response.http_response
150
151        if response.status_code not in [200, 202]:
152            map_error(status_code=response.status_code, response=response, error_map=error_map)
153            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
154            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
155
156        if cls:
157            return cls(pipeline_response, None, {})
158
159    _restart_hosts_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/restartHosts'}  # type: ignore
160
161    def begin_restart_hosts(
162        self,
163        resource_group_name,  # type: str
164        cluster_name,  # type: str
165        hosts,  # type: List[str]
166        **kwargs  # type: Any
167    ):
168        # type: (...) -> LROPoller[None]
169        """Restarts the specified HDInsight cluster hosts.
170
171        :param resource_group_name: The name of the resource group.
172        :type resource_group_name: str
173        :param cluster_name: The name of the cluster.
174        :type cluster_name: str
175        :param hosts: The list of hosts to restart.
176        :type hosts: list[str]
177        :keyword callable cls: A custom type or function that will be passed the direct response
178        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
179        :keyword polling: By default, your polling method will be ARMPolling.
180         Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
181        :paramtype polling: bool or ~azure.core.polling.PollingMethod
182        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
183        :return: An instance of LROPoller that returns either None or the result of cls(response)
184        :rtype: ~azure.core.polling.LROPoller[None]
185        :raises ~azure.core.exceptions.HttpResponseError:
186        """
187        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
188        cls = kwargs.pop('cls', None)  # type: ClsType[None]
189        lro_delay = kwargs.pop(
190            'polling_interval',
191            self._config.polling_interval
192        )
193        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
194        if cont_token is None:
195            raw_result = self._restart_hosts_initial(
196                resource_group_name=resource_group_name,
197                cluster_name=cluster_name,
198                hosts=hosts,
199                cls=lambda x,y,z: x,
200                **kwargs
201            )
202
203        kwargs.pop('error_map', None)
204        kwargs.pop('content_type', None)
205
206        def get_long_running_output(pipeline_response):
207            if cls:
208                return cls(pipeline_response, None, {})
209
210        path_format_arguments = {
211            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
212            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
213            'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'),
214        }
215
216        if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments,  **kwargs)
217        elif polling is False: polling_method = NoPolling()
218        else: polling_method = polling
219        if cont_token:
220            return LROPoller.from_continuation_token(
221                polling_method=polling_method,
222                continuation_token=cont_token,
223                client=self._client,
224                deserialization_callback=get_long_running_output
225            )
226        else:
227            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
228    begin_restart_hosts.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/restartHosts'}  # type: ignore
229
230    def get_async_operation_status(
231        self,
232        resource_group_name,  # type: str
233        cluster_name,  # type: str
234        operation_id,  # type: str
235        **kwargs  # type: Any
236    ):
237        # type: (...) -> "_models.AsyncOperationResult"
238        """Gets the async operation status.
239
240        :param resource_group_name: The name of the resource group.
241        :type resource_group_name: str
242        :param cluster_name: The name of the cluster.
243        :type cluster_name: str
244        :param operation_id: The long running operation id.
245        :type operation_id: str
246        :keyword callable cls: A custom type or function that will be passed the direct response
247        :return: AsyncOperationResult, or the result of cls(response)
248        :rtype: ~azure.mgmt.hdinsight.models.AsyncOperationResult
249        :raises: ~azure.core.exceptions.HttpResponseError
250        """
251        cls = kwargs.pop('cls', None)  # type: ClsType["_models.AsyncOperationResult"]
252        error_map = {
253            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
254        }
255        error_map.update(kwargs.pop('error_map', {}))
256        api_version = "2018-06-01-preview"
257        accept = "application/json"
258
259        # Construct URL
260        url = self.get_async_operation_status.metadata['url']  # type: ignore
261        path_format_arguments = {
262            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
263            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
264            'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'),
265            'operationId': self._serialize.url("operation_id", operation_id, 'str'),
266        }
267        url = self._client.format_url(url, **path_format_arguments)
268
269        # Construct parameters
270        query_parameters = {}  # type: Dict[str, Any]
271        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
272
273        # Construct headers
274        header_parameters = {}  # type: Dict[str, Any]
275        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
276
277        request = self._client.get(url, query_parameters, header_parameters)
278        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
279        response = pipeline_response.http_response
280
281        if response.status_code not in [200]:
282            map_error(status_code=response.status_code, response=response, error_map=error_map)
283            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
284            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
285
286        deserialized = self._deserialize('AsyncOperationResult', pipeline_response)
287
288        if cls:
289            return cls(pipeline_response, deserialized, {})
290
291        return deserialized
292    get_async_operation_status.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/restartHosts/azureasyncoperations/{operationId}'}  # type: ignore
293