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