#! /usr/bin/env python3 from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from contextlib import closing from sql import sql_queries import snowflake.connector import psycopg2 import smtplib import argparse import sys import json import datetime with open('config.json', 'r') as f: config = json.load(f) sf_user = config['snowflake']["user"] sf_password = config['snowflake']["password"] sf_account = config['snowflake']["account"] sf_warehouse = config['snowflake']['warehouse'] db_name_slz = config['postgres_slz']["database"] db_user_slz = config['postgres_slz']["user"] db_password_slz = config['postgres_slz']["password"] db_host_slz = config['postgres_slz']["host"] db_port_slz = config['postgres_slz']["port"] local_db_name = config['failure_counter']["database"] local_db_user = config['failure_counter']["user"] local_db_password = config['failure_counter']["password"] local_db_host = config['failure_counter']["host"] local_db_port = config['failure_counter']["port"] failure_count_increase = "UPDATE failed_count SET failed_count = failed_count + 1, last = 'FAILED', last_updated = NOW() WHERE count_id = 'smemaxea';" failure_count_to_zero = "UPDATE failed_count SET failed_count = 0, last = 'OK', last_updated = NOW() WHERE count_id = 'smemaxea';" def postgres_update_failure_count(sql_query): with closing(psycopg2.connect(database=local_db_name, user=local_db_user, password=local_db_password, host=local_db_host, port=local_db_port)) as connection: with connection.cursor() as cursor: cursor.execute(sql_query) connection.commit() def create_arg_parser(): parser = argparse.ArgumentParser() parser.add_argument('-m', '--mail', nargs='+', action='store', dest='recipients', type=str) parser.add_argument('-p', '--print', action="store_const", const=True) return parser def send_mail(recipients: str, message: str, status: str) -> None: # Create a multipart message msg = MIMEMultipart() body_part = MIMEText(message, 'plain') msg['Subject'] = f"[{status}][PROD] SME MAX (Exploration Area)" msg['From'] = "support.sme@dataart.com" msg['To'] = recipients # Add body to email msg.attach(body_part) # Create SMTP object server = smtplib.SMTP('relay1.dataart.com', 25) server.sendmail(msg['From'], msg['To'].split(','), msg.as_string()) server.quit() def snowflake_fetch_data(sql_query) -> dict: ctx = snowflake.connector.connect( user=sf_user, password=sf_password, account=sf_account, warehouse=sf_warehouse ) cs = ctx.cursor(snowflake.connector.DictCursor) try: cs.execute(sql_query) result_dict = cs.fetchall() finally: cs.close() ctx.close() return result_dict def postgres_fetch_data_slz(sql_query) -> list: result_list = [] with closing(psycopg2.connect(database=db_name_slz, user=db_user_slz, password=db_password_slz, host=db_host_slz, port=db_port_slz)) as connection: with connection.cursor() as cursor: cursor.execute(sql_query) columns = cursor.description rows = cursor.fetchall() for row in rows: tmp = {} for i in range(len(columns)): tmp[columns[i][0]] = row[i] result_list.append(tmp) return result_list def check_1_to_9() -> dict: result_dict = {} full_log = {} ### Check 1 SLZ status (expected result: 0 results) ################################################ tmp_pg_check_1 = postgres_fetch_data_slz(sql_queries.pg_check_1) print(f"SLZ_STATUS_CHECK_1: - {tmp_pg_check_1}") #Check if tmp_pg_check_1: full_log["SLZ_STATUS_CHECK_1"] = {} result_dict["SLZ_STATUS_CHECK_1"] = {} for item in tmp_pg_check_1: full_log["SLZ_STATUS_CHECK_1"].update({item['REPORT_DATE'].strftime("%Y-%m-%d"): item['MISSING_REPORTS'].lower()}) print(f"{item['REPORT_DATE']} - {item['MISSING_REPORTS']}") result_dict["SLZ_STATUS_CHECK_1"].update({item['REPORT_DATE'].strftime("%Y-%m-%d"): item['MISSING_REPORTS'].lower()}) else: full_log["SLZ_STATUS_CHECK_1"] = {'SLZ_STATUS_CHECK_1': 'OK: Query returned 0 results'} ### Check 2 Raw Data uploaded without errors (expected result: 0 results) ################################################ tmp_sf_check_2 = snowflake_fetch_data(sql_queries.sf_check_2) sf_check_2_count = int(tmp_sf_check_2[0]['count']) print(f"CHECK_2: - count:{sf_check_2_count}") full_log["CHECK_2"] = {} if sf_check_2_count > 0: result_dict["CHECK_2"] = {} result_dict["CHECK_2"] = {'CHECK_2': 'FAILED: Query returned more than 0'} full_log["CHECK_2"] = result_dict["CHECK_2"] else: full_log["CHECK_2"] = {'CHECK_2': 'OK: Query returned 0'} ### Check 3 RAW -> Report for previous day is uploaded to Snowflake - ALBUM_MAPPING (expected result: result == TRUE) ################################################ tmp_sf_check_3 = snowflake_fetch_data(sql_queries.sf_check_3) if tmp_sf_check_3: sf_check_3_result = tmp_sf_check_3[0]['result'] expected = True print(f"CHECK_3: - {sf_check_3_result}") full_log["CHECK_3"] = {'CHECK_3_RESULT': sf_check_3_result} if sf_check_3_result != expected: result_dict["CHECK_3"] = {'CHECK_3_RESULT': "Failed: Query returned sf_check_3_result"} else: result_dict["CHECK_3"] = {'CHECK_3_RESULT': "Failed: Query returned nothing"} full_log["CHECK_3"] = {'CHECK_3_RESULT': "Failed: Query returned nothing"} ### Check 4 RAW -> Report for previous day is uploaded to Snowflake - TRACK_MAPPING (expected result: result == TRUE) ################################################ tmp_sf_check_4 = snowflake_fetch_data(sql_queries.sf_check_4) if tmp_sf_check_4: sf_check_4_result = tmp_sf_check_4[0]['result'] expected = True print(f"CHECK_4: - {sf_check_4_result}") full_log["CHECK_4"] = {'CHECK_4_RESULT': sf_check_4_result} if sf_check_4_result != expected: result_dict["CHECK_4"] = {'CHECK_4_RESULT': "Failed: Query returned sf_check_4_result"} else: result_dict["CHECK_4"] = {'CHECK_4_RESULT': "Failed: Query returned nothing"} full_log["CHECK_4"] = {'CHECK_4_RESULT': "Failed: Query returned nothing"} ### Check 5 MAIN -> RAW → EXP - SME_MAX_ALBUM_MAPPING - Import status successful (expected result: Counts match inside every step) ################################################ tmp_sf_check_5 = snowflake_fetch_data(sql_queries.sf_check_5) print(f"CHECK_5: - {len(tmp_sf_check_5)} ROWS") full_log["CHECK_5"] = {'CHECK_5': f"Query returned {len(tmp_sf_check_5)} results"} if len(tmp_sf_check_5) > 0: result_dict["CHECK_5"] = full_log["CHECK_5"] ### Check 6 MAIN -> ETL DIM_TIKTOK_TOP_CHART (expected result: Counts match inside every step) ################################################ tmp_sf_check_6 = snowflake_fetch_data(sql_queries.sf_check_6) sf_check_6_dest = int(tmp_sf_check_6[0]['count']) sf_check_6_src = int(tmp_sf_check_6[1]['count']) print(f"SRC_CHECK_6: - {sf_check_6_src}") print(f"DEST_CHECK_6: - {sf_check_6_dest}") full_log["CHECK_6"] = {'SRC_CHECK_6': sf_check_6_src, 'DEST_CHECK_6': sf_check_6_dest} if sf_check_6_src != sf_check_6_dest: result_dict["CHECK_6"] = full_log["CHECK_6"] ### Check 7 MAIN -> ETL FACT_TIKTOK_TOP_CHART_ISRC (expected result: Counts match inside every step) ################################################ tmp_sf_check_7 = snowflake_fetch_data(sql_queries.sf_check_7) sf_check_7_src = int(tmp_sf_check_7[0]['count']) sf_check_7_dest = int(tmp_sf_check_7[1]['count']) print(f"SRC_CHECK_7: - {sf_check_7_src}") print(f"DEST_CHECK_7: - {sf_check_7_dest}") full_log["CHECK_7"] = {'SRC_CHECK_7': sf_check_7_src, 'DEST_CHECK_7': sf_check_7_dest} if sf_check_7_src != sf_check_7_dest: result_dict["CHECK_7"] = full_log["CHECK_7"] ### Check 8 MAIN -> ETL FACT_TIKTOK_TOP_CHART_ISRC_LIFETIME (expected result: Counts match inside every step) ################################################ tmp_sf_check_8 = snowflake_fetch_data(sql_queries.sf_check_8) sf_check_8_src = int(tmp_sf_check_8[0]['count']) sf_check_8_dest = int(tmp_sf_check_8[1]['count']) print(f"SRC_CHECK_8: - {sf_check_8_src}") print(f"DEST_CHECK_8: - {sf_check_8_dest}") full_log["CHECK_8"] = {'SRC_CHECK_8': sf_check_8_src, 'DEST_CHECK_8': sf_check_8_dest} if sf_check_8_src != sf_check_8_dest: result_dict["CHECK_8"] = full_log["CHECK_8"] ### Check 9 MAIN -> ETL DIM_TIKTOK_TOP_SONG (expected result: Counts match inside every step) ################################################ tmp_sf_check_9 = snowflake_fetch_data(sql_queries.sf_check_9) sf_check_9_result = int(tmp_sf_check_9[0]['count']) print(f"SRC_CHECK_9: - {sf_check_9_result}") full_log["CHECK_9"] = {'SRC_CHECK_9': sf_check_9_result} if sf_check_9_result != 1: result_dict["CHECK_9"] = {'SRC_CHECK_9': 'FAILED: Query count does not return 1'} return result_dict, full_log ################# run the all steps ###################### def run_steps() -> dict: message_dict = {'name':"[PROD] SME MAX (Exploration Area)",'status': "", 'date': "", 'info': "", 'details': "", 'full_log': ""} # set date according to sql searching date, currently it's `today` message_dict["date"] = datetime.datetime.now().strftime("%Y-%m-%d") result_dict_1_to_9, monitoring_1_to_9_log = check_1_to_9() message_dict['full_log'] = {**monitoring_1_to_9_log} message_dict['details'] = {**result_dict_1_to_9} if result_dict_1_to_9: postgres_update_failure_count(failure_count_increase) message_dict['status'] = "FAILED" message_dict['info'] = "Some steps failed" else: postgres_update_failure_count(failure_count_to_zero) message_dict['status'] = "OK" message_dict['info'] = "All step completed successfully" return message_dict if __name__ == '__main__': # # check command line parameters and print or email result parser = create_arg_parser() arg_list = parser.parse_args() if len(sys.argv[1:]) > 0: result = run_steps() with open('/tmp/sme_max_daily_log.json', 'w') as json_file: json.dump(result, json_file, indent=4) if arg_list.recipients: recipients = arg_list.recipients[0] send_mail(recipients=recipients, message=json.dumps(result, indent=4), status=result['status']) if arg_list.print: print(json.dumps(result, indent=4)) else: parser.print_help()