graph3.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. # Copyright 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import pydot
  15. import cgi
  16. import simplejson as json
  17. import datetime
  18. import argparse
  19. from synapse.events import FrozenEvent
  20. from synapse.util.frozenutils import unfreeze
  21. from six import string_types
  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, string_types):
  47. pass
  48. else:
  49. value = json.dumps(value)
  50. content.append(
  51. "<b>%s</b>: %s," % (
  52. cgi.escape(key, quote=True).encode("ascii", 'xmlcharrefreplace'),
  53. cgi.escape(value, quote=True).encode("ascii", 'xmlcharrefreplace'),
  54. )
  55. )
  56. content = "<br/>\n".join(content)
  57. print content
  58. label = (
  59. "<"
  60. "<b>%(name)s </b><br/>"
  61. "Type: <b>%(type)s </b><br/>"
  62. "State key: <b>%(state_key)s </b><br/>"
  63. "Content: <b>%(content)s </b><br/>"
  64. "Time: <b>%(time)s </b><br/>"
  65. "Depth: <b>%(depth)s </b><br/>"
  66. ">"
  67. ) % {
  68. "name": event.event_id,
  69. "type": event.type,
  70. "state_key": event.get("state_key", None),
  71. "content": content,
  72. "time": t,
  73. "depth": event.depth,
  74. }
  75. node = pydot.Node(
  76. name=event.event_id,
  77. label=label,
  78. )
  79. node_map[event.event_id] = node
  80. graph.add_node(node)
  81. print "Created Nodes"
  82. for event in events:
  83. for prev_id, _ in event.prev_events:
  84. try:
  85. end_node = node_map[prev_id]
  86. except:
  87. end_node = pydot.Node(
  88. name=prev_id,
  89. label="<<b>%s</b>>" % (prev_id,),
  90. )
  91. node_map[prev_id] = end_node
  92. graph.add_node(end_node)
  93. edge = pydot.Edge(node_map[event.event_id], end_node)
  94. graph.add_edge(edge)
  95. print "Created edges"
  96. graph.write('%s.dot' % file_prefix, format='raw', prog='dot')
  97. print "Created Dot"
  98. graph.write_svg("%s.svg" % file_prefix, prog='dot')
  99. print "Created svg"
  100. if __name__ == "__main__":
  101. parser = argparse.ArgumentParser(
  102. description="Generate a PDU graph for a given room by reading "
  103. "from a file with line deliminated events. \n"
  104. "Requires pydot."
  105. )
  106. parser.add_argument(
  107. "-p", "--prefix", dest="prefix",
  108. help="String to prefix output files with",
  109. default="graph_output"
  110. )
  111. parser.add_argument(
  112. "-l", "--limit",
  113. help="Only retrieve the last N events.",
  114. )
  115. parser.add_argument('event_file')
  116. parser.add_argument('room')
  117. args = parser.parse_args()
  118. make_graph(args.event_file, args.room, args.prefix, args.limit)