test_rollback_worker.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  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. from typing import List
  15. from unittest import mock
  16. from twisted.test.proto_helpers import MemoryReactor
  17. from synapse.app.generic_worker import GenericWorkerServer
  18. from synapse.server import HomeServer
  19. from synapse.storage.database import LoggingDatabaseConnection
  20. from synapse.storage.prepare_database import PrepareDatabaseException, prepare_database
  21. from synapse.storage.schema import SCHEMA_VERSION
  22. from synapse.types import JsonDict
  23. from synapse.util import Clock
  24. from tests.unittest import HomeserverTestCase
  25. def fake_listdir(filepath: str) -> List[str]:
  26. """
  27. A fake implementation of os.listdir which we can use to mock out the filesystem.
  28. Args:
  29. filepath: The directory to list files for.
  30. Returns:
  31. A list of files and folders in the directory.
  32. """
  33. if filepath.endswith("full_schemas"):
  34. return [str(SCHEMA_VERSION)]
  35. return ["99_add_unicorn_to_database.sql"]
  36. class WorkerSchemaTests(HomeserverTestCase):
  37. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  38. hs = self.setup_test_homeserver(homeserver_to_use=GenericWorkerServer)
  39. return hs
  40. def default_config(self) -> JsonDict:
  41. conf = super().default_config()
  42. # Mark this as a worker app.
  43. conf["worker_app"] = "yes"
  44. conf["instance_map"] = {"main": {"host": "127.0.0.1", "port": 0}}
  45. return conf
  46. def test_rolling_back(self) -> None:
  47. """Test that workers can start if the DB is a newer schema version"""
  48. db_pool = self.hs.get_datastores().main.db_pool
  49. db_conn = LoggingDatabaseConnection(
  50. db_pool._db_pool.connect(),
  51. db_pool.engine,
  52. "tests",
  53. )
  54. cur = db_conn.cursor()
  55. cur.execute("UPDATE schema_version SET version = ?", (SCHEMA_VERSION + 1,))
  56. db_conn.commit()
  57. prepare_database(db_conn, db_pool.engine, self.hs.config)
  58. def test_not_upgraded_old_schema_version(self) -> None:
  59. """Test that workers don't start if the DB has an older schema version"""
  60. db_pool = self.hs.get_datastores().main.db_pool
  61. db_conn = LoggingDatabaseConnection(
  62. db_pool._db_pool.connect(),
  63. db_pool.engine,
  64. "tests",
  65. )
  66. cur = db_conn.cursor()
  67. cur.execute("UPDATE schema_version SET version = ?", (SCHEMA_VERSION - 1,))
  68. db_conn.commit()
  69. with self.assertRaises(PrepareDatabaseException):
  70. prepare_database(db_conn, db_pool.engine, self.hs.config)
  71. def test_not_upgraded_current_schema_version_with_outstanding_deltas(self) -> None:
  72. """
  73. Test that workers don't start if the DB is on the current schema version,
  74. but there are still outstanding delta migrations to run.
  75. """
  76. db_pool = self.hs.get_datastores().main.db_pool
  77. db_conn = LoggingDatabaseConnection(
  78. db_pool._db_pool.connect(),
  79. db_pool.engine,
  80. "tests",
  81. )
  82. # Set the schema version of the database to the current version
  83. cur = db_conn.cursor()
  84. cur.execute("UPDATE schema_version SET version = ?", (SCHEMA_VERSION,))
  85. db_conn.commit()
  86. # Path `os.listdir` here to make synapse think that there is a migration
  87. # file ready to be run.
  88. # Note that we can't patch this function for the whole method, else Synapse
  89. # will try to find the file when building the database initially.
  90. with mock.patch("os.listdir", mock.Mock(side_effect=fake_listdir)):
  91. with self.assertRaises(PrepareDatabaseException):
  92. # Synapse should think that there is an outstanding migration file due to
  93. # patching 'os.listdir' in the function decorator.
  94. #
  95. # We expect Synapse to raise an exception to indicate the master process
  96. # needs to apply this migration file.
  97. prepare_database(db_conn, db_pool.engine, self.hs.config)