1
0

graph.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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 argparse
  15. import cgi
  16. import datetime
  17. import json
  18. import urllib.request
  19. from typing import List
  20. import pydot
  21. def make_name(pdu_id: str, origin: str) -> str:
  22. return f"{pdu_id}@{origin}"
  23. def make_graph(pdus: List[dict], filename_prefix: str) -> None:
  24. """
  25. Generate a dot and SVG file for a graph of events in the room based on the
  26. topological ordering by querying a homeserver.
  27. """
  28. pdu_map = {}
  29. node_map = {}
  30. origins = set()
  31. colors = {"red", "green", "blue", "yellow", "purple"}
  32. for pdu in pdus:
  33. origins.add(pdu.get("origin"))
  34. color_map = {color: color for color in colors if color in origins}
  35. colors -= set(color_map.values())
  36. color_map[None] = "black"
  37. for o in origins:
  38. if o in color_map:
  39. continue
  40. try:
  41. c = colors.pop()
  42. color_map[o] = c
  43. except Exception:
  44. print("Run out of colours!")
  45. color_map[o] = "black"
  46. graph = pydot.Dot(graph_name="Test")
  47. for pdu in pdus:
  48. name = make_name(pdu.get("pdu_id"), pdu.get("origin"))
  49. pdu_map[name] = pdu
  50. t = datetime.datetime.fromtimestamp(float(pdu["ts"]) / 1000).strftime(
  51. "%Y-%m-%d %H:%M:%S,%f"
  52. )
  53. label = (
  54. "<"
  55. "<b>%(name)s </b><br/>"
  56. "Type: <b>%(type)s </b><br/>"
  57. "State key: <b>%(state_key)s </b><br/>"
  58. "Content: <b>%(content)s </b><br/>"
  59. "Time: <b>%(time)s </b><br/>"
  60. "Depth: <b>%(depth)s </b><br/>"
  61. ">"
  62. ) % {
  63. "name": name,
  64. "type": pdu.get("pdu_type"),
  65. "state_key": pdu.get("state_key"),
  66. "content": cgi.escape(json.dumps(pdu.get("content")), quote=True),
  67. "time": t,
  68. "depth": pdu.get("depth"),
  69. }
  70. node = pydot.Node(name=name, label=label, color=color_map[pdu.get("origin")])
  71. node_map[name] = node
  72. graph.add_node(node)
  73. for pdu in pdus:
  74. start_name = make_name(pdu.get("pdu_id"), pdu.get("origin"))
  75. for i, o in pdu.get("prev_pdus", []):
  76. end_name = make_name(i, o)
  77. if end_name not in node_map:
  78. print("%s not in nodes" % end_name)
  79. continue
  80. edge = pydot.Edge(node_map[start_name], node_map[end_name])
  81. graph.add_edge(edge)
  82. # Add prev_state edges, if they exist
  83. if pdu.get("prev_state_id") and pdu.get("prev_state_origin"):
  84. prev_state_name = make_name(
  85. pdu.get("prev_state_id"), pdu.get("prev_state_origin")
  86. )
  87. if prev_state_name in node_map:
  88. state_edge = pydot.Edge(
  89. node_map[start_name], node_map[prev_state_name], style="dotted"
  90. )
  91. graph.add_edge(state_edge)
  92. graph.write("%s.dot" % filename_prefix, format="raw", prog="dot")
  93. # graph.write_png("%s.png" % filename_prefix, prog='dot')
  94. graph.write_svg("%s.svg" % filename_prefix, prog="dot")
  95. def get_pdus(host: str, room: str) -> List[dict]:
  96. transaction = json.loads(
  97. urllib.request.urlopen(
  98. f"http://{host}/_matrix/federation/v1/context/{room}/"
  99. ).read()
  100. )
  101. return transaction["pdus"]
  102. if __name__ == "__main__":
  103. parser = argparse.ArgumentParser(
  104. description="Generate a PDU graph for a given room by talking "
  105. "to the given homeserver to get the list of PDUs. \n"
  106. "Requires pydot."
  107. )
  108. parser.add_argument(
  109. "-p", "--prefix", dest="prefix", help="String to prefix output files with"
  110. )
  111. parser.add_argument("host")
  112. parser.add_argument("room")
  113. args = parser.parse_args()
  114. host = args.host
  115. room = args.room
  116. prefix = args.prefix if args.prefix else "%s_graph" % (room)
  117. pdus = get_pdus(host, room)
  118. make_graph(pdus, prefix)