graph2.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. # Copyright 2014-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 sqlite3
  15. import pydot
  16. import cgi
  17. import json
  18. import datetime
  19. import argparse
  20. from synapse.events import FrozenEvent
  21. from synapse.util.frozenutils import unfreeze
  22. def make_graph(db_name, room_id, file_prefix, limit):
  23. conn = sqlite3.connect(db_name)
  24. sql = (
  25. "SELECT json FROM event_json as j "
  26. "INNER JOIN events as e ON e.event_id = j.event_id "
  27. "WHERE j.room_id = ?"
  28. )
  29. args = [room_id]
  30. if limit:
  31. sql += (
  32. " ORDER BY topological_ordering DESC, stream_ordering DESC "
  33. "LIMIT ?"
  34. )
  35. args.append(limit)
  36. c = conn.execute(sql, args)
  37. events = [FrozenEvent(json.loads(e[0])) for e in c.fetchall()]
  38. events.sort(key=lambda e: e.depth)
  39. node_map = {}
  40. state_groups = {}
  41. graph = pydot.Dot(graph_name="Test")
  42. for event in events:
  43. c = conn.execute(
  44. "SELECT state_group FROM event_to_state_groups "
  45. "WHERE event_id = ?",
  46. (event.event_id,)
  47. )
  48. res = c.fetchone()
  49. state_group = res[0] if res else None
  50. if state_group is not None:
  51. state_groups.setdefault(state_group, []).append(event.event_id)
  52. t = datetime.datetime.fromtimestamp(
  53. float(event.origin_server_ts) / 1000
  54. ).strftime('%Y-%m-%d %H:%M:%S,%f')
  55. content = json.dumps(unfreeze(event.get_dict()["content"]))
  56. label = (
  57. "<"
  58. "<b>%(name)s </b><br/>"
  59. "Type: <b>%(type)s </b><br/>"
  60. "State key: <b>%(state_key)s </b><br/>"
  61. "Content: <b>%(content)s </b><br/>"
  62. "Time: <b>%(time)s </b><br/>"
  63. "Depth: <b>%(depth)s </b><br/>"
  64. "State group: %(state_group)s<br/>"
  65. ">"
  66. ) % {
  67. "name": event.event_id,
  68. "type": event.type,
  69. "state_key": event.get("state_key", None),
  70. "content": cgi.escape(content, quote=True),
  71. "time": t,
  72. "depth": event.depth,
  73. "state_group": state_group,
  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. for event in events:
  82. for prev_id, _ in event.prev_events:
  83. try:
  84. end_node = node_map[prev_id]
  85. except:
  86. end_node = pydot.Node(
  87. name=prev_id,
  88. label="<<b>%s</b>>" % (prev_id,),
  89. )
  90. node_map[prev_id] = end_node
  91. graph.add_node(end_node)
  92. edge = pydot.Edge(node_map[event.event_id], end_node)
  93. graph.add_edge(edge)
  94. for group, event_ids in state_groups.items():
  95. if len(event_ids) <= 1:
  96. continue
  97. cluster = pydot.Cluster(
  98. str(group),
  99. label="<State Group: %s>" % (str(group),)
  100. )
  101. for event_id in event_ids:
  102. cluster.add_node(node_map[event_id])
  103. graph.add_subgraph(cluster)
  104. graph.write('%s.dot' % file_prefix, format='raw', prog='dot')
  105. graph.write_svg("%s.svg" % file_prefix, prog='dot')
  106. if __name__ == "__main__":
  107. parser = argparse.ArgumentParser(
  108. description="Generate a PDU graph for a given room by talking "
  109. "to the given homeserver to get the list of PDUs. \n"
  110. "Requires pydot."
  111. )
  112. parser.add_argument(
  113. "-p", "--prefix", dest="prefix",
  114. help="String to prefix output files with",
  115. default="graph_output"
  116. )
  117. parser.add_argument(
  118. "-l", "--limit",
  119. help="Only retrieve the last N events.",
  120. )
  121. parser.add_argument('db')
  122. parser.add_argument('room')
  123. args = parser.parse_args()
  124. make_graph(args.db, args.room, args.prefix, args.limit)