update_database 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2019 The Matrix.org Foundation C.I.C.
  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 argparse
  17. import logging
  18. import sys
  19. import yaml
  20. from twisted.internet import defer, reactor
  21. from synapse.config.homeserver import HomeServerConfig
  22. from synapse.metrics.background_process_metrics import run_as_background_process
  23. from synapse.server import HomeServer
  24. from synapse.storage import DataStore
  25. from synapse.storage.engines import create_engine
  26. from synapse.storage.prepare_database import prepare_database
  27. logger = logging.getLogger("update_database")
  28. class MockHomeserver(HomeServer):
  29. DATASTORE_CLASS = DataStore
  30. def __init__(self, config, database_engine, db_conn, **kwargs):
  31. super(MockHomeserver, self).__init__(
  32. config.server_name,
  33. reactor=reactor,
  34. config=config,
  35. database_engine=database_engine,
  36. **kwargs
  37. )
  38. self.database_engine = database_engine
  39. self.db_conn = db_conn
  40. def get_db_conn(self):
  41. return self.db_conn
  42. if __name__ == "__main__":
  43. parser = argparse.ArgumentParser(
  44. description=(
  45. "Updates a synapse database to the latest schema and runs background updates"
  46. " on it."
  47. )
  48. )
  49. parser.add_argument("-v", action='store_true')
  50. parser.add_argument(
  51. "--database-config",
  52. type=argparse.FileType('r'),
  53. required=True,
  54. help="A database config file for either a SQLite3 database or a PostgreSQL one.",
  55. )
  56. args = parser.parse_args()
  57. logging_config = {
  58. "level": logging.DEBUG if args.v else logging.INFO,
  59. "format": "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s",
  60. }
  61. logging.basicConfig(**logging_config)
  62. # Load, process and sanity-check the config.
  63. hs_config = yaml.safe_load(args.database_config)
  64. if "database" not in hs_config:
  65. sys.stderr.write("The configuration file must have a 'database' section.\n")
  66. sys.exit(4)
  67. config = HomeServerConfig()
  68. config.parse_config_dict(hs_config, "", "")
  69. # Create the database engine and a connection to it.
  70. database_engine = create_engine(config.database_config)
  71. db_conn = database_engine.module.connect(
  72. **{
  73. k: v
  74. for k, v in config.database_config.get("args", {}).items()
  75. if not k.startswith("cp_")
  76. }
  77. )
  78. # Update the database to the latest schema.
  79. prepare_database(db_conn, database_engine, config=config)
  80. db_conn.commit()
  81. # Instantiate and initialise the homeserver object.
  82. hs = MockHomeserver(
  83. config,
  84. database_engine,
  85. db_conn,
  86. db_config=config.database_config,
  87. )
  88. # setup instantiates the store within the homeserver object.
  89. hs.setup()
  90. store = hs.get_datastore()
  91. @defer.inlineCallbacks
  92. def run_background_updates():
  93. yield store.run_background_updates(sleep=False)
  94. # Stop the reactor to exit the script once every background update is run.
  95. reactor.stop()
  96. # Apply all background updates on the database.
  97. reactor.callWhenRunning(lambda: run_as_background_process(
  98. "background_updates", run_background_updates
  99. ))
  100. reactor.run()