workers.py 7.5 KB

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