|
| 1 | +import os |
| 2 | +import time |
| 3 | +import uuid |
| 4 | +import zipfile |
| 5 | + |
| 6 | +import requests |
| 7 | +from pydantic import BaseSettings |
| 8 | + |
| 9 | +import dbt.tracking |
| 10 | +from dbt.config.runtime import UnsetProfile, load_project |
| 11 | +from dbt.constants import ( |
| 12 | + CATALOG_FILENAME, |
| 13 | + MANIFEST_FILE_NAME, |
| 14 | + RUN_RESULTS_FILE_NAME, |
| 15 | + SOURCE_RESULT_FILE_NAME, |
| 16 | +) |
| 17 | +from dbt.events.types import ArtifactUploadSkipped, ArtifactUploadSuccess |
| 18 | +from dbt.exceptions import DbtProjectError |
| 19 | +from dbt_common.events.functions import fire_event |
| 20 | +from dbt_common.exceptions import DbtBaseException as DbtException |
| 21 | + |
| 22 | +MAX_RETRIES = 3 |
| 23 | + |
| 24 | +EXECUTION_ARTIFACTS = [MANIFEST_FILE_NAME, RUN_RESULTS_FILE_NAME] |
| 25 | + |
| 26 | +ARTIFACTS_TO_UPLOAD = { |
| 27 | + "retry": EXECUTION_ARTIFACTS, |
| 28 | + "clone": EXECUTION_ARTIFACTS, |
| 29 | + "build": EXECUTION_ARTIFACTS, |
| 30 | + "run": EXECUTION_ARTIFACTS, |
| 31 | + "run-operation": EXECUTION_ARTIFACTS, |
| 32 | + "seed": EXECUTION_ARTIFACTS, |
| 33 | + "snapshot": EXECUTION_ARTIFACTS, |
| 34 | + "test": EXECUTION_ARTIFACTS, |
| 35 | + "freshness": [MANIFEST_FILE_NAME, SOURCE_RESULT_FILE_NAME], |
| 36 | + "generate": [MANIFEST_FILE_NAME, CATALOG_FILENAME], |
| 37 | +} |
| 38 | + |
| 39 | + |
| 40 | +class ArtifactUploadConfig(BaseSettings): |
| 41 | + tenant_hostname: str |
| 42 | + DBT_CLOUD_TOKEN: str |
| 43 | + DBT_CLOUD_ACCOUNT_ID: str |
| 44 | + DBT_CLOUD_ENVIRONMENT_ID: str |
| 45 | + |
| 46 | + def get_ingest_url(self): |
| 47 | + return f"https://{self.tenant_hostname}/api/private/accounts/{self.DBT_CLOUD_ACCOUNT_ID}/environments/{self.DBT_CLOUD_ENVIRONMENT_ID}/ingests/" |
| 48 | + |
| 49 | + def get_complete_url(self, ingest_id): |
| 50 | + return f"{self.get_ingest_url()}{ingest_id}/" |
| 51 | + |
| 52 | + def get_headers(self, invocation_id=None): |
| 53 | + if invocation_id is None: |
| 54 | + invocation_id = str(uuid.uuid4()) |
| 55 | + return { |
| 56 | + "Accept": "application/json", |
| 57 | + "X-Invocation-Id": invocation_id, |
| 58 | + "Authorization": f"Token {self.DBT_CLOUD_TOKEN}", |
| 59 | + } |
| 60 | + |
| 61 | + |
| 62 | +def _retry_with_backoff(operation_name, func, max_retries=MAX_RETRIES, retry_codes=None): |
| 63 | + """Execute a function with exponential backoff retry logic. |
| 64 | +
|
| 65 | + Args: |
| 66 | + operation_name: Name of the operation for error messages |
| 67 | + func: Function to execute that returns (success, result) |
| 68 | + max_retries: Maximum number of retry attempts |
| 69 | +
|
| 70 | + Returns: |
| 71 | + The result from the function if successful |
| 72 | +
|
| 73 | + Raises: |
| 74 | + DbtException: If all retry attempts fail |
| 75 | + """ |
| 76 | + if retry_codes is None: |
| 77 | + retry_codes = [500, 502, 503, 504] |
| 78 | + retry_delay = 1 |
| 79 | + for attempt in range(max_retries): |
| 80 | + try: |
| 81 | + success, result = func() |
| 82 | + if success: |
| 83 | + return result |
| 84 | + |
| 85 | + if result.status_code not in retry_codes: |
| 86 | + raise DbtException(f"Error {operation_name}: {result}") |
| 87 | + if attempt == max_retries - 1: # Last attempt |
| 88 | + raise DbtException(f"Error {operation_name}: {result}") |
| 89 | + except requests.RequestException as e: |
| 90 | + if attempt == max_retries - 1: # Last attempt |
| 91 | + raise DbtException(f"Error {operation_name}: {str(e)}") |
| 92 | + |
| 93 | + time.sleep(retry_delay) |
| 94 | + retry_delay *= 2 # exponential backoff |
| 95 | + |
| 96 | + |
| 97 | +def upload_artifacts(project_dir, target_path, command): |
| 98 | + # Check if there are artifacts to upload for this command |
| 99 | + if command not in ARTIFACTS_TO_UPLOAD: |
| 100 | + fire_event(ArtifactUploadSkipped(msg=f"No artifacts to upload for command {command}")) |
| 101 | + return |
| 102 | + |
| 103 | + # read configurations |
| 104 | + try: |
| 105 | + project = load_project( |
| 106 | + project_dir, version_check=False, profile=UnsetProfile(), cli_vars=None |
| 107 | + ) |
| 108 | + if not project.dbt_cloud or "tenant_hostname" not in project.dbt_cloud: |
| 109 | + raise DbtProjectError("dbt_cloud.tenant_hostname not found in dbt_project.yml") |
| 110 | + tenant_hostname = project.dbt_cloud["tenant_hostname"] |
| 111 | + if not tenant_hostname: |
| 112 | + raise DbtProjectError("dbt_cloud.tenant_hostname is empty in dbt_project.yml") |
| 113 | + except Exception as e: |
| 114 | + raise DbtProjectError( |
| 115 | + f"Error reading dbt_cloud.tenant_hostname from dbt_project.yml: {str(e)}" |
| 116 | + ) |
| 117 | + |
| 118 | + config = ArtifactUploadConfig(tenant_hostname=tenant_hostname) |
| 119 | + |
| 120 | + if not target_path: |
| 121 | + target_path = "target" |
| 122 | + |
| 123 | + # Create zip file with artifacts |
| 124 | + zip_file_name = "target.zip" |
| 125 | + with zipfile.ZipFile(zip_file_name, "w") as z: |
| 126 | + for artifact in ARTIFACTS_TO_UPLOAD[command]: |
| 127 | + z.write(os.path.join(target_path, artifact), artifact) |
| 128 | + |
| 129 | + # Step 1: Create ingest request with retry |
| 130 | + def create_ingest(): |
| 131 | + response = requests.post(url=config.get_ingest_url(), headers=config.get_headers()) |
| 132 | + return response.status_code == 200, response |
| 133 | + |
| 134 | + response = _retry_with_backoff("creating ingest request", create_ingest) |
| 135 | + response_data = response.json() |
| 136 | + ingest_id = response_data["data"]["id"] |
| 137 | + upload_url = response_data["data"]["upload_url"] |
| 138 | + |
| 139 | + # Step 2: Upload the zip file to the provided URL with retry |
| 140 | + with open(zip_file_name, "rb") as f: |
| 141 | + file_data = f.read() |
| 142 | + |
| 143 | + def upload_file(): |
| 144 | + upload_response = requests.put(url=upload_url, data=file_data) |
| 145 | + return upload_response.status_code in (200, 204), upload_response |
| 146 | + |
| 147 | + _retry_with_backoff("uploading artifacts", upload_file) |
| 148 | + |
| 149 | + # Step 3: Mark the ingest as successful with retry |
| 150 | + def complete_ingest(): |
| 151 | + complete_response = requests.patch( |
| 152 | + url=config.get_complete_url(ingest_id), |
| 153 | + headers=config.get_headers(), |
| 154 | + json={"upload_status": "SUCCESS"}, |
| 155 | + ) |
| 156 | + return complete_response.status_code == 204, complete_response |
| 157 | + |
| 158 | + _retry_with_backoff("completing ingest", complete_ingest) |
| 159 | + |
| 160 | + fire_event(ArtifactUploadSuccess(msg=f"command {command} completed successfully")) |
| 161 | + if dbt.tracking.active_user is not None: |
| 162 | + dbt.tracking.track_artifact_upload({"command": command}) |
0 commit comments