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, Optional, TypeVar, Union
23
24    T = TypeVar('T')
25    ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
26
27class VirtualMachineExtensionsOperations(object):
28    """VirtualMachineExtensionsOperations 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.compute.v2017_12_01.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 _create_or_update_initial(
50        self,
51        resource_group_name,  # type: str
52        vm_name,  # type: str
53        vm_extension_name,  # type: str
54        extension_parameters,  # type: "_models.VirtualMachineExtension"
55        **kwargs  # type: Any
56    ):
57        # type: (...) -> "_models.VirtualMachineExtension"
58        cls = kwargs.pop('cls', None)  # type: ClsType["_models.VirtualMachineExtension"]
59        error_map = {
60            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
61        }
62        error_map.update(kwargs.pop('error_map', {}))
63        api_version = "2017-12-01"
64        content_type = kwargs.pop("content_type", "application/json")
65        accept = "application/json"
66
67        # Construct URL
68        url = self._create_or_update_initial.metadata['url']  # type: ignore
69        path_format_arguments = {
70            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
71            'vmName': self._serialize.url("vm_name", vm_name, 'str'),
72            'vmExtensionName': self._serialize.url("vm_extension_name", vm_extension_name, 'str'),
73            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
74        }
75        url = self._client.format_url(url, **path_format_arguments)
76
77        # Construct parameters
78        query_parameters = {}  # type: Dict[str, Any]
79        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
80
81        # Construct headers
82        header_parameters = {}  # type: Dict[str, Any]
83        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
84        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
85
86        body_content_kwargs = {}  # type: Dict[str, Any]
87        body_content = self._serialize.body(extension_parameters, 'VirtualMachineExtension')
88        body_content_kwargs['content'] = body_content
89        request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
90        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
91        response = pipeline_response.http_response
92
93        if response.status_code not in [200, 201]:
94            map_error(status_code=response.status_code, response=response, error_map=error_map)
95            raise HttpResponseError(response=response, error_format=ARMErrorFormat)
96
97        if response.status_code == 200:
98            deserialized = self._deserialize('VirtualMachineExtension', pipeline_response)
99
100        if response.status_code == 201:
101            deserialized = self._deserialize('VirtualMachineExtension', pipeline_response)
102
103        if cls:
104            return cls(pipeline_response, deserialized, {})
105
106        return deserialized
107    _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}'}  # type: ignore
108
109    def begin_create_or_update(
110        self,
111        resource_group_name,  # type: str
112        vm_name,  # type: str
113        vm_extension_name,  # type: str
114        extension_parameters,  # type: "_models.VirtualMachineExtension"
115        **kwargs  # type: Any
116    ):
117        # type: (...) -> LROPoller["_models.VirtualMachineExtension"]
118        """The operation to create or update the extension.
119
120        :param resource_group_name: The name of the resource group.
121        :type resource_group_name: str
122        :param vm_name: The name of the virtual machine where the extension should be created or
123         updated.
124        :type vm_name: str
125        :param vm_extension_name: The name of the virtual machine extension.
126        :type vm_extension_name: str
127        :param extension_parameters: Parameters supplied to the Create Virtual Machine Extension
128         operation.
129        :type extension_parameters: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineExtension
130        :keyword callable cls: A custom type or function that will be passed the direct response
131        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
132        :keyword polling: By default, your polling method will be ARMPolling.
133         Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
134        :paramtype polling: bool or ~azure.core.polling.PollingMethod
135        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
136        :return: An instance of LROPoller that returns either VirtualMachineExtension or the result of cls(response)
137        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.compute.v2017_12_01.models.VirtualMachineExtension]
138        :raises ~azure.core.exceptions.HttpResponseError:
139        """
140        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
141        cls = kwargs.pop('cls', None)  # type: ClsType["_models.VirtualMachineExtension"]
142        lro_delay = kwargs.pop(
143            'polling_interval',
144            self._config.polling_interval
145        )
146        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
147        if cont_token is None:
148            raw_result = self._create_or_update_initial(
149                resource_group_name=resource_group_name,
150                vm_name=vm_name,
151                vm_extension_name=vm_extension_name,
152                extension_parameters=extension_parameters,
153                cls=lambda x,y,z: x,
154                **kwargs
155            )
156
157        kwargs.pop('error_map', None)
158        kwargs.pop('content_type', None)
159
160        def get_long_running_output(pipeline_response):
161            deserialized = self._deserialize('VirtualMachineExtension', pipeline_response)
162
163            if cls:
164                return cls(pipeline_response, deserialized, {})
165            return deserialized
166
167        path_format_arguments = {
168            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
169            'vmName': self._serialize.url("vm_name", vm_name, 'str'),
170            'vmExtensionName': self._serialize.url("vm_extension_name", vm_extension_name, 'str'),
171            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
172        }
173
174        if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments,  **kwargs)
175        elif polling is False: polling_method = NoPolling()
176        else: polling_method = polling
177        if cont_token:
178            return LROPoller.from_continuation_token(
179                polling_method=polling_method,
180                continuation_token=cont_token,
181                client=self._client,
182                deserialization_callback=get_long_running_output
183            )
184        else:
185            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
186    begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}'}  # type: ignore
187
188    def _update_initial(
189        self,
190        resource_group_name,  # type: str
191        vm_name,  # type: str
192        vm_extension_name,  # type: str
193        extension_parameters,  # type: "_models.VirtualMachineExtensionUpdate"
194        **kwargs  # type: Any
195    ):
196        # type: (...) -> "_models.VirtualMachineExtension"
197        cls = kwargs.pop('cls', None)  # type: ClsType["_models.VirtualMachineExtension"]
198        error_map = {
199            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
200        }
201        error_map.update(kwargs.pop('error_map', {}))
202        api_version = "2017-12-01"
203        content_type = kwargs.pop("content_type", "application/json")
204        accept = "application/json"
205
206        # Construct URL
207        url = self._update_initial.metadata['url']  # type: ignore
208        path_format_arguments = {
209            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
210            'vmName': self._serialize.url("vm_name", vm_name, 'str'),
211            'vmExtensionName': self._serialize.url("vm_extension_name", vm_extension_name, 'str'),
212            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
213        }
214        url = self._client.format_url(url, **path_format_arguments)
215
216        # Construct parameters
217        query_parameters = {}  # type: Dict[str, Any]
218        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
219
220        # Construct headers
221        header_parameters = {}  # type: Dict[str, Any]
222        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
223        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
224
225        body_content_kwargs = {}  # type: Dict[str, Any]
226        body_content = self._serialize.body(extension_parameters, 'VirtualMachineExtensionUpdate')
227        body_content_kwargs['content'] = body_content
228        request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
229        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
230        response = pipeline_response.http_response
231
232        if response.status_code not in [200]:
233            map_error(status_code=response.status_code, response=response, error_map=error_map)
234            raise HttpResponseError(response=response, error_format=ARMErrorFormat)
235
236        deserialized = self._deserialize('VirtualMachineExtension', pipeline_response)
237
238        if cls:
239            return cls(pipeline_response, deserialized, {})
240
241        return deserialized
242    _update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}'}  # type: ignore
243
244    def begin_update(
245        self,
246        resource_group_name,  # type: str
247        vm_name,  # type: str
248        vm_extension_name,  # type: str
249        extension_parameters,  # type: "_models.VirtualMachineExtensionUpdate"
250        **kwargs  # type: Any
251    ):
252        # type: (...) -> LROPoller["_models.VirtualMachineExtension"]
253        """The operation to update the extension.
254
255        :param resource_group_name: The name of the resource group.
256        :type resource_group_name: str
257        :param vm_name: The name of the virtual machine where the extension should be updated.
258        :type vm_name: str
259        :param vm_extension_name: The name of the virtual machine extension.
260        :type vm_extension_name: str
261        :param extension_parameters: Parameters supplied to the Update Virtual Machine Extension
262         operation.
263        :type extension_parameters: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineExtensionUpdate
264        :keyword callable cls: A custom type or function that will be passed the direct response
265        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
266        :keyword polling: By default, your polling method will be ARMPolling.
267         Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
268        :paramtype polling: bool or ~azure.core.polling.PollingMethod
269        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
270        :return: An instance of LROPoller that returns either VirtualMachineExtension or the result of cls(response)
271        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.compute.v2017_12_01.models.VirtualMachineExtension]
272        :raises ~azure.core.exceptions.HttpResponseError:
273        """
274        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
275        cls = kwargs.pop('cls', None)  # type: ClsType["_models.VirtualMachineExtension"]
276        lro_delay = kwargs.pop(
277            'polling_interval',
278            self._config.polling_interval
279        )
280        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
281        if cont_token is None:
282            raw_result = self._update_initial(
283                resource_group_name=resource_group_name,
284                vm_name=vm_name,
285                vm_extension_name=vm_extension_name,
286                extension_parameters=extension_parameters,
287                cls=lambda x,y,z: x,
288                **kwargs
289            )
290
291        kwargs.pop('error_map', None)
292        kwargs.pop('content_type', None)
293
294        def get_long_running_output(pipeline_response):
295            deserialized = self._deserialize('VirtualMachineExtension', pipeline_response)
296
297            if cls:
298                return cls(pipeline_response, deserialized, {})
299            return deserialized
300
301        path_format_arguments = {
302            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
303            'vmName': self._serialize.url("vm_name", vm_name, 'str'),
304            'vmExtensionName': self._serialize.url("vm_extension_name", vm_extension_name, 'str'),
305            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
306        }
307
308        if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments,  **kwargs)
309        elif polling is False: polling_method = NoPolling()
310        else: polling_method = polling
311        if cont_token:
312            return LROPoller.from_continuation_token(
313                polling_method=polling_method,
314                continuation_token=cont_token,
315                client=self._client,
316                deserialization_callback=get_long_running_output
317            )
318        else:
319            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
320    begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}'}  # type: ignore
321
322    def _delete_initial(
323        self,
324        resource_group_name,  # type: str
325        vm_name,  # type: str
326        vm_extension_name,  # type: str
327        **kwargs  # type: Any
328    ):
329        # type: (...) -> Optional["_models.OperationStatusResponse"]
330        cls = kwargs.pop('cls', None)  # type: ClsType[Optional["_models.OperationStatusResponse"]]
331        error_map = {
332            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
333        }
334        error_map.update(kwargs.pop('error_map', {}))
335        api_version = "2017-12-01"
336        accept = "application/json"
337
338        # Construct URL
339        url = self._delete_initial.metadata['url']  # type: ignore
340        path_format_arguments = {
341            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
342            'vmName': self._serialize.url("vm_name", vm_name, 'str'),
343            'vmExtensionName': self._serialize.url("vm_extension_name", vm_extension_name, 'str'),
344            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
345        }
346        url = self._client.format_url(url, **path_format_arguments)
347
348        # Construct parameters
349        query_parameters = {}  # type: Dict[str, Any]
350        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
351
352        # Construct headers
353        header_parameters = {}  # type: Dict[str, Any]
354        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
355
356        request = self._client.delete(url, query_parameters, header_parameters)
357        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
358        response = pipeline_response.http_response
359
360        if response.status_code not in [200, 202, 204]:
361            map_error(status_code=response.status_code, response=response, error_map=error_map)
362            raise HttpResponseError(response=response, error_format=ARMErrorFormat)
363
364        deserialized = None
365        if response.status_code == 200:
366            deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
367
368        if cls:
369            return cls(pipeline_response, deserialized, {})
370
371        return deserialized
372    _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}'}  # type: ignore
373
374    def begin_delete(
375        self,
376        resource_group_name,  # type: str
377        vm_name,  # type: str
378        vm_extension_name,  # type: str
379        **kwargs  # type: Any
380    ):
381        # type: (...) -> LROPoller["_models.OperationStatusResponse"]
382        """The operation to delete the extension.
383
384        :param resource_group_name: The name of the resource group.
385        :type resource_group_name: str
386        :param vm_name: The name of the virtual machine where the extension should be deleted.
387        :type vm_name: str
388        :param vm_extension_name: The name of the virtual machine extension.
389        :type vm_extension_name: str
390        :keyword callable cls: A custom type or function that will be passed the direct response
391        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
392        :keyword polling: By default, your polling method will be ARMPolling.
393         Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
394        :paramtype polling: bool or ~azure.core.polling.PollingMethod
395        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
396        :return: An instance of LROPoller that returns either OperationStatusResponse or the result of cls(response)
397        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.compute.v2017_12_01.models.OperationStatusResponse]
398        :raises ~azure.core.exceptions.HttpResponseError:
399        """
400        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
401        cls = kwargs.pop('cls', None)  # type: ClsType["_models.OperationStatusResponse"]
402        lro_delay = kwargs.pop(
403            'polling_interval',
404            self._config.polling_interval
405        )
406        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
407        if cont_token is None:
408            raw_result = self._delete_initial(
409                resource_group_name=resource_group_name,
410                vm_name=vm_name,
411                vm_extension_name=vm_extension_name,
412                cls=lambda x,y,z: x,
413                **kwargs
414            )
415
416        kwargs.pop('error_map', None)
417        kwargs.pop('content_type', None)
418
419        def get_long_running_output(pipeline_response):
420            deserialized = self._deserialize('OperationStatusResponse', pipeline_response)
421
422            if cls:
423                return cls(pipeline_response, deserialized, {})
424            return deserialized
425
426        path_format_arguments = {
427            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
428            'vmName': self._serialize.url("vm_name", vm_name, 'str'),
429            'vmExtensionName': self._serialize.url("vm_extension_name", vm_extension_name, 'str'),
430            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
431        }
432
433        if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments,  **kwargs)
434        elif polling is False: polling_method = NoPolling()
435        else: polling_method = polling
436        if cont_token:
437            return LROPoller.from_continuation_token(
438                polling_method=polling_method,
439                continuation_token=cont_token,
440                client=self._client,
441                deserialization_callback=get_long_running_output
442            )
443        else:
444            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
445    begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}'}  # type: ignore
446
447    def get(
448        self,
449        resource_group_name,  # type: str
450        vm_name,  # type: str
451        vm_extension_name,  # type: str
452        expand=None,  # type: Optional[str]
453        **kwargs  # type: Any
454    ):
455        # type: (...) -> "_models.VirtualMachineExtension"
456        """The operation to get the extension.
457
458        :param resource_group_name: The name of the resource group.
459        :type resource_group_name: str
460        :param vm_name: The name of the virtual machine containing the extension.
461        :type vm_name: str
462        :param vm_extension_name: The name of the virtual machine extension.
463        :type vm_extension_name: str
464        :param expand: The expand expression to apply on the operation.
465        :type expand: str
466        :keyword callable cls: A custom type or function that will be passed the direct response
467        :return: VirtualMachineExtension, or the result of cls(response)
468        :rtype: ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineExtension
469        :raises: ~azure.core.exceptions.HttpResponseError
470        """
471        cls = kwargs.pop('cls', None)  # type: ClsType["_models.VirtualMachineExtension"]
472        error_map = {
473            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
474        }
475        error_map.update(kwargs.pop('error_map', {}))
476        api_version = "2017-12-01"
477        accept = "application/json"
478
479        # Construct URL
480        url = self.get.metadata['url']  # type: ignore
481        path_format_arguments = {
482            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
483            'vmName': self._serialize.url("vm_name", vm_name, 'str'),
484            'vmExtensionName': self._serialize.url("vm_extension_name", vm_extension_name, 'str'),
485            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
486        }
487        url = self._client.format_url(url, **path_format_arguments)
488
489        # Construct parameters
490        query_parameters = {}  # type: Dict[str, Any]
491        if expand is not None:
492            query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')
493        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
494
495        # Construct headers
496        header_parameters = {}  # type: Dict[str, Any]
497        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
498
499        request = self._client.get(url, query_parameters, header_parameters)
500        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
501        response = pipeline_response.http_response
502
503        if response.status_code not in [200]:
504            map_error(status_code=response.status_code, response=response, error_map=error_map)
505            raise HttpResponseError(response=response, error_format=ARMErrorFormat)
506
507        deserialized = self._deserialize('VirtualMachineExtension', pipeline_response)
508
509        if cls:
510            return cls(pipeline_response, deserialized, {})
511
512        return deserialized
513    get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}'}  # type: ignore
514