homeserver.py 15 KB

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