MySQL 9.2.0
Source Code Documentation
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
metadata_cache.h
Go to the documentation of this file.
1/*
2 Copyright (c) 2016, 2024, 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 /** @brief Returns list of managed servers in a cluster
101 *
102 *
103 * @return std::vector containing ManagedInstance objects
104 */
105 metadata_cache::cluster_nodes_list_t get_cluster_nodes();
106
107 /** @brief Returns object containing current Cluster Topology
108 */
109 metadata_cache::ClusterTopology get_cluster_topology();
110
111 /** Wait until cluster PRIMARY changes.
112 *
113 * wait until a change of the PRIMARY is noticed
114 *
115 * leave early if
116 *
117 * - 'timeout' expires
118 * - process shutdown is requested
119 *
120 * function has to handle two scenarios:
121 *
122 * connection to PRIMARY fails because:
123 *
124 * 1. PRIMARY died and group relects a new member
125 * 2. network to PRIMARY lost, but GR sees no fault and PRIMARY does not
126 * change.
127 *
128 * Therefore, if the connection to PRIMARY fails, wait for change of the
129 * membership or timeout, whatever happens earlier.
130 *
131 * @param server_uuid server-uuid of the PRIMARY that we failed to connect
132 * @param timeout - amount of time to wait for a failover
133 * @return true if a primary member exists
134 */
135 bool wait_primary_failover(const std::string &server_uuid,
137
138 /** @brief refresh cluster information */
139 void refresh_thread();
140
141 /** @brief run refresh thread */
142 static void *run_thread(void *context);
143
144 /**
145 * @brief Register observer that is notified when there is a change in the
146 * cluster nodes setup/state discovered.
147 *
148 * @param listener Observer object that is notified when cluster nodes
149 * state is changed.
150 */
153
154 /**
155 * @brief Unregister observer previously registered with add_state_listener()
156 *
157 * @param listener Observer object that should be unregistered.
158 */
161
162 /**
163 * @brief Register observer that is notified when the state of listening
164 * socket acceptors should be updated on the next metadata refresh.
165 *
166 * @param listener Observer object that is notified when replicaset nodes
167 * state is changed.
168 */
169 void add_acceptor_handler_listener(
171
172 /**
173 * @brief Unregister observer previously registered with
174 * add_acceptor_handler_listener()
175 *
176 * @param listener Observer object that should be unregistered.
177 */
178 void remove_acceptor_handler_listener(
180
181 /**
182 * @brief Register observer that is notified on each metadata refresh event.
183 *
184 * @param listener Observer object that is notified on md refresh.
185 */
186 void add_md_refresh_listener(
188
189 /**
190 * @brief Unregister observer previously registered with
191 * add_md_refresh_listener()
192 *
193 * @param listener Observer object that should be unregistered.
194 */
195 void remove_md_refresh_listener(
197
199 return stats_([](auto const &stats)
201 return {stats.refresh_failed,
202 stats.refresh_succeeded,
203 stats.last_refresh_succeeded,
204 stats.last_refresh_failed,
205 stats.last_metadata_server_host,
206 stats.last_metadata_server_port};
207 });
208 }
209
210 std::chrono::milliseconds ttl() const { return ttl_config_.ttl; }
211 mysqlrouter::TargetCluster target_cluster() const { return target_cluster_; }
212
213 virtual mysqlrouter::ClusterType cluster_type() const noexcept = 0;
214
215 void enable_fetch_auth_metadata() { auth_metadata_fetch_enabled_ = true; }
216
217 void force_cache_update() { on_refresh_requested(); }
218
219 void check_auth_metadata_timers() const;
220
221 std::pair<bool, MetaData::auth_credentials_t::mapped_type>
222 get_rest_user_auth_data(const std::string &user);
223
224 /**
225 * Toggle socket acceptors state update on next metadata refresh.
226 */
228 trigger_acceptor_update_on_next_refresh_ = true;
229 }
230
231 void add_routing_guidelines_update_callbacks(
233 update_callback,
235 on_routing_guidelines_change_callback);
236
237 void clear_routing_guidelines_update_callbacks();
238
239 void add_router_info_update_callback(
241
242 void clear_router_info_update_callback();
243
244 protected:
245 /** @brief Refreshes the cache
246 *
247 */
248 virtual bool refresh(bool needs_writable_node) = 0;
249
250 void on_refresh_failed(bool terminated, bool md_servers_reachable = false);
251 void on_refresh_succeeded(
252 const metadata_cache::metadata_server_t &metadata_server);
253
254 // Called each time the metadata has changed and we need to notify
255 // the subscribed observers
256 void on_instances_changed(const bool md_servers_reachable,
257 uint64_t view_id = 0);
258
259 /**
260 * Called when the listening sockets acceptors state should be updated but
261 * replicaset instances has not changed (in that case socket acceptors would
262 * be handled when calling on_instances_changed).
263 */
264 void on_handle_sockets_acceptors();
265
266 /**
267 * Called on each metadata refresh.
268 *
269 * @param[in] cluster_nodes_changed Information whether there was a change
270 * in instances reported by metadata refresh.
271 * @param[in] routing_guidelines_doc Routing guidelines document fetched from
272 * metadata, used by the guidelines engine.
273 */
274 void on_md_refresh(const bool cluster_nodes_changed,
275 const std::string &routing_guidelines_doc);
276
277 // Called each time we were requested to refresh the metadata
278 void on_refresh_requested();
279
280 // Called each time the metadata refresh completed execution
281 void on_refresh_completed();
282
283 // Update rest users authentication data
284 bool update_auth_cache();
285
286 // Update current Router attributes in the metadata
287 void update_router_attributes();
288
289 // Update Router last_check_in timestamp in the metadata
290 void update_router_last_check_in();
291
292 // Report name of the routing guideline that is currently used.
293 void update_reported_routing_guideline_name(
294 const std::string &guideline_name);
295
296 void update_routing_guidelines(const std::string &routing_guidelines_doc);
297
298 // Stores the current cluster state and topology.
300
301 // identifies the Cluster we work with
303
304 // Id of the ClusterSet in case of the ClusterSet setup
305 const std::string clusterset_id_;
306
307 // The list of servers that contain the metadata about the managed
308 // topology.
310
311 // Metadata TTL configuration.
313
314 // SSL options for MySQL connections
316
317 // id of the Router in the cluster metadata
318 unsigned router_id_;
319
321 // Authentication data for the rest users
323
324 std::chrono::system_clock::time_point last_credentials_update_;
325 };
326
327 Monitor<RestAuthData> rest_auth_{{}};
328
329 // Authentication data should be fetched only when metadata_cache is used as
330 // an authentication backend
331 bool auth_metadata_fetch_enabled_{false};
332
333 // Stores the pointer to the transport layer implementation. The transport
334 // layer communicates with the servers storing the metadata and fetches the
335 // topology information.
336 std::shared_ptr<MetaData> meta_data_;
337
338 /** @brief refresh thread facade */
340
341 /** @brief notification thread facade */
343
344 // This mutex is used to ensure that a lookup of the metadata is consistent
345 // with the changes in the metadata due to a cache refresh.
347
348 // This mutex ensures that a refresh of the servers that contain the metadata
349 // is consistent with the use of the server list.
351
352 // Flag used to terminate the refresh thread.
353 std::atomic<bool> terminated_{false};
354
355 bool refresh_requested_{false};
356
358
360
361 std::condition_variable refresh_wait_;
363
364 std::condition_variable refresh_completed_;
366
372
373 std::set<metadata_cache::ClusterStateListenerInterface *> state_listeners_;
374 std::set<metadata_cache::AcceptorUpdateHandlerInterface *>
376 std::set<metadata_cache::MetadataRefreshListenerInterface *>
379 update_routing_guidelines_callback_{nullptr};
383 std::vector<metadata_cache::MetadataCacheAPI::update_router_info_callback_t>
385
386 struct Stats {
387 std::chrono::system_clock::time_point last_refresh_failed;
388 std::chrono::system_clock::time_point last_refresh_succeeded;
389 uint64_t refresh_failed{0};
390 uint64_t refresh_succeeded{0};
391
394 };
395
396 Monitor<Stats> stats_{{}};
397
398 bool initial_attributes_update_done_{false};
399 uint32_t periodic_stats_update_counter_{1};
400 std::chrono::steady_clock::time_point last_periodic_stats_update_timestamp_{
401 std::chrono::steady_clock::now()};
402
403 bool ready_announced_{false};
404
405 /**
406 * Flag indicating if socket acceptors state should be updated on next
407 * metadata refresh even if instance information has not changed.
408 */
409 std::atomic<bool> trigger_acceptor_update_on_next_refresh_{false};
410
412
413 bool needs_initial_attributes_update();
414 bool needs_last_check_in_update();
415
418};
419
421
422/** Gets user readable information string about the nodes attributes
423 * related to _hidden and _disconnect_existing_sessions_when_hidden tags.
424 */
425std::string get_hidden_info(const metadata_cache::ManagedInstance &instance);
426
427namespace metadata_cache {
428
433
434} // namespace metadata_cache
435
436#endif // METADATA_CACHE_METADATA_CACHE_INCLUDED
The ClusterMetadata class encapsulates a connection to the Metadata server.
Definition: cluster_metadata.h:65
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:312
const std::string clusterset_id_
Definition: metadata_cache.h:305
metadata_cache::MetadataCacheAPIBase::RefreshStatus refresh_status()
Definition: metadata_cache.h:198
mysqlrouter::TargetCluster target_cluster_
Definition: metadata_cache.h:302
std::condition_variable refresh_completed_
Definition: metadata_cache.h:364
std::mutex cache_refreshing_mutex_
Definition: metadata_cache.h:346
mysql_harness::MySQLRouterThread refresh_thread_
refresh thread facade
Definition: metadata_cache.h:339
std::mutex cluster_instances_change_callbacks_mtx_
Definition: metadata_cache.h:367
bool use_cluster_notifications_
Definition: metadata_cache.h:357
std::shared_ptr< MetaData > meta_data_
Definition: metadata_cache.h:336
std::chrono::milliseconds ttl() const
Definition: metadata_cache.h:210
std::vector< metadata_cache::MetadataCacheAPI::on_routing_guidelines_change_callback_t > on_routing_guidelines_change_callbacks_
Definition: metadata_cache.h:382
std::string current_routing_guidelines_doc_
Definition: metadata_cache.h:416
metadata_cache::ClusterTopology cluster_topology_
Definition: metadata_cache.h:299
std::set< metadata_cache::ClusterStateListenerInterface * > state_listeners_
Definition: metadata_cache.h:373
bool close_connection_after_refresh_
Definition: metadata_cache.h:359
std::set< metadata_cache::MetadataRefreshListenerInterface * > md_refresh_listeners_
Definition: metadata_cache.h:377
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:384
virtual mysqlrouter::ClusterType cluster_type() const noexcept=0
std::condition_variable refresh_wait_
Definition: metadata_cache.h:361
metadata_cache::RouterAttributes router_attributes_
Definition: metadata_cache.h:411
std::mutex refresh_wait_mtx_
Definition: metadata_cache.h:362
metadata_cache::metadata_servers_list_t metadata_servers_
Definition: metadata_cache.h:309
std::mutex router_info_update_callback_mtx_
Definition: metadata_cache.h:371
std::string last_routing_guidelines_used_
Definition: metadata_cache.h:417
unsigned router_id_
Definition: metadata_cache.h:318
std::mutex metadata_servers_mutex_
Definition: metadata_cache.h:350
std::mutex routing_guidelines_update_callback_mtx_
Definition: metadata_cache.h:370
std::mutex refresh_completed_mtx_
Definition: metadata_cache.h:365
std::mutex md_refresh_callbacks_mtx_
Definition: metadata_cache.h:369
std::mutex acceptor_handler_callbacks_mtx_
Definition: metadata_cache.h:368
mysqlrouter::SSLOptions ssl_options_
Definition: metadata_cache.h:315
void handle_sockets_acceptors_on_md_refresh()
Toggle socket acceptors state update on next metadata refresh.
Definition: metadata_cache.h:227
mysqlrouter::TargetCluster target_cluster() const
Definition: metadata_cache.h:211
void force_cache_update()
Definition: metadata_cache.h:217
std::set< metadata_cache::AcceptorUpdateHandlerInterface * > acceptor_update_listeners_
Definition: metadata_cache.h:375
mysql_harness::MySQLRouterThread notification_thread_
notification thread facade
Definition: metadata_cache.h:342
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:104
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:433
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:420
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:413
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:135
static void start(mysql_harness::PluginFuncEnv *env)
Definition: http_auth_backend_plugin.cc:180
#define METADATA_CACHE_EXPORT
Definition: metadata_cache_export.h:15
char * user
Definition: mysqladmin.cc:67
char server_uuid[UUID_LENGTH+1]
Definition: mysqld.cc:1489
static bool timeout(bool(*wait_condition)())
Timeout function.
Definition: log0meb.cc:498
Definition: metadata_cache.h:49
std::vector< metadata_server_t > metadata_servers_list_t
Definition: metadata_cache_datatypes.h:168
bool operator!=(const metadata_cache::ManagedCluster &cluster_a, const metadata_cache::ManagedCluster &cluster_b)
Definition: metadata_cache.cc:313
std::vector< ManagedInstance > cluster_nodes_list_t
Definition: metadata_cache_datatypes.h:164
bool operator==(const metadata_cache::ManagedCluster &cluster_a, const metadata_cache::ManagedCluster &cluster_b)
Definition: metadata_cache.cc:294
static const size_t kDefaultStackSizeInKiloBytes
Definition: mysql_router_thread.h:44
ClusterType
Definition: cluster_metadata.h:116
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:2876
std::string to_string(metadata_cache::ServerMode mode)
Definition: metadata_cache.cc:341
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:354
Definition: metadata_cache.h:320
MetaData::auth_credentials_t rest_auth_data_
Definition: metadata_cache.h:322
std::chrono::system_clock::time_point last_credentials_update_
Definition: metadata_cache.h:324
Definition: metadata_cache.h:386
uint16_t last_metadata_server_port
Definition: metadata_cache.h:393
std::chrono::system_clock::time_point last_refresh_failed
Definition: metadata_cache.h:387
std::chrono::system_clock::time_point last_refresh_succeeded
Definition: metadata_cache.h:388
std::string last_metadata_server_host
Definition: metadata_cache.h:392
Represents a cluster (a GR group or AR members) and its metadata servers.
Definition: metadata_cache_datatypes.h:207
Metadata TTL configuration.
Definition: metadata_cache.h:203
Definition: metadata_cache_datatypes.h:263
SSL connection related options.
Definition: datatypes.h:34
Definition: mysqlslap.cc:242
double seconds()
Definition: task.cc:314