|
| 1 | +import { existsSync, readFile, readFileSync } from 'node:fs'; |
| 2 | +import { join } from 'node:path'; |
| 3 | +import axios, { AxiosInstance, AxiosResponse } from 'axios'; |
| 4 | +import { GoogleAuth } from 'google-auth-library'; |
| 5 | +import { func, funcClass } from '#functionSchema/functionDecorators'; |
| 6 | + |
| 7 | +const AUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'; |
| 8 | + |
| 9 | +interface DagConfig { |
| 10 | + [key: string]: any; |
| 11 | +} |
| 12 | + |
| 13 | +interface DagRun { |
| 14 | + conf: any; |
| 15 | + dag_id: string; |
| 16 | + dag_run_id: string; |
| 17 | + data_interval_end: string; |
| 18 | + data_interval_start: string; |
| 19 | + end_date: string; |
| 20 | + execution_date: string; |
| 21 | + external_trigger: boolean; |
| 22 | + last_scheduling_decision: string; |
| 23 | + logical_date: string; |
| 24 | + note: string; |
| 25 | + run_type: string; |
| 26 | + start_date: string; |
| 27 | + state: string; |
| 28 | +} |
| 29 | + |
| 30 | +interface TaskInstance { |
| 31 | + dag_id: string; |
| 32 | + dag_run_id: string; |
| 33 | + duration: number; |
| 34 | + end_date: string; |
| 35 | + execution_date: string; |
| 36 | + executor: string; |
| 37 | + executor_config: string; |
| 38 | + hostname: string; |
| 39 | + map_index: number; |
| 40 | + max_tries: number; |
| 41 | + note: string; |
| 42 | + operator: string; |
| 43 | + pid: number; |
| 44 | + pool: string; |
| 45 | + pool_slots: number; |
| 46 | + priority_weight: number; |
| 47 | + queue: string; |
| 48 | + queued_when: string; |
| 49 | + rendered_fields: any; |
| 50 | + rendered_map_index: number; |
| 51 | + sla_miss: any | null; |
| 52 | + start_date: string; |
| 53 | + state: string; |
| 54 | + task_display_name: string; |
| 55 | + task_id: string; |
| 56 | + trigger: any | null; |
| 57 | + triggerer_job: any | null; |
| 58 | + try_number: number; |
| 59 | + unixname: string; |
| 60 | +} |
| 61 | + |
| 62 | +let airflowMapping: Record<string, string> | undefined; |
| 63 | + |
| 64 | +/** |
| 65 | + * Required the file airflow.json to be present in the root of the project. |
| 66 | + * The file should contain a JSON object with the following format: |
| 67 | + * { |
| 68 | + * "gcpProjectId": "https://airflow.example.com" |
| 69 | + * } |
| 70 | + */ |
| 71 | +@funcClass(__filename) |
| 72 | +export class ComposerAirflowClient { |
| 73 | + private auth: GoogleAuth; |
| 74 | + private httpClient: AxiosInstance; |
| 75 | + |
| 76 | + constructor() { |
| 77 | + // Initialize GoogleAuth client using Application Default Credentials (ADC) |
| 78 | + this.auth = new GoogleAuth({ scopes: [AUTH_SCOPE] }); |
| 79 | + this.httpClient = axios.create({ timeout: 90000 }); |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * Helper function to determine the Composer Airflow Web Server URL based on Google Cloud project ID. |
| 84 | + */ |
| 85 | + private getWebServerUrl(gcpProjectId: string): string { |
| 86 | + if (!airflowMapping) { |
| 87 | + const airflowFilePath = join(process.cwd(), 'airflow.json'); |
| 88 | + if (!existsSync(airflowFilePath)) throw new Error(`Airflow config file not found at: ${airflowFilePath}`); |
| 89 | + airflowMapping = JSON.parse(readFileSync(airflowFilePath).toString()); |
| 90 | + if (!airflowMapping) throw new Error('Invalid Airflow config'); |
| 91 | + } |
| 92 | + if (!airflowMapping[gcpProjectId]) { |
| 93 | + throw new Error(`No Airflow config found for project ID: ${gcpProjectId} Valid project IDs: ${Object.keys(airflowMapping).join(', ')}`); |
| 94 | + } |
| 95 | + return airflowMapping[gcpProjectId]; |
| 96 | + } |
| 97 | + |
| 98 | + /** |
| 99 | + * Fetches DAG runs for the given DAG ID and Google Cloud Project. |
| 100 | + * |
| 101 | + * @param gcpProjectId The Google Cloud Project ID where the Composer environment lives. |
| 102 | + * @param dagId The ID of the DAG to fetch runs for. |
| 103 | + * @param limit The maximum number of runs to fetch. (Defaults to 20) |
| 104 | + */ |
| 105 | + @func() |
| 106 | + public async fetchDagRuns(gcpProjectId: string, dagId: string, limit = 20): Promise<DagRun[]> { |
| 107 | + const airflowWebServerUrl = this.getWebServerUrl(gcpProjectId); |
| 108 | + const token = await this.getAuthToken(); |
| 109 | + |
| 110 | + const url = `${airflowWebServerUrl}/api/v1/dags/${dagId}/dagRuns?limit=${limit}`; |
| 111 | + const response = await this.makeRequest(url, 'GET', token); |
| 112 | + |
| 113 | + return response.data.dag_runs; |
| 114 | + } |
| 115 | + |
| 116 | + /** |
| 117 | + * Fetches all task instances for a specific DAG run. |
| 118 | + * @param gcpProjectId The Google Cloud Project ID. |
| 119 | + * @param dagId The ID of the DAG. |
| 120 | + * @param dagRunId The ID of the specific DAG run. |
| 121 | + * @returns A promise that resolves to an array of task instance objects. |
| 122 | + */ |
| 123 | + @func() |
| 124 | + public async fetchTaskInstances(gcpProjectId: string, dagId: string, dagRunId: string): Promise<TaskInstance[]> { |
| 125 | + const airflowWebServerUrl = this.getWebServerUrl(gcpProjectId); |
| 126 | + const token = await this.getAuthToken(); |
| 127 | + |
| 128 | + const url = `${airflowWebServerUrl}/api/v1/dags/${dagId}/dagRuns/${dagRunId}/taskInstances`; |
| 129 | + const response = await this.makeRequest(url, 'GET', token); |
| 130 | + |
| 131 | + return response.data.task_instances; |
| 132 | + } |
| 133 | + |
| 134 | + /** |
| 135 | + * Fetches the raw log for a specific task attempt. |
| 136 | + * @param gcpProjectId The Google Cloud Project ID. |
| 137 | + * @param dagId The ID of the DAG. |
| 138 | + * @param dagRunId The ID of the DAG run. |
| 139 | + * @param taskId The ID of the task. |
| 140 | + * @param tryNumber The attempt number of the task. |
| 141 | + * @returns A promise that resolves to the raw log content as a string. |
| 142 | + */ |
| 143 | + @func() |
| 144 | + public async fetchTaskLog(gcpProjectId: string, dagId: string, dagRunId: string, taskId: string, tryNumber: number): Promise<string> { |
| 145 | + const airflowWebServerUrl = this.getWebServerUrl(gcpProjectId); |
| 146 | + const token = await this.getAuthToken(); |
| 147 | + |
| 148 | + const url = `${airflowWebServerUrl}/api/v1/dags/${dagId}/dagRuns/${dagRunId}/taskInstances/${taskId}/logs/${tryNumber}`; |
| 149 | + const response = await this.makeRequest(url, 'GET', token); |
| 150 | + |
| 151 | + return response.data; |
| 152 | + } |
| 153 | + |
| 154 | + /** |
| 155 | + * Fetches detailed metadata for a specific DAG. |
| 156 | + * @param gcpProjectId The Google Cloud Project ID. |
| 157 | + * @param dagId The ID of the DAG. |
| 158 | + * @returns A promise that resolves to the DAG detail object. |
| 159 | + */ |
| 160 | + @func() |
| 161 | + public async fetchDagDetails(gcpProjectId: string, dagId: string): Promise<any> { |
| 162 | + const airflowWebServerUrl = this.getWebServerUrl(gcpProjectId); |
| 163 | + const token = await this.getAuthToken(); |
| 164 | + const url = `${airflowWebServerUrl}/api/v1/dags/${dagId}`; |
| 165 | + const response = await this.makeRequest(url, 'GET', token); |
| 166 | + return response.data; |
| 167 | + } |
| 168 | + |
| 169 | + /** |
| 170 | + * Fetches the current Airflow configuration (airflow.cfg). |
| 171 | + * @param gcpProjectId The Google Cloud Project ID. |
| 172 | + * @returns A promise that resolves to the Airflow configuration object. |
| 173 | + */ |
| 174 | + @func() |
| 175 | + public async fetchAirflowConfig(gcpProjectId: string): Promise<any> { |
| 176 | + const airflowWebServerUrl = this.getWebServerUrl(gcpProjectId); |
| 177 | + const token = await this.getAuthToken(); |
| 178 | + |
| 179 | + const url = `${airflowWebServerUrl}/api/v1/config`; |
| 180 | + const response = await this.makeRequest(url, 'GET', token); |
| 181 | + |
| 182 | + return response.data; |
| 183 | + } |
| 184 | + |
| 185 | + /** |
| 186 | + * Fetches a short-lived access token needed for authorization. |
| 187 | + * This method supports the manual token handling approach seen in fetchDagRuns. |
| 188 | + * @returns The access token string. |
| 189 | + */ |
| 190 | + private async getAuthToken(): Promise<string> { |
| 191 | + const token = await this.auth.getAccessToken(); |
| 192 | + if (!token || typeof token !== 'string' || token.length === 0) throw new Error('Failed to retrieve access token.'); |
| 193 | + return token; |
| 194 | + } |
| 195 | + |
| 196 | + /** |
| 197 | + * Generic request handler that uses the retrieved token for authorization. |
| 198 | + * @param url The full URL to fetch. |
| 199 | + * @param method The HTTP method ('GET', 'POST', etc.). |
| 200 | + * @param token The Bearer token for Authorization. |
| 201 | + * @param data Optional payload data for POST/PUT requests. |
| 202 | + * @returns The Axios response object. |
| 203 | + */ |
| 204 | + private async makeRequest(url: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', token: string, data?: object): Promise<AxiosResponse> { |
| 205 | + try { |
| 206 | + console.debug(`Making ${method} request to: ${url}`); |
| 207 | + const response = await this.httpClient({ |
| 208 | + method, |
| 209 | + url, |
| 210 | + data: data, |
| 211 | + headers: { |
| 212 | + Authorization: `Bearer ${token}`, |
| 213 | + 'Content-Type': 'application/json', |
| 214 | + }, |
| 215 | + }); |
| 216 | + return response; |
| 217 | + } catch (error) { |
| 218 | + if (axios.isAxiosError(error) && error.response) { |
| 219 | + const status = error.response.status; |
| 220 | + if (status === 403) throw new Error(`403 Forbidden: Check Airflow RBAC roles for your account. Details: ${JSON.stringify(error.response.data)}`); |
| 221 | + throw new Error(`Request failed with status ${status}: ${error.response.statusText}. ` + `Response data: ${JSON.stringify(error.response.data)}`); |
| 222 | + } |
| 223 | + throw error; |
| 224 | + } |
| 225 | + } |
| 226 | +} |
0 commit comments