1_los.py 9.66 KB
Newer Older
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
import json, os
from datetime import date
import calendar

from airflow import DAG
from airflow.operators.python import PythonOperator, BranchPythonOperator, ShortCircuitOperator
from airflow.operators.bash import BashOperator

from datetime import datetime, timedelta
from airflow.providers.sftp.operators.sftp import SFTPOperator
from airflow.models import Variable
from airflow.providers.postgres.operators.postgres import PostgresOperator

from airflow.operators.trigger_dagrun import TriggerDagRunOperator
from airflow.utils.trigger_rule import TriggerRule

from airflow.models.xcom import XCom
from airflow.decorators import task
from airflow.hooks.postgres_hook import PostgresHook
from airflow import XComArg

yesterday_nodash = (datetime.now() - timedelta(1)).strftime('%Y%m%d') if Variable.get(
    "DATE_OF_DATA") == 'today' else Variable.get("DATE_OF_DATA")
yesterday_strip = datetime.strptime(yesterday_nodash, '%Y%m%d').strftime('%Y-%m-%d')
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
25
yesterday_lusa = (datetime.strptime(yesterday_nodash, '%Y%m%d') - timedelta(1)).strftime('%Y%m%d')
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
26
d = f"""{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"""
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
27 28
cron_tab = None if Variable.get("CRON_JOB") == 'manual' else Variable.get("CRON_JOB")

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
29 30 31
today = d[:]

POSTGRES_CONN_ID = Variable.get("DS_DB")
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
32 33 34 35
POSTGRES_SCHEMA = 'ds_los' + Variable.get("ENV_T24")
DS_CONN_ID = Variable.get("DS_LOS")
DS_FOLDER = 'los'
DS_DB = 'los'
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
36 37 38
DS_SCHEMA = 'public'
DS_CREATE_TABLE = ''

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
39 40

def create_ddl(schema, column):
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
41
    return f"""select string_agg(x,'') from (select
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
42
    'create table {POSTGRES_SCHEMA}."'||table_catalog||'_'||table_name|| '" ( ' || string_agg('"'||column_name||'"', ' text,' order by ordinal_position) || ' text'|| ' ); ' as x
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
43 44 45

from information_schema.columns where table_schema = '{schema}'
and table_name in ({column})
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
46 47
group by table_catalog, table_schema, table_name) as x ;"""

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
48 49 50 51

def _start():
    print("Start :: Extractor ")

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
52

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
53 54 55 56 57 58 59 60 61 62 63 64 65
def check_done_ext(**kwargs):
    from random import randint

    # number = randint(0, 10)

    if os.path.isfile(f'''{Variable.get("LOCAL_PATH")}{DS_FOLDER}/{yesterday_nodash}/done_ext.csv'''):
        print("A")
        return False
    else:
        print("B")
        # STOP DAG
        return True

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
66

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
67
def ds_list_extractor():
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
68
    sql_stmt = f"""select * from ds_conf.ds_extractor_list_extractor('los', '{yesterday_strip}');"""
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
69 70 71 72 73 74 75 76 77
    pg_hook = PostgresHook(
        postgres_conn_id=POSTGRES_CONN_ID,
    )
    pg_conn = pg_hook.get_conn()
    cursor = pg_conn.cursor()
    cursor.execute(sql_stmt)
    files = cursor.fetchall()
    return files

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
78

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
79 80 81 82 83
def ds_get_syntax(ti):
    iris = ti.xcom_pull(task_ids=['ds_list_extractor'])
    if not iris:
        raise Exception('No data.')
    return [{"op_kwargs": {
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
84 85 86 87
        "copy_sql": f"""COPY "{table['table_source']}".{table['file_id'].replace(".", "_")} to STDOUT delimiter '|' CSV header""",
        "file_id": f"""{table['table_source']}_{table['file_id']}""",
        "database": f"""{table['table_source']}"""}
        }
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
88 89 90
        for
        table in json.loads(iris[0][0][0])]

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
91 92 93 94 95 96 97

def ds_get_csv(ti, copy_sql, file_id, database):
    pg_hook = PostgresHook(
        postgres_conn_id=DS_CONN_ID,
        schema=database
    )
    print('INFO::',pg_hook)
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
98 99 100 101
    pg_hook.copy_expert(copy_sql, filename=f"""{Variable.get("LOCAL_PATH")}{DS_FOLDER}/""" + (
        f"""{yesterday_nodash}/{yesterday_nodash}.""" if Variable.get(
            "WITH_DATE") == 'Y' else '') + f"""{file_id}.csv""")

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
102

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
103 104 105 106 107 108
#
# def ds_drop_syntax(ti):
#     iris = ti.xcom_pull(task_ids=['ds_list_extractor'])
#     if not iris:
#         raise Exception('No data.')
#     return [{
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
109
#         "sql": f"""drop table ds_los.{table['file_id'].replace(".", "_")} CASCADE;"""}
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
110 111 112 113 114 115 116
#         for
#         table in json.loads(iris[0][0][0])]


def ds_get_ddl(ti):
    global DS_CREATE_TABLE
    iris = ti.xcom_pull(task_ids=['ds_list_extractor'])
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
117
    sql_table = []
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
118
    for table in json.loads(iris[0][0][0]):
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
119 120 121 122 123 124 125 126 127 128 129 130
        print(create_ddl(table['table_source'], f"""'{table['file_id']}'"""))
        sql_stmt = create_ddl(table['table_source'], f"""'{table['file_id']}'""")
        pg_hook = PostgresHook(
            postgres_conn_id=DS_CONN_ID,
            schema=table['table_source']
        )
        pg_conn = pg_hook.get_conn()
        cursor = pg_conn.cursor()
        cursor.execute(sql_stmt)
        sql_table.append(cursor.fetchall()[0][0])
    return sql_table

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
131 132 133 134 135 136 137 138 139 140 141

def pg_ddl_syntax(ti):
    print(ti.xcom_pull(task_ids=['ds_get_ddl'])[0])
    return [{"sql": ti.xcom_pull(task_ids=['ds_get_ddl'])[0]}]


def pg_push_syntax(ti):
    iris = ti.xcom_pull(task_ids=['ds_list_extractor'])
    if not iris:
        raise Exception('No data.')
    return [{"op_kwargs": {
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
142 143
        "copy_sql": f"""COPY {POSTGRES_SCHEMA}."{table['table_source']}_{table['file_id'].replace(".", "_")}" from STDOUT delimiter '|' CSV header""",
        "file_id": f"""{table['table_source']}_{table['file_id']}""",}}
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
144 145 146
        for
        table in json.loads(iris[0][0][0])]

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
147

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
148 149 150 151 152 153
def pg_push_csv(ti, copy_sql, file_id):
    pg_hook = PostgresHook.get_hook(POSTGRES_CONN_ID)
    pg_hook.copy_expert(copy_sql, filename=f"""{Variable.get("LOCAL_PATH")}{DS_FOLDER}/""" + (
        f"""{yesterday_nodash}/{yesterday_nodash}.""" if Variable.get(
            "WITH_DATE") == 'Y' else '') + f"""{file_id}.csv""")

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
154 155

with DAG("APJ_1_los",
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
156
         start_date=datetime(2021, 1, 1),
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
157
         schedule=cron_tab,
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
         catchup=False,
         concurrency=3) as dag:
    begin = PythonOperator(
        task_id=f"Begin",
        python_callable=_start,
        op_kwargs={

        }
    )

    history_start = PostgresOperator(
        sql=f"""INSERT INTO ds_conf."Datasource_history"
        (source, start_time, finish_time, status, env, date_of_data) VALUES
        ('{POSTGRES_SCHEMA}'::varchar(255), '{today}'::timestamp with time zone, '{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}'::timestamp with time zone, 'ONPROCESS'::varchar(100), '', '{yesterday_nodash}');""",
        task_id="history_start",
        postgres_conn_id=POSTGRES_CONN_ID,
    )

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
176 177 178 179 180 181 182
    check_done_ext = ShortCircuitOperator(
        task_id="check_done_ext",
        provide_context=True,
        python_callable=check_done_ext,
        op_kwargs={},
    )

Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
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
    create_folder = BashOperator(
        task_id='create_folder',
        bash_command=f"""mkdir -p {Variable.get("LOCAL_PATH")}{DS_FOLDER}/{yesterday_nodash}"""
    )

    ds_list_extractor = PythonOperator(
        task_id='ds_list_extractor',
        python_callable=ds_list_extractor,
        do_xcom_push=True
    )

    ds_get_syntax = PythonOperator(
        task_id='ds_syntax_get',
        python_callable=ds_get_syntax
    )

    ds_table_to_csv = PythonOperator.partial(
        task_id="ds_table_to_csv",
        python_callable=ds_get_csv,
        dag=dag
    ).expand_kwargs(
        XComArg(ds_get_syntax),
    )

    ds_get_ddl = PythonOperator(
        task_id='ds_get_ddl',
        python_callable=ds_get_ddl,
        do_xcom_push=True
    )

    # ds_drop_syntax = PythonOperator(
    #     task_id='ds_drop_syntax',
    #     python_callable=ds_drop_syntax
    # )

    pg_drop_schema = PostgresOperator(
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
219
        sql=f"""drop schema IF EXISTS {POSTGRES_SCHEMA} CASCADE;""",
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
220 221 222 223 224
        task_id="pg_drop_schema",
        postgres_conn_id=POSTGRES_CONN_ID,
    )

    pg_create_schema = PostgresOperator(
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
225
        sql=f"""create schema IF NOT EXISTS {POSTGRES_SCHEMA};""",
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
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
        task_id="pg_create_schema",
        postgres_conn_id=POSTGRES_CONN_ID,
    )

    pg_ddl_syntax = PythonOperator(
        task_id='pg_ddl_syntax',
        python_callable=pg_ddl_syntax
    )

    pg_create_table = PostgresOperator.partial(
        task_id="pg_create_table",
        postgres_conn_id=POSTGRES_CONN_ID,
    ).expand_kwargs(
        XComArg(pg_ddl_syntax),
    )

    pg_push_syntax = PythonOperator(
        task_id='pg_syntax_push',
        python_callable=pg_push_syntax
    )

    pg_csv_to_table = PythonOperator.partial(
        task_id="pg_csv_to_table",
        python_callable=pg_push_csv,
        dag=dag
    ).expand_kwargs(
        XComArg(pg_push_syntax),
    )

    set_access_schemma = PostgresOperator(
        sql=f"""GRANT USAGE ON SCHEMA {POSTGRES_SCHEMA} TO readaccess;""",
        task_id="set_access_schemma",
        postgres_conn_id=POSTGRES_CONN_ID,
    )

    set_access_all_table = PostgresOperator(
        sql=f"""GRANT SELECT ON ALL TABLES IN SCHEMA {POSTGRES_SCHEMA} TO readaccess;""",
        task_id="set_access_all_table",
        postgres_conn_id=POSTGRES_CONN_ID,
    )

    ds_ext_done = BashOperator(
        task_id="ds_ext_done",
        bash_command=f"""
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
         touch  /opt/airflow/dags/DFE/{DS_FOLDER}/{yesterday_nodash}/done_ext.csv;
         """,
    )

        
    ds_to_history = PostgresOperator(
        sql=f"""select ds_conf.ds_t24_create_table_history_surrounding('{yesterday_strip}', '{POSTGRES_SCHEMA}');""",
        task_id="ds_to_history",
        postgres_conn_id=POSTGRES_CONN_ID,
    )

    delete_before = BashOperator(
        task_id="delete_before",
        bash_command=f"""
         rm -r /opt/airflow/dags/DFE/{DS_FOLDER}/{yesterday_lusa};
         """,
Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
286 287 288 289 290 291 292 293 294 295 296 297 298
    )

    history_finish = PostgresOperator(
        sql=f"""
               UPDATE ds_conf."Datasource_history"
                   SET status = 'DONE', finish_time = '{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}'::timestamp with time zone
               WHERE source = '{POSTGRES_SCHEMA}' and status = 'ONPROCESS';
    """,
        task_id="history_finish",
        postgres_conn_id=POSTGRES_CONN_ID,
    )


Margrenzo Gunawan's avatar
Margrenzo Gunawan committed
299
    begin >> check_done_ext >> history_start >> create_folder >> ds_list_extractor >> ds_get_syntax >> ds_table_to_csv >> ds_get_ddl >> pg_drop_schema >> pg_create_schema >> pg_ddl_syntax >> pg_create_table >> pg_push_syntax >> pg_csv_to_table >> set_access_schemma >> set_access_all_table >> ds_ext_done  >> ds_to_history >> delete_before >> history_finish