MySQL 26.10.0
Source Code Documentation
metadata_cache.h
Go to the documentation of this file.
1/*
2 Copyright (c) 2016, 2026, Oracle and/or its affiliates.
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License, version 2.0,
6 as published by the Free Software Foundation.
7
8 This program is designed to work with certain software (including
9 but not limited to OpenSSL) that is licensed under separate terms,
10 as designated in a particular file or component or in included license
11 documentation. The authors of MySQL hereby grant you an additional
12 permission to link the program and your derivative works with the
13 separately licensed software that they have either included with
14 the program or referenced in the documentation.
15
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
20
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
24*/
25
26#ifndef METADATA_CACHE_METADATA_CACHE_INCLUDED
27#define METADATA_CACHE_METADATA_CACHE_INCLUDED
28
30
31#include <atomic>
32#include <chrono>
33#include <ctime>
34#include <memory>
35#include <mutex>
36#include <set>
37#include <string>
38
40#include "mysql_router_thread.h"
43
44class ClusterMetadata;
45
46/** @class MetadataCache
47 *
48 * The MetadataCache manages cached information fetched from the
49 * MySQL Server.
50 *
51 */
54 public:
55 /**
56 * Initialize a connection to the MySQL Metadata server.
57 *
58 * @param router_id id of the router in the cluster metadata
59 * @param clusterset_id UUID of the ClusterSet the Cluster belongs to (if
60 * bootstrapped as a ClusterSet, empty otherwise)
61 * @param metadata_servers The servers that store the metadata
62 * @param cluster_metadata metadata of the cluster
63 * @param ttl_config metadata TTL configuration
64 * @param ssl_options SSL related options for connection
65 * @param target_cluster object identifying the Cluster this operation refers
66 * to
67 * @param router_attributes Router attributes to be registered in the metadata
68 * @param thread_stack_size The maximum memory allocated for thread's stack
69 * @param use_cluster_notifications Flag indicating if the metadata cache
70 * should use GR notifications as an additional trigger for metadata refresh
71 * @param close_connection_after_refresh if the connection should be closed
72 * after a refresh.
73 */
75 const unsigned router_id, const std::string &clusterset_id,
76 const std::vector<mysql_harness::TcpDestination> &metadata_servers,
77 std::shared_ptr<MetaData> cluster_metadata,
79 const mysqlrouter::SSLOptions &ssl_options,
80 const mysqlrouter::TargetCluster &target_cluster,
81 const metadata_cache::RouterAttributes &router_attributes,
82 size_t thread_stack_size = mysql_harness::kDefaultStackSizeInKiloBytes,
83 bool use_cluster_notifications = false,
84 bool close_connection_after_refresh = false);
85
86 ~MetadataCache() override;
87
88 /** @brief Starts the Metadata Cache
89 *
90 * Starts the Metadata Cache and launch thread.
91 */
92 void start();
93
94 /** @brief Stops the Metadata Cache
95 *
96 * Stops the Metadata Cache and the launch thread.
97 */
98 void stop() noexcept;
99
100 /** Reapply TLS material for metadata sessions created after this call. */
101 void reload_tls();
102
103 /** @brief Returns list of managed servers in a cluster
104 *
105 *
106 * @return std::vector containing ManagedInstance objects
107 */
108 metadata_cache::cluster_nodes_list_t get_cluster_nodes();
109
110 /** @brief Returns object containing current Cluster Topology
111 */
112 metadata_cache::ClusterTopology get_cluster_topology();
113
114 /** Wait until cluster PRIMARY changes.
115 *
116 * wait until a change of the PRIMARY is noticed
117 *
118 * leave early if
119 *
120 * - 'timeout' expires
121 * - process shutdown is requested
122 *
123 * function has to handle two scenarios:
124 *
125 * connection to PRIMARY fails because:
126 *
127 * 1. PRIMARY died and group relects a new member
128 * 2. network to PRIMARY lost, but GR sees no fault and PRIMARY does not
129 * change.
130 *
131 * Therefore, if the connection to PRIMARY fails, wait for change of the
132 * membership or timeout, whatever happens earlier.
133 *
134 * @param server_uuid server-uuid of the PRIMARY that we failed to connect
135 * @param timeout - amount of time to wait for a failover
136 * @return true if a primary member exists
137 */
138 bool wait_primary_failover(const std::string &server_uuid,
140
141 /** @brief refresh cluster information */
142 void refresh_thread();
143
144 /** @brief run refresh thread */
145 static void *run_thread(void *context);
146
147 /**
148 * @brief Register observer that is notified when there is a change in the
149 * cluster nodes setup/state discovered.
150 *
151 * @param listener Observer object that is notified when cluster nodes
152 * state is changed.
153 */
156
157 /**
158 * @brief Unregister observer previously registered with add_state_listener()
159 *
160 * @param listener Observer object that should be unregistered.
161 */
164
165 /**
166 * @brief Register observer that is notified when the state of listening
167 * socket acceptors should be updated on the next metadata refresh.
168 *
169 * @param listener Observer object that is notified when replicaset nodes
170 * state is changed.
171 */
172 void add_acceptor_handler_listener(
174
175 /**
176 * @brief Unregister observer previously registered with
177 * add_acceptor_handler_listener()
178 *
179 * @param listener Observer object that should be unregistered.
180 */
181 void remove_acceptor_handler_listener(
183
184 /**
185 * @brief Register observer that is notified on each metadata refresh event.
186 *
187 * @param listener Observer object that is notified on md refresh.
188 */
189 void add_md_refresh_listener(
191
192 /**
193 * @brief Unregister observer previously registered with
194 * add_md_refresh_listener()
195 *
196 * @param listener Observer object that should be unregistered.
197 */
198 void remove_md_refresh_listener(
200
202 return stats_([](auto const &stats)
204 return {stats.refresh_failed,
205 stats.refresh_succeeded,
206 stats.last_refresh_succeeded,
207 stats.last_refresh_failed,
208 stats.last_metadata_server_host,
209 stats.last_metadata_server_port};
210 });
211 }
212
213 std::chrono::milliseconds ttl() const { return ttl_config_.ttl; }
214 mysqlrouter::TargetCluster target_cluster() const { return target_cluster_; }
215
217
218 void enable_fetch_auth_metadata() { auth_metadata_fetch_enabled_ = true; }
219
220 void force_cache_update() { on_refresh_requested(); }
221
222 void check_auth_metadata_timers() const;
223
224 std::pair<bool, MetaData::auth_credentials_t::mapped_type>
225 get_rest_user_auth_data(const std::string &user);
226
227 /**
228 * Toggle socket acceptors state update on next metadata refresh.
229 */
231 trigger_acceptor_update_on_next_refresh_ = true;
232 }
233
234 void add_routing_guidelines_update_callbacks(
236 update_callback,
238 on_routing_guidelines_change_callback);
239
240 void clear_routing_guidelines_update_callbacks();
241
242 void add_router_info_update_callback(
244
245 void clear_router_info_update_callback();
246
247 protected:
248 /** @brief Refreshes the cache
249 *
250 */
251 virtual bool refresh(bool needs_writable_node) = 0;
252
253 void on_refresh_failed(bool md_servers_reachable = false);
254 void on_refresh_succeeded(
255 const metadata_cache::metadata_server_t &metadata_server);
256
257 // Called each time the metadata has changed and we need to notify
258 // the subscribed observers
259 void on_instances_changed(const bool md_servers_reachable,
260 uint64_t view_id = 0);
261
262 /**
263 * Called when the listening sockets acceptors state should be updated but
264 * replicaset instances has not changed (in that case socket acceptors would
265 * be handled when calling on_instances_changed).
266 */
267 void on_handle_sockets_acceptors();
268
269 /**
270 * Called on each metadata refresh.
271 *
272 * @param[in] cluster_nodes_changed Information whether there was a change
273 * in instances reported by metadata refresh.
274 * @param[in] routing_guidelines_doc Routing guidelines document fetched from
275 * metadata, used by the guidelines engine.
276 */
277 void on_md_refresh(const bool cluster_nodes_changed,
278 const std::string &routing_guidelines_doc);
279
280 // Called each time we were requested to refresh the metadata
281 void on_refresh_requested();
282
283 // Called each time the metadata refresh completed execution
284 void on_refresh_completed();
285
286 // Update rest users authentication data
287 bool update_auth_cache();
288
289 // Update current Router attributes in the metadata
290 void update_router_attributes();
291
292 // Update Router last_check_in timestamp in the metadata
293 void update_router_last_check_in();
294
295 // Report name of the routing guideline that is currently used.
296 void update_reported_routing_guideline_name(
297 const std::string &guideline_name);
298
299 void update_routing_guidelines(const std::string &routing_guidelines_doc);
300
301 // Stores the current cluster state and topology.
303
304 // identifies the Cluster we work with
306
307 // Id of the ClusterSet in case of the ClusterSet setup
308 const std::string clusterset_id_;
309
310 // The list of servers that contain the metadata about the managed
311 // topology.
313
314 // Metadata TTL configuration.
316
317 // SSL options for MySQL connections
319
320 // id of the Router in the cluster metadata
321 unsigned router_id_;
322
324 // Authentication data for the rest users
326
327 std::chrono::system_clock::time_point last_credentials_update_;
328 };
329
330 Monitor<RestAuthData> rest_auth_{{}};
331
332 // Authentication data should be fetched only when metadata_cache is used as
333 // an authentication backend
334 bool auth_metadata_fetch_enabled_{false};
335
336 // Stores the pointer to the transport layer implementation. The transport
337 // layer communicates with the servers storing the metadata and fetches the
338 // topology information.
339 std::shared_ptr<MetaData> meta_data_;
340
341 /** @brief refresh thread facade */
343
344 /** @brief notification thread facade */
346
347 // This mutex is used to ensure that a lookup of the metadata is consistent
348 // with the changes in the metadata due to a cache refresh.
350
351 // This mutex ensures that a refresh of the servers that contain the metadata
352 // is consistent with the use of the server list.
354
355 // Flag used to terminate the refresh thread.
356 std::atomic<bool> terminated_{false};
357
358 bool refresh_requested_{false};
359
361
363
364 std::condition_variable refresh_wait_;
366
367 std::condition_variable refresh_completed_;
369
375
376 std::set<metadata_cache::ClusterStateListenerInterface *> state_listeners_;
377 std::set<metadata_cache::AcceptorUpdateHandlerInterface *>
379 std::set<metadata_cache::MetadataRefreshListenerInterface *>
382 update_routing_guidelines_callback_{nullptr};
386 std::vector<metadata_cache::MetadataCacheAPI::update_router_info_callback_t>
388
389 struct Stats {
390 std::chrono::system_clock::time_point last_refresh_failed;
391 std::chrono::system_clock::time_point last_refresh_succeeded;
392 uint64_t refresh_failed{0};
393 uint64_t refresh_succeeded{0};
394
397 };
398
399 Monitor<Stats> stats_{{}};
400
401 bool initial_attributes_update_done_{false};
402 uint32_t periodic_stats_update_counter_{1};
403 std::chrono::steady_clock::time_point last_periodic_stats_update_timestamp_{
404 std::chrono::steady_clock::now()};
405
406 bool ready_announced_{false};
407
408 /**
409 * Flag indicating if socket acceptors state should be updated on next
410 * metadata refresh even if instance information has not changed.
411 */
412 std::atomic<bool> trigger_acceptor_update_on_next_refresh_{false};
413
415
416 bool needs_initial_attributes_update();
417 bool needs_last_check_in_update();
418
421};
422
424
425/** Gets user readable information string about the nodes attributes
426 * related to _hidden and _disconnect_existing_sessions_when_hidden tags.
427 */
428std::string get_hidden_info(const metadata_cache::ManagedInstance &instance);
429
430namespace metadata_cache {
431
436
437} // namespace metadata_cache
438
439#endif // METADATA_CACHE_METADATA_CACHE_INCLUDED
The ClusterMetadata class encapsulates a connection to the Metadata server.
Definition: cluster_metadata.h:67
std::map< std::string, std::pair< std::string, JsonDocument > > auth_credentials_t
Definition: metadata.h:58
The MetadataCache manages cached information fetched from the MySQL Server.
Definition: metadata_cache.h:53
metadata_cache::MetadataCacheTTLConfig ttl_config_
Definition: metadata_cache.h:315
const std::string clusterset_id_
Definition: metadata_cache.h:308
metadata_cache::MetadataCacheAPIBase::RefreshStatus refresh_status()
Definition: metadata_cache.h:201
mysqlrouter::TargetCluster target_cluster_
Definition: metadata_cache.h:305
std::condition_variable refresh_completed_
Definition: metadata_cache.h:367
std::mutex cache_refreshing_mutex_
Definition: metadata_cache.h:349
mysql_harness::MySQLRouterThread refresh_thread_
refresh thread facade
Definition: metadata_cache.h:342
std::mutex cluster_instances_change_callbacks_mtx_
Definition: metadata_cache.h:370
bool use_cluster_notifications_
Definition: metadata_cache.h:360
std::shared_ptr< MetaData > meta_data_
Definition: metadata_cache.h:339
std::chrono::milliseconds ttl() const
Definition: metadata_cache.h:213
std::vector< metadata_cache::MetadataCacheAPI::on_routing_guidelines_change_callback_t > on_routing_guidelines_change_callbacks_
Definition: metadata_cache.h:385
std::string current_routing_guidelines_doc_
Definition: metadata_cache.h:419
metadata_cache::ClusterTopology cluster_topology_
Definition: metadata_cache.h:302
std::set< metadata_cache::ClusterStateListenerInterface * > state_listeners_
Definition: metadata_cache.h:376
bool close_connection_after_refresh_
Definition: metadata_cache.h:362
std::set< metadata_cache::MetadataRefreshListenerInterface * > md_refresh_listeners_
Definition: metadata_cache.h:380
virtual bool refresh(bool needs_writable_node)=0
Refreshes the cache.
std::vector< metadata_cache::MetadataCacheAPI::update_router_info_callback_t > update_router_info_callbacks_
Definition: metadata_cache.h:387
virtual mysqlrouter::ClusterType cluster_type() const noexcept=0
std::condition_variable refresh_wait_
Definition: metadata_cache.h:364
metadata_cache::RouterAttributes router_attributes_
Definition: metadata_cache.h:414
std::mutex refresh_wait_mtx_
Definition: metadata_cache.h:365
metadata_cache::metadata_servers_list_t metadata_servers_
Definition: metadata_cache.h:312
std::mutex router_info_update_callback_mtx_
Definition: metadata_cache.h:374
std::string last_routing_guidelines_used_
Definition: metadata_cache.h:420
unsigned router_id_
Definition: metadata_cache.h:321
std::mutex metadata_servers_mutex_
Definition: metadata_cache.h:353
std::mutex routing_guidelines_update_callback_mtx_
Definition: metadata_cache.h:373
std::mutex refresh_completed_mtx_
Definition: metadata_cache.h:368
std::mutex md_refresh_callbacks_mtx_
Definition: metadata_cache.h:372
std::mutex acceptor_handler_callbacks_mtx_
Definition: metadata_cache.h:371
mysqlrouter::SSLOptions ssl_options_
Definition: metadata_cache.h:318
void handle_sockets_acceptors_on_md_refresh()
Toggle socket acceptors state update on next metadata refresh.
Definition: metadata_cache.h:230
mysqlrouter::TargetCluster target_cluster() const
Definition: metadata_cache.h:214
void force_cache_update()
Definition: metadata_cache.h:220
std::set< metadata_cache::AcceptorUpdateHandlerInterface * > acceptor_update_listeners_
Definition: metadata_cache.h:378
mysql_harness::MySQLRouterThread notification_thread_
notification thread facade
Definition: metadata_cache.h:345
Monitor pattern.
Definition: monitor.h:39
Abstract class that provides interface for listener on whether the listening sockets acceptors state ...
Definition: metadata_cache.h:109
Abstract class that provides interface for listener on cluster status changes.
Definition: metadata_cache.h:82
Abstract class that provides interface for adding and removing observers on cluster status changes.
Definition: metadata_cache.h:167
virtual void add_state_listener(ClusterStateListenerInterface *listener)=0
Register observer that is notified when there is a change in the cluster nodes setup/state discovered...
virtual void remove_state_listener(ClusterStateListenerInterface *listener)=0
Unregister observer previously registered with add_state_listener()
Class ManagedInstance represents a server managed by the topology.
Definition: metadata_cache_datatypes.h:108
std::function< void(const routing_guidelines::Router_info &)> update_router_info_callback_t
Callback used to update the router information used by the routing guidelines engine.
Definition: metadata_cache.h:436
std::function< void(const routing_guidelines::Routing_guidelines_engine::RouteChanges &)> on_routing_guidelines_change_callback_t
Callback used to verify existing connections according to the new routing guidelines.
Definition: metadata_cache.h:423
std::function< routing_guidelines::Routing_guidelines_engine::RouteChanges(const std::string &)> update_routing_guidelines_callback_t
Callback which is going to update the routing guidelines used by the routing guidelines engine.
Definition: metadata_cache.h:416
Abstract class that provides interface for listener on metadata refresh.
Definition: metadata_cache.h:134
MySQLRouterThread provides higher level interface to managing threads.
Definition: mysql_router_thread.h:80
Definition: destination.h:40
Definition: cluster_metadata.h:179
static void start(mysql_harness::PluginFuncEnv *env)
Definition: http_auth_backend_plugin.cc:180
#define METADATA_CACHE_EXPORT
Definition: metadata_cache_export.h:15
static void stop(mysql_harness::PluginFuncEnv *)
Definition: mysql_rest_service_plugin.cc:413
char * user
Definition: mysqladmin.cc:67
char server_uuid[UUID_LENGTH+1]
Definition: mysqld.cc:1508
static bool timeout(bool(*wait_condition)())
Timeout function.
Definition: log0meb.cc:499
Definition: metadata_cache.h:49
std::vector< metadata_server_t > metadata_servers_list_t
Definition: metadata_cache_datatypes.h:178
bool operator!=(const metadata_cache::ManagedCluster &cluster_a, const metadata_cache::ManagedCluster &cluster_b)
Definition: metadata_cache.cc:333
std::vector< ManagedInstance > cluster_nodes_list_t
Definition: metadata_cache_datatypes.h:174
bool operator==(const metadata_cache::ManagedCluster &cluster_a, const metadata_cache::ManagedCluster &cluster_b)
Definition: metadata_cache.cc:314
std::chrono::seconds seconds
Definition: authorize_manager.cc:71
std::chrono::milliseconds milliseconds
Definition: authorize_manager.cc:70
noexcept
The return type for any call_and_catch(f, args...) call where f(args...) returns Type.
Definition: call_and_catch.h:76
static const size_t kDefaultStackSizeInKiloBytes
Definition: mysql_router_thread.h:44
ClusterType
Definition: cluster_metadata.h:157
ServerMode
Definition: datatypes.h:50
mode
Definition: file_handle.h:61
std::vector< T, ut::allocator< T > > vector
Specialization of vector which uses allocator.
Definition: ut0new.h:2724
std::string to_string(metadata_cache::ServerMode mode)
Definition: metadata_cache.cc:361
std::string get_hidden_info(const metadata_cache::ManagedInstance &instance)
Gets user readable information string about the nodes attributes related to _hidden and _disconnect_e...
Definition: metadata_cache.cc:374
Definition: metadata_cache.h:323
MetaData::auth_credentials_t rest_auth_data_
Definition: metadata_cache.h:325
std::chrono::system_clock::time_point last_credentials_update_
Definition: metadata_cache.h:327
Definition: metadata_cache.h:389
uint16_t last_metadata_server_port
Definition: metadata_cache.h:396
std::chrono::system_clock::time_point last_refresh_failed
Definition: metadata_cache.h:390
std::chrono::system_clock::time_point last_refresh_succeeded
Definition: metadata_cache.h:391
std::string last_metadata_server_host
Definition: metadata_cache.h:395
Represents a cluster (a GR group or AR members) and its metadata servers.
Definition: metadata_cache_datatypes.h:217
Metadata TTL configuration.
Definition: metadata_cache.h:203
Definition: metadata_cache_datatypes.h:273
SSL connection related options.
Definition: datatypes.h:34
Definition: mysqlslap.cc:243