...
Raw data means the data which we received directly from source, in our case it Synapse repository project. Synapse is sending access records to s3 with firehose kinesis delivery stream.
For each access record we need to modify the requesturl field calculate new fields like client, client_version etc from existing data according to business logic, Processing of data includes taking raw data and modifying the requesturl field for each recordcalculating new field data.
Now we want to keep processed data at in glue table having a separate storage location of S3 which will be partitioned on basis of timestamp of access record as year, month and day. And want to execute Athena query on it. Data should be stored in Parquet format, Parquet is column based file format and fast file type to read.
The ETL job script would like as below:
Code Block | ||
---|---|---|
| ||
""" This script executed by a Glue job. The job take the access record data from S3 and process it. Processed data stored in S3 in a parquet file partitioned by timestamp of record as year / month / day. """ import sys import datetime import re from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job from awsglue.dynamicframe import argsDynamicFrame = getResolvedOptions(sys.argv, ["JOB_NAME"]) sc = SparkContext() glueContext = GlueContext(sc) spark = glueContext.spark_session job = Job(glueContext) job.init(args["JOB_NAME"], args) # Script generated for node S3 bucket S3bucket_node1 = glueContext # Get access record from source and create dynamic frame for futher processing def get_dynamic_frame(connection_type, file_format, source_path, glue_context): dynamic_frame = glue_context.create_dynamic_frame.from_options( format_options={"multiline": True}, connection_type="s3",connection_type, format="json",file_format, connection_options={ "paths": ["s3://dev.log.sagebase.org/accessRecord/"],source_path], "recurse": True, "groupFiles": "inPartition", "recursegroupSize": True,"1048576", }, transformation_ctx="S3bucketdynamic_node1", ) # Script generated for node ApplyMapping ApplyMapping_node2frame") return dynamic_frame def apply_mapping(dynamic_frame): mapped_dynamic_frame = ApplyMapping.apply( frame=S3bucketdynamic_node1frame, mappings=[ ("payload.datesessionId", "string", "dateSESSION_ID", "string"), ("payload.requestURL", "string", "requesturl", "string"), ..... ("payload.xforwardedFor", "string" ], "xforwardedfor", "string"), ("payload.oauthClientId", "null", "oauthclientid", "string"), ("payload.success", "boolean", "success", "boolean"),transformation_ctx="mapped_dynamic_frame") return mapped_dynamic_frame # process the access record def transform(dynamic_record): #transformation ("payload.sessionId", "string", "sessionid", "string"), return dynamic_record def main(): ("payload.queryString", "null", "querystring", "string"), # Get args and setup environment args = getResolvedOptions("payloadsys.method"argv, "string", "method", "string"), ("payload.basicAuthUsername", "null", "basicauthusername", "string"), ("payload.instance["JOB_NAME", "stringS3_SOURCE_PATH", "instanceDATABASE_NAME", "stringTABLE_NAME"]), sc = SparkContext() ("payload.stack", "string", "stack", "string"), glue_context = GlueContext(sc) spark ("payload.host", "string", "host", "string"), = glue_context.spark_session job = Job(glue_context) job.init("payload.elapseMS", "int", "elapsems", "int"),args["JOB_NAME"], args) dynamic_frame = get_dynamic_frame("payload.threadIds3", "intjson", "threadid", "int"),args["S3_SOURCE_PATH"], glue_context) mapped_dynamic_frame = apply_mapping(dynamic_frame) ("payload.userId", "int", "userid", "int"), transformed_dynamic_frame = mapped_dynamic_frame.map(f=transform) ("payload.authenticationMethod", "null", "authenticationmethod", "string"), # Write the processed access records to destination ("payload.returnObjectId", "null", "returnobjectid", "string"), write_dynamic_frame = glue_context.write_dynamic_frame.from_catalog( ("payload.origin", "null", "origin", "string") frame=transformed_dynamic_frame, ("payload.via", "null", "via", "string")database=args["DATABASE_NAME"], table_name=args["TABLE_NAME"], ("payload.vmId", "stringadditional_options={"partitionKeys": ["year", "vmidmonth", "stringday")]}, ("payload.userAgent", "string", "useragent", "string"), transformation_ctx="write_dynamic_frame") job.commit() if __name__ == "__main__": main() ("payload.responseStatus", "int", "responsestatus", "int"), |
Challenges
As we deploy every week new stack, ETL job should not reprocess the old or already processed data again.
2. How we will maintain the versioning of script of glue job, which means define infrastructure that should take the script and push it into s3 ( deployment process of script)
3. How to trigger the job e.g on demand, or on schedule time.
4. How to handle duplicate data.
Proposed solution :
The ETL job will be static not created in every release.
Create a GitHub project(Synapse-ETL-Jobs) for our etl job. Add GitHub action to create tag/release which will zip the source code and version it with every merge in develop branch, basically use GitHub as artifactory. In Synapse-Stack-Builder project create a new workflow, which will first download the python script form Syanpse-ETL-Jobs from latest tag and upload it to s3 from where glue job and take it for processing.Then create stack with cloud-formation template that will setup a glue job ,glue table, trigger and required resources.Build should include testing.
It should be configurable parameter in stack builder. it should get triggered every hour.( In future we can find another way which can notify that new data is available for processing).
One way to avoid duplicate data is we can used both source and destination as glue table for job and then use left join to identify the duplicate as below (for now we are not considering duplicate, in future we can look into it, if it will create problem)
Code Block |
---|
stagingdatasource = gc.create_dynamic_frame.from_catalog( ("timestamp", "bigint", "timestamp", "bigint")database="stagingdatabase", ], transformationtable_ctxname="ApplyMappingstaging_source_node2table", ) def transform(dynamicRecord): tempVar = dynamicRecord["requestURL"].lower(transformation_ctx="stagingdatasource") if tempVar.startswith("/entity/md5"): targetdatasource = gc.create_dynamic_frame.from_catalog( tempVar database= "/entity/md5/#""targetdatabase", elif tempVar.startswith("/evaluation/name"): redshift_tmp_dir=args["TempDir"], tempVar table_name= "/evaluation/name/#""target_table", elif tempVar.startswith("/entity/alias"): transformation_ctx="targetdatasource") columnmapping = ApplyMapping.apply( tempVar = "/entity/alias/#" else: frame=stagingdatasource, tempVar mappings=[("description", "string", "/#description", "string"), ("id", "int", "id", "int")], dynamicRecord["requestURL"] = tempVartransformation_ctx="columnmapping") ta = columnmapping.toDF().alias('ta') tb print("Schema for mapped_medicare DynamicFrame:" + tempVar) return dynamicRecord= targetdatasource.toDF().alias('tb') left_join = ta\ mapped_record.join(tb, ta.value == ApplyMapping_node2.map(f = transform) mapped_record.printSchema(tb.value, how='left')\ .filter(col('tb.value').isNull())\ .select('ta.*') # ScriptInspect generatedleft forjoin node S3 bucket S3bucket_node3 =# glueContext.write_dynamic_frame.from_options( left_join.show() frame=mapped_record, finaldf = connection_type="s3", format="praquet",DynamicFrame.fromDF(left_join, gc, "nested") connection_options={gc.write_dynamic_frame.from_catalog( "path": "s3://dev.log.sagebase.org/processedAccessRecord/"frame=finaldf, database="compressiontargetdatabase": "gzip", "partitionKeys": [redshift_tmp_dir=args["TempDir"], }, transformationtable_ctxname="S3buckettarget_node3table", ) |
Challenges
As we deploy every week new stack, ETL job should not reprocess the old or already processed data again.
How we will maintain the versioning of script of glue job, which means define infrastructure that should take the script and push it into s3 ( deployment process of script)
How to trigger the job e.g on demand, or on schedule time.
How to handle duplicate data.
Processed data destination
...
Processed data destination
Processed data should be stored in S3 having portioned on access record timestamp. eg
dev.log.sagebase.org/processedAccessRecord/year/month/day.
Integrate with Redash
we need to integrate the processed access records to redash board which we used in our stack review meeting four audit purposes.
Alternative to access record processing :
While sending access record from synapse repository to firehose kinesis we can store both request url and processed url/ or only processed url. And kinesis should use dynamic partitioning on timestamp of access record to store data on s3. Now the data stored is already processed.Create a table from source S3 and Athena can query the data. ( not adequate because we might want to process data further, we need raw data in json format so it is available in readable format as well as processed data in parquet formate to query faster).