workers.py 7.0 KB

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