Advertisement
Guest User

Untitled

a guest
Mar 2nd, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.36 KB | None | 0 0
  1. # MIT License
  2.  
  3. # Copyright (c) 2019 Bellhops Inc.
  4.  
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11.  
  12. # The above copyright notice and this permission notice shall be included in all
  13. # copies or substantial portions of the Software.
  14.  
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22.  
  23. import os
  24. import datetime
  25. import logging
  26. import sys
  27. import botocore
  28.  
  29. from sqlalchemy import MetaData
  30. from sqlalchemy import Table
  31. from geoalchemy2 import Table as GeoTable
  32. from geoalchemy2.types import Geography
  33. from sqlalchemy import Column, NVARCHAR, NUMERIC
  34. from sqlalchemy.schema import CreateTable
  35. from sqlalchemy.sql.sqltypes import TEXT, NullType, ARRAY
  36. from sqlalchemy.dialects import postgresql
  37. from sqlalchemy.dialects.postgresql.base import DOUBLE_PRECISION
  38.  
  39. from airflow.hooks.postgres_hook import PostgresHook
  40. from airflow.hooks.S3_hook import S3Hook
  41. from airflow.models import Variable
  42. from airflow.operators.subdag_operator import SubDagOperator
  43. from airflow.operators.python_operator import PythonOperator
  44.  
  45. from airflow import utils as airflow_utils
  46.  
  47.  
  48. class Pump(object):
  49.  
  50. def __init__(self, table_name, origin_conn_id, origin_schema_name,
  51. destination_conn_id, destination_schema_name, destination_db_type, s3_conn_id,
  52. s3_bucket, s3_directory, drop_destination_table=False):
  53. self.table_name = table_name
  54. self.origin_hook = PostgresHook(postgres_conn_id=origin_conn_id)
  55. self.origin_conn_uri = self.origin_hook.get_uri()
  56. self.origin_schema_name = origin_schema_name
  57. self.destination_hook = PostgresHook(postgres_conn_id=destination_conn_id)
  58. self.destination_schema_name = destination_schema_name
  59. self.destination_db_type = destination_db_type
  60. self.s3_hook = S3Hook(aws_conn_id=s3_conn_id)
  61. self.drop_destination_table = drop_destination_table
  62. self.s3_bucket = s3_bucket
  63. self.s3_directory = s3_directory
  64.  
  65. self.origin_engine = self.origin_hook.get_sqlalchemy_engine()
  66. self.origin_metadata = MetaData(schema=self.origin_schema_name)
  67. self.origin_table_name_with_schema = '.'.join([self.origin_schema_name, self.table_name])
  68. self.destination_table_name_with_schema = '.'.join([self.destination_schema_name, self.table_name])
  69.  
  70. self.bucket_name = self.s3_bucket
  71. self.directory_name = self.s3_directory
  72. self.s3_file_name = '''{directory_name}/{table_name}'''.format(directory_name=self.directory_name,
  73. table_name=table_name) + '_{:%Y-%m-%dT%H%M}'.format(datetime.datetime.now()) + '.csv'
  74. self.destination_conn_uri = self.destination_hook.get_uri()
  75. self.destination_engine = self.destination_hook.get_sqlalchemy_engine()
  76. self.aws_key, self.aws_pass, _, _ = self.s3_hook._get_credentials(None)
  77.  
  78. self.local_file = None
  79.  
  80. @property
  81. def origin_has_table(self):
  82. return self.origin_engine.has_table(self.table_name, schema=self.origin_schema_name)
  83.  
  84. @property
  85. def destination_has_table(self):
  86. return self.destination_engine.has_table(self.table_name, schema=self.destination_schema_name)
  87.  
  88. @property
  89. def is_destination_type_redshift(self):
  90. return self.destination_db_type == 'redshift'
  91.  
  92. def get_columns_from_table(self, table):
  93. logging.info("Getting columns for {table}.".format(table=table.name))
  94. columns = []
  95. for column in table.columns:
  96. if self.is_destination_type_redshift:
  97. logging.info("Changing column constraints for {table}.".format(table=table.name))
  98. if column.name == 'id':
  99. columns.append(Column(column.name, column.type, primary_key=True, autoincrement=False))
  100. elif type(column.type) is TEXT:
  101. columns.append(Column(column.name, NVARCHAR(65535)))
  102. elif type(column.type) is DOUBLE_PRECISION:
  103. columns.append(Column(column.name, NUMERIC(20, 5)))
  104. elif type(column.type) is NullType:
  105. columns.append(Column(column.name, NVARCHAR(65535)))
  106. elif type(column.type) is Geography:
  107. columns.append(Column(column.name, NVARCHAR(65535)))
  108. else:
  109. columns.append(Column(column.name, column.type))
  110. else:
  111. if type(column.type) is DOUBLE_PRECISION:
  112. columns.append(Column(column.name, NUMERIC(20, 5)))
  113. else:
  114. columns.append(Column(column.name, column.type))
  115. return columns
  116.  
  117. def execute_psql_command(self, conn_uri, command, password=None):
  118. if password:
  119. psql_query = '''export PGPASSWORD='{password}'; psql "{conn_url}" -c "{command}" '''.format(
  120. conn_url=conn_uri, command=command, password=password)
  121. print(psql_query)
  122. os.system(psql_query)
  123. else:
  124. psql_query = '''psql "{conn_url}" -c "{command}" '''.format(
  125. conn_url=conn_uri, command=command)
  126. print(psql_query)
  127. res = os.system(psql_query)
  128. if res != 0:
  129. sys.exit(1)
  130.  
  131. def create_directory(self, directory):
  132. os.system('''mkdir -p {directory}'''.format(directory=directory))
  133. return directory
  134.  
  135. def remove_local_file(self):
  136. command = '''rm -f {file_path}'''.format(file_path=self.local_file)
  137. logging.info("Removing file with command: {command}".format(command=command))
  138. os.system(command)
  139.  
  140. def copy_table_to_local_csv_command(self, table_name):
  141. pump_tmp_directory = Variable.get('PUMP_TMP_DIRECTORY', default_var='/tmp/pump')
  142. directory = self.create_directory("{pump_tmp_directory}/{destination_schema_name}".format(
  143. destination_schema_name=self.destination_schema_name,
  144. pump_tmp_directory=pump_tmp_directory
  145. ))
  146. file_ = "{directory}/{table_name}".format(directory=directory, table_name=table_name) + '_{:%Y-%m-%dT%H%M}'.format(datetime.datetime.now()) + '.csv'
  147. command = '''\COPY (SELECT * FROM {table_name}) TO '{file}' HEADER CSV;'''.format(
  148. table_name=table_name,
  149. file=file_
  150. )
  151. self.local_file = file_
  152. logging.info("Dumped table {table_name} to file {file_name}".format(table_name=self.table_name, file_name=self.local_file))
  153. return command
  154.  
  155. def copy_s3_file_to_table_command(self, table_name, schema_name, bucket_name, file_name, aws_key, aws_pass):
  156. table_name = '.'.join([schema_name, table_name])
  157. command = '''COPY {table_name} FROM 's3://{bucket_name}/{file}' credentials 'aws_access_key_id={aws_key};aws_secret_access_key={aws_pass}' IGNOREHEADER 1 CSV;'''.format(
  158. table_name=table_name,
  159. bucket_name=bucket_name,
  160. file=file_name,
  161. aws_key=aws_key,
  162. aws_pass=aws_pass
  163. )
  164. return command
  165.  
  166. def copy_local_file_to_table_command(self, table_name, schema_name, file_name):
  167. table_name = '.'.join([schema_name, table_name])
  168. command = '''\COPY {table_name} FROM '{file}' HEADER CSV;'''.format(
  169. table_name=table_name,
  170. file=file_name,
  171. )
  172. return command
  173.  
  174. def copy_table_to_local_file(self):
  175. command = self.copy_table_to_local_csv_command(self.origin_table_name_with_schema)
  176. conn = self.origin_hook.get_connection(self.origin_hook.postgres_conn_id)
  177. conn_uri = 'postgres://{user}@{host}:{port}/{schema}'.format(user=conn.login,
  178. host=conn.host,
  179. port=conn.port,
  180. schema=conn.schema)
  181. self.execute_psql_command(conn_uri, command, conn.password)
  182.  
  183. def copy_table_to_s3(self):
  184. logging.info("Copying local file to s3 bucket:{bucket} file: {file}".format(bucket=self.bucket_name,
  185. file=self.s3_file_name))
  186. self.s3_hook.load_file(
  187. self.local_file,
  188. self.s3_file_name,
  189. bucket_name=self.bucket_name,
  190. replace=True,
  191. )
  192.  
  193. def remove_s3_file(self):
  194. logging.info("Removing file from s3 bucket:{bucket} file: {file}".format(bucket=self.bucket_name,
  195. file=self.s3_file_name))
  196. boto_client = self.s3_hook.get_conn()
  197. try:
  198. boto_client.head_object(Bucket=self.s3_bucket, Key=self.s3_file_name)
  199. boto_client.delete_object(Bucket=self.s3_bucket, Key=self.s3_file_name)
  200. except botocore.exceptions.ClientError as e:
  201. logging.info("Could not find file. Error {}".format(e))
  202.  
  203. def copy_s3_file_to_table(self):
  204. logging.info("Copying file from s3 bucket:{bucket} file: {file} to table {table_name}".format(
  205. bucket=self.bucket_name,
  206. file=self.s3_file_name,
  207. table_name=self.table_name))
  208. command = self.copy_s3_file_to_table_command(table_name=self.table_name,
  209. schema_name=self.destination_schema_name,
  210. bucket_name=self.bucket_name,
  211. file_name=self.s3_file_name,
  212. aws_key=self.aws_key,
  213. aws_pass=self.aws_pass)
  214. self.destination_hook.run(command)
  215.  
  216. def copy_local_file_to_table(self):
  217. logging.info("Copying local file {local_file} to {table_name}".format(
  218. table_name=self.table_name,
  219. local_file=self.local_file
  220. ))
  221. command = self.copy_local_file_to_table_command(table_name=self.table_name,
  222. schema_name=self.destination_schema_name,
  223. file_name=self.local_file)
  224. self.execute_psql_command(self.destination_conn_uri, command)
  225.  
  226. def ddl_statement_create_table(self):
  227. if self.is_destination_type_redshift:
  228. table = Table(self.table_name, self.origin_metadata, autoload=True, autoload_with=self.origin_engine)
  229. else:
  230. table = GeoTable(self.table_name, self.origin_metadata, autoload=True, autoload_with=self.origin_engine)
  231. columns = self.get_columns_from_table(table)
  232. destination_table = Table(self.table_name, MetaData(schema=self.destination_schema_name), *columns)
  233. created_table = CreateTable(destination_table).compile(dialect=postgresql.dialect())
  234. created_table_ddl = str(created_table)
  235. logging.info("Created table: {created_table_ddl}".format(created_table_ddl=created_table_ddl))
  236. return created_table_ddl
  237.  
  238. def ddl_statement_truncate_table(self):
  239. truncate_table_ddl = '''TRUNCATE TABLE {table_name}'''.format(table_name=self.destination_table_name_with_schema)
  240. return truncate_table_ddl
  241.  
  242. def ddl_statement_drop_table(self):
  243. drop_table_ddl = '''DROP TABLE IF EXISTS {table_name} CASCADE'''.format(table_name=self.destination_table_name_with_schema)
  244. return drop_table_ddl
  245.  
  246. def create_table(self):
  247. create_ddl_statement = self.ddl_statement_create_table()
  248. truncate_ddl_statement = self.ddl_statement_truncate_table()
  249. drop_ddl_statement = self.ddl_statement_drop_table()
  250.  
  251. if self.drop_destination_table:
  252. self.destination_hook.run(drop_ddl_statement)
  253. elif self.destination_has_table:
  254. self.destination_hook.run(truncate_ddl_statement)
  255.  
  256. if not self.destination_has_table:
  257. self.destination_hook.run(create_ddl_statement)
  258.  
  259. def create_and_load_table(self):
  260. if self.origin_has_table:
  261. self.copy_table_to_local_file()
  262. self.create_table()
  263. if self.is_destination_type_redshift:
  264. self.copy_table_to_s3()
  265. self.copy_s3_file_to_table()
  266. self.remove_s3_file()
  267. else:
  268. self.copy_local_file_to_table()
  269. self.remove_local_file()
  270. else:
  271. logging.error("Origin hook {origin_hook} does not have table {table} in schema {schema}".format(
  272. origin_hook=self.origin_hook,
  273. table=self.table_name,
  274. schema=self.origin_schema_name
  275. ))
  276. sys.exit(1)
  277.  
  278.  
  279. class PumpSubDagOperator(SubDagOperator):
  280.  
  281. @airflow_utils.apply_defaults
  282. def __init__(self, dag, task_id, start_date, schedule_interval, default_args, table_names, pump_config, **kwargs):
  283.  
  284. self.start_date = start_date
  285. self.dag_schedule_interval = schedule_interval
  286. self.default_args = default_args
  287.  
  288. self.table_names = table_names
  289. self.origin_conn_id = pump_config['origin_conn_id']
  290. self.destination_conn_id = pump_config['destination_conn_id']
  291. self.origin_schema_name = pump_config['origin_schema_name']
  292. self.destination_schema_name = pump_config['destination_schema_name']
  293. self.destination_db_type = pump_config['destination_db_type']
  294. self.s3_conn_id = pump_config['s3_conn_id']
  295. self.s3_bucket = pump_config['s3_bucket']
  296. self.s3_directory = pump_config['s3_directory']
  297. if 'drop_destination_table' in pump_config:
  298. self.drop_destination_table = bool(pump_config['drop_destination_table'])
  299. else:
  300. self.drop_destination_table = False
  301.  
  302. from airflow import DAG # circular import
  303.  
  304. self.sub_dag_name = dag.dag_id + '.' + task_id
  305. self.subdag = DAG(
  306. self.sub_dag_name,
  307. start_date=self.start_date,
  308. schedule_interval=self.dag_schedule_interval,
  309. default_args=self.default_args
  310. )
  311.  
  312. self.init_tasks()
  313.  
  314. super(PumpSubDagOperator, self).__init__(
  315. dag=dag,
  316. subdag=self.subdag,
  317. task_id=task_id,
  318. trigger_rule='all_done'
  319. )
  320.  
  321. @property
  322. def task_type(self):
  323. return 'SubDagOperator'
  324.  
  325. def pump_table(self, table_name, **kwargs):
  326. pump = Pump(
  327. table_name=table_name,
  328. origin_conn_id=self.origin_conn_id,
  329. destination_conn_id=self.destination_conn_id,
  330. origin_schema_name=self.origin_schema_name,
  331. destination_schema_name=self.destination_schema_name,
  332. destination_db_type=self.destination_db_type,
  333. s3_conn_id=self.s3_conn_id,
  334. s3_bucket=self.s3_bucket,
  335. s3_directory=self.s3_directory,
  336. drop_destination_table=self.drop_destination_table
  337. )
  338. pump.create_and_load_table()
  339.  
  340. def create_task(self, table_name):
  341. task = PythonOperator(
  342. task_id="pump_{table_name}".format(table_name=table_name),
  343. python_callable=self.pump_table,
  344. op_kwargs={
  345. "table_name": table_name
  346. },
  347. dag=self.subdag
  348. )
  349.  
  350. def init_tasks(self):
  351. for table_name in self.table_names:
  352. self.create_task(table_name)
  353.  
  354.  
  355. if __name__ == '__main__':
  356. pump = Pump(
  357. table_name='test',
  358. origin_conn_id='airflow_origin_conn_name',
  359. origin_schema_name='origin_schema',
  360. destination_conn_id='airflow_destination_conn_name',
  361. destination_schema_name='destination_schema',
  362. destination_db_type='postgres',
  363. s3_conn_id='airflow_s3_conn_name',
  364. s3_bucket='bucket_name',
  365. s3_directory='directory_name_in_bucket',
  366. drop_destination_table=True
  367. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement