Source code for airflow.providers.google.cloud.transfers.cassandra_to_gcs
## Licensed to the Apache Software Foundation (ASF) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The ASF licenses this file# to you under the Apache License, Version 2.0 (the# "License"); you may not use this file except in compliance# with the License. You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing,# software distributed under the License is distributed on an# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY# KIND, either express or implied. See the License for the# specific language governing permissions and limitations# under the License."""This module contains operator for copying data from Cassandra to Google Cloud Storage in JSON format."""from__future__importannotationsimportjsonfrombase64importb64encodefromdatetimeimportdatetimefromdecimalimportDecimalfromtempfileimportNamedTemporaryFilefromtypingimportTYPE_CHECKING,Any,Iterable,NewType,SequencefromuuidimportUUIDfromcassandra.utilimportDate,OrderedMapSerializedKey,SortedSet,Timefromairflow.exceptionsimportAirflowExceptionfromairflow.modelsimportBaseOperatorfromairflow.providers.apache.cassandra.hooks.cassandraimportCassandraHookfromairflow.providers.google.cloud.hooks.gcsimportGCSHookifTYPE_CHECKING:fromairflow.utils.contextimportContext
[docs]classCassandraToGCSOperator(BaseOperator):""" Copy data from Cassandra to Google Cloud Storage in JSON format. Note: Arrays of arrays are not supported. :param cql: The CQL to execute on the Cassandra table. :param bucket: The bucket to upload to. :param filename: The filename to use as the object name when uploading to Google Cloud Storage. A {} should be specified in the filename to allow the operator to inject file numbers in cases where the file is split due to size. :param schema_filename: If set, the filename to use as the object name when uploading a .json file containing the BigQuery schema fields for the table that was dumped from MySQL. :param approx_max_file_size_bytes: This operator supports the ability to split large table dumps into multiple files (see notes in the filename param docs above). This param allows developers to specify the file size of the splits. Check https://cloud.google.com/storage/quotas to see the maximum allowed file size for a single object. :param cassandra_conn_id: Reference to a specific Cassandra hook. :param gzip: Option to compress file for upload :param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param query_timeout: (Optional) The amount of time, in seconds, used to execute the Cassandra query. If not set, the timeout value will be set in Session.execute() by Cassandra driver. If set to None, there is no timeout. :param encode_uuid: (Optional) Option to encode UUID or not when upload from Cassandra to GCS. Default is to encode UUID. """
def__init__(self,*,cql:str,bucket:str,filename:str,schema_filename:str|None=None,approx_max_file_size_bytes:int=1900000000,gzip:bool=False,cassandra_conn_id:str="cassandra_default",gcp_conn_id:str="google_cloud_default",impersonation_chain:str|Sequence[str]|None=None,query_timeout:float|None|NotSetType=NOT_SET,encode_uuid:bool=True,**kwargs,)->None:super().__init__(**kwargs)self.cql=cqlself.bucket=bucketself.filename=filenameself.schema_filename=schema_filenameself.approx_max_file_size_bytes=approx_max_file_size_bytesself.cassandra_conn_id=cassandra_conn_idself.gcp_conn_id=gcp_conn_idself.gzip=gzipself.impersonation_chain=impersonation_chainself.query_timeout=query_timeoutself.encode_uuid=encode_uuid# Default Cassandra to BigQuery type mapping
[docs]defexecute(self,context:Context):hook=CassandraHook(cassandra_conn_id=self.cassandra_conn_id)query_extra={}ifself.query_timeoutisnotNOT_SET:query_extra["timeout"]=self.query_timeoutcursor=hook.get_conn().execute(self.cql,**query_extra)# If a schema is set, create a BQ schema JSON file.ifself.schema_filename:self.log.info("Writing local schema file")schema_file=self._write_local_schema_file(cursor)# Flush file before uploadingschema_file["file_handle"].flush()self.log.info("Uploading schema file to GCS.")self._upload_to_gcs(schema_file)schema_file["file_handle"].close()counter=0self.log.info("Writing local data files")forfile_to_uploadinself._write_local_data_files(cursor):# Flush file before uploadingfile_to_upload["file_handle"].flush()self.log.info("Uploading chunk file #%d to GCS.",counter)self._upload_to_gcs(file_to_upload)self.log.info("Removing local file")file_to_upload["file_handle"].close()counter+=1# Close all sessions and connection associated with this Cassandra clusterhook.shutdown_cluster()
def_write_local_data_files(self,cursor):""" Takes a cursor, and writes results to a local file. :return: A dictionary where keys are filenames to be used as object names in GCS, and values are file handles to local files that contain the data for the GCS objects. """file_no=0tmp_file_handle=NamedTemporaryFile(delete=True)file_to_upload={"file_name":self.filename.format(file_no),"file_handle":tmp_file_handle,}forrowincursor:row_dict=self.generate_data_dict(row._fields,row)content=json.dumps(row_dict).encode("utf-8")tmp_file_handle.write(content)# Append newline to make dumps BigQuery compatible.tmp_file_handle.write(b"\n")iftmp_file_handle.tell()>=self.approx_max_file_size_bytes:file_no+=1yieldfile_to_uploadtmp_file_handle=NamedTemporaryFile(delete=True)file_to_upload={"file_name":self.filename.format(file_no),"file_handle":tmp_file_handle,}yieldfile_to_uploaddef_write_local_schema_file(self,cursor):""" Takes a cursor, and writes the BigQuery schema for the results to a local file system. :return: A dictionary where key is a filename to be used as an object name in GCS, and values are file handles to local files that contains the BigQuery schema fields in .json format. """schema=[]tmp_schema_file_handle=NamedTemporaryFile(delete=True)forname,type_inzip(cursor.column_names,cursor.column_types):schema.append(self.generate_schema_dict(name,type_))json_serialized_schema=json.dumps(schema).encode("utf-8")tmp_schema_file_handle.write(json_serialized_schema)schema_file_to_upload={"file_name":self.schema_filename,"file_handle":tmp_schema_file_handle,}returnschema_file_to_uploaddef_upload_to_gcs(self,file_to_upload):"""Upload a file (data split or schema .json file) to Google Cloud Storage."""hook=GCSHook(gcp_conn_id=self.gcp_conn_id,impersonation_chain=self.impersonation_chain,)hook.upload(bucket_name=self.bucket,object_name=file_to_upload.get("file_name"),filename=file_to_upload.get("file_handle").name,mime_type="application/json",gzip=self.gzip,)
[docs]defgenerate_data_dict(self,names:Iterable[str],values:Any)->dict[str,Any]:"""Generates data structure that will be stored as file in GCS."""return{n:self.convert_value(v)forn,vinzip(names,values)}
[docs]defconvert_value(self,value:Any|None)->Any|None:"""Convert value to BQ type."""ifnotvalue:returnvalueelifisinstance(value,(str,int,float,bool,dict)):returnvalueelifisinstance(value,bytes):returnb64encode(value).decode("ascii")elifisinstance(value,UUID):ifself.encode_uuid:returnb64encode(value.bytes).decode("ascii")else:returnstr(value)elifisinstance(value,(datetime,Date)):returnstr(value)elifisinstance(value,Decimal):returnfloat(value)elifisinstance(value,Time):returnstr(value).split(".")[0]elifisinstance(value,(list,SortedSet)):returnself.convert_array_types(value)elifhasattr(value,"_fields"):returnself.convert_user_type(value)elifisinstance(value,tuple):returnself.convert_tuple_type(value)elifisinstance(value,OrderedMapSerializedKey):returnself.convert_map_type(value)else:raiseAirflowException("Unexpected value: "+str(value))
[docs]defconvert_array_types(self,value:list[Any]|SortedSet)->list[Any]:"""Maps convert_value over array."""return[self.convert_value(nested_value)fornested_valueinvalue]
[docs]defconvert_user_type(self,value:Any)->dict[str,Any]:""" Converts a user type to RECORD that contains n fields, where n is the number of attributes. Each element in the user type class will be converted to its corresponding data type in BQ. """names=value._fieldsvalues=[self.convert_value(getattr(value,name))fornameinnames]returnself.generate_data_dict(names,values)
[docs]defconvert_tuple_type(self,values:tuple[Any])->dict[str,Any]:""" Converts a tuple to RECORD that contains n fields. Each field will be converted to its corresponding data type in bq and will be named 'field_<index>', where index is determined by the order of the tuple elements defined in cassandra. """names=["field_"+str(i)foriinrange(len(values))]returnself.generate_data_dict(names,values)
[docs]defconvert_map_type(self,value:OrderedMapSerializedKey)->list[dict[str,Any]]:""" Converts a map to a repeated RECORD that contains two fields: 'key' and 'value'. Each will be converted to its corresponding data type in BQ. """converted_map=[]fork,vinzip(value.keys(),value.values()):converted_map.append({"key":self.convert_value(k),"value":self.convert_value(v)})returnconverted_map
[docs]defget_bq_fields(cls,type_:Any)->list[dict[str,Any]]:"""Converts non simple type value to BQ representation."""ifcls.is_simple_type(type_):return[]# In case of not simple typenames:list[str]=[]types:list[Any]=[]ifcls.is_array_type(type_)andcls.is_record_type(type_.subtypes[0]):names=type_.subtypes[0].fieldnamestypes=type_.subtypes[0].subtypeselifcls.is_record_type(type_):names=type_.fieldnamestypes=type_.subtypesiftypesandnotnamesandtype_.cassname=="TupleType":names=["field_"+str(i)foriinrange(len(types))]eliftypesandnotnamesandtype_.cassname=="MapType":names=["key","value"]return[cls.generate_schema_dict(n,t)forn,tinzip(names,types)]
@staticmethod
[docs]defis_simple_type(type_:Any)->bool:"""Check if type is a simple type."""returntype_.cassnameinCassandraToGCSOperator.CQL_TYPE_MAP
@staticmethod
[docs]defis_array_type(type_:Any)->bool:"""Check if type is an array type."""returntype_.cassnamein["ListType","SetType"]
@staticmethod
[docs]defis_record_type(type_:Any)->bool:"""Checks the record type."""returntype_.cassnamein["UserType","TupleType","MapType"]
@classmethod
[docs]defget_bq_type(cls,type_:Any)->str:"""Converts type to equivalent BQ type."""ifcls.is_simple_type(type_):returnCassandraToGCSOperator.CQL_TYPE_MAP[type_.cassname]elifcls.is_record_type(type_):return"RECORD"elifcls.is_array_type(type_):returncls.get_bq_type(type_.subtypes[0])else:raiseAirflowException("Not a supported type_: "+type_.cassname)
@classmethod
[docs]defget_bq_mode(cls,type_:Any)->str:"""Converts type to equivalent BQ mode."""ifcls.is_array_type(type_)ortype_.cassname=="MapType":return"REPEATED"elifcls.is_record_type(type_)orcls.is_simple_type(type_):return"NULLABLE"else:raiseAirflowException("Not a supported type_: "+type_.cassname)