mongodb.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import pymongo
  2. import traceback
  3. from colorama import Fore
  4. from toolset.utils.output_helper import log
  5. from toolset.databases.abstract_database import AbstractDatabase
  6. class Database(AbstractDatabase):
  7. @classmethod
  8. def get_connection(cls, config):
  9. return pymongo.MongoClient(host = config.database_host)
  10. @classmethod
  11. def get_current_world_table(cls, config):
  12. results_json = []
  13. try:
  14. worlds_json = {}
  15. print("DATABASE_HOST: %s" % config.database_host)
  16. connection = cls.get_connection(config)
  17. db = connection.hello_world
  18. for world in db.world.find():
  19. if "randomNumber" in world:
  20. if "id" in world:
  21. worlds_json[str(int(world["id"]))] = int(
  22. world["randomNumber"])
  23. elif "_id" in world:
  24. worlds_json[str(int(world["_id"]))] = int(
  25. world["randomNumber"])
  26. results_json.append(worlds_json)
  27. connection.close()
  28. except Exception:
  29. tb = traceback.format_exc()
  30. log("ERROR: Unable to load current MongoDB World table.",
  31. color=Fore.RED)
  32. log(tb)
  33. return results_json
  34. @classmethod
  35. def test_connection(cls, config):
  36. try:
  37. connection = cls.get_connection(config)
  38. db = connection.hello_world
  39. db.world.find()
  40. db.close()
  41. return True
  42. except:
  43. return False
  44. @classmethod
  45. def get_queries(cls, config):
  46. co = cls.get_connection(config)
  47. status = co.admin.command(pymongo.son_manipulator.SON([('serverStatus', 1)]))
  48. return int(status["opcounters"]["query"]) + int(status["opcounters"]["update"]) #get_queries returns all the queries
  49. @classmethod
  50. def get_rows(cls, config):
  51. co = cls.get_connection(config)
  52. status = co.admin.command(pymongo.son_manipulator.SON([('serverStatus', 1)]))
  53. return int(status["opcounters"]["query"]) * cls.get_rows_per_query(co)
  54. @classmethod
  55. def get_rows_updated(cls, config):
  56. co = cls.get_connection(config)
  57. status = co.admin.command(pymongo.son_manipulator.SON([('serverStatus', 1)]))
  58. return int(status["opcounters"]["update"]) * cls.get_rows_per_query(co)
  59. @classmethod
  60. def reset_cache(cls, config):
  61. co = cls.get_connection(config)
  62. co.admin.command({"planCacheClear": "world"})
  63. co.admin.command({"planCacheClear": "fortune"})
  64. @classmethod
  65. def get_rows_per_query(cls, co):
  66. rows_per_query = 1
  67. if cls.tbl_name == "fortune":
  68. rows_per_query = co["hello_world"][cls.tbl_name].count_documents({})
  69. return rows_per_query