update_synapse_database.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #!/usr/bin/env python
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import argparse
  16. import logging
  17. import sys
  18. import yaml
  19. from matrix_common.versionstring import get_distribution_version_string
  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. logger = logging.getLogger("update_database")
  26. class MockHomeserver(HomeServer):
  27. DATASTORE_CLASS = DataStore
  28. def __init__(self, config, **kwargs):
  29. super(MockHomeserver, self).__init__(
  30. config.server.server_name, reactor=reactor, config=config, **kwargs
  31. )
  32. self.version_string = "Synapse/" + get_distribution_version_string(
  33. "matrix-synapse"
  34. )
  35. def run_background_updates(hs):
  36. store = hs.get_datastores().main
  37. async def run_background_updates():
  38. await store.db_pool.updates.run_background_updates(sleep=False)
  39. # Stop the reactor to exit the script once every background update is run.
  40. reactor.stop()
  41. def run():
  42. # Apply all background updates on the database.
  43. defer.ensureDeferred(
  44. run_as_background_process("background_updates", run_background_updates)
  45. )
  46. reactor.callWhenRunning(run)
  47. reactor.run()
  48. def main():
  49. parser = argparse.ArgumentParser(
  50. description=(
  51. "Updates a synapse database to the latest schema and optionally runs background updates"
  52. " on it."
  53. )
  54. )
  55. parser.add_argument("-v", action="store_true")
  56. parser.add_argument(
  57. "--database-config",
  58. type=argparse.FileType("r"),
  59. required=True,
  60. help="Synapse configuration file, giving the details of the database to be updated",
  61. )
  62. parser.add_argument(
  63. "--run-background-updates",
  64. action="store_true",
  65. required=False,
  66. help="run background updates after upgrading the database schema",
  67. )
  68. args = parser.parse_args()
  69. logging_config = {
  70. "level": logging.DEBUG if args.v else logging.INFO,
  71. "format": "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s",
  72. }
  73. logging.basicConfig(**logging_config)
  74. # Load, process and sanity-check the config.
  75. hs_config = yaml.safe_load(args.database_config)
  76. if "database" not in hs_config:
  77. sys.stderr.write("The configuration file must have a 'database' section.\n")
  78. sys.exit(4)
  79. config = HomeServerConfig()
  80. config.parse_config_dict(hs_config, "", "")
  81. # Instantiate and initialise the homeserver object.
  82. hs = MockHomeserver(config)
  83. # Setup instantiates the store within the homeserver object and updates the
  84. # DB.
  85. hs.setup()
  86. if args.run_background_updates:
  87. run_background_updates(hs)
  88. if __name__ == "__main__":
  89. main()