|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Upload to Azure Blob Storage.""" |
| 16 | + |
| 17 | +import io |
| 18 | +import urllib.parse |
| 19 | +from typing import Optional |
| 20 | + |
| 21 | +from azure.storage.blob import BlobServiceClient, BlobClient # type: ignore |
| 22 | +from azure.core.exceptions import ResourceNotFoundError # type: ignore |
| 23 | +from azure.identity import DefaultAzureCredential # type: ignore |
| 24 | + |
| 25 | +from streamer.cloud.base import CloudUploaderBase |
| 26 | + |
| 27 | + |
| 28 | +# Azure Append Blobs can accept chunks of any size, but we'll use a reasonable buffer size. |
| 29 | +APPEND_BLOB_BUFFER_SIZE = (4 << 20) # 4MB |
| 30 | + |
| 31 | + |
| 32 | +class AzureStorageUploader(CloudUploaderBase): |
| 33 | + """See base class for interface docs.""" |
| 34 | + |
| 35 | + def __init__(self, upload_location: str) -> None: |
| 36 | + # Parse the upload location (URL). |
| 37 | + # Expected format: azure://storageaccount.blob.core.windows.net/container/path |
| 38 | + url = urllib.parse.urlparse(upload_location) |
| 39 | + if not url.netloc: |
| 40 | + raise ValueError(f"Invalid Azure storage URL format: {upload_location}") |
| 41 | + |
| 42 | + # Extract storage account from the netloc |
| 43 | + # netloc format: storageaccount.blob.core.windows.net |
| 44 | + account_url = f"https://{url.netloc}" |
| 45 | + |
| 46 | + # Initialize the BlobServiceClient with DefaultAzureCredential |
| 47 | + try: |
| 48 | + credential = DefaultAzureCredential() |
| 49 | + self._blob_service_client = BlobServiceClient(account_url=account_url, credential=credential) |
| 50 | + except Exception as e: |
| 51 | + raise RuntimeError(f"Failed to initialize Azure credentials for {account_url}: {e}") |
| 52 | + |
| 53 | + # Extract container name and base path from the URL path |
| 54 | + # First part of path is container, everything after is base path |
| 55 | + path_parts = url.path.strip('/').split('/', 1) |
| 56 | + if not path_parts or not path_parts[0]: |
| 57 | + raise ValueError(f"Container name not found in URL: {upload_location}") |
| 58 | + |
| 59 | + self._container_name = path_parts[0] |
| 60 | + # Base path within the container (everything after container name) |
| 61 | + self._base_path = path_parts[1] if len(path_parts) > 1 else '' |
| 62 | + |
| 63 | + # State for chunked uploads: |
| 64 | + self._blob_client: Optional[BlobClient] = None |
| 65 | + self._data_buffer: bytes = b'' |
| 66 | + |
| 67 | + def write_non_chunked(self, path: str, data: bytes) -> None: |
| 68 | + """Write the non-chunked data to the destination.""" |
| 69 | + full_path = self._get_full_path(path) |
| 70 | + |
| 71 | + blob_client = self._blob_service_client.get_blob_client( |
| 72 | + container=self._container_name, |
| 73 | + blob=full_path |
| 74 | + ) |
| 75 | + |
| 76 | + # Upload the blob with cache control headers |
| 77 | + blob_client.upload_blob( |
| 78 | + data=data, |
| 79 | + overwrite=True |
| 80 | + ) |
| 81 | + |
| 82 | + def start_chunked(self, path: str) -> None: |
| 83 | + """Set up for a chunked transfer to the destination.""" |
| 84 | + full_path = self._get_full_path(path) |
| 85 | + |
| 86 | + self._blob_client = self._blob_service_client.get_blob_client( |
| 87 | + container=self._container_name, |
| 88 | + blob=full_path |
| 89 | + ) |
| 90 | + |
| 91 | + self._blob_client.create_append_blob() |
| 92 | + |
| 93 | + # Reset state for new chunked upload |
| 94 | + self._data_buffer = b'' |
| 95 | + |
| 96 | + def write_chunk(self, data: bytes, force: bool = False) -> None: |
| 97 | + """Handle a single chunk of data.""" |
| 98 | + if not self._blob_client: |
| 99 | + raise RuntimeError("start_chunked() must be called before write_chunk()") |
| 100 | + |
| 101 | + # Accumulate data in buffer |
| 102 | + self._data_buffer += data |
| 103 | + |
| 104 | + # Append data when we have enough data or when forced |
| 105 | + buffer_size = len(self._data_buffer) |
| 106 | + if buffer_size >= APPEND_BLOB_BUFFER_SIZE or (buffer_size > 0 and force): |
| 107 | + # Append the data to the blob |
| 108 | + self._blob_client.append_block( |
| 109 | + data=self._data_buffer |
| 110 | + ) |
| 111 | + |
| 112 | + # Clear the buffer |
| 113 | + self._data_buffer = b'' |
| 114 | + |
| 115 | + def end_chunked(self) -> None: |
| 116 | + """End the chunked transfer.""" |
| 117 | + if not self._blob_client: |
| 118 | + raise RuntimeError("start_chunked() must be called before end_chunked()") |
| 119 | + |
| 120 | + # Upload any remaining data in the buffer |
| 121 | + self.write_chunk(b'', force=True) |
| 122 | + |
| 123 | + # For append blobs, no additional commit operation is needed |
| 124 | + # The data is already committed with each append_block call |
| 125 | + # Reset state |
| 126 | + self.reset() |
| 127 | + |
| 128 | + def delete(self, path: str) -> None: |
| 129 | + """Delete the file from cloud storage.""" |
| 130 | + full_path = self._get_full_path(path) |
| 131 | + |
| 132 | + blob_client = self._blob_service_client.get_blob_client( |
| 133 | + container=self._container_name, |
| 134 | + blob=full_path |
| 135 | + ) |
| 136 | + |
| 137 | + try: |
| 138 | + blob_client.delete_blob() |
| 139 | + except ResourceNotFoundError: |
| 140 | + # Blob doesn't exist, which is fine for delete operation |
| 141 | + pass |
| 142 | + |
| 143 | + def reset(self) -> None: |
| 144 | + """Reset any chunked output state.""" |
| 145 | + self._blob_client = None |
| 146 | + self._data_buffer = b'' |
| 147 | + |
| 148 | + def _get_full_path(self, path: str) -> str: |
| 149 | + """Construct the full blob path by combining base path and relative path.""" |
| 150 | + # Remove leading slashes to avoid empty path segments |
| 151 | + clean_path = path.lstrip('/') |
| 152 | + |
| 153 | + if self._base_path: |
| 154 | + # Ensure proper path separation |
| 155 | + base = self._base_path.rstrip('/') |
| 156 | + return f"{base}/{clean_path}" if clean_path else base |
| 157 | + else: |
| 158 | + return clean_path |
0 commit comments