You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

210 lines
7.6 KiB

  1. # Copyright 2019 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. import os
  15. import re
  16. import threading
  17. from typing import Callable, Dict
  18. from ._base import Config, ConfigError
  19. # The prefix for all cache factor-related environment variables
  20. _CACHE_PREFIX = "SYNAPSE_CACHE_FACTOR"
  21. # Map from canonicalised cache name to cache.
  22. _CACHES = {} # type: Dict[str, Callable[[float], None]]
  23. # a lock on the contents of _CACHES
  24. _CACHES_LOCK = threading.Lock()
  25. _DEFAULT_FACTOR_SIZE = 0.5
  26. _DEFAULT_EVENT_CACHE_SIZE = "10K"
  27. class CacheProperties:
  28. def __init__(self):
  29. # The default factor size for all caches
  30. self.default_factor_size = float(
  31. os.environ.get(_CACHE_PREFIX, _DEFAULT_FACTOR_SIZE)
  32. )
  33. self.resize_all_caches_func = None
  34. properties = CacheProperties()
  35. def _canonicalise_cache_name(cache_name: str) -> str:
  36. """Gets the canonical form of the cache name.
  37. Since we specify cache names in config and environment variables we need to
  38. ignore case and special characters. For example, some caches have asterisks
  39. in their name to denote that they're not attached to a particular database
  40. function, and these asterisks need to be stripped out
  41. """
  42. cache_name = re.sub(r"[^A-Za-z_1-9]", "", cache_name)
  43. return cache_name.lower()
  44. def add_resizable_cache(
  45. cache_name: str, cache_resize_callback: Callable[[float], None]
  46. ):
  47. """Register a cache that's size can dynamically change
  48. Args:
  49. cache_name: A reference to the cache
  50. cache_resize_callback: A callback function that will be ran whenever
  51. the cache needs to be resized
  52. """
  53. # Some caches have '*' in them which we strip out.
  54. cache_name = _canonicalise_cache_name(cache_name)
  55. # sometimes caches are initialised from background threads, so we need to make
  56. # sure we don't conflict with another thread running a resize operation
  57. with _CACHES_LOCK:
  58. _CACHES[cache_name] = cache_resize_callback
  59. # Ensure all loaded caches are sized appropriately
  60. #
  61. # This method should only run once the config has been read,
  62. # as it uses values read from it
  63. if properties.resize_all_caches_func:
  64. properties.resize_all_caches_func()
  65. class CacheConfig(Config):
  66. section = "caches"
  67. _environ = os.environ
  68. @staticmethod
  69. def reset():
  70. """Resets the caches to their defaults. Used for tests."""
  71. properties.default_factor_size = float(
  72. os.environ.get(_CACHE_PREFIX, _DEFAULT_FACTOR_SIZE)
  73. )
  74. properties.resize_all_caches_func = None
  75. with _CACHES_LOCK:
  76. _CACHES.clear()
  77. def generate_config_section(self, **kwargs):
  78. return """\
  79. ## Caching ##
  80. # Caching can be configured through the following options.
  81. #
  82. # A cache 'factor' is a multiplier that can be applied to each of
  83. # Synapse's caches in order to increase or decrease the maximum
  84. # number of entries that can be stored.
  85. # The number of events to cache in memory. Not affected by
  86. # caches.global_factor.
  87. #
  88. #event_cache_size: 10K
  89. caches:
  90. # Controls the global cache factor, which is the default cache factor
  91. # for all caches if a specific factor for that cache is not otherwise
  92. # set.
  93. #
  94. # This can also be set by the "SYNAPSE_CACHE_FACTOR" environment
  95. # variable. Setting by environment variable takes priority over
  96. # setting through the config file.
  97. #
  98. # Defaults to 0.5, which will half the size of all caches.
  99. #
  100. #global_factor: 1.0
  101. # A dictionary of cache name to cache factor for that individual
  102. # cache. Overrides the global cache factor for a given cache.
  103. #
  104. # These can also be set through environment variables comprised
  105. # of "SYNAPSE_CACHE_FACTOR_" + the name of the cache in capital
  106. # letters and underscores. Setting by environment variable
  107. # takes priority over setting through the config file.
  108. # Ex. SYNAPSE_CACHE_FACTOR_GET_USERS_WHO_SHARE_ROOM_WITH_USER=2.0
  109. #
  110. # Some caches have '*' and other characters that are not
  111. # alphanumeric or underscores. These caches can be named with or
  112. # without the special characters stripped. For example, to specify
  113. # the cache factor for `*stateGroupCache*` via an environment
  114. # variable would be `SYNAPSE_CACHE_FACTOR_STATEGROUPCACHE=2.0`.
  115. #
  116. per_cache_factors:
  117. #get_users_who_share_room_with_user: 2.0
  118. """
  119. def read_config(self, config, **kwargs):
  120. self.event_cache_size = self.parse_size(
  121. config.get("event_cache_size", _DEFAULT_EVENT_CACHE_SIZE)
  122. )
  123. self.cache_factors = {} # type: Dict[str, float]
  124. cache_config = config.get("caches") or {}
  125. self.global_factor = cache_config.get(
  126. "global_factor", properties.default_factor_size
  127. )
  128. if not isinstance(self.global_factor, (int, float)):
  129. raise ConfigError("caches.global_factor must be a number.")
  130. # Set the global one so that it's reflected in new caches
  131. properties.default_factor_size = self.global_factor
  132. # Load cache factors from the config
  133. individual_factors = cache_config.get("per_cache_factors") or {}
  134. if not isinstance(individual_factors, dict):
  135. raise ConfigError("caches.per_cache_factors must be a dictionary")
  136. # Canonicalise the cache names *before* updating with the environment
  137. # variables.
  138. individual_factors = {
  139. _canonicalise_cache_name(key): val
  140. for key, val in individual_factors.items()
  141. }
  142. # Override factors from environment if necessary
  143. individual_factors.update(
  144. {
  145. _canonicalise_cache_name(key[len(_CACHE_PREFIX) + 1 :]): float(val)
  146. for key, val in self._environ.items()
  147. if key.startswith(_CACHE_PREFIX + "_")
  148. }
  149. )
  150. for cache, factor in individual_factors.items():
  151. if not isinstance(factor, (int, float)):
  152. raise ConfigError(
  153. "caches.per_cache_factors.%s must be a number" % (cache,)
  154. )
  155. self.cache_factors[cache] = factor
  156. # Resize all caches (if necessary) with the new factors we've loaded
  157. self.resize_all_caches()
  158. # Store this function so that it can be called from other classes without
  159. # needing an instance of Config
  160. properties.resize_all_caches_func = self.resize_all_caches
  161. def resize_all_caches(self):
  162. """Ensure all cache sizes are up to date
  163. For each cache, run the mapped callback function with either
  164. a specific cache factor or the default, global one.
  165. """
  166. # block other threads from modifying _CACHES while we iterate it.
  167. with _CACHES_LOCK:
  168. for cache_name, callback in _CACHES.items():
  169. new_factor = self.cache_factors.get(cache_name, self.global_factor)
  170. callback(new_factor)