graph3.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. from __future__ import print_function
  2. # Copyright 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import pydot
  16. import cgi
  17. import simplejson as json
  18. import datetime
  19. import argparse
  20. from synapse.events import FrozenEvent
  21. from synapse.util.frozenutils import unfreeze
  22. def make_graph(file_name, room_id, file_prefix, limit):
  23. print("Reading lines")
  24. with open(file_name) as f:
  25. lines = f.readlines()
  26. print("Read lines")
  27. events = [FrozenEvent(json.loads(line)) for line in lines]
  28. print("Loaded events.")
  29. events.sort(key=lambda e: e.depth)
  30. print("Sorted events")
  31. if limit:
  32. events = events[-int(limit) :]
  33. node_map = {}
  34. graph = pydot.Dot(graph_name="Test")
  35. for event in events:
  36. t = datetime.datetime.fromtimestamp(
  37. float(event.origin_server_ts) / 1000
  38. ).strftime("%Y-%m-%d %H:%M:%S,%f")
  39. content = json.dumps(unfreeze(event.get_dict()["content"]), indent=4)
  40. content = content.replace("\n", "<br/>\n")
  41. print(content)
  42. content = []
  43. for key, value in unfreeze(event.get_dict()["content"]).items():
  44. if value is None:
  45. value = "<null>"
  46. elif isinstance(value, str):
  47. pass
  48. else:
  49. value = json.dumps(value)
  50. content.append(
  51. "<b>%s</b>: %s,"
  52. % (
  53. cgi.escape(key, quote=True).encode("ascii", "xmlcharrefreplace"),
  54. cgi.escape(value, quote=True).encode("ascii", "xmlcharrefreplace"),
  55. )
  56. )
  57. content = "<br/>\n".join(content)
  58. print(content)
  59. label = (
  60. "<"
  61. "<b>%(name)s </b><br/>"
  62. "Type: <b>%(type)s </b><br/>"
  63. "State key: <b>%(state_key)s </b><br/>"
  64. "Content: <b>%(content)s </b><br/>"
  65. "Time: <b>%(time)s </b><br/>"
  66. "Depth: <b>%(depth)s </b><br/>"
  67. ">"
  68. ) % {
  69. "name": event.event_id,
  70. "type": event.type,
  71. "state_key": event.get("state_key", None),
  72. "content": content,
  73. "time": t,
  74. "depth": event.depth,
  75. }
  76. node = pydot.Node(name=event.event_id, label=label)
  77. node_map[event.event_id] = node
  78. graph.add_node(node)
  79. print("Created Nodes")
  80. for event in events:
  81. for prev_id, _ in event.prev_events:
  82. try:
  83. end_node = node_map[prev_id]
  84. except:
  85. end_node = pydot.Node(name=prev_id, label="<<b>%s</b>>" % (prev_id,))
  86. node_map[prev_id] = end_node
  87. graph.add_node(end_node)
  88. edge = pydot.Edge(node_map[event.event_id], end_node)
  89. graph.add_edge(edge)
  90. print("Created edges")
  91. graph.write("%s.dot" % file_prefix, format="raw", prog="dot")
  92. print("Created Dot")
  93. graph.write_svg("%s.svg" % file_prefix, prog="dot")
  94. print("Created svg")
  95. if __name__ == "__main__":
  96. parser = argparse.ArgumentParser(
  97. description="Generate a PDU graph for a given room by reading "
  98. "from a file with line deliminated events. \n"
  99. "Requires pydot."
  100. )
  101. parser.add_argument(
  102. "-p",
  103. "--prefix",
  104. dest="prefix",
  105. help="String to prefix output files with",
  106. default="graph_output",
  107. )
  108. parser.add_argument("-l", "--limit", help="Only retrieve the last N events.")
  109. parser.add_argument("event_file")
  110. parser.add_argument("room")
  111. args = parser.parse_args()
  112. make_graph(args.event_file, args.room, args.prefix, args.limit)