-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathingestion.py
More file actions
321 lines (265 loc) · 13.3 KB
/
Copy pathingestion.py
File metadata and controls
321 lines (265 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
"""Ingestion task group."""
import logging
from typing import Any, Literal
from airflow.exceptions import AirflowException
from airflow.sdk import Variable, task, task_group
from data_manipulation.constants import DB_URI_PREFIX
from data_manipulation.encryption import decrypt_credentials
from data_manipulation.ingestion import (
ingest_data_from_database_into_postgis,
ingest_data_from_file_into_postgis,
ingest_data_from_ftp_into_postgis,
ingest_data_from_ogc_service_into_postgis,
ingest_data_from_url_into_postgis,
)
from utils import (
get_data_sql_engine,
get_datafeeder_sql_engine,
get_source_sql_engine,
get_staging_schema,
)
logger = logging.getLogger(__name__)
def ingestion_group(group_id: Literal["initial_ingestion", "refresh_ingestion"]):
"""Factory function that creates an ingestion task group.
Args:
group_id: Identifier for the task group (initial_ingestion or refresh_ingestion)
Returns:
A task group for data ingestion
"""
@task_group(group_id=group_id) # type: ignore[misc]
def _ingestion_impl() -> None:
"""Task group for ingestion tasks.
Tasks can access runtime configuration via context.
"""
@task.branch(task_id="select_ingestion_mode") # type: ignore[misc]
def do_branching(**context: dict[str, Any]) -> str | bool:
params = context.get("params", {})
source_type = params.get("source_type")
logger.info(f"Ingestion source_type: {source_type}")
match source_type:
case "FILE":
return f"{group_id}.file_ingest_step"
case "URL":
return f"{group_id}.url_ingest_step"
case "FTP":
return f"{group_id}.ftp_ingest_step"
case "DATABASE":
return f"{group_id}.database_ingest_step"
case "API":
return f"{group_id}.api_ingest_step"
case _:
raise AirflowException(f"Unsupported source_type: {source_type}")
@task(task_id="file_ingest_step")
def file_ingest_step(**context: dict[str, Any]) -> None:
params = context.get("params", {})
ti = context.get("ti")
# Try to get staging_table_name from params first (staging_dag case)
target_table_name = params.get("staging_table_name")
# If not in params, try XCom from generate_staging_table_name (process_dag scheduled case)
if not target_table_name and ti:
target_table_name = ti.xcom_pull(task_ids="generate_staging_table_name")
logger.info(f"Using staging_table_name from XCom: {target_table_name}")
else:
logger.info(f"Using staging_table_name from params: {target_table_name}")
if not target_table_name:
raise AirflowException("staging_table_name is not provided")
engine = get_data_sql_engine()
try:
ingest_data_from_file_into_postgis(
params.get("source", ""),
target_table_name,
engine,
schema=get_staging_schema(),
)
except Exception as e:
raise AirflowException(f"Failed to ingest data from file: {e}")
@task(task_id="url_ingest_step")
def url_ingest_step(**context: dict[str, Any]) -> None:
params = context.get("params", {})
ti = context.get("ti")
# Try to get staging_table_name from params first (staging_dag case)
target_table_name = params.get("staging_table_name")
# If not in params, try XCom from generate_staging_table_name (process_dag scheduled case)
if not target_table_name and ti:
target_table_name = ti.xcom_pull(task_ids="generate_staging_table_name")
logger.info(f"Using staging_table_name from XCom: {target_table_name}")
else:
logger.info(f"Using staging_table_name from params: {target_table_name}")
if not target_table_name:
raise AirflowException("staging_table_name is not provided")
# Decrypt Basic Auth credentials if provided
auth = None
encrypted_credentials = params.get("encrypted_credentials")
if encrypted_credentials:
try:
encryption_key = Variable.get("datafeeder_encryption_key", default=None)
if not encryption_key:
raise AirflowException(
"Encryption key not found in Airflow Variables under 'datafeeder_encryption_key'"
)
engine = get_datafeeder_sql_engine()
with engine.connect() as conn:
username, password = decrypt_credentials(
conn, encrypted_credentials, encryption_key
)
auth = (username, password)
logger.info("Successfully decrypted Basic Auth credentials")
except Exception as e:
logger.error(f"Failed to decrypt Basic Auth credentials: {e}")
raise AirflowException(f"Failed to decrypt credentials: {e}")
engine = get_data_sql_engine()
try:
ingest_data_from_url_into_postgis(
params.get("source", ""),
target_table_name,
engine,
schema=get_staging_schema(),
auth=auth,
)
except Exception as e:
raise AirflowException(f"Failed to ingest data from URL: {e}")
@task(task_id="ftp_ingest_step")
def ftp_ingest_step(**context: dict[str, Any]) -> None:
params = context.get("params", {})
ti = context.get("ti")
# Try to get staging_table_name from params first (staging_dag case)
target_table_name = params.get("staging_table_name")
# If not in params, try XCom from generate_staging_table_name (process_dag scheduled case)
if not target_table_name and ti:
target_table_name = ti.xcom_pull(task_ids="generate_staging_table_name")
logger.info(f"Using staging_table_name from XCom: {target_table_name}")
else:
logger.info(f"Using staging_table_name from params: {target_table_name}")
if not target_table_name:
raise AirflowException("staging_table_name is not provided")
# Decrypt Ftp credentials if provided
auth = None
encrypted_credentials = params.get("encrypted_credentials")
if encrypted_credentials:
try:
encryption_key = Variable.get("datafeeder_encryption_key", default=None)
if not encryption_key:
raise AirflowException(
"Encryption key not found in Airflow Variables under 'datafeeder_encryption_key'"
)
engine = get_datafeeder_sql_engine()
with engine.connect() as conn:
username, password = decrypt_credentials(
conn, encrypted_credentials, encryption_key
)
auth = (username, password)
logger.info("Successfully decrypted Ftp credentials")
except Exception as e:
logger.error(f"Failed to decrypt Ftp credentials: {e}")
raise AirflowException(f"Failed to decrypt credentials: {e}")
try:
engine = get_data_sql_engine()
schema = get_staging_schema()
ingest_data_from_ftp_into_postgis(
params.get("source", ""), target_table_name, engine, schema, auth
)
except Exception as e:
raise AirflowException(f"Failed to ingest data from FTP: {e}")
@task(task_id="database_ingest_step")
def database_ingest_step(**context: dict[str, Any]) -> None:
params = context.get("params", {})
ti = context.get("ti")
target_table_name = params.get("staging_table_name")
if not target_table_name and ti:
target_table_name = ti.xcom_pull(task_ids="generate_staging_table_name")
logger.info(f"Using staging_table_name from XCom: {target_table_name}")
else:
logger.info(f"Using staging_table_name from params: {target_table_name}")
if not target_table_name:
raise AirflowException("staging_table_name is not provided")
source = params.get("source", "")
# Expected format: db://{db_key}/{schema}/{table}
if not source.startswith(DB_URI_PREFIX):
raise AirflowException(
f"Invalid database source URL format: '{source}'. Expected db://{{db_key}}/{{schema}}/{{table}}"
)
try:
db_key, source_schema, source_table = source.removeprefix(DB_URI_PREFIX).split(
"/", 2
)
except ValueError:
raise AirflowException(
f"Invalid database source URL format: '{source}'. Expected db://{{db_key}}/{{schema}}/{{table}}"
)
if not db_key or not source_schema or not source_table:
raise AirflowException(
f"Invalid database source URL: db_key, schema, and table must all be non-empty (got '{source}')"
)
try:
source_engine = get_source_sql_engine(db_key)
target_engine = get_data_sql_engine()
ingest_data_from_database_into_postgis(
source_schema=source_schema,
source_table=source_table,
source_engine=source_engine,
target_table=target_table_name,
target_engine=target_engine,
target_schema=get_staging_schema(),
)
except AirflowException:
raise
except Exception as e:
raise AirflowException(f"Failed to ingest data from database {source}: {e}")
@task(task_id="api_ingest_step")
def api_ingest_step(**context: dict[str, Any]) -> None:
params = context.get("params", {})
ti = context.get("ti")
target_table_name = params.get("staging_table_name")
if not target_table_name and ti:
target_table_name = ti.xcom_pull(task_ids="generate_staging_table_name")
logger.info(f"Using staging_table_name from XCom: {target_table_name}")
else:
logger.info(f"Using staging_table_name from params: {target_table_name}")
if not target_table_name:
raise AirflowException("staging_table_name is not provided")
source = params.get("source", "")
source_layer = params.get("source_layer", "")
source_protocol = params.get("source_protocol", "wfs") or "wfs"
if not source_layer:
raise AirflowException("source_layer is required for API import")
# Decrypt Basic Auth credentials if provided (e.g. protected WFS/OAPIF services)
auth = None
encrypted_credentials = params.get("encrypted_credentials")
if encrypted_credentials:
try:
encryption_key = Variable.get("datafeeder_encryption_key", default=None)
if not encryption_key:
raise AirflowException(
"Encryption key not found in Airflow Variables under 'datafeeder_encryption_key'"
)
datafeeder_engine = get_datafeeder_sql_engine()
with datafeeder_engine.connect() as conn:
username, password = decrypt_credentials(
conn, encrypted_credentials, encryption_key
)
auth = (username, password)
logger.info("Successfully decrypted Basic Auth credentials")
except Exception as e:
logger.error(f"Failed to decrypt Basic Auth credentials: {e}")
raise AirflowException(f"Failed to decrypt credentials: {e}")
engine = get_data_sql_engine()
try:
ingest_data_from_ogc_service_into_postgis(
source,
source_layer,
source_protocol,
target_table_name,
engine,
schema=get_staging_schema(),
auth=auth,
)
except Exception as e:
raise AirflowException(f"Failed to ingest data from OGC service: {e}")
do_branching() >> [
file_ingest_step(),
ftp_ingest_step(),
url_ingest_step(),
database_ingest_step(),
api_ingest_step(),
]
return _ingestion_impl