workers.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. # print ()
  81. # print (error)
  82. # print ()
  83. finally:
  84. self.caller.notify()
  85. def _apply(self):
  86. pass
  87. def get(self):
  88. pass
  89. def notify(self):
  90. self.caller.notify()
  91. def tablename(self,name) :
  92. PREFIX_SEPARATOR = '_' if '_' not in self.prefix else ''
  93. SCHEMA_SEPARATOR = '' if self.schema.strip() =='' else '.'
  94. TABLE_NAME = PREFIX_SEPARATOR.join([self.prefix,name])
  95. return SCHEMA_SEPARATOR.join([self.schema,TABLE_NAME])
  96. class CreateSQL(Worker) :
  97. """
  98. This class is intended to create an SQL Table given the
  99. """
  100. def __init__(self,**_args):
  101. super().__init__(**_args)
  102. self._sql = _args['sql']
  103. def init(self,**_args):
  104. super().init(**_args)
  105. def _apply(self) :
  106. sqltable = self.tablename(self._info['args']['table'])
  107. # log = {"context":self.name(),"args":{"table":self._info['args']['table'],"sql":self._sql}}
  108. log = {"context":self.name(),"args":{"table":sqltable,"sql":self._sql.replace(":table",sqltable)}}
  109. try:
  110. writer = transport.factory.instance(**self._info)
  111. writer.apply(self._sql.replace(":table",sqltable))
  112. writer.close()
  113. log['status'] = 1
  114. self.status = 1
  115. except Exception as e:
  116. log['status'] = 0
  117. log['info'] = {"error":e.args[0]}
  118. # print (e)
  119. finally:
  120. self.log(**log)
  121. class Reader(Worker):
  122. """
  123. read from mongodb and and make the data available to a third party
  124. :param pipeline mongodb command
  125. :param max_rows maximum rows to be written in a single insert
  126. """
  127. def __init__(self,**_args):
  128. super().__init__(**_args)
  129. self.pipeline = _args['mongo'] #-- pipeline in the context of mongodb NOT ETL
  130. self.MAX_ROWS = _args['max_rows']
  131. self.table = _args['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. N = len(self.rows) / self.MAX_ROWS if len(self.rows) > self.MAX_ROWS else 1
  152. N = int(N)
  153. # self.rows = rows
  154. _log = {"context":self.name(),"args":self._info['args']['db'], "status":1,"info":{"rows":len(self.rows),"table":self.table,"segments":N}}
  155. self.rows = np.array_split(self.rows,N)
  156. # self.get = lambda : rows #np.array_split(rows,N)
  157. self.reader.close()
  158. self.status = 1
  159. #
  160. except Exception as e :
  161. log['status'] = 0
  162. log['info'] = {"error":e.args[0]}
  163. self.log(**_log)
  164. # @TODO: Call the caller and notify it that this here is done
  165. def get(self):
  166. return self.rows
  167. class Writer(Worker):
  168. def __init__(self,**_args):
  169. super().__init__(**_args)
  170. def init(self,**_args):
  171. """
  172. :param store output data-store needed for writing
  173. :param invalues input values with to be written somewhere
  174. """
  175. super().init(**_args)
  176. self._invalues = _args['invalues']
  177. def _apply(self):
  178. # table = self._info['args']['table'] if 'table' in self._info['args'] else 'N/A'
  179. table = self.tablename(self._info['args']['table'])
  180. self._info['args']['table'] = table;
  181. writer = transport.factory.instance(**self._info)
  182. index = 0
  183. if self._invalues :
  184. for rows in self._invalues :
  185. # print (['segment # ',index,len(rows)])
  186. self.log(**{"context":self.name(),"segment":(index+1),"args":{"rows":len(rows),"table":table}})
  187. if len(rows) :
  188. #
  189. # @TODO: Upgrade to mongodb 4.0+ and remove the line below
  190. # Upon upgrade use the operator "$toString" in export.init function
  191. #
  192. rows = [dict(item,**{"_id":str(item["_id"])}) for item in rows]
  193. writer.write(rows)
  194. index += 1
  195. # for _e in rows :
  196. # writer.write(_e)
  197. self.status = 1
  198. else:
  199. print ("No data was passed")
  200. writer.close()
  201. #_args = {"type":"mongo.MongoReader","args":{"db":"parserio","doc":"logs"}}
  202. #reader = Reader()
  203. #reader.init(store = _args,pipeline={"distinct":"claims","key":"name"})
  204. #reader._apply()
  205. #print (reader.get())
  206. #for row in reader.get() :
  207. # print (row)