homeserver.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2014, 2015 OpenMarket Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import sys
  17. sys.dont_write_bytecode = True
  18. from synapse.storage import prepare_database, UpgradeDatabaseException
  19. from synapse.server import HomeServer
  20. from synapse.python_dependencies import check_requirements
  21. from twisted.internet import reactor
  22. from twisted.enterprise import adbapi
  23. from twisted.web.resource import Resource
  24. from twisted.web.static import File
  25. from twisted.web.server import Site
  26. from synapse.http.server import JsonResource, RootRedirect
  27. from synapse.rest.appservice.v1 import AppServiceRestResource
  28. from synapse.rest.media.v0.content_repository import ContentRepoResource
  29. from synapse.rest.media.v1.media_repository import MediaRepositoryResource
  30. from synapse.http.server_key_resource import LocalKey
  31. from synapse.http.matrixfederationclient import MatrixFederationHttpClient
  32. from synapse.api.urls import (
  33. CLIENT_PREFIX, FEDERATION_PREFIX, WEB_CLIENT_PREFIX, CONTENT_REPO_PREFIX,
  34. SERVER_KEY_PREFIX, MEDIA_PREFIX, CLIENT_V2_ALPHA_PREFIX, APP_SERVICE_PREFIX,
  35. STATIC_PREFIX
  36. )
  37. from synapse.config.homeserver import HomeServerConfig
  38. from synapse.crypto import context_factory
  39. from synapse.util.logcontext import LoggingContext
  40. from synapse.rest.client.v1 import ClientV1RestResource
  41. from synapse.rest.client.v2_alpha import ClientV2AlphaRestResource
  42. from daemonize import Daemonize
  43. import twisted.manhole.telnet
  44. import synapse
  45. import logging
  46. import os
  47. import re
  48. import subprocess
  49. import sqlite3
  50. import syweb
  51. logger = logging.getLogger(__name__)
  52. class SynapseHomeServer(HomeServer):
  53. def build_http_client(self):
  54. return MatrixFederationHttpClient(self)
  55. def build_resource_for_client(self):
  56. return ClientV1RestResource(self)
  57. def build_resource_for_client_v2_alpha(self):
  58. return ClientV2AlphaRestResource(self)
  59. def build_resource_for_federation(self):
  60. return JsonResource(self)
  61. def build_resource_for_app_services(self):
  62. return AppServiceRestResource(self)
  63. def build_resource_for_web_client(self):
  64. syweb_path = os.path.dirname(syweb.__file__)
  65. webclient_path = os.path.join(syweb_path, "webclient")
  66. return File(webclient_path) # TODO configurable?
  67. def build_resource_for_static_content(self):
  68. return File("static")
  69. def build_resource_for_content_repo(self):
  70. return ContentRepoResource(
  71. self, self.upload_dir, self.auth, self.content_addr
  72. )
  73. def build_resource_for_media_repository(self):
  74. return MediaRepositoryResource(self)
  75. def build_resource_for_server_key(self):
  76. return LocalKey(self)
  77. def build_db_pool(self):
  78. return adbapi.ConnectionPool(
  79. "sqlite3", self.get_db_name(),
  80. check_same_thread=False,
  81. cp_min=1,
  82. cp_max=1,
  83. cp_openfun=prepare_database, # Prepare the database for each conn
  84. # so that :memory: sqlite works
  85. )
  86. def create_resource_tree(self, web_client, redirect_root_to_web_client):
  87. """Create the resource tree for this Home Server.
  88. This in unduly complicated because Twisted does not support putting
  89. child resources more than 1 level deep at a time.
  90. Args:
  91. web_client (bool): True to enable the web client.
  92. redirect_root_to_web_client (bool): True to redirect '/' to the
  93. location of the web client. This does nothing if web_client is not
  94. True.
  95. """
  96. # list containing (path_str, Resource) e.g:
  97. # [ ("/aaa/bbb/cc", Resource1), ("/aaa/dummy", Resource2) ]
  98. desired_tree = [
  99. (CLIENT_PREFIX, self.get_resource_for_client()),
  100. (CLIENT_V2_ALPHA_PREFIX, self.get_resource_for_client_v2_alpha()),
  101. (FEDERATION_PREFIX, self.get_resource_for_federation()),
  102. (CONTENT_REPO_PREFIX, self.get_resource_for_content_repo()),
  103. (SERVER_KEY_PREFIX, self.get_resource_for_server_key()),
  104. (MEDIA_PREFIX, self.get_resource_for_media_repository()),
  105. (APP_SERVICE_PREFIX, self.get_resource_for_app_services()),
  106. (STATIC_PREFIX, self.get_resource_for_static_content())
  107. ]
  108. if web_client:
  109. logger.info("Adding the web client.")
  110. desired_tree.append((WEB_CLIENT_PREFIX,
  111. self.get_resource_for_web_client()))
  112. if web_client and redirect_root_to_web_client:
  113. self.root_resource = RootRedirect(WEB_CLIENT_PREFIX)
  114. else:
  115. self.root_resource = Resource()
  116. # ideally we'd just use getChild and putChild but getChild doesn't work
  117. # unless you give it a Request object IN ADDITION to the name :/ So
  118. # instead, we'll store a copy of this mapping so we can actually add
  119. # extra resources to existing nodes. See self._resource_id for the key.
  120. resource_mappings = {}
  121. for (full_path, resource) in desired_tree:
  122. logger.info("Attaching %s to path %s", resource, full_path)
  123. last_resource = self.root_resource
  124. for path_seg in full_path.split('/')[1:-1]:
  125. if path_seg not in last_resource.listNames():
  126. # resource doesn't exist, so make a "dummy resource"
  127. child_resource = Resource()
  128. last_resource.putChild(path_seg, child_resource)
  129. res_id = self._resource_id(last_resource, path_seg)
  130. resource_mappings[res_id] = child_resource
  131. last_resource = child_resource
  132. else:
  133. # we have an existing Resource, use that instead.
  134. res_id = self._resource_id(last_resource, path_seg)
  135. last_resource = resource_mappings[res_id]
  136. # ===========================
  137. # now attach the actual desired resource
  138. last_path_seg = full_path.split('/')[-1]
  139. # if there is already a resource here, thieve its children and
  140. # replace it
  141. res_id = self._resource_id(last_resource, last_path_seg)
  142. if res_id in resource_mappings:
  143. # there is a dummy resource at this path already, which needs
  144. # to be replaced with the desired resource.
  145. existing_dummy_resource = resource_mappings[res_id]
  146. for child_name in existing_dummy_resource.listNames():
  147. child_res_id = self._resource_id(existing_dummy_resource,
  148. child_name)
  149. child_resource = resource_mappings[child_res_id]
  150. # steal the children
  151. resource.putChild(child_name, child_resource)
  152. # finally, insert the desired resource in the right place
  153. last_resource.putChild(last_path_seg, resource)
  154. res_id = self._resource_id(last_resource, last_path_seg)
  155. resource_mappings[res_id] = resource
  156. return self.root_resource
  157. def _resource_id(self, resource, path_seg):
  158. """Construct an arbitrary resource ID so you can retrieve the mapping
  159. later.
  160. If you want to represent resource A putChild resource B with path C,
  161. the mapping should looks like _resource_id(A,C) = B.
  162. Args:
  163. resource (Resource): The *parent* Resource
  164. path_seg (str): The name of the child Resource to be attached.
  165. Returns:
  166. str: A unique string which can be a key to the child Resource.
  167. """
  168. return "%s-%s" % (resource, path_seg)
  169. def start_listening(self, secure_port, unsecure_port):
  170. if secure_port is not None:
  171. reactor.listenSSL(
  172. secure_port, Site(self.root_resource), self.tls_context_factory
  173. )
  174. logger.info("Synapse now listening on port %d", secure_port)
  175. if unsecure_port is not None:
  176. reactor.listenTCP(
  177. unsecure_port, Site(self.root_resource)
  178. )
  179. logger.info("Synapse now listening on port %d", unsecure_port)
  180. def get_version_string():
  181. null = open(os.devnull, 'w')
  182. cwd = os.path.dirname(os.path.abspath(__file__))
  183. try:
  184. git_branch = subprocess.check_output(
  185. ['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
  186. stderr=null,
  187. cwd=cwd,
  188. ).strip()
  189. git_branch = "b=" + git_branch
  190. except subprocess.CalledProcessError:
  191. git_branch = ""
  192. try:
  193. git_tag = subprocess.check_output(
  194. ['git', 'describe', '--exact-match'],
  195. stderr=null,
  196. cwd=cwd,
  197. ).strip()
  198. git_tag = "t=" + git_tag
  199. except subprocess.CalledProcessError:
  200. git_tag = ""
  201. try:
  202. git_commit = subprocess.check_output(
  203. ['git', 'rev-parse', '--short', 'HEAD'],
  204. stderr=null,
  205. cwd=cwd,
  206. ).strip()
  207. except subprocess.CalledProcessError:
  208. git_commit = ""
  209. try:
  210. dirty_string = "-this_is_a_dirty_checkout"
  211. is_dirty = subprocess.check_output(
  212. ['git', 'describe', '--dirty=' + dirty_string],
  213. stderr=null,
  214. cwd=cwd,
  215. ).strip().endswith(dirty_string)
  216. git_dirty = "dirty" if is_dirty else ""
  217. except subprocess.CalledProcessError:
  218. git_dirty = ""
  219. if git_branch or git_tag or git_commit or git_dirty:
  220. git_version = ",".join(
  221. s for s in
  222. (git_branch, git_tag, git_commit, git_dirty,)
  223. if s
  224. )
  225. return (
  226. "Synapse/%s (%s)" % (
  227. synapse.__version__, git_version,
  228. )
  229. ).encode("ascii")
  230. return ("Synapse/%s" % (synapse.__version__,)).encode("ascii")
  231. def setup():
  232. config = HomeServerConfig.load_config(
  233. "Synapse Homeserver",
  234. sys.argv[1:],
  235. generate_section="Homeserver"
  236. )
  237. config.setup_logging()
  238. check_requirements()
  239. version_string = get_version_string()
  240. logger.info("Server hostname: %s", config.server_name)
  241. logger.info("Server version: %s", version_string)
  242. if re.search(":[0-9]+$", config.server_name):
  243. domain_with_port = config.server_name
  244. else:
  245. domain_with_port = "%s:%s" % (config.server_name, config.bind_port)
  246. tls_context_factory = context_factory.ServerContextFactory(config)
  247. hs = SynapseHomeServer(
  248. config.server_name,
  249. domain_with_port=domain_with_port,
  250. upload_dir=os.path.abspath("uploads"),
  251. db_name=config.database_path,
  252. tls_context_factory=tls_context_factory,
  253. config=config,
  254. content_addr=config.content_addr,
  255. version_string=version_string,
  256. )
  257. hs.create_resource_tree(
  258. web_client=config.webclient,
  259. redirect_root_to_web_client=True,
  260. )
  261. db_name = hs.get_db_name()
  262. logger.info("Preparing database: %s...", db_name)
  263. try:
  264. with sqlite3.connect(db_name) as db_conn:
  265. prepare_database(db_conn)
  266. except UpgradeDatabaseException:
  267. sys.stderr.write(
  268. "\nFailed to upgrade database.\n"
  269. "Have you checked for version specific instructions in"
  270. " UPGRADES.rst?\n"
  271. )
  272. sys.exit(1)
  273. logger.info("Database prepared in %s.", db_name)
  274. if config.manhole:
  275. f = twisted.manhole.telnet.ShellFactory()
  276. f.username = "matrix"
  277. f.password = "rabbithole"
  278. f.namespace['hs'] = hs
  279. reactor.listenTCP(config.manhole, f, interface='127.0.0.1')
  280. bind_port = config.bind_port
  281. if config.no_tls:
  282. bind_port = None
  283. hs.start_listening(bind_port, config.unsecure_port)
  284. hs.get_pusherpool().start()
  285. hs.get_state_handler().start_caching()
  286. hs.get_datastore().start_profiling()
  287. hs.get_replication_layer().start_get_pdu_cache()
  288. if config.daemonize:
  289. print config.pid_file
  290. daemon = Daemonize(
  291. app="synapse-homeserver",
  292. pid=config.pid_file,
  293. action=run,
  294. auto_close_fds=False,
  295. verbose=True,
  296. logger=logger,
  297. )
  298. daemon.start()
  299. else:
  300. reactor.run()
  301. def run():
  302. with LoggingContext("run"):
  303. reactor.run()
  304. def main():
  305. with LoggingContext("main"):
  306. check_requirements()
  307. setup()
  308. if __name__ == '__main__':
  309. main()