main.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import json
  2. from node import Node
  3. from network_api import NetworkAPI
  4. from multiprocessing import Process
  5. import random
  6. import time
  7. import os
  8. def create_node(meta):
  9. node = Node(meta)
  10. node.run()
  11. if __name__ == "__main__":
  12. names = os.listdir(r'data\raft_front_end\public\log')
  13. content = {}
  14. for name in names:
  15. path = 'data/raft_front_end/public/log/' + name
  16. os.remove(path)
  17. num = input("[-]请输入节点数量:")
  18. ip = "localhost"
  19. base_port = 10000
  20. client_port = 9999
  21. nodes_meta = []
  22. network_api = NetworkAPI((ip, client_port))
  23. for i in range(int(num)):
  24. node_meta = {
  25. "id": str(i),
  26. "addr": ("localhost", base_port + i),
  27. "peers": {str(j): ("localhost", base_port + j) for j in range(int(num)) if j != i},
  28. }
  29. nodes_meta.append(node_meta)
  30. # create_node(node_meta)
  31. p = Process(target=create_node, args=(node_meta,), daemon=True)
  32. p.start()
  33. address = random.choice(nodes_meta)["addr"]
  34. # while True:
  35. # print('233ok')
  36. # time.sleep(30)
  37. time.sleep(10)
  38. while True:
  39. message = input("[-]请输入要记录的日志:(输入exit退出)")
  40. if message == 'exit':
  41. break
  42. # message = '233ok'
  43. data = {
  44. "type": "client_append_entries",
  45. "timestamp": int(time.time()),
  46. "message": message,
  47. }
  48. print("send: ", data)
  49. network_api.send(data, address)
  50. # time.sleep(5)
  51. names = os.listdir(r'data\raft_front_end\public\log')
  52. content = {
  53. 'log': []
  54. }
  55. for name in names:
  56. if name.endswith('log.json'):
  57. path = 'data/raft_front_end/public/log/' + name
  58. with open(path, 'r') as f:
  59. data = json.load(f)
  60. content['log'].append(data)
  61. with open('data/raft_front_end/public/log/log.json', 'w') as f:
  62. json.dump(content, f, indent=4)