logger.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import os
  2. import json
  3. class Log(object):
  4. def __init__(self, filename):
  5. self.filename = filename
  6. if os.path.exists(self.filename):
  7. with open(self.filename, "r") as f:
  8. self.entries = json.load(f)
  9. else:
  10. self.entries = []
  11. self.save()
  12. @property
  13. def last_log_index(self):
  14. return len(self.entries) - 1
  15. @property
  16. def last_log_term(self):
  17. return self.get_log_term(self.last_log_index)
  18. def get_log_term(self, log_index):
  19. """
  20. leader do
  21. follower
  22. """
  23. if log_index >= len(self.entries):
  24. return -1
  25. elif log_index < 0:
  26. return -1
  27. else:
  28. return self.entries[log_index]["term"]
  29. def get_entries(self, next_index):
  30. """
  31. leader do
  32. """
  33. # print('get_entries')
  34. return self.entries[max(0, next_index):]
  35. def delete_entries(self, prev_log_index):
  36. # print('delete_entries')
  37. self.entries = self.entries[: max(0, prev_log_index)]
  38. self.save()
  39. def append_entries(self, prev_log_index, entries):
  40. # print('append_entries')
  41. self.entries = self.entries[: max(0, prev_log_index + 1)] + entries
  42. self.save()
  43. def save(self):
  44. with open(self.filename, "w") as f:
  45. json.dump(self.entries, f, indent=4)