Files
doczyai-pipelines/archive/airflow/dags/client_name_dag.py
T

140 lines
4.2 KiB
Python
Raw Normal View History

2024-03-28 12:15:15 -05:00
import re
import pandas as pd
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from datetime import datetime, timedelta
2024-03-28 13:48:46 -05:00
from airflow.providers.snowflake.hooks.snowflake import SnowflakeHook
from airflow.operators.empty import EmptyOperator
import logging
from airflow.exceptions import AirflowFailException
2024-03-28 12:15:15 -05:00
2024-03-28 13:15:58 -05:00
2024-03-28 13:48:46 -05:00
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
2024-03-28 13:15:58 -05:00
SNOWFLAKE_CONN_ID = "doczy_dev_snowflake"
DAG_ID = "load_client_config"
2024-09-30 12:21:29 +01:00
DATABASE = "DOCZY_DEV"
2024-03-28 13:15:58 -05:00
# bucket = "airflow-data-ingestion"
2024-09-30 12:21:29 +01:00
TAGS = ["dev", "config_interface", "dataload"]
2024-03-28 13:15:58 -05:00
2024-03-28 13:48:46 -05:00
def process_csv_in_s3(**kwargs):
2024-03-28 12:15:15 -05:00
s3_hook = S3Hook(aws_conn_id="aws_default")
2024-03-28 13:15:58 -05:00
bucket_name = "doczy-dev-infra-raw-data-ingestion"
2024-09-30 12:21:29 +01:00
key_prefix = "client_names_openair/"
2024-03-28 13:48:46 -05:00
# List objects within the specified bucket and key prefix
objects = s3_hook.list_keys(bucket_name=bucket_name, prefix=key_prefix)
2024-09-30 12:21:29 +01:00
2024-03-28 13:48:46 -05:00
# Sort the objects by their last modified date and select the latest
if objects:
2024-09-30 12:21:29 +01:00
latest_file_key = sorted(objects)[
-1
] # Assuming file names include a timestamp or incrementing number
2024-03-28 13:48:46 -05:00
# Get the latest file from S3
file_content = s3_hook.read_key(latest_file_key, bucket_name)
2024-09-30 12:21:29 +01:00
2024-03-28 13:48:46 -05:00
# Convert string to DataFrame
from io import StringIO
2024-09-30 12:21:29 +01:00
2024-03-28 13:48:46 -05:00
df = pd.read_csv(StringIO(file_content))
# Apply the generate_s3_path function
2024-09-30 12:21:29 +01:00
df["s3_path"] = df["customer_name"].apply(generate_s3_path)
2024-03-28 13:48:46 -05:00
# Convert DataFrame to CSV string
csv_buffer = StringIO()
df.to_csv(csv_buffer, index=False)
csv_content = csv_buffer.getvalue()
# Replace the file in S3 with the processed content
s3_hook.load_string(
string_data=csv_content,
key=latest_file_key,
bucket_name=bucket_name,
2024-09-30 12:21:29 +01:00
replace=True,
2024-03-28 13:48:46 -05:00
)
# Push the latest file name to XCom
2024-09-30 12:21:29 +01:00
if "latest_file_key" in locals():
kwargs["ti"].xcom_push(key="file_name", value=latest_file_key.split("/")[-1])
2024-03-28 13:48:46 -05:00
else:
print("No files found in the specified path.")
2024-03-28 12:15:15 -05:00
2024-09-30 12:21:29 +01:00
2024-03-28 12:15:15 -05:00
def generate_s3_path(client_name):
# Your function as provided
2024-09-30 12:21:29 +01:00
client_name = client_name.rstrip(".")
pattern = r"[^0-9a-zA-Z!_.()*\'-]"
multi_underscore_pattern = r"_{2,}"
intermediate_name = re.sub(pattern, "_", client_name)
final_name = re.sub(multi_underscore_pattern, "_", intermediate_name)
2024-03-28 12:15:15 -05:00
final_name = final_name.lower()
2024-09-30 12:21:29 +01:00
base_s3_path = "s3://"
2024-03-28 12:15:15 -05:00
return base_s3_path + final_name + "/"
2024-09-30 12:21:29 +01:00
2024-03-28 13:48:46 -05:00
def call_stored_proc(proc_name, **kwargs):
2024-09-30 12:21:29 +01:00
# Pull the file name from XCom
file_name = kwargs["ti"].xcom_pull(task_ids="process_csv", key="file_name")
2024-03-28 13:48:46 -05:00
logger.info(f"File name: {file_name}")
2024-09-30 12:21:29 +01:00
dwh_hook = SnowflakeHook(snowflake_conn_id=SNOWFLAKE_CONN_ID)
2024-03-28 13:48:46 -05:00
with dwh_hook.get_conn() as conn:
# dwh_hook.set_autocommit(conn,autocommit=False)
cur = conn.cursor()
cur.execute(f"CALL {DATABASE}.STG.{proc_name}('{file_name}');")
result = cur.fetchone()
2024-09-30 12:21:29 +01:00
if result[0] == "Setup, Load, and Audit Complete":
logger.info("PROCEDURE EXECUTED SUCCESSFULLY")
2024-03-28 13:48:46 -05:00
else:
2024-09-30 12:21:29 +01:00
raise AirflowFailException(
"Check the DAG logs for more information. ERROR FROM SNOWFLAKE: ",
result,
)
2024-03-28 13:48:46 -05:00
logger.info(f"QUERY EXECUTION RESULT: {str(result)}")
2024-09-30 12:21:29 +01:00
2024-03-28 12:15:15 -05:00
default_args = {
2024-09-30 12:21:29 +01:00
"owner": "airflow",
"depends_on_past": False,
"start_date": datetime(2024, 3, 28),
"retries": 1,
"retry_delay": timedelta(minutes=5),
2024-03-28 12:15:15 -05:00
}
dag = DAG(
2024-03-28 13:31:25 -05:00
DAG_ID,
2024-03-28 12:15:15 -05:00
default_args=default_args,
2024-03-28 13:55:11 -05:00
start_date=datetime(2024, 3, 28),
catchup=False,
2024-09-30 12:21:29 +01:00
description="Process a CSV in S3 and replace it",
schedule_interval="@daily",
2024-03-28 12:15:15 -05:00
)
2024-09-30 12:21:29 +01:00
begin_job = EmptyOperator(task_id="Begin")
2024-03-28 13:48:46 -05:00
2024-03-28 12:15:15 -05:00
process_csv_task = PythonOperator(
2024-09-30 12:21:29 +01:00
task_id="process_csv",
2024-03-28 12:15:15 -05:00
python_callable=process_csv_in_s3,
2024-03-28 13:48:46 -05:00
provide_context=True,
2024-09-30 12:21:29 +01:00
dag=dag,
2024-03-28 12:15:15 -05:00
)
2024-03-28 13:48:46 -05:00
load_client_config = PythonOperator(
2024-03-28 14:08:33 -05:00
task_id="load_client_config",
2024-03-28 13:48:46 -05:00
python_callable=call_stored_proc,
dag=dag,
provide_context=True,
2024-09-30 12:21:29 +01:00
op_kwargs={"proc_name": "LOAD_CLIENT_CONFIG"},
2024-03-28 13:48:46 -05:00
)
2024-09-30 12:21:29 +01:00
end_job = EmptyOperator(task_id="End")
2024-03-28 13:48:46 -05:00
2024-09-30 12:21:29 +01:00
begin_job >> process_csv_task >> load_client_config >> end_job