workers.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. """
  2. HealthcareIO - The Phi Technology LLC 2020
  3. This file contains functionalities that implement elements of an ETL pipeline that will consist of various workers.
  4. The pipeline is built around an observer design pattern.
  5. @TODO: Integrate with airflow and other process monitoring tools
  6. """
  7. import transport
  8. import os
  9. from multiprocessing import Process, Lock
  10. import numpy as np
  11. import json
  12. import pandas as pd
  13. class Subject (Process):
  14. cache = pd.DataFrame()
  15. lock = Lock()
  16. @staticmethod
  17. def log(_args):
  18. Subject.lock.acquire()
  19. try:
  20. Subject.cache = Subject.cache.append(pd.DataFrame([_args]))
  21. except Exception as e :
  22. print (e)
  23. finally:
  24. Subject.lock.release()
  25. def __init__(self,**_args):
  26. super().__init__()
  27. self.observers = _args['observers']
  28. self.index = 0
  29. self.name = _args['name']
  30. self.table = self.observers[1].table
  31. self.m = {}
  32. pass
  33. def run(self):
  34. self.notify()
  35. def notify(self):
  36. if self.index < len(self.observers) :
  37. observer = self.observers[self.index]
  38. _observer = None if self.index == 0 else self.observers[self.index -1]
  39. _invalues = None if not _observer else _observer.get()
  40. if _observer is None :
  41. self.m['table'] = self.name
  42. observer.init(caller=self,invalues = _invalues)
  43. self.index += 1
  44. observer.execute()
  45. print ({"table":self.table,"module":observer.name(),"status":observer.status})
  46. # self.m[observer.name()] = observer.status
  47. else:
  48. pass
  49. class Worker :
  50. def __init__(self,**_args):
  51. #PATH = os.sep.join([os.environ['HOME'],'.healthcareio','config.json'])
  52. #CONFIG = json.loads((open(PATH)).read())
  53. self._info = _args['store']
  54. self.logs = []
  55. self.schema = _args['schema']
  56. self.prefix = _args['prefix']
  57. self.status = 0
  58. def name(self):
  59. return self.__class__.__name__
  60. def log (self,**_args):
  61. """
  62. This function is designed to log to either the console or a data-store
  63. """
  64. # print (_args)
  65. pass
  66. def init(self,**_args):
  67. """
  68. Initializing a worker with arguments needed for it to perform it's task basic information needed are
  69. :param caller caller to be notified
  70. :param store data-store information i.e (pgsql,couchdb, mongo ...)
  71. """
  72. self.caller = _args['caller']
  73. #self._info = _args['store']
  74. self._invalues = _args['invalues'] if 'invalues' in _args else None
  75. def execute(self):
  76. try:
  77. self._apply()
  78. except Exception as error:
  79. pass
  80. finally:
  81. self.caller.notify()
  82. def _apply(self):
  83. pass
  84. def get(self):
  85. pass
  86. def notify(self):
  87. self.caller.notify()
  88. def tablename(self,name) :
  89. PREFIX_SEPARATOR = '_' if '_' not in self.prefix else ''
  90. SCHEMA_SEPARATOR = '' if self.schema.strip() =='' else '.'
  91. TABLE_NAME = PREFIX_SEPARATOR.join([self.prefix,name])
  92. return SCHEMA_SEPARATOR.join([self.schema,TABLE_NAME])
  93. class CreateSQL(Worker) :
  94. """
  95. This class is intended to create an SQL Table given the
  96. """
  97. def __init__(self,**_args):
  98. super().__init__(**_args)
  99. self._sql = _args['sql']
  100. def init(self,**_args):
  101. super().init(**_args)
  102. def _apply(self) :
  103. sqltable = self._info['table'] if 'provider' in self._info else self._info['args']['table']
  104. sqltable = self.tablename(sqltable)
  105. # log = {"context":self.name(),"args":{"table":self._info['args']['table'],"sql":self._sql}}
  106. log = {"context":self.name(),"args":{"table":sqltable,"sql":self._sql.replace(":table",sqltable)}}
  107. try:
  108. writer = transport.factory.instance(**self._info)
  109. writer.apply(self._sql.replace(":table",sqltable))
  110. writer.close()
  111. log['status'] = 1
  112. self.status = 1
  113. except Exception as e:
  114. log['status'] = 0
  115. log['info'] = {"error":e.args[0]}
  116. # print (e)
  117. finally:
  118. self.log(**log)
  119. class Reader(Worker):
  120. """
  121. read from mongodb and and make the data available to a third party
  122. :param pipeline mongodb command
  123. :param max_rows maximum rows to be written in a single insert
  124. """
  125. def __init__(self,**_args):
  126. super().__init__(**_args)
  127. # self.pipeline = _args['mongo'] #-- pipeline in the context of mongodb NOT ETL
  128. # self.pipeline = _args['mongo'] if 'mongo' in _args else _args['sql']
  129. self.pipeline = _args['read'] ;
  130. self.MAX_ROWS = _args['max_rows']
  131. self.table = _args['table'] #-- target table
  132. # is_demo = 'features' not in _args or ('features' in _args and ('export_etl' not in _args['features'] or _args['features']['export_etl'] == 0))
  133. #
  134. # @TODO: Bundle the limits with the features so as to insure that it doesn't come across as a magic number
  135. #
  136. # LIMIT = -1
  137. # if is_demo :
  138. # LIMIT = 10000
  139. # if set(['find','distinct']) & set(self.pipeline.keys()) :
  140. # self.pipeline['limit'] = LIMIT
  141. # elif 'aggregate' in self.pipeline :
  142. # self.pipeline['pipeline'] = [{"$limit":LIMIT}] + self.pipeline['pipeline']
  143. # self.log(**{"context":self.name(),"demo":is_demo,"args":{"limit":LIMIT}})
  144. def init(self,**_args):
  145. super().init(**_args)
  146. self.rows = []
  147. def _apply(self):
  148. try:
  149. self.reader = transport.factory.instance(**self._info) ;
  150. # self.rows = self.reader.read(mongo=self.pipeline)
  151. self.rows = self.reader.read(**self.pipeline)
  152. if type(self.rows) == pd.DataFrame :
  153. self.rows = self.rows.to_dict(orient='records')
  154. # if 'provider' in self._info and self._info['provider'] == 'sqlite' :
  155. # self.rows = self.rows.apply(lambda row: json.loads(row.data),axis=1).tolist()
  156. N = len(self.rows) / self.MAX_ROWS if len(self.rows) > self.MAX_ROWS else 1
  157. N = int(N)
  158. # self.rows = rows
  159. _log = {"context":self.name(), "status":1,"info":{"rows":len(self.rows),"table":self.table,"segments":N}}
  160. self.rows = np.array_split(self.rows,N)
  161. # self.get = lambda : rows #np.array_split(rows,N)
  162. self.reader.close()
  163. self.status = 1
  164. #
  165. except Exception as e :
  166. _log['status'] = 0
  167. _log['info'] = {"error":e.args[0]}
  168. print (e)
  169. self.log(**_log)
  170. # @TODO: Call the caller and notify it that this here is done
  171. def get(self):
  172. return self.rows
  173. class Writer(Worker):
  174. def __init__(self,**_args):
  175. super().__init__(**_args)
  176. if 'provider' in self._info :
  177. self._info['context'] = 'write'
  178. def init(self,**_args):
  179. """
  180. :param store output data-store needed for writing
  181. :param invalues input values with to be written somewhere
  182. """
  183. super().init(**_args)
  184. self._invalues = _args['invalues']
  185. def _apply(self):
  186. # table = self._info['args']['table'] if 'table' in self._info['args'] else 'N/A'
  187. # table = self.tablename(self._info['args']['table'])
  188. if 'provider' in self._info :
  189. table = self.tablename(self._info['table'])
  190. self._info['table'] = table
  191. else:
  192. table = self.tablename(self._info['args']['table'])
  193. self._info['args']['table'] = table
  194. writer = transport.factory.instance(**self._info)
  195. index = 0
  196. if self._invalues :
  197. for rows in self._invalues :
  198. # print (['segment # ',index,len(rows)])
  199. # self.log(**{"context":self.name(),"segment":(index+1),"args":{"rows":len(rows),"table":table}})
  200. if len(rows) > 0:
  201. #
  202. # @TODO: Upgrade to mongodb 4.0+ and remove the line below
  203. # Upon upgrade use the operator "$toString" in export.init function
  204. #
  205. rows = [dict(item,**{"_id":str(item["_id"])}) for item in rows]
  206. writer.write(rows)
  207. index += 1
  208. # for _e in rows :
  209. # writer.write(_e)
  210. self.status = 1
  211. else:
  212. print ("No data was passed")
  213. writer.close()
  214. #_args = {"type":"mongo.MongoReader","args":{"db":"parserio","doc":"logs"}}
  215. #reader = Reader()
  216. #reader.init(store = _args,pipeline={"distinct":"claims","key":"name"})
  217. #reader._apply()
  218. #print (reader.get())
  219. #for row in reader.get() :
  220. # print (row)