1# --------------------------------------------------------------------------
2#
3# Copyright (c) Microsoft Corporation. All rights reserved.
4#
5# The MIT License (MIT)
6#
7# Permission is hereby granted, free of charge, to any person obtaining a copy
8# of this software and associated documentation files (the ""Software""), to
9# deal in the Software without restriction, including without limitation the
10# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
11# sell copies of the Software, and to permit persons to whom the Software is
12# furnished to do so, subject to the following conditions:
13#
14# The above copyright notice and this permission notice shall be included in
15# all copies or substantial portions of the Software.
16#
17# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23# IN THE SOFTWARE.
24#
25# --------------------------------------------------------------------------
26import json
27import logging
28import re
29import time
30import uuid
31
32from azure.core.pipeline import PipelineContext, PipelineRequest
33from azure.core.pipeline.policies import HTTPPolicy
34from azure.core.pipeline.transport import HttpRequest
35
36
37_LOGGER = logging.getLogger(__name__)
38
39
40class ARMAutoResourceProviderRegistrationPolicy(HTTPPolicy):
41 """Auto register an ARM resource provider if not done yet."""
42
43 def send(self, request):
44 # type: (PipelineRequest[HTTPRequestType], Any) -> PipelineResponse[HTTPRequestType, HTTPResponseType]
45 http_request = request.http_request
46 response = self.next.send(request)
47 if response.http_response.status_code == 409:
48 rp_name = self._check_rp_not_registered_err(response)
49 if rp_name:
50 url_prefix = self._extract_subscription_url(http_request.url)
51 if not self._register_rp(request, url_prefix, rp_name):
52 return response
53 # Change the 'x-ms-client-request-id' otherwise the Azure endpoint
54 # just returns the same 409 payload without looking at the actual query
55 if "x-ms-client-request-id" in http_request.headers:
56 http_request.headers["x-ms-client-request-id"] = str(uuid.uuid4())
57 response = self.next.send(request)
58 return response
59
60 @staticmethod
61 def _check_rp_not_registered_err(response):
62 try:
63 response = json.loads(response.http_response.text())
64 if response["error"]["code"] == "MissingSubscriptionRegistration":
65 match = re.match(r".*'(.*)'", response["error"]["message"])
66 return match.group(1)
67 except Exception: # pylint: disable=broad-except
68 pass
69 return None
70
71 @staticmethod
72 def _extract_subscription_url(url):
73 """Extract the first part of the URL, just after subscription:
74 https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
75 """
76 match = re.match(r".*/subscriptions/[a-f0-9-]+/", url, re.IGNORECASE)
77 if not match:
78 raise ValueError("Unable to extract subscription ID from URL")
79 return match.group(0)
80
81 @staticmethod
82 def _build_next_request(initial_request, method, url):
83 request = HttpRequest(method, url)
84 context = PipelineContext(initial_request.context.transport, **initial_request.context.options)
85 return PipelineRequest(request, context)
86
87 def _register_rp(self, initial_request, url_prefix, rp_name):
88 """Synchronously register the RP is paremeter.
89
90 Return False if we have a reason to believe this didn't work
91 """
92 post_url = "{}providers/{}/register?api-version=2016-02-01".format(url_prefix, rp_name)
93 get_url = "{}providers/{}?api-version=2016-02-01".format(url_prefix, rp_name)
94 _LOGGER.warning(
95 "Resource provider '%s' used by this operation is not " "registered. We are registering for you.",
96 rp_name,
97 )
98 post_response = self.next.send(self._build_next_request(initial_request, "POST", post_url))
99 if post_response.http_response.status_code != 200:
100 _LOGGER.warning("Registration failed. Please register manually.")
101 return False
102
103 while True:
104 time.sleep(10)
105 get_response = self.next.send(self._build_next_request(initial_request, "GET", get_url))
106 rp_info = json.loads(get_response.http_response.text())
107 if rp_info["registrationState"] == "Registered":
108 _LOGGER.warning("Registration succeeded.")
109 return True