smart-logger 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. #!/usr/bin/env python
  2. """
  3. This framework allows data to be logged to a given data store i.e :
  4. - disk, cloud (google, dropbox, box, sugarsync or s3) or a queue server
  5. The intent of the framework is to work as a standalone or embedded in code as a logging framework
  6. usage:
  7. dependencies :
  8. data-transport pip install git+https://dev.the-phi.com/git/steve/data-transport.git
  9. """
  10. import smart
  11. import smart.top
  12. import smart.folder
  13. import smart.top
  14. import smart.logger
  15. import smart.files
  16. import uuid
  17. import typer
  18. import meta
  19. import json
  20. import os
  21. import transport
  22. import shutil
  23. from datetime import datetime
  24. _cli = typer.Typer()
  25. import plugin_ix
  26. # iregistry = plugins.Registry(meta.__home__)
  27. @_cli.command(name='log-intruder')
  28. def intrusion(path:str='/var/log/auth.log', year:int=datetime.now().year):
  29. """
  30. This function
  31. """
  32. _r = smart.logger.read(path=path,year=year)
  33. if _r :
  34. for _id in _r :
  35. if hasattr(smart.logger,_id):
  36. try:
  37. _pointer = getattr(smart.logger,_id)
  38. _df = _pointer(_r[_id])
  39. post(_df,_id)
  40. except Exception as e:
  41. print (e)
  42. pass
  43. else:
  44. print ()
  45. print ("Nothing out of the ordinary was found in")
  46. print (f"{path}")
  47. @_cli.command(name='top')
  48. def apply_apps (app:str=None,user:str=None):
  49. """
  50. This function looks at applications/commands running on the system
  51. """
  52. _df = smart.top.read(name=app)
  53. _id = 'apps' if not app else app
  54. # if app :
  55. # _index = _df.name == app
  56. # if _index.sum() :
  57. # _df = _df[_index]
  58. post(_df,_id)
  59. @_cli.command(name='archive')
  60. def _archive():
  61. """
  62. This function will archive the database, by renaming it into
  63. """
  64. _suffix = datetime.now()
  65. _suffix = "-".join([str(_value) for _value in [_suffix.year,_suffix.month,_suffix.day,_suffix.hour,_suffix.minute]])
  66. _path = os.sep.join([meta.__home__,meta.__database__])
  67. _src = _path + '.db3'
  68. if os.path.exists(_src):
  69. _target = _path +'-archived-on-'+ _suffix+'.db3'
  70. shutil.move(_src,_target)
  71. _msg = f"""Archive created successfully at:
  72. {_target}"""
  73. else:
  74. _msg = """
  75. Archive function is not available at this time, please try after logs have been stored
  76. """
  77. print(_msg)
  78. @_cli.command(name='folder')
  79. def apply_folder(path:str):
  80. """
  81. This function will read the content of a folder and generate a
  82. """
  83. _df = smart.folder.read(path=path)
  84. # print (_df)
  85. post(_df,'folders')
  86. pass
  87. @_cli.command (name='files')
  88. def apply_files(folder:str) :
  89. _df = smart.files.read(folder)
  90. post(_df,'files')
  91. @_cli.command(name='init')
  92. # @plugins.cli.appr(name='init')
  93. def apply_signup (email:str,key:str=None,provider:str='sqlite') :
  94. """
  95. Initialize smart-logger so it is able to store your if need be
  96. """
  97. _config = {"system":{"email":email,"uid":str(uuid.uuid4()),"version":meta.__version__},"store":{"provider":provider,"context":"write"}}
  98. _db = meta.__database__
  99. if provider in ['sqlite','sqlite3'] :
  100. _db = os.sep.join([meta.__home__,_db+'.db3'])
  101. _config['store']['database'] = _db
  102. else:
  103. _config['store']['database'] = _db
  104. #
  105. # Let us store this in a folder
  106. _PATH = meta.__home__
  107. _verb = "written"
  108. if not os.path.exists(_PATH) :
  109. os.mkdir(_PATH)
  110. else:
  111. _verb = "updated"
  112. f = open(os.sep.join([_PATH,'config.json']),'w')
  113. f.write(json.dumps(_config))
  114. f.close()
  115. _msg = f"""
  116. The configuration file was {_verb} successfully at {meta.__home__}
  117. data store:
  118. provider {provider}
  119. database {_db}
  120. If your database has security enabled, consider updating "{meta.__home__}{os.sep}config.json" For appropriate security
  121. Visit https://github.com/lnyemba/data-transport for more.metarmation
  122. """
  123. print ()
  124. print (_msg)
  125. pass
  126. def post(_df,_table):
  127. """
  128. Store data in a given location
  129. """
  130. _path = os.sep.join([meta.__home__,'config.json'])
  131. f = open (_path)
  132. _config = json.loads(f.read())
  133. f.close()
  134. _store = _config['store']
  135. # if _store['provider'] in ['mongodb','mongo','couch','couchdb'] :
  136. # _store['collection'] = _table
  137. # else:
  138. # _store['table'] = _table
  139. _store['table'] = _table
  140. # writer = transport.factory.instance(**_store)
  141. writer = transport.get.writer(**_store)
  142. writer.write(_df)
  143. if hasattr(writer,'close') :
  144. writer.close()
  145. if __name__ == '__main__' :
  146. os.environ['REGISTRY_FOLDER'] = meta.__home__
  147. # print (os.environ['REGISTRY_FOLDER'])
  148. _cli.add_typer(plugin_ix.cli.appr,name='registry',help='Initialize smart-logger registry for plugins ')
  149. # del os.environ['REGISTRY_FOLDER']
  150. _cli()