|
4 | 4 |
|
5 | 5 | import json |
6 | 6 | import logging |
7 | | -import os |
8 | | -import subprocess |
9 | 7 | import tempfile |
10 | 8 | import time |
| 9 | +import urllib.request |
11 | 10 | from pathlib import Path |
12 | 11 | from subprocess import CalledProcessError |
13 | 12 | from types import TracebackType |
|
19 | 18 | log = logging.getLogger(__name__) |
20 | 19 | log.addHandler(logging.NullHandler()) |
21 | 20 |
|
| 21 | +# The files that make up the deployable function app package. |
| 22 | +FUNCTION_APP_FILES = [ |
| 23 | + Path("host.json"), |
| 24 | + Path("requirements.txt"), |
| 25 | + Path("function_app.py"), |
| 26 | +] |
| 27 | + |
| 28 | +# Kudu deployment status codes (from /api/deployments/latest). |
| 29 | +_DEPLOY_STATUS_FAILED = 3 |
| 30 | +_DEPLOY_STATUS_SUCCESS = 4 |
| 31 | + |
| 32 | + |
| 33 | +def build_function_zip(zip_path: Path) -> None: |
| 34 | + """Write the function app package to zip_path.""" |
| 35 | + with ZipFile(zip_path, "w") as zipf: |
| 36 | + for path in FUNCTION_APP_FILES: |
| 37 | + zipf.write(path, path.name) |
| 38 | + |
22 | 39 |
|
23 | 40 | class FuncApp: |
24 | 41 | """Basic class for managing function apps.""" |
@@ -103,16 +120,7 @@ def __init__( |
103 | 120 | name, resource_group, Path(self.tempfile.name), subscription=subscription |
104 | 121 | ) |
105 | 122 |
|
106 | | - self.zip_paths = [ |
107 | | - Path("host.json"), |
108 | | - Path("requirements.txt"), |
109 | | - Path("function_app.py"), |
110 | | - ] |
111 | | - |
112 | | - with ZipFile(self.tempfile, "w") as zipf: |
113 | | - for path in self.zip_paths: |
114 | | - zipf.write(path, path.name) |
115 | | - |
| 123 | + build_function_zip(Path(self.tempfile.name)) |
116 | 124 | self.tempfile.close() |
117 | 125 |
|
118 | 126 | def deploy(self) -> None: |
@@ -141,56 +149,88 @@ def deploy(self) -> None: |
141 | 149 |
|
142 | 150 |
|
143 | 151 | class FuncAppBundle(FuncApp): |
144 | | - """Publishes the function app using the core-tools tooling.""" |
| 152 | + """Publishes the function app via the Azure "One Deploy" endpoint. |
| 153 | +
|
| 154 | + Used when shared-key access is disabled. Both 'az functionapp deployment |
| 155 | + source config-zip' and 'az functionapp deploy' insist on fetching SCM basic |
| 156 | + publishing credentials, which are disabled on such apps, so they fail with |
| 157 | + HTTP 403. Instead we POST the package straight to the One Deploy endpoint |
| 158 | + with an AAD bearer token, which is accepted. This needs only 'az' (for the |
| 159 | + token); no Docker image or Azure Functions Core Tools are required. |
| 160 | + """ |
| 161 | + |
| 162 | + # Poll the deployment for at most this long (remote build can be slow). |
| 163 | + _DEPLOY_TIMEOUT_S = 600 |
| 164 | + _DEPLOY_POLL_INTERVAL_S = 15 |
145 | 165 |
|
146 | 166 | def __init__( |
147 | 167 | self, name: str, resource_group: str, subscription: Optional[str] = None |
148 | 168 | ) -> None: |
149 | 169 | """Create a FuncAppBundle object.""" |
| 170 | + self.tempfile = tempfile.NamedTemporaryFile(suffix=".zip", delete=False) |
150 | 171 | super().__init__( |
151 | | - name, resource_group, Path("function_app.zip"), subscription=subscription |
| 172 | + name, resource_group, Path(self.tempfile.name), subscription=subscription |
152 | 173 | ) |
| 174 | + build_function_zip(Path(self.tempfile.name)) |
| 175 | + self.tempfile.close() |
| 176 | + |
| 177 | + def _access_token(self) -> str: |
| 178 | + """Get an AAD access token for the deployment endpoint.""" |
| 179 | + token: str = AzCmdJson( |
| 180 | + ["az", "account", "get-access-token", "--query", "accessToken"], |
| 181 | + subscription=self.subscription, |
| 182 | + ).run() |
| 183 | + return token |
153 | 184 |
|
154 | 185 | def deploy(self) -> None: |
155 | | - """Deploy the function application.""" |
156 | | - log.info("Deploying function app code") |
157 | | - cwd = Path.cwd() |
158 | | - |
159 | | - # Mint an access token on the host: the host 'az' can read its own |
160 | | - # credential cache, whereas the (older) 'az' inside the core-tools image |
161 | | - # cannot deserialise a cache written by a newer host 'az'. So instead of |
162 | | - # mounting ~/.azure into the container, pass a token to 'func' directly. |
163 | | - token_cmd = ["az", "account", "get-access-token", "--query", "accessToken"] |
164 | | - token = AzCmdJson(token_cmd, subscription=self.subscription).run() |
165 | | - |
166 | | - # Pass the token via the environment so it never appears in the logged |
167 | | - # command line or the container's process arguments. |
168 | | - func_cmd = f'func azure functionapp publish {self.name} --python --build remote --access-token "$FUNC_ACCESS_TOKEN"' |
169 | | - if self.subscription: |
170 | | - func_cmd += f" --subscription {self.subscription}" |
171 | | - |
172 | | - # Publish the application using the core-tools tooling. |
173 | | - # |
174 | | - # The image's Python version need not match the app runtime: with |
175 | | - # '--build remote' the build runs on Azure (Oryx) at the target |
176 | | - # runtime, and this image only packages and uploads. 3.11 is the newest |
177 | | - # published core-tools image (no 3.12/3.13 exists), and it deploys |
178 | | - # 3.13 apps fine. |
179 | | - cmd = [ |
180 | | - "docker", |
181 | | - "run", |
182 | | - "--rm", |
183 | | - "-e", |
184 | | - "FUNC_ACCESS_TOKEN", |
185 | | - "-v", |
186 | | - f"{cwd}:/function_app", |
187 | | - "-w", |
188 | | - "/function_app", |
189 | | - "mcr.microsoft.com/azure-functions/python:4-python3.11-core-tools", |
190 | | - "bash", |
191 | | - "-c", |
192 | | - func_cmd, |
193 | | - ] |
194 | | - log.debug("Running %s", cmd) |
195 | | - subprocess.run(cmd, check=True, env={**os.environ, "FUNC_ACCESS_TOKEN": token}) |
| 186 | + """Deploy the function app via One Deploy with a bearer token.""" |
| 187 | + log.info("Deploying function app code to %s", self.name) |
| 188 | + token = self._access_token() |
| 189 | + |
| 190 | + data = self.output_path.read_bytes() |
| 191 | + # RemoteBuild=true runs the build on Azure (Oryx) at the app's own |
| 192 | + # runtime, so nothing local needs to match the target Python version. |
| 193 | + url = ( |
| 194 | + f"https://{self.name}.scm.azurewebsites.net/api/publish" |
| 195 | + "?type=zip&RemoteBuild=true" |
| 196 | + ) |
| 197 | + request = urllib.request.Request( # noqa: S310 |
| 198 | + url, |
| 199 | + data=data, |
| 200 | + method="POST", |
| 201 | + headers={ |
| 202 | + "Authorization": f"Bearer {token}", |
| 203 | + "Content-Type": "application/zip", |
| 204 | + }, |
| 205 | + ) |
| 206 | + with urllib.request.urlopen(request) as response: # noqa: S310 |
| 207 | + log.info("Deployment accepted (HTTP %s), awaiting build", response.status) |
| 208 | + |
| 209 | + self._wait_for_deployment(token) |
196 | 210 | log.info("Function app code published to %s", self.name) |
| 211 | + |
| 212 | + def _wait_for_deployment(self, token: str) -> None: |
| 213 | + """Poll the latest deployment until it succeeds, or raise on failure.""" |
| 214 | + url = f"https://{self.name}.scm.azurewebsites.net/api/deployments/latest" |
| 215 | + deadline = time.monotonic() + self._DEPLOY_TIMEOUT_S |
| 216 | + while time.monotonic() < deadline: |
| 217 | + request = urllib.request.Request( # noqa: S310 |
| 218 | + url, headers={"Authorization": f"Bearer {token}"} |
| 219 | + ) |
| 220 | + with urllib.request.urlopen(request) as response: # noqa: S310 |
| 221 | + info = json.loads(response.read()) |
| 222 | + |
| 223 | + status = info.get("status") |
| 224 | + log.info("Deployment status: %s (%s)", status, info.get("status_text", "")) |
| 225 | + if status == _DEPLOY_STATUS_SUCCESS: |
| 226 | + return |
| 227 | + if status == _DEPLOY_STATUS_FAILED: |
| 228 | + raise RuntimeError( |
| 229 | + f"Deployment of {self.name} failed: {info.get('status_text', '')}" |
| 230 | + ) |
| 231 | + time.sleep(self._DEPLOY_POLL_INTERVAL_S) |
| 232 | + |
| 233 | + raise TimeoutError( |
| 234 | + f"Deployment of {self.name} did not complete within " |
| 235 | + f"{self._DEPLOY_TIMEOUT_S}s" |
| 236 | + ) |
0 commit comments