etl.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. #!/usr/bin/env python
  2. __doc__ = """
  3. (c) 2018 - 2021 data-transport
  4. steve@the-phi.com, The Phi Technology LLC
  5. https://dev.the-phi.com/git/steve/data-transport.git
  6. This program performs ETL between 9 supported data sources : Couchdb, Mongodb, Mysql, Mariadb, PostgreSQL, Netezza,Redshift, Sqlite, File
  7. LICENSE (MIT)
  8. Copyright 2016-2020, The Phi Technology LLC
  9. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  12. Usage :
  13. transport --config <path-to-file.json> --procs <number-procs>
  14. @TODO: Create tables if they don't exist for relational databases
  15. example of configuration :
  16. 1. Move data from a folder to a data-store
  17. transport [--folder <path> ] --config <config.json> #-- assuming the configuration doesn't have folder
  18. transport --folder <path> --provider <postgresql|mongo|sqlite> --<database|db> <name> --table|doc <document_name>
  19. In this case the configuration should look like :
  20. {folder:..., target:{}}
  21. 2. Move data from one source to another
  22. transport --config <file.json>
  23. {source:{..},target:{..}} or [{source:{..},target:{..}},{source:{..},target:{..}}]
  24. """
  25. import pandas as pd
  26. import numpy as np
  27. import json
  28. import sys
  29. import transport
  30. import time
  31. from multiprocessing import Process
  32. SYS_ARGS = {}
  33. if len(sys.argv) > 1:
  34. N = len(sys.argv)
  35. for i in range(1,N):
  36. value = None
  37. if sys.argv[i].startswith('--'):
  38. key = sys.argv[i][2:] #.replace('-','')
  39. SYS_ARGS[key] = 1
  40. if i + 1 < N:
  41. value = sys.argv[i + 1] = sys.argv[i+1].strip()
  42. if key and value and not value.startswith('--'):
  43. SYS_ARGS[key] = value
  44. i += 2
  45. class Post(Process):
  46. def __init__(self,**args):
  47. super().__init__()
  48. self.store = args['target']
  49. if 'provider' not in args['target'] :
  50. pass
  51. self.PROVIDER = args['target']['type']
  52. # self.writer = transport.factory.instance(**args['target'])
  53. else:
  54. self.PROVIDER = args['target']['provider']
  55. self.store['context'] = 'write'
  56. # self.store = args['target']
  57. self.store['lock'] = True
  58. # self.writer = transport.instance(**args['target'])
  59. #
  60. # If the table doesn't exists maybe create it ?
  61. #
  62. self.rows = args['rows']
  63. # self.rows = args['rows'].fillna('')
  64. def log(self,**_args) :
  65. if ETL.logger :
  66. ETL.logger.info(**_args)
  67. def run(self):
  68. _info = {"values":self.rows} if 'couch' in self.PROVIDER else self.rows
  69. writer = transport.factory.instance(**self.store)
  70. writer.write(_info)
  71. writer.close()
  72. class ETL (Process):
  73. logger = None
  74. def __init__(self,**_args):
  75. super().__init__()
  76. self.name = _args['id'] if 'id' in _args else 'UNREGISTERED'
  77. if 'provider' not in _args['source'] :
  78. #@deprecate
  79. self.reader = transport.factory.instance(**_args['source'])
  80. else:
  81. #
  82. # This is the new interface
  83. _args['source']['context'] = 'read'
  84. self.reader = transport.instance(**_args['source'])
  85. #
  86. # do we have an sql query provided or not ....
  87. # self.sql = _args['source']['sql'] if 'sql' in _args['source'] else None
  88. self.cmd = _args['source']['cmd'] if 'cmd' in _args['source'] else None
  89. self._oargs = _args['target'] #transport.factory.instance(**_args['target'])
  90. self.JOB_COUNT = _args['jobs']
  91. self.jobs = []
  92. # self.logger = transport.factory.instance(**_args['logger'])
  93. def log(self,**_args) :
  94. if ETL.logger :
  95. ETL.logger.info(**_args)
  96. def run(self):
  97. if self.cmd :
  98. idf = self.reader.read(**self.cmd)
  99. else:
  100. idf = self.reader.read()
  101. idf = pd.DataFrame(idf)
  102. # idf = idf.replace({np.nan: None}, inplace = True)
  103. idf.columns = [str(name).replace("b'",'').replace("'","").strip() for name in idf.columns.tolist()]
  104. self.log(rows=idf.shape[0],cols=idf.shape[1],jobs=self.JOB_COUNT)
  105. #
  106. # writing the data to a designated data source
  107. #
  108. try:
  109. self.log(module='write',action='partitioning',jobs=self.JOB_COUNT)
  110. rows = np.array_split(np.arange(0,idf.shape[0]),self.JOB_COUNT)
  111. #
  112. # @TODO: locks
  113. for i in np.arange(self.JOB_COUNT) :
  114. # _id = ' '.join([str(i),' table ',self.name])
  115. indexes = rows[i]
  116. segment = idf.loc[indexes,:].copy() #.to_dict(orient='records')
  117. _name = "partition-"+str(i)
  118. if segment.shape[0] == 0 :
  119. continue
  120. proc = Post(target = self._oargs,rows = segment,name=_name)
  121. self.jobs.append(proc)
  122. proc.start()
  123. self.log(module='write',action='working',segment=str(self.name),table=self.name,rows=segment.shape[0])
  124. # while self.jobs :
  125. # jobs = [job for job in proc if job.is_alive()]
  126. # time.sleep(1)
  127. except Exception as e:
  128. print (e)
  129. def is_done(self):
  130. self.jobs = [proc for proc in self.jobs if proc.is_alive()]
  131. return len(self.jobs) == 0
  132. def instance(**_args):
  133. """
  134. :path ,index, id
  135. :param _info list of objects with {source,target}`
  136. :param logger
  137. """
  138. logger = _args['logger'] if 'logger' in _args else None
  139. if 'path' in _args :
  140. _info = json.loads((open(_args['path'])).read())
  141. if 'index' in _args :
  142. _index = int(_args['index'])
  143. _info = _info[_index]
  144. elif 'id' in _args :
  145. _info = [_item for _item in _info if '_id' in _item and _item['id'] == _args['id']]
  146. _info = _info[0] if _info else _info
  147. else:
  148. _info = _args['info']
  149. if logger and type(logger) != str:
  150. ETL.logger = logger
  151. elif logger == 'console':
  152. ETL.logger = transport.factory.instance(provider='console',context='write',lock=True)
  153. if type(_info) in [list,dict] :
  154. _info = _info if type(_info) != dict else [_info]
  155. #
  156. # The assumption here is that the objects within the list are {source,target}
  157. jobs = []
  158. for _item in _info :
  159. _item['jobs'] = 5 if 'procs' not in _args else int(_args['procs'])
  160. _job = ETL(**_item)
  161. _job.start()
  162. jobs.append(_job)
  163. return jobs
  164. else:
  165. return None
  166. if __name__ == '__main__' :
  167. _info = json.loads(open (SYS_ARGS['config']).read())
  168. index = int(SYS_ARGS['index']) if 'index' in SYS_ARGS else None
  169. procs = []
  170. for _config in _info :
  171. if 'source' in SYS_ARGS :
  172. _config['source'] = {"type":"disk.DiskReader","args":{"path":SYS_ARGS['source'],"delimiter":","}}
  173. _config['jobs'] = 3 if 'jobs' not in SYS_ARGS else int(SYS_ARGS['jobs'])
  174. etl = ETL (**_config)
  175. if index is None:
  176. etl.start()
  177. procs.append(etl)
  178. elif _info.index(_config) == index :
  179. # print (_config)
  180. procs = [etl]
  181. etl.start()
  182. break
  183. #
  184. #
  185. N = len(procs)
  186. while procs :
  187. procs = [thread for thread in procs if not thread.is_done()]
  188. if len(procs) < N :
  189. print (["Finished ",(N-len(procs)), " remaining ", len(procs)])
  190. N = len(procs)
  191. time.sleep(1)
  192. # print ("We're done !!")