Debian Codegraph @

storage/innobase/log/log0meb.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 2018, 2026, Oracle and/or its affiliates.
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License, version 2.0,
7 as published by the Free Software Foundation.
8
9 This program is designed to work with certain software (including
10 but not limited to OpenSSL) that is licensed under separate terms,
11 as designated in a particular file or component or in included license
12 documentation. The authors of MySQL hereby grant you an additional
13 permission to link the program and your derivative works with the
14 separately licensed software that they have either included with
15 the program or referenced in the documentation.
16
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License, version 2.0, for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26 *****************************************************************************/
27
28 #include "log0meb.h"
29
30 #include <ctype.h>
31 #include <limits.h>
32 #include <cstring>
33 #include <queue>
34 #include <sstream>
35 #include <string>
36 #include <vector>
37
38 #include "mysql/components/services/dynamic_privilege.h"
39 #include "mysql/components/services/udf_registration.h"
40 #include "mysql/plugin.h"
41 #include "mysql/service_plugin_registry.h"
42 #include "sql/mysqld.h"
43 #include "sql/sql_class.h"
44
45 #include "db0err.h"
46 #include "dict0dd.h"
47 #include "ha_innodb.h"
48 #include "log0chkp.h"
49 #include "log0encryption.h"
50 #include "log0files_io.h"
51 #include "log0write.h"
52 #include "os0event.h"
53 #include "os0file.h"
54 #include "os0thread-create.h"
55 #include "sess0sess.h"
56 #include "srv0dynamic_procedures.h"
57 #include "srv0srv.h"
58 #include "sync0sync.h"
59 #include "ut0mutex.h"
60 #include "ut0new.h"
61
62 namespace meb {
63 constexpr const char *innodb_redo_log_archive_privilege{
64 "INNODB_REDO_LOG_ARCHIVE"};
65 constexpr const char *backup_admin_privilege{"BACKUP_ADMIN"};
66 constexpr const char *logmsgpfx{"innodb_redo_log_archive: "};
67 #define LOGMSGPFX std::string(logmsgpfx)
68 constexpr size_t QUEUE_BLOCK_SIZE = 4096;
69 constexpr size_t QUEUE_SIZE_MAX = 16384;
70
71 #ifdef UNIV_PFS_THREAD
72 mysql_pfs_key_t redo_log_archive_consumer_thread_key;
73 #endif /* UNIV_PFS_THREAD */
74
75 #ifdef UNIV_PFS_IO
76 mysql_pfs_key_t redo_log_archive_file_key;
77 #endif /* UNIV_PFS_IO */
78
79 /** Encapsulates a log block of size QUEUE_BLOCK_SIZE, enqueued by the
80 producer, dequeued by the consumer and written into the redo log
81 archive file. */
82 class Block {
83 public:
84 /** Constructor initializes the byte array to all 0's and sets that the log
85 block is not the last log block enqueued (is_final_block = false). */
86 Block() { reset(); }
87
88 /** Destructor initializes the byte array to all 0's and sets that the log
89 block is not the last log block enqueued (is_final_block = false). */
90 ~Block() { reset(); }
91
92 Block &operator=(const Block &) = default;
93
94 /** Resets the data in the log block, initializing the byte array to all 0's
95 and sets that the block is not the last log block enqueued
96 (is_final_block = false) */
97 void reset() {
98 memset(m_block, 0, QUEUE_BLOCK_SIZE);
99 m_is_final_block = false;
100 m_is_flush_block = false;
101 m_offset = 0;
102 }
103
104 /** Get the byte array of size QUEUE_BLOCK_SIZE associated with this
105 object.
106
107 @retval byte[] The byte array of size QUEUE_BLOCK_SIZE in this
108 object. */
109 [[nodiscard]] const byte *get_queue_block() const { return m_block; }
110
111 /** Copy a log block from the given position inside the input byte array. Note
112 that a complete log block is of size OS_FILE_LOG_BLOCK_SIZE. A log block
113 could also be of size less than OS_FILE_LOG_BLOCK_SIZE, in which case it
114 is overwritten in the next iteration of log writing by InnoDB.
115
116 @param[in] block The byte array containing the log block to be stored in
117 this log block object.
118 @param[in] pos The position inside the byte array from which a log block
119 should be copied.
120
121 @retval true if a complete redo log block (multiple of
122 OS_FILE_LOG_BLOCK_SIZE) was copied.
123 @retval false otherwise. */
124 [[nodiscard]] bool put_log_block(const byte block[], const size_t pos) {
125 ut_ad(!full());
126
127 size_t size = log_block_get_data_len(block + pos);
128
129 /* if the incoming log block is empty */
130 if (size == 0) {
131 return false; /* purecov: inspected */
132 }
133
134 memcpy(m_block + m_offset, block + pos, OS_FILE_LOG_BLOCK_SIZE);
135
136 /* If the incoming log block is complete. */
137 if (size == OS_FILE_LOG_BLOCK_SIZE) {
138 m_offset += size;
139 return true;
140 }
141 return false;
142 }
143
144 /** Return the is_final_block flag.
145
146 @retval true if the is_final_block flag is true.
147 false if the is_final_block flag is false. */
148 [[nodiscard]] bool get_is_final_block() const { return m_is_final_block; }
149
150 /** Set the is_final_block flag.
151
152 @param[in] is_final_block the state of the is_final_block flag. */
153 void set_is_final_block(const bool is_final_block) {
154 m_is_final_block = is_final_block;
155 }
156
157 /** Return if the log block is full.
158
159 Condition is (m_offset == QUEUE_BLOCK_SIZE). Since we increment
160 m_offset by OS_FILE_LOG_BLOCK_SIZE only, the equivalent condition
161 is (m_offset > QUEUE_BLOCK_SIZE - OS_FILE_LOG_BLOCK_SIZE). The
162 latter one convinces the fortify tool, that we will never overrun
163 the buffer, while the first one is insufficient for the tool.
164
165 @retval true if the log block has QUEUE_BLOCK_SIZE bytes.
166 @retval false otherwise. */
167 [[nodiscard]] bool full() const {
168 return (m_offset > QUEUE_BLOCK_SIZE - OS_FILE_LOG_BLOCK_SIZE);
169 }
170
171 /// Whether this block is a flush block. A flush block is made from
172 /// the current temporary block redo_log_archive_tmp_block on a flush
173 /// request. A flush block may be full or not, depending on the
174 /// current work of the "producer". To avoid races set this variable
175 /// only under the log writer mutex. The "consumer" shall not update
176 /// its file write offset when it writes a flush block. The next
177 /// regular block shall overwrite it.
178 bool m_is_flush_block{false};
179
180 private:
181 /** The bytes in the log block object. */
182 byte m_block[QUEUE_BLOCK_SIZE];
183 /** Offset inside the byte array of the log block object at which the next
184 redo log block should be written. */
185 size_t m_offset{0};
186 /** Flag indicating if this is the last block enqueued by the producer. */
187 bool m_is_final_block{false};
188 };
189
190 /** This template class implements a queue that,
191
192 1. Implements a Ring Buffer.
193 1.1 The ring buffer can store QUEUE_SIZE_MAX elements.
194 1.2 Each element of the ring buffer stores log blocks of size
195 QUEUE_BLOCK_SIZE.
196 2. Blocks for more data to be enqueued if the queue is empty.
197 3. Blocks for data to be dequeued if the queue is full.
198 4. Is thread safe. */
199 template <typename T>
200 class Queue {
201 public:
202 /** Create the queue with essential objects. */
203 void create() {
204 ut_ad(m_enqueue_event == nullptr);
205 ut_ad(m_dequeue_event == nullptr);
206 ut_ad(m_ring_buffer == nullptr);
207 m_front = -1;
208 m_rear = -1;
209 m_size = 0;
210 m_enqueue_event = os_event_create();
211 m_dequeue_event = os_event_create();
212 mutex_create(LATCH_ID_REDO_LOG_ARCHIVE_QUEUE_MUTEX, &m_mutex);
213 }
214
215 /** Initialize the ring buffer by allocating memory and initialize the
216 indexes of the queue. The initialization is done in a separate
217 method so that the ring buffer is allocated memory only when redo
218 log archiving is started.
219 @param[in] size The size of the ring buffer. */
220 void init(const int size) {
221 mutex_enter(&m_mutex);
222 ut_ad(m_enqueue_event != nullptr);
223 ut_ad(m_dequeue_event != nullptr);
224 ut_ad(m_ring_buffer == nullptr);
225
226 m_front = -1;
227 m_rear = -1;
228 m_size = size;
229
230 m_ring_buffer.reset(new T[m_size]);
231 mutex_exit(&m_mutex);
232 }
233
234 /** Deinitialize the ring buffer by deallocating memory and reset the
235 indexes of the queue. */
236 void deinit() {
237 mutex_enter(&m_mutex);
238 m_ring_buffer.reset();
239 m_front = -1;
240 m_rear = -1;
241 m_size = 0;
242
243 while (m_waiting_for_dequeue || m_waiting_for_enqueue) {
244 /* purecov: begin inspected */
245 if (m_waiting_for_dequeue) os_event_set(m_dequeue_event);
246 if (m_waiting_for_enqueue) os_event_set(m_enqueue_event);
247 mutex_exit(&m_mutex);
248 std::this_thread::yield();
249 mutex_enter(&m_mutex);
250 /* purecov: end */
251 }
252 mutex_exit(&m_mutex);
253 }
254
255 /** Delete the queue and its essential objects. */
256 void drop() {
257 deinit();
258 mutex_enter(&m_mutex);
259 os_event_destroy(m_enqueue_event);
260 os_event_destroy(m_dequeue_event);
261 m_enqueue_event = nullptr;
262 m_dequeue_event = nullptr;
263 mutex_exit(&m_mutex);
264 mutex_free(&m_mutex);
265 }
266
267 /* Enqueue the log block into the queue and update the indexes in the ring
268 buffer.
269
270 @param[in] lb The log block that needs to be enqueued. */
271 void enqueue(const T &lb) {
272 /* Enter the critical section before enqueuing log blocks to ensure thread
273 safe writes. */
274 mutex_enter(&m_mutex);
275
276 /* If the queue is full, wait for a dequeue. */
277 while ((m_ring_buffer != nullptr) && (m_front == ((m_rear + 1) % m_size))) {
278 /* purecov: begin inspected */
279 m_waiting_for_dequeue = true;
280 mutex_exit(&m_mutex);
281 os_event_wait(m_dequeue_event);
282 os_event_reset(m_dequeue_event);
283 mutex_enter(&m_mutex);
284 /* purecov: end */
285 }
286 m_waiting_for_dequeue = false;
287
288 if (m_ring_buffer != nullptr) {
289 /* Perform the insert into the ring buffer and update the indexes. */
290 if (m_front == -1) {
291 m_front = 0;
292 }
293 m_rear = (m_rear + 1) % m_size;
294 m_ring_buffer[m_rear] = lb;
295 os_event_set(m_enqueue_event);
296 }
297
298 mutex_exit(&m_mutex);
299 }
300
301 /** Dequeue the log block from the queue and update the indexes in the ring
302 buffer.
303
304 @param[out] lb The log that was dequeued from the queue. */
305 void dequeue(T &lb) {
306 /* Enter the critical section before dequeuing log blocks to ensure thread
307 safe reads. */
308 mutex_enter(&m_mutex);
309
310 /* If the queue is empty wait for an enqueue. */
311 while ((m_ring_buffer != nullptr) && (m_front == -1)) {
312 m_waiting_for_enqueue = true;
313 mutex_exit(&m_mutex);
314 os_event_wait(m_enqueue_event);
315 os_event_reset(m_enqueue_event);
316 mutex_enter(&m_mutex);
317 }
318 m_waiting_for_enqueue = false;
319
320 if (m_ring_buffer != nullptr) {
321 /* Perform the reads from the ring buffer and update the indexes. */
322 lb = m_ring_buffer[m_front];
323 if (m_front == m_rear) {
324 m_front = -1;
325 m_rear = -1;
326 } else {
327 m_front = (m_front + 1) % m_size;
328 }
329 os_event_set(m_dequeue_event);
330 }
331
332 mutex_exit(&m_mutex);
333 }
334
335 bool empty() { return m_front == -1; }
336
337 private:
338 /** Whether the producer waits for a dequeue event. */
339 bool m_waiting_for_dequeue{false};
340 /** Whether the consumer waits for an enqueue event. */
341 bool m_waiting_for_enqueue{false};
342 /** Index representing the front of the ring buffer. */
343 int m_front{-1};
344 /** Index representing the rear of the ring buffer. */
345 int m_rear{-1};
346 /** The total number of elements in the ring buffer. */
347 int m_size{0};
348
349 /** The buffer containing the contents of the queue. */
350 std::unique_ptr<T[]> m_ring_buffer{};
351
352 /** The queue mutex, used to lock the queue during the enqueue and dequeue
353 operations, to ensure thread safety. */
354 ib_mutex_t m_mutex{};
355
356 /** When the queue is full, enqueue operations wait on this event. When it is
357 set, it indicates that a dequeue has happened and there is space in the
358 queue.*/
359 os_event_t m_dequeue_event{};
360
361 /** When the queue is empty, dequeue operatios wait on this event. When it is
362 set, it indicates that a enqueue operation has happened and there is an
363 element in the queue, that can be dequeued. */
364 os_event_t m_enqueue_event{};
365 };
366
367 /*
368 The Guardian cares for a safe report of control stay in a block. If
369 constructed as a local stack object, it sets the state as true until
370 control leaves the enclosing block. When control leaves the block,
371 regardless how, the Guardian is destructed and it resets the state to
372 false.
373
374 NOTE: The constructor must be called under the mutex!
375 NOTE: The destructor must *NOT* be called under the mutex!
376 */
377 class Guardian {
378 /* Reference to a state flag */
379 bool *m_state;
380 /* Reference to an event. */
381 os_event_t *m_event;
382 /* Reference to a mutex. */
383 ib_mutex_t *m_mutex;
384
385 public:
386 /*
387 Constructor
388 @param[in,out] state state flag to set/reset
389 @param[in,out] event optional event to set when flag is set/reset
390 @param[in,out] mutex mutex to use for reset
391 */
392 Guardian(bool *state, os_event_t *event, ib_mutex_t *mutex)
393 : m_state(state), m_event(event), m_mutex(mutex) {
394 *m_state = true;
395 if ((m_event != nullptr) && (*m_event != nullptr)) {
396 os_event_set(*m_event);
397 }
398 }
399 ~Guardian() {
400 mutex_enter(m_mutex);
401 *m_state = false;
402 if ((m_event != nullptr) && (*m_event != nullptr)) {
403 os_event_set(*m_event);
404 }
405 mutex_exit(m_mutex);
406 }
407 };
408
409 /* The innodb_redo_log_archive_dirs plugin variable value. */
410 char *redo_log_archive_dirs{};
411
412 /*
413 Whether redo_log_archive has already been initialized.
414 This could be read by redo_log_archive_session_end() even before
415 the InnoDB subsystem has started. Hence the atomic qualifier.
416 */
417 static std::atomic<bool> redo_log_archive_initialized{};
418
419 /** Mutex to synchronize start and stop of the redo log archiving. */
420 static ib_mutex_t redo_log_archive_admin_mutex;
421
422 /*
423 CAUTION: Global variables!
424
425 WARNING: To avoid races, all these variables must be read/written
426 under the redo_log_archive_admin_mutex only.
427 */
428
429 /** Boolean indicating whether the redo log archiving is active. */
430 static bool redo_log_archive_active{false};
431
432 /** Session */
433 static innodb_session_t *redo_log_archive_session{};
434 static THD *redo_log_archive_thd{};
435 static bool redo_log_archive_session_ending{false};
436
437 /** Error message recorded during redo log archiving. */
438 static std::string redo_log_archive_recorded_error{};
439
440 /** String containing the redo log archive filename. */
441 static std::string redo_log_archive_file_pathname{};
442
443 /** The file handle to the redo log archive file. */
444 static pfs_os_file_t redo_log_archive_file_handle{};
445
446 /** Whether the consumer thread is running. */
447 static bool redo_log_archive_consume_running{false};
448
449 /** Whether the consumer has completed. */
450 static bool redo_log_archive_consume_complete{true};
451
452 /** Event to inform that the consumer has exited after purging all the queue
453 elements or that it got a flush block. */
454 static os_event_t redo_log_archive_consume_event{};
455
456 /** Whether the consumer has copied a flush block. */
457 static bool redo_log_archive_consume_flushed{false};
458
459 /**
460 Boolean indicating whether to produce queue blocks.
461
462 WARNING: To avoid races, this variable must be read/written
463 under the 'log_sys.writer_mutex' only.
464 */
465 static bool redo_log_archive_produce_blocks{false};
466
467 /**
468 Temporary block used to build complete redo log blocks of size
469 QUEUE_BLOCK_SIZE by the producer.
470
471 WARNING: To avoid races, this variable must be read/written
472 under the 'log_sys.writer_mutex' only.
473 */
474 static Block redo_log_archive_tmp_block{};
475
476 /** Queue into which the producer enqueues redo log blocks of size
477 QUEUE_BLOCK_SIZE, and from which the consumer reads redo log
478 blocks of size QUEUE_BLOCK_SIZE. */
479 static Queue<Block> redo_log_archive_queue{};
480
481 /* Forward declarations */
482 static void redo_log_archive_consumer();
483 static bool terminate_consumer(bool rapid);
484
485 /* Function to check conditions. */
486 static bool consumer_is_running() { return redo_log_archive_consume_running; }
487 static bool consumer_not_running() { return !redo_log_archive_consume_running; }
488 static bool consumer_not_flushed() { return !redo_log_archive_consume_flushed; }
489
490 /**
491 Timeout function. Checks one of the conditions above.
492 @param[in] wait_condition function to return true for continued waiting
493 @return whether the wait timed out
494 @note This function must be called under the redo_log_archive_admin_mutex!
495 */
496 static bool timeout(bool (*wait_condition)()) {
497 float seconds_to_wait{600.0f};
498 DBUG_EXECUTE_IF(
499 "innodb_redo_log_archive_start_timeout",
500 if (wait_condition == &consumer_not_running) seconds_to_wait = 0.125f;);
501 while ((*wait_condition)() && (seconds_to_wait > 0.0f) &&
502 (redo_log_archive_consume_event != nullptr)) {
503 os_event_t consume_event = redo_log_archive_consume_event;
504 mutex_exit(&redo_log_archive_admin_mutex);
505 // Use 0.125 seconds as it can be accurately represented by "float".
506 os_event_wait_time(consume_event, std::chrono::milliseconds{125});
507 seconds_to_wait -= 0.125f;
508 os_event_reset(consume_event);
509 mutex_enter(&redo_log_archive_admin_mutex);
510 }
511 return (seconds_to_wait <= 0.0f);
512 }
513
514 bool register_privilege(const char *priv_name) {
515 ut_ad(priv_name != nullptr);
516 SERVICE_TYPE(registry) *reg = mysql_plugin_registry_acquire();
517 if (reg == nullptr) {
518 /* purecov: begin inspected */
519 LogErr(
520 ERROR_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
521 (LOGMSGPFX + "mysql_plugin_registry_acquire() returns NULL").c_str());
522 return true;
523 /* purecov: end */
524 }
525
526 bool failed = false;
527 // Multiple other implementations use
528 // "dynamic_privilege_register.mysql_server"
529 my_service<SERVICE_TYPE(dynamic_privilege_register)> reg_priv(
530 "dynamic_privilege_register", reg);
531 if (reg_priv.is_valid()) {
532 if (reg_priv->register_privilege(priv_name, strlen(priv_name))) {
533 /* purecov: begin inspected */
534 LogErr(ERROR_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
535 (LOGMSGPFX + "cannot register privilege '" + priv_name + "'")
536 .c_str());
537 failed = true;
538 /* purecov: end */
539 }
540 }
541 mysql_plugin_registry_release(reg);
542 return failed;
543 }
544
545 bool innodb_redo_log_archive_start_init(UDF_INIT *initid [[maybe_unused]],
546 UDF_ARGS *args, char *message);
547 void innodb_redo_log_archive_start_deinit(UDF_INIT *initid [[maybe_unused]]);
548 long long innodb_redo_log_archive_start(UDF_INIT *initid [[maybe_unused]],
549 UDF_ARGS *args,
550 unsigned char *null_value
551 [[maybe_unused]],
552 unsigned char *error [[maybe_unused]]);
553 bool innodb_redo_log_archive_stop_init(UDF_INIT *initid [[maybe_unused]],
554 UDF_ARGS *args, char *message);
555 void innodb_redo_log_archive_stop_deinit(UDF_INIT *initid [[maybe_unused]]);
556 long long innodb_redo_log_archive_stop(UDF_INIT *initid [[maybe_unused]],
557 UDF_ARGS *args [[maybe_unused]],
558 unsigned char *null_value
559 [[maybe_unused]],
560 unsigned char *error [[maybe_unused]]);
561 bool innodb_redo_log_archive_flush_init(UDF_INIT *initid [[maybe_unused]],
562 UDF_ARGS *args, char *message);
563
564 void innodb_redo_log_archive_flush_deinit(UDF_INIT *initid [[maybe_unused]]);
565 long long innodb_redo_log_archive_flush(UDF_INIT *initid [[maybe_unused]],
566 UDF_ARGS *args [[maybe_unused]],
567 unsigned char *null_value
568 [[maybe_unused]],
569 unsigned char *error [[maybe_unused]]);
570 bool innodb_redo_log_sharp_checkpoint_init([[maybe_unused]] UDF_INIT *initid,
571 UDF_ARGS *args, char *message);
572 void innodb_redo_log_sharp_checkpoint_deinit([[maybe_unused]] UDF_INIT *initid);
573 long long innodb_redo_log_sharp_checkpoint(
574 [[maybe_unused]] UDF_INIT *initid, [[maybe_unused]] UDF_ARGS *args,
575 [[maybe_unused]] unsigned char *null_value,
576 [[maybe_unused]] unsigned char *error);
577 bool innodb_redo_log_consumer_register_init([[maybe_unused]] UDF_INIT *initid,
578 UDF_ARGS *args, char *message);
579 void innodb_redo_log_consumer_register_deinit(
580 [[maybe_unused]] UDF_INIT *initid);
581 long long innodb_redo_log_consumer_register(
582 [[maybe_unused]] UDF_INIT *initid, [[maybe_unused]] UDF_ARGS *args,
583 [[maybe_unused]] unsigned char *null_value,
584 [[maybe_unused]] unsigned char *error);
585 bool innodb_redo_log_consumer_unregister_init([[maybe_unused]] UDF_INIT *initid,
586 UDF_ARGS *args, char *message);
587 void innodb_redo_log_consumer_unregister_deinit(
588 [[maybe_unused]] UDF_INIT *initid);
589 long long innodb_redo_log_consumer_unregister(
590 [[maybe_unused]] UDF_INIT *initid, [[maybe_unused]] UDF_ARGS *args,
591 [[maybe_unused]] unsigned char *null_value,
592 [[maybe_unused]] unsigned char *error);
593 bool innodb_redo_log_consumer_advance_init([[maybe_unused]] UDF_INIT *initid,
594 UDF_ARGS *args, char *message);
595 void innodb_redo_log_consumer_advance_deinit([[maybe_unused]] UDF_INIT *initid);
596 long long innodb_redo_log_consumer_advance(
597 [[maybe_unused]] UDF_INIT *initid, UDF_ARGS *args,
598 [[maybe_unused]] unsigned char *null_value,
599 [[maybe_unused]] unsigned char *error);
600
601 /**
602 This component's UDFs.mysql
603 */
604 class Dynamic_procedures : public srv::Dynamic_procedures {
605 protected:
606 std::vector<srv::dynamic_procedure_data_t> get_procedures() const override {
607 return {
608 {"innodb_redo_log_archive_start", innodb_redo_log_archive_start,
609 innodb_redo_log_archive_start_init,
610 innodb_redo_log_archive_start_deinit},
611 {"innodb_redo_log_archive_stop", innodb_redo_log_archive_stop,
612 innodb_redo_log_archive_stop_init,
613 innodb_redo_log_archive_stop_deinit},
614 {"innodb_redo_log_archive_flush", innodb_redo_log_archive_flush,
615 innodb_redo_log_archive_flush_init,
616 innodb_redo_log_archive_flush_deinit},
617 {"innodb_redo_log_sharp_checkpoint", innodb_redo_log_sharp_checkpoint,
618 innodb_redo_log_sharp_checkpoint_init,
619 innodb_redo_log_sharp_checkpoint_deinit},
620 {"innodb_redo_log_consumer_advance", innodb_redo_log_consumer_advance,
621 innodb_redo_log_consumer_advance_init,
622 innodb_redo_log_consumer_advance_deinit},
623 {"innodb_redo_log_consumer_register", innodb_redo_log_consumer_register,
624 innodb_redo_log_consumer_register_init,
625 innodb_redo_log_consumer_register_deinit},
626 {"innodb_redo_log_consumer_unregister",
627 innodb_redo_log_consumer_unregister,
628 innodb_redo_log_consumer_unregister_init,
629 innodb_redo_log_consumer_unregister_deinit}};
630 }
631 std::string get_module_name() const override {
632 return "innodb_redo_log_archive";
633 }
634 };
635
636 Dynamic_procedures s_dynamic_procedures;
637
638 /**
639 Initialize redo log archiving.
640 To be called when the InnoDB handlerton is initialized.
641 */
642 void redo_log_archive_init() {
643 DBUG_TRACE;
644 /* Do not acquire the logwriter mutex at this early stage. */
645 redo_log_archive_produce_blocks = false;
646 if (redo_log_archive_initialized) {
647 redo_log_archive_deinit();
648 }
649 mutex_create(LATCH_ID_REDO_LOG_ARCHIVE_ADMIN_MUTEX,
650 &redo_log_archive_admin_mutex);
651 mutex_enter(&redo_log_archive_admin_mutex);
652 redo_log_archive_active = false;
653 redo_log_archive_session = nullptr;
654 redo_log_archive_thd = nullptr;
655 redo_log_archive_session_ending = false;
656 /* Keep recorded_error */
657 redo_log_archive_file_pathname.clear();
658 redo_log_archive_consume_complete = true;
659 redo_log_archive_file_handle.m_file = OS_FILE_CLOSED;
660 redo_log_archive_queue.create();
661 bool failed = false;
662 if (register_privilege(innodb_redo_log_archive_privilege)) {
663 failed = true;
664 } else if (!s_dynamic_procedures.register_procedures()) {
665 failed = true;
666 }
667 mutex_exit(&redo_log_archive_admin_mutex);
668 redo_log_archive_initialized = true;
669 if (failed) {
670 redo_log_archive_deinit();
671 }
672 }
673
674 /**
675 Drop potential left-over resources to avoid leaks.
676
677 NOTE: This function must be called under the redo_log_archive_admin_mutex!
678
679 @param[in] force whether to drop resources even if
680 consumer cannot be stopped
681 @return status
682 @retval false success
683 @retval true failure
684 */
685 static bool drop_remnants(bool force) {
686 DBUG_TRACE;
687 /* Do not start if a consumer is still lurking around. */
688 if (redo_log_archive_consume_running) {
689 /* purecov: begin inspected */
690 if (!redo_log_archive_recorded_error.empty()) {
691 redo_log_archive_recorded_error.append("; ");
692 }
693 redo_log_archive_recorded_error.append(
694 "Consumer thread did not terminate properly");
695 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
696 (LOGMSGPFX + redo_log_archive_recorded_error).c_str());
697 if (terminate_consumer(/*rapid*/ true) && !force) {
698 return true;
699 }
700 /* purecov: end */
701 }
702 if (redo_log_archive_consume_event != nullptr) {
703 /* purecov: begin inspected */
704 os_event_destroy(redo_log_archive_consume_event);
705 redo_log_archive_consume_event = nullptr;
706 /* purecov: end */
707 }
708 if (redo_log_archive_file_handle.m_file != OS_FILE_CLOSED) {
709 /* purecov: begin inspected */
710 os_file_close(redo_log_archive_file_handle);
711 redo_log_archive_file_handle.m_file = OS_FILE_CLOSED;
712 /* purecov: end */
713 }
714 if (!redo_log_archive_file_pathname.empty()) {
715 /* purecov: begin inspected */
716 os_file_delete_if_exists(redo_log_archive_file_key,
717 redo_log_archive_file_pathname.c_str(), nullptr);
718 /* purecov: end */
719 }
720 return false;
721 }
722
723 /**
724 De-initialize redo log archiving.
725 To be called when the InnoDB handlerton is de-initialized.
726 */
727 void redo_log_archive_deinit() {
728 DBUG_TRACE;
729 if (redo_log_archive_initialized) {
730 redo_log_archive_initialized = false;
731 /* Do not acquire the logwriter mutex at this late stage. */
732 redo_log_archive_produce_blocks = false;
733 /* Unregister the UDFs. */
734 s_dynamic_procedures.unregister();
735 mutex_enter(&redo_log_archive_admin_mutex);
736 if (redo_log_archive_active) {
737 /* purecov: begin inspected */ /* Only needed at shutdown. */
738 terminate_consumer(/*rapid*/ true);
739 /* purecov: end */
740 }
741 drop_remnants(/*force*/ true);
742 redo_log_archive_file_pathname.clear();
743 redo_log_archive_recorded_error.clear();
744 redo_log_archive_session_ending = false;
745 redo_log_archive_thd = nullptr;
746 redo_log_archive_session = nullptr;
747 redo_log_archive_active = false;
748 redo_log_archive_queue.drop();
749 mutex_exit(&redo_log_archive_admin_mutex);
750 mutex_free(&redo_log_archive_admin_mutex);
751 }
752 }
753
754 /**
755 Check whether a valid value is given to innodb_redo_log_archive_dirs.
756 This function is registered as a callback with MySQL.
757 @param[in] thd thread handle
758 @param[in] var pointer to system variable
759 @param[out] save immediate result for update function
760 @param[in] value incoming string
761 @return 0 for valid contents
762 */
763 int validate_redo_log_archive_dirs(THD *thd [[maybe_unused]],
764 SYS_VAR *var [[maybe_unused]], void *save,
765 struct st_mysql_value *value) {
766 ut_a(save != nullptr);
767 ut_a(value != nullptr);
768 char buff[STRING_BUFFER_USUAL_SIZE];
769 int len = sizeof(buff);
770 int ret = 0;
771 const char *irla_dirs = value->val_str(value, buff, &len);
772
773 if (irla_dirs && (irla_dirs == buff)) {
774 irla_dirs = thd_strmake(thd, irla_dirs, len);
775 }
776
777 /* Parse the variable contents. */
778 const char *ptr = irla_dirs;
779 while ((ptr != nullptr) && (*ptr != '\0')) {
780 /* Search colon. */
781 const char *terminator = strchr(ptr, ':');
782 if (terminator == nullptr) {
783 /* No colon contained. */
784 ret = 1;
785 break;
786 }
787 /* Search semi-colon. */
788 ptr = strchr(terminator + 1, ';');
789 if (ptr != nullptr) {
790 if (ptr == terminator + 1) {
791 /* path name is empty. */
792 ret = 1;
793 break;
794 }
795 ptr++;
796 } else {
797 /* No semicolon found. */
798 if (terminator[1] == '\0') {
799 /* Path name is empty. */
800 ret = 1;
801 }
802 }
803 }
804 if (ret == 0) {
805 *static_cast<const char **>(save) = irla_dirs;
806 }
807 return (ret);
808 }
809
810 /**
811 Verify that thd has a certain privilege.
812 @param[in,out] thd current THD instance, current session
813 @param[in] priv_name name of the required privilege
814 @return status
815 @retval false privilege is granted
816 @retval true privilege is denied
817 */
818 static bool verify_privilege(THD *thd, const char *priv_name) {
819 DBUG_TRACE;
820 if (thd == nullptr) {
821 /* service interface does not allow this. */
822 /* purecov: begin inspected */
823 my_error(ER_INVALID_USE_OF_NULL, MYF(0));
824 return true;
825 /* purecov: end */
826 }
827 auto sctx = thd->security_context();
828 if (!(sctx->has_global_grant(priv_name, strlen(priv_name)).first)) {
829 my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), priv_name);
830 return true;
831 }
832 return false;
833 }
834
835 /**
836 Get the directory behind the label in a semi-colon separated list of
837 labeled directories.
838 @param[in] label label for the selected directory; can be empty
839 @param[out] dir directory path name
840 @return status
841 @retval false success
842 @retval true failure
843 */
844 static bool get_labeled_directory(const char *label, std::string *dir) {
845 DBUG_TRACE;
846 DBUG_PRINT("redo_log_archive",
847 ("label: '%s' dirs: '%s'", label, redo_log_archive_dirs));
848 size_t label_len = strlen(label);
849 const char *ptr = redo_log_archive_dirs;
850 while ((ptr != nullptr) && (*ptr != '\0')) {
851 /* Search colon. */
852 const char *terminator = strchr(ptr, ':');
853 if (terminator == nullptr) {
854 /* No colon found - no label. */
855 /* purecov: begin inspected */
856 /* validate_redo_log_archive_dirs prevents this. */
857 ptr = nullptr;
858 break;
859 /* purecov: end */
860 }
861 if (((terminator - ptr) == std::ptrdiff_t(label_len)) &&
862 (0 == strncmp(ptr, label, label_len))) {
863 /* Found the matching label. Set ptr behind the colon. */
864 ptr = terminator + 1;
865 break;
866 }
867 /* Search semi-colon. */
868 ptr = strchr(terminator + 1, ';');
869 if (ptr != nullptr) {
870 ptr++;
871 }
872 }
873 if (ptr == nullptr) {
874 my_error(ER_INNODB_REDO_LOG_ARCHIVE_LABEL_NOT_FOUND, MYF(0), label);
875 return true;
876 }
877 /* Search semi-colon. */
878 const char *terminator = strchr(ptr, ';');
879 if ((terminator == ptr) || (ptr[0] == '\0')) {
880 /* validate_redo_log_archive_dirs() does not allow this. */
881 /* purecov: begin inspected */
882 my_error(ER_INNODB_REDO_LOG_ARCHIVE_DIR_EMPTY, MYF(0), label);
883 return true;
884 /* purecov: end */
885 }
886 dir->assign(ptr, (terminator != nullptr) ? (terminator - ptr) : strlen(ptr));
887 DBUG_PRINT("redo_log_archive", ("dir: '%s'", dir->c_str()));
888 #ifdef DEBUG_REDO_LOG_ARCHIVE_EXTRA_LOG
889 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
890 (LOGMSGPFX + "selected dir '" + dir + "'").c_str());
891 #endif /* DEBUG_REDO_LOG_ARCHIVE_EXTRA_LOG */
892 return false;
893 }
894
895 #ifndef _WIN32
896 /**
897 Verify that a file system object does not grant permissions to everyone.
898 @param[in] path path name of the file system object
899 @return status
900 @retval false success
901 @retval true failure
902 */
903 static bool verify_no_world_permissions(const Fil_path &path) {
904 DBUG_TRACE;
905 struct stat statbuf;
906 int ret = stat(path.abs_path().c_str(), &statbuf);
907 if ((ret != 0) || ((statbuf.st_mode & S_IRWXO) != 0)) {
908 my_error(ER_INNODB_REDO_LOG_ARCHIVE_DIR_PERMISSIONS, MYF(0), path());
909 return true;
910 }
911 return false;
912 }
913 #endif /* _WIN32 */
914
915 /**
916 Trim trailing directory delimiters from a path name.
917 @param[in] path_name path name
918 @return trimmed path name
919 */
920 static std::string trim_path_name(const std::string &path_name) {
921 std::string trimmed_name(path_name);
922 while ((trimmed_name.length() > 0) &&
923 (trimmed_name[trimmed_name.length() - 1] == OS_PATH_SEPARATOR)) {
924 trimmed_name.pop_back();
925 }
926 return trimmed_name;
927 }
928
929 /**
930 Append a trailing directory delimiter to a path name.
931 This is done to support regression tests, which may want to replace
932 path names based on server variable values, that could contain a
933 trailing directory delimiter.
934 @param[in] path_name path name
935 @return trimmed path name
936 */
937 static std::string delimit_dir_name(const std::string &path_name) {
938 std::string delimited_name(trim_path_name(path_name));
939 delimited_name.push_back(OS_PATH_SEPARATOR);
940 return delimited_name;
941 }
942
943 /**
944 Append a path to a vector of directory paths.
945 Append a variable name to a vector of variable names.
946 The variable names belong to the server variables, from which the
947 directory paths have been taken. The matching pair shares the same
948 vector index.
949 Only non-NULL, non-empty path names and their corresponding
950 variable names are appended.
951 The appended paths are normalized absolute real path names.
952 @param[in] variable_name variable name from which the path comes
953 @param[in] path_name path name, may be NULL or empty
954 @param[out] variables vector of variable names
955 @param[out] directories vector of directory paths
956 */
957 static void append_path(const char *variable_name, const char *path_name,
958 std::vector<std::string> *variables,
959 std::vector<Fil_path> *directories) {
960 DBUG_TRACE;
961 #ifdef DEBUG_REDO_LOG_ARCHIVE_EXTRA
962 DBUG_PRINT("redo_log_archive",
963 ("append_path '%s' '%s'", variable_name, path_name));
964 #endif /* DEBUG_REDO_LOG_ARCHIVE_EXTRA */
965 if ((path_name != nullptr) && (path_name[0] != '\0')) {
966 Fil_path path(delimit_dir_name(path_name), /*normalize*/ true);
967 /*
968 Do not add datadir multiple times. Most variables default to datadir.
969 Datadir is added first and so occupies vector slot zero.
970 */
971 if ((directories->size() == 0) ||
972 (path.abs_path() != directories->at(0).abs_path())) {
973 #ifdef DEBUG_REDO_LOG_ARCHIVE_EXTRA
974 DBUG_PRINT("redo_log_archive", ("add server directory '%s' '%s'",
975 variable_name, path.abs_path().c_str()));
976 #endif /* DEBUG_REDO_LOG_ARCHIVE_EXTRA */
977 variables->push_back(variable_name);
978 directories->push_back(path);
979 }
980 }
981 }
982
983 /**
984 Verify that a path name is not in, under, or above a server directory.
985 @param[in] path normalized absolute real path name
986 @return status
987 @retval false success
988 @retval true failure
989 */
990 static bool verify_no_server_directory(const Fil_path &path) {
991 DBUG_TRACE;
992
993 /* Collect server directories as normalized absolute real path names. */
994 std::vector<std::string> variables;
995 std::vector<Fil_path> directories;
996 append_path("datadir", mysql_real_data_home_ptr, &variables, &directories);
997 append_path("innodb_data_home_dir", srv_data_home, &variables, &directories);
998 append_path("innodb_directories", srv_innodb_directories, &variables,
999 &directories);
1000 append_path("innodb_log_group_home_dir", srv_log_group_home_dir, &variables,
1001 &directories);
1002 append_path("innodb_temp_tablespaces_dir", ibt::srv_temp_dir, &variables,
1003 &directories);
1004 append_path("innodb_tmpdir", thd_innodb_tmpdir(nullptr), &variables,
1005 &directories);
1006 append_path("innodb_undo_directory", srv_undo_dir, &variables, &directories);
1007 append_path("secure_file_priv", opt_secure_file_priv, &variables,
1008 &directories);
1009
1010 /* Test the target path against the collected directories. */
1011 std::string target(trim_path_name(path.abs_path()));
1012 size_t target_len = target.length();
1013 #ifdef DEBUG_REDO_LOG_ARCHIVE_EXTRA
1014 DBUG_PRINT("redo_log_archive", ("target directory '%s'", target.c_str()));
1015 #endif /* DEBUG_REDO_LOG_ARCHIVE_EXTRA */
1016 #ifdef DEBUG_REDO_LOG_ARCHIVE_EXTRA_LOG
1017 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
1018 (LOGMSGPFX + "compare '" + target + "'").c_str());
1019 #endif /* DEBUG_REDO_LOG_ARCHIVE_EXTRA_LOG */
1020
1021 for (int idx = 0; idx < int(std::min(variables.size(), directories.size()));
1022 idx++) {
1023 Fil_path compare_path = directories[idx];
1024 std::string compare = trim_path_name(compare_path.abs_path());
1025 size_t compare_len = compare.length();
1026 size_t min_len = std::min(target_len, compare_len);
1027 #ifdef DEBUG_REDO_LOG_ARCHIVE_EXTRA
1028 DBUG_PRINT("redo_log_archive", ("compare directory '%s'", compare.c_str()));
1029 DBUG_PRINT("redo_log_archive",
1030 ("target len: %lu compare len: %lu min len: %lu",
1031 static_cast<unsigned long int>(target_len),
1032 static_cast<unsigned long int>(compare_len),
1033 static_cast<unsigned long int>(min_len)));
1034 DBUG_EXECUTE(
1035 "redo_log_archive", if (target_len > compare_len) {
1036 DBUG_PRINT("redo_log_archive",
1037 ("target at: %lu is: '%c'",
1038 static_cast<unsigned long int>(compare_len),
1039 target[compare_len]));
1040 });
1041 DBUG_EXECUTE(
1042 "redo_log_archive", if (compare_len > target_len) {
1043 DBUG_PRINT("redo_log_archive",
1044 ("compare at: %lu is: '%c'",
1045 static_cast<unsigned long int>(target_len),
1046 compare[target_len]));
1047 });
1048 #endif /* DEBUG_REDO_LOG_ARCHIVE_EXTRA */
1049 #ifdef DEBUG_REDO_LOG_ARCHIVE_EXTRA_LOG
1050 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
1051 (LOGMSGPFX + "with '" + compare + "'").c_str());
1052 #endif /* DEBUG_REDO_LOG_ARCHIVE_EXTRA_LOG */
1053 if (((compare_len == target_len) ||
1054 ((compare_len < target_len) &&
1055 (target[compare_len] == OS_PATH_SEPARATOR)) ||
1056 ((target_len < compare_len) &&
1057 (compare[target_len] == OS_PATH_SEPARATOR))) &&
1058 #ifdef _WIN32
1059 (0 == native_strncasecmp(target.c_str(), compare.c_str(), min_len))
1060 #else /* _WIN32 */
1061 (0 == strncmp(target.c_str(), compare.c_str(), min_len))
1062 #endif /* _WIN32 */
1063 ) {
1064 #ifdef DEBUG_REDO_LOG_ARCHIVE_EXTRA_LOG
1065 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
1066 (LOGMSGPFX + "match").c_str());
1067 #endif /* DEBUG_REDO_LOG_ARCHIVE_EXTRA_LOG */
1068 my_error(ER_INNODB_REDO_LOG_ARCHIVE_DIR_CLASH, MYF(0), path(),
1069 variables[idx].c_str(), compare_path());
1070 return true;
1071 }
1072 }
1073 #ifdef DEBUG_REDO_LOG_ARCHIVE_EXTRA_LOG
1074 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
1075 (LOGMSGPFX + "no match").c_str());
1076 #endif /* DEBUG_REDO_LOG_ARCHIVE_EXTRA_LOG */
1077 return false;
1078 }
1079
1080 /**
1081 Construct the file path name as directory/archive.serverUUID.000001.log.
1082 @param[in] path normalized absolute real path name
1083 @param[out] file_pathname file path name
1084 */
1085 static void construct_file_pathname(const Fil_path &path,
1086 std::string *file_pathname) {
1087 DBUG_TRACE;
1088 file_pathname->assign(path.path());
1089 if (file_pathname->empty() || (file_pathname->back() != OS_PATH_SEPARATOR)) {
1090 file_pathname->push_back(OS_PATH_SEPARATOR); /* purecov: inspected */
1091 }
1092 file_pathname->append("archive.");
1093 file_pathname->append(server_uuid_ptr);
1094 file_pathname->append(".000001.log");
1095 #ifdef DEBUG_REDO_LOG_ARCHIVE_EXTRA
1096 DBUG_PRINT("redo_log_archive",
1097 ("redo log archive file '%s'", file_pathname->c_str()));
1098 #endif /* DEBUG_REDO_LOG_ARCHIVE_EXTRA */
1099 }
1100
1101 /**
1102 Execute security checks and construct a file path name.
1103 @param[in] label a label from innodb_redo_log_archive_dirs
1104 @param[in] subdir a plain directory name, on Unix/Linux/Mac
1105 no slash ('/') is allowed, on Windows no
1106 slash ('/'), backslash ('\'), nor colon
1107 (':') is allowed in the argument.
1108 Can be NULL or empty
1109 @param[out] file_pathname the secure file path name
1110 @return status
1111 @retval false success
1112 @retval true failure
1113 */
1114 static bool construct_secure_file_path_name(const char *label,
1115 const char *subdir,
1116 std::string *file_pathname) {
1117 DBUG_TRACE;
1118
1119 /* 'label' must not be NULL, but can be empty. */
1120 if (label == nullptr) {
1121 /* mysqlbackup component does not allow this. */
1122 /* purecov: begin inspected */
1123 my_error(ER_INVALID_USE_OF_NULL, MYF(0));
1124 return true;
1125 /* purecov: end */
1126 }
1127
1128 /* 'subdir' is allowed to be NULL or empty. */
1129
1130 /*
1131 Security measure: Require the innodb_redo_log_archive_dirs plugin
1132 variable to be non-NULL and non-empty.
1133 */
1134 if ((redo_log_archive_dirs == nullptr) ||
1135 (redo_log_archive_dirs[0] == '\0')) {
1136 my_error(ER_INNODB_REDO_LOG_ARCHIVE_DIRS_INVALID, MYF(0));
1137 return true;
1138 }
1139
1140 /*
1141 Get the directory behind the label in the redo log archive dirs
1142 plugin variable. 'label' can be empty.
1143 */
1144 std::string directory;
1145 if (get_labeled_directory(label, &directory)) {
1146 return true;
1147 }
1148
1149 /*
1150 Security measure: If 'subdir' is given, it must be a plain directory
1151 name. Append it to the directory name.
1152 */
1153 if ((subdir != nullptr) && (subdir[0] != '\0')) {
1154 if (Fil_path::type_of_path(subdir) != Fil_path::file_name_only) {
1155 my_error(ER_INNODB_REDO_LOG_ARCHIVE_START_SUBDIR_PATH, MYF(0));
1156 return true;
1157 }
1158 if (directory.back() != OS_PATH_SEPARATOR) {
1159 directory.push_back(OS_PATH_SEPARATOR);
1160 }
1161 directory.append(subdir);
1162 #ifdef DEBUG_REDO_LOG_ARCHIVE_EXTRA_LOG
1163 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
1164 (LOGMSGPFX + "subdir path '" + directory + "'").c_str());
1165 #endif /* DEBUG_REDO_LOG_ARCHIVE_EXTRA_LOG */
1166 }
1167
1168 /*
1169 Security measure: The directory path name must lead to an existing
1170 directory. The server does not create it.
1171 */
1172 Fil_path subdir_path(directory, /*normalize*/ false);
1173 if (!subdir_path.is_directory_and_exists()) {
1174 my_error(ER_INNODB_REDO_LOG_ARCHIVE_NO_SUCH_DIR, MYF(0), subdir_path());
1175 return true;
1176 }
1177
1178 /*
1179 Security measure: The directory must not be in, under, or above a
1180 server directory.
1181 */
1182 if (verify_no_server_directory(subdir_path)) {
1183 return true;
1184 }
1185
1186 #ifndef _WIN32
1187 /*
1188 Security measure: The directory must not grant permissions to everyone.
1189 */
1190 if (verify_no_world_permissions(subdir_path)) {
1191 return true;
1192 }
1193 #endif /* _WIN32 */
1194
1195 /*
1196 Security measure: Do not allow arbitrary names, but construct the
1197 file name as archive.serverUUID.000001.log.
1198 */
1199 construct_file_pathname(subdir_path, file_pathname);
1200
1201 return false;
1202 }
1203
1204 /*
1205 Terminate the consumer thread.
1206
1207 In the normal case the redo_log_archive_tmp_block is marked as the final
1208 block and enqueued, so that the consumer writes it to the file and
1209 ends. In the rapid case redo_log_archive_consume_complete is set and
1210 the queue is cleared.
1211
1212 NOTE: This function must be called under the redo_log_archive_admin_mutex!
1213
1214 @param[in] rapid whether a rapid termination is requested
1215 @return status
1216 @retval false success
1217 @retval true failure
1218 */
1219 static bool terminate_consumer(bool rapid) {
1220 DBUG_TRACE;
1221 if (rapid) {
1222 redo_log_archive_consume_complete = true;
1223 redo_log_archive_queue.deinit();
1224 } else if (redo_log_archive_consume_running) {
1225 /*
1226 Mark the last block as the final block and enqueue it for writing
1227 into the redo log archive file. This is required in any case if the
1228 consumer is still active. It may be waiting on the queue.
1229
1230 If this call is from session end, then an error message is recorded
1231 and the consumer sees it after dequeueing a block. It will skip all
1232 blocks, but still terminate on the final block only.
1233 */
1234 mutex_exit(&redo_log_archive_admin_mutex);
1235 log_writer_mutex_enter(*log_sys);
1236 redo_log_archive_tmp_block.set_is_final_block(true);
1237 redo_log_archive_queue.enqueue(redo_log_archive_tmp_block);
1238 redo_log_archive_tmp_block.reset();
1239 log_writer_mutex_exit(*log_sys);
1240 mutex_enter(&redo_log_archive_admin_mutex);
1241 }
1242
1243 /*
1244 Wait for the consumer to terminate. The
1245 redo_log_archive_consume_event is set after the final block
1246 is written into the redo log archive file.
1247 */
1248 if (timeout(&consumer_is_running)) {
1249 /* This would require yet another tricky error injection. */
1250 /* purecov: begin inspected */
1251 if (!redo_log_archive_recorded_error.empty()) {
1252 redo_log_archive_recorded_error.append("; ");
1253 }
1254 redo_log_archive_recorded_error.append(
1255 "Termination of the consumer thread timed out");
1256 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
1257 (LOGMSGPFX + redo_log_archive_recorded_error).c_str());
1258 my_error(ER_INNODB_REDO_LOG_ARCHIVE_FAILED, MYF(0),
1259 redo_log_archive_recorded_error.c_str());
1260 return true;
1261 /* purecov: end */
1262 }
1263
1264 srv_threads.m_backup_log_archiver.join();
1265 return false;
1266 }
1267
1268 /*
1269 Start the redo log archiving.
1270 */
1271 static bool redo_log_archive_start(THD *thd, const char *label,
1272 const char *subdir) {
1273 DBUG_TRACE;
1274 DBUG_PRINT("redo_log_archive", ("label: '%s' subdir: '%s'",
1275 (label == nullptr) ? "[NULL]" : label,
1276 (subdir == nullptr) ? "[NULL]" : subdir));
1277 /* Security measure: Require the redo log archive privilege. */
1278 if (verify_privilege(thd, innodb_redo_log_archive_privilege)) {
1279 return true;
1280 }
1281
1282 /* Synchronize with with other threads while using global objects. */
1283 mutex_enter(&redo_log_archive_admin_mutex);
1284
1285 /*
1286 Redo log archiving must not already be active. Do this check early,
1287 because other error reports in checking the parameters might be
1288 confusing, if archiving is active already.
1289 */
1290 if (redo_log_archive_active) {
1291 my_error(ER_INNODB_REDO_LOG_ARCHIVE_ACTIVE, MYF(0),
1292 redo_log_archive_file_pathname.c_str());
1293 mutex_exit(&redo_log_archive_admin_mutex);
1294 return true;
1295 }
1296
1297 /* Redo logging must be enabled for archiving to start. */
1298 if (!mtr_t::s_logging.is_enabled()) {
1299 my_error(ER_INNODB_REDO_DISABLED, MYF(0));
1300 mutex_exit(&redo_log_archive_admin_mutex);
1301 return true;
1302 }
1303
1304 /* Drop potential left-over resources to avoid leaks. */
1305 if (drop_remnants(/*force*/ false)) {
1306 /* purecov: begin inspected */
1307 mutex_exit(&redo_log_archive_admin_mutex);
1308 return true;
1309 /* purecov: end */
1310 }
1311
1312 /*
1313 Construct a file path name.
1314 */
1315 std::string file_pathname;
1316 if (construct_secure_file_path_name(label, subdir, &file_pathname)) {
1317 mutex_exit(&redo_log_archive_admin_mutex);
1318 return true;
1319 }
1320
1321 /* Get current session. */
1322 innodb_session_t *session = thd_to_innodb_session(thd);
1323 ut_ad(session != nullptr);
1324
1325 /*
1326 Create the redo log archive file. We create it with read-only access rights,
1327 however, the returned handle will be open for read-write.
1328 */
1329 bool success;
1330 #ifndef _WIN32
1331 pfs_os_file_t file_handle =
1332 os_file_create_simple_no_error_handling_with_umask(
1333 redo_log_archive_file_key, file_pathname.c_str(), OS_FILE_CREATE,
1334 OS_FILE_READ_WRITE, /*read_only*/ false, S_IRUSR | S_IRGRP, &success);
1335
1336 #else
1337 pfs_os_file_t file_handle = os_file_create_simple_no_error_handling(
1338 redo_log_archive_file_key, file_pathname.c_str(), OS_FILE_CREATE,
1339 OS_FILE_READ_WRITE, /*read_only*/ false, &success);
1340 #endif
1341 if (!success) {
1342 int os_errno = errno;
1343 char errbuf[MYSYS_STRERROR_SIZE];
1344 my_strerror(errbuf, sizeof(errbuf), os_errno);
1345
1346 /* On Windows it fails with 0 if the file exists. */
1347 if ((os_errno != 0) && (os_errno != EEXIST)) {
1348 /* Found cases, where the file had been created in spite of !success. */
1349 /* purecov: begin inspected */
1350 os_file_delete_if_exists(redo_log_archive_file_key, file_pathname.c_str(),
1351 nullptr);
1352 /* purecov: end */
1353 }
1354 my_error(ER_INNODB_REDO_LOG_ARCHIVE_FILE_CREATE, MYF(0),
1355 file_pathname.c_str(), os_errno, errbuf);
1356 mutex_exit(&redo_log_archive_admin_mutex);
1357 return true;
1358 }
1359 DBUG_PRINT("redo_log_archive", ("Created redo_log_archive_file_pathname '%s'",
1360 file_pathname.c_str()));
1361
1362 /*
1363 Create the consume_event.
1364 */
1365 os_event_t consume_event = os_event_create();
1366 DBUG_EXECUTE_IF("redo_log_archive_bad_alloc", os_event_destroy(consume_event);
1367 consume_event = nullptr;);
1368 if (consume_event == nullptr) {
1369 os_file_close(file_handle);
1370 os_file_delete_if_exists(redo_log_archive_file_key, file_pathname.c_str(),
1371 nullptr);
1372 my_error(ER_STD_BAD_ALLOC_ERROR, MYF(0), "redo_log_archive_consume_event",
1373 "redo_log_archive_start");
1374 mutex_exit(&redo_log_archive_admin_mutex);
1375 return true;
1376 }
1377 os_event_reset(consume_event);
1378 DBUG_PRINT("redo_log_archive", ("Created consume_event"));
1379
1380 /*
1381 Initialize the temporary block. At this stage the producer is not
1382 enabled. So we do not need to use the log writer mutex.
1383 */
1384 redo_log_archive_tmp_block.reset();
1385
1386 /* Initialize the queue. */
1387 redo_log_archive_queue.init(QUEUE_SIZE_MAX);
1388
1389 /* Set the redo log archiving to active. */
1390 redo_log_archive_consume_event = consume_event;
1391 redo_log_archive_consume_complete = false;
1392 redo_log_archive_file_handle = file_handle;
1393 redo_log_archive_file_pathname = file_pathname;
1394 redo_log_archive_recorded_error.clear();
1395 redo_log_archive_session_ending = false;
1396 redo_log_archive_thd = thd;
1397 redo_log_archive_session = session;
1398 redo_log_archive_active = true;
1399
1400 srv_threads.m_backup_log_archiver = os_thread_create(
1401 redo_log_archive_consumer_thread_key, 0, redo_log_archive_consumer);
1402
1403 mutex_exit(&redo_log_archive_admin_mutex);
1404
1405 /* Create the consumer thread. */
1406 DBUG_PRINT("redo_log_archive", ("Creating consumer thread"));
1407
1408 srv_threads.m_backup_log_archiver.start();
1409
1410 /*
1411 Wait for the consumer to start. We do not want to report success
1412 before the consumer thread has started to work.
1413 */
1414 mutex_enter(&redo_log_archive_admin_mutex);
1415 if (timeout(&consumer_not_running)) {
1416 os_event_destroy(redo_log_archive_consume_event);
1417 redo_log_archive_consume_event = nullptr;
1418 redo_log_archive_consume_complete = true;
1419 if (redo_log_archive_file_handle.m_file != OS_FILE_CLOSED) {
1420 os_file_close(redo_log_archive_file_handle);
1421 redo_log_archive_file_handle.m_file = OS_FILE_CLOSED;
1422 }
1423 os_file_delete_if_exists(redo_log_archive_file_key,
1424 redo_log_archive_file_pathname.c_str(), nullptr);
1425 redo_log_archive_file_pathname.clear();
1426 /* Keep recorded_error */
1427 redo_log_archive_session_ending = false;
1428 redo_log_archive_thd = nullptr;
1429 redo_log_archive_session = nullptr;
1430 redo_log_archive_active = false;
1431 redo_log_archive_queue.deinit();
1432 mutex_exit(&redo_log_archive_admin_mutex);
1433 /* Don't leave this with a stray thread. */
1434 srv_threads.m_backup_log_archiver.join();
1435 my_error(ER_INNODB_REDO_LOG_ARCHIVE_START_TIMEOUT, MYF(0));
1436 return true;
1437 }
1438 mutex_exit(&redo_log_archive_admin_mutex);
1439 DBUG_PRINT("redo_log_archive", ("Redo log archiving started"));
1440 return false;
1441 }
1442
1443 /*
1444 Stop the redo log archiving.
1445
1446 This can either be called
1447 - through the service interface
1448 - when redo log archiving is active and in good state
1449 => Stop in normal, clean way.
1450 - when redo log archiving is active and in error state
1451 => Stop quickly and return the error.
1452
1453 - when redo log archiving is inactive and an error is recorded
1454 => Return the recorded error.
1455 - when redo log archiving is inactive
1456 => Return an error.
1457
1458 - at session end when redo log archiving is active
1459 => Stop quickly and record an error for the next stop operation.
1460 */
1461 static bool redo_log_archive_stop(THD *thd) {
1462 DBUG_TRACE;
1463
1464 /*
1465 Security measure: Require the redo log archive privilege.
1466 */
1467 if (verify_privilege(thd, innodb_redo_log_archive_privilege)) {
1468 return true;
1469 }
1470
1471 /* Synchronize with with other threads while using global objects. */
1472 mutex_enter(&redo_log_archive_admin_mutex);
1473
1474 /*
1475 If redo log archiving is inactive, the stop request fails.
1476 If there was an error recorded, return it.
1477 */
1478 if (!redo_log_archive_active) {
1479 DBUG_PRINT("redo_log_archive", ("Not active"));
1480 if (!redo_log_archive_recorded_error.empty()) {
1481 DBUG_PRINT("redo_log_archive", ("Recorded error '%s'",
1482 redo_log_archive_recorded_error.c_str()));
1483 my_error(ER_INNODB_REDO_LOG_ARCHIVE_FAILED, MYF(0),
1484 redo_log_archive_recorded_error.c_str());
1485 /* Do not clear the error, it may be wanted by another session again. */
1486 mutex_exit(&redo_log_archive_admin_mutex);
1487 return true;
1488 }
1489 my_error(ER_INNODB_REDO_LOG_ARCHIVE_INACTIVE, MYF(0));
1490 mutex_exit(&redo_log_archive_admin_mutex);
1491 return true;
1492 }
1493
1494 /*
1495 Redo log archiving is still active.
1496 We must not stop it if another session has started it.
1497 */
1498 if ((redo_log_archive_session != thd_to_innodb_session(thd)) ||
1499 (redo_log_archive_thd != thd)) {
1500 my_error(ER_INNODB_REDO_LOG_ARCHIVE_SESSION, MYF(0));
1501 mutex_exit(&redo_log_archive_admin_mutex);
1502 return true;
1503 }
1504
1505 DBUG_PRINT("redo_log_archive", ("Stopping redo log archiving on '%s'",
1506 redo_log_archive_file_pathname.c_str()));
1507
1508 /*
1509 This session has started the redo log archiving.
1510 The call can be from the service interface or from session end.
1511 Disable the producer as soon as possible.
1512 */
1513 mutex_exit(&redo_log_archive_admin_mutex);
1514 ut_ad(log_sys != nullptr);
1515 log_writer_mutex_enter(*log_sys);
1516 redo_log_archive_produce_blocks = false;
1517 log_writer_mutex_exit(*log_sys);
1518 mutex_enter(&redo_log_archive_admin_mutex);
1519
1520 if (terminate_consumer(/*rapid*/ false)) {
1521 return true; /* purecov: inspected */
1522 }
1523 redo_log_archive_queue.deinit();
1524 /*
1525 Publish the stop state.
1526 */
1527 os_event_destroy(redo_log_archive_consume_event);
1528 redo_log_archive_consume_event = nullptr;
1529 redo_log_archive_consume_complete = true;
1530 if (redo_log_archive_file_handle.m_file != OS_FILE_CLOSED) {
1531 /* purecov: begin inspected */
1532 os_file_close(redo_log_archive_file_handle);
1533 redo_log_archive_file_handle.m_file = OS_FILE_CLOSED;
1534 /* purecov: end */
1535 }
1536 /*
1537 If redo log archiving was in error state, remove the redo log
1538 archive file, if the consumer has not already done it.
1539 */
1540 if (!redo_log_archive_recorded_error.empty() &&
1541 !redo_log_archive_file_pathname.empty()) {
1542 DBUG_PRINT("redo_log_archive", ("Recorded error '%s'",
1543 redo_log_archive_recorded_error.c_str()));
1544 DBUG_PRINT("redo_log_archive", ("Delete redo log archive file '%s'",
1545 redo_log_archive_file_pathname.c_str()));
1546 os_file_delete_if_exists(redo_log_archive_file_key,
1547 redo_log_archive_file_pathname.c_str(), nullptr);
1548 }
1549 redo_log_archive_file_pathname.clear();
1550 /* Keep recorded_error */
1551 redo_log_archive_thd = nullptr;
1552 redo_log_archive_session = nullptr;
1553 redo_log_archive_active = false;
1554
1555 DBUG_PRINT("redo_log_archive", ("Redo log archiving stopped"));
1556
1557 /*
1558 If the stop was called after the occurrence of an error condition,
1559 - Session that started redo log archiving terminated,
1560 - Error while trying to write into the redo log archive,
1561 report the error message back to the caller.
1562
1563 But do not report an error if the session is ending. The session
1564 might be in error already.
1565 */
1566 if (!redo_log_archive_recorded_error.empty() &&
1567 !redo_log_archive_session_ending) {
1568 /* purecov: begin inspected */
1569 my_error(ER_INNODB_REDO_LOG_ARCHIVE_FAILED, MYF(0),
1570 redo_log_archive_recorded_error.c_str());
1571 /* Do not clear the error, it may be wanted by another session again. */
1572 mutex_exit(&redo_log_archive_admin_mutex);
1573 return true;
1574 /* purecov: end */
1575 }
1576 mutex_exit(&redo_log_archive_admin_mutex);
1577 /* Success */
1578 return false;
1579 }
1580
1581 /*
1582 Flush the redo log archive queue.
1583 */
1584 static bool redo_log_archive_flush(THD *thd) {
1585 DBUG_TRACE;
1586
1587 /*
1588 Security measure: Require the redo log archive privilege.
1589 */
1590 if (verify_privilege(thd, innodb_redo_log_archive_privilege)) {
1591 return true;
1592 }
1593
1594 /* Synchronize with with other threads while using global objects. */
1595 mutex_enter(&redo_log_archive_admin_mutex);
1596
1597 /*
1598 If redo log archiving is inactive, the flush request fails.
1599 If there was an error recorded, return it.
1600 */
1601 if (!redo_log_archive_active) {
1602 DBUG_PRINT("redo_log_archive", ("Not active"));
1603 my_error(ER_INNODB_REDO_LOG_ARCHIVE_INACTIVE, MYF(0));
1604 mutex_exit(&redo_log_archive_admin_mutex);
1605 return true;
1606 }
1607
1608 /*
1609 Redo log archiving is still active.
1610 We must not flush it if another session has started it.
1611 */
1612 if ((redo_log_archive_session != thd_to_innodb_session(thd)) ||
1613 (redo_log_archive_thd != thd)) {
1614 my_error(ER_INNODB_REDO_LOG_ARCHIVE_SESSION, MYF(0));
1615 mutex_exit(&redo_log_archive_admin_mutex);
1616 return true;
1617 }
1618
1619 DBUG_PRINT("redo_log_archive", ("Flushing the redo log archive on '%s'",
1620 redo_log_archive_file_pathname.c_str()));
1621
1622 /*
1623 This session has started the redo log archiving. Execute the flush.
1624 Take the log writer mutex, mark the temporary block as a flush
1625 block, enqueue it, and remove the mark again. The queue took a copy
1626 of the block, including its mark. Do not leave the block modified
1627 nor reset it. Normal use of it shall go on. The consumer shall write
1628 it to the archive log file, but not update the file offset, so that
1629 the next regular block overwrites it.
1630 */
1631 redo_log_archive_consume_flushed = false;
1632 mutex_exit(&redo_log_archive_admin_mutex);
1633 ut_ad(log_sys != nullptr);
1634 log_writer_mutex_enter(*log_sys);
1635 redo_log_archive_tmp_block.m_is_flush_block = true;
1636 redo_log_archive_queue.enqueue(redo_log_archive_tmp_block);
1637 redo_log_archive_tmp_block.m_is_flush_block = false;
1638 /* Do not reset the block. The producer shall continue to fill it. */
1639 log_writer_mutex_exit(*log_sys);
1640
1641 /*
1642 Wait for the consumer to copy the flush block. The
1643 redo_log_archive_consume_event is set after the flush block
1644 is written into the redo log archive file.
1645 */
1646 mutex_enter(&redo_log_archive_admin_mutex);
1647 if (timeout(&consumer_not_flushed)) {
1648 /* This would require yet another tricky error injection. */
1649 /* purecov: begin inspected */
1650 if (!redo_log_archive_recorded_error.empty()) {
1651 redo_log_archive_recorded_error.append("; ");
1652 }
1653 redo_log_archive_recorded_error.append(
1654 "Flushing of the archive log timed out");
1655 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
1656 (LOGMSGPFX + redo_log_archive_recorded_error).c_str());
1657 my_error(ER_INNODB_REDO_LOG_ARCHIVE_FAILED, MYF(0),
1658 redo_log_archive_recorded_error.c_str());
1659 mutex_exit(&redo_log_archive_admin_mutex);
1660 return true;
1661 /* purecov: end */
1662 }
1663
1664 /* Success */
1665 DBUG_PRINT("redo_log_archive", ("Redo log archive flushed"));
1666 mutex_exit(&redo_log_archive_admin_mutex);
1667 return false;
1668 }
1669
1670 static std::unique_ptr<Log_user_consumer> log_meb_consumer;
1671 static innodb_session_t *log_meb_consumer_session;
1672
1673 static bool redo_log_consumer_register(innodb_session_t *session) {
1674 log_t &log = *log_sys;
1675
1676 IB_mutex_guard checkpointer_latch{&(log.checkpointer_mutex),
1677 UT_LOCATION_HERE};
1678
1679 IB_mutex_guard files_latch{&(log.m_files_mutex), UT_LOCATION_HERE};
1680
1681 if (session == nullptr || log_meb_consumer_session != nullptr) {
1682 return true;
1683 }
1684
1685 ut_a(log_meb_consumer.get() == nullptr);
1686
1687 log_meb_consumer = std::make_unique<Log_user_consumer>("MEB");
1688
1689 log_meb_consumer->set_consumed_lsn(log_get_checkpoint_lsn(log));
1690
1691 log_consumer_register(log, log_meb_consumer.get());
1692
1693 log_meb_consumer_session = session;
1694
1695 return false;
1696 }
1697
1698 static bool redo_log_consumer_unregister(innodb_session_t *session) {
1699 log_t &log = *log_sys;
1700
1701 IB_mutex_guard files_latch{&(log.m_files_mutex), UT_LOCATION_HERE};
1702
1703 if (session == nullptr || log_meb_consumer_session != session) {
1704 return true;
1705 }
1706
1707 ut_a(log_meb_consumer.get() != nullptr);
1708
1709 log_consumer_unregister(log, log_meb_consumer.get());
1710 log_meb_consumer.reset();
1711
1712 log_meb_consumer_session = nullptr;
1713
1714 return false;
1715 }
1716
1717 static bool redo_log_consumer_advance(innodb_session_t *session, lsn_t lsn) {
1718 IB_mutex_guard files_latch{&(log_sys->m_files_mutex), UT_LOCATION_HERE};
1719
1720 if (session == nullptr || log_meb_consumer_session != session) {
1721 return true;
1722 }
1723
1724 ut_a(log_meb_consumer.get() != nullptr);
1725
1726 if (lsn < log_meb_consumer->get_consumed_lsn()) {
1727 return true;
1728 }
1729
1730 log_meb_consumer->set_consumed_lsn(lsn);
1731 return false;
1732 }
1733
1734 /*
1735 Security function to be called when the current session ends.
1736 */
1737 void redo_log_archive_session_end(innodb_session_t *session) {
1738 /*
1739 This function can be called after the InnoDB handlerton has been
1740 initialized and before InnoDB is started. In such case the
1741 redo_log_archive_admin_mutex has not yet been created. To prevent
1742 the access of a non-existing mutex, the global atomic variable
1743 redo_log_archive_initialized can be used as it is true only when the
1744 mutex exists. Due to the std::atomic qualifier it should be thread
1745 safe in protecting access to the mutex.
1746 */
1747 if (redo_log_archive_initialized) {
1748 bool stop_required = false;
1749 THD *thd{};
1750
1751 /* Synchronize with with other threads while using global objects. */
1752 mutex_enter(&redo_log_archive_admin_mutex);
1753 if (redo_log_archive_active) {
1754 if (redo_log_archive_session == session) {
1755 DBUG_PRINT("redo_log_archive",
1756 ("Redo log archiving is active by this session. Stopping."));
1757 stop_required = true;
1758 redo_log_archive_session_ending = true;
1759 thd = redo_log_archive_thd;
1760 if (!redo_log_archive_recorded_error.empty()) {
1761 redo_log_archive_recorded_error.append("; "); /* purecov: inspected */
1762 }
1763 redo_log_archive_recorded_error.append(
1764 "Session terminated with active redo log archiving");
1765 }
1766 }
1767 mutex_exit(&redo_log_archive_admin_mutex);
1768
1769 if (stop_required && (thd != nullptr)) {
1770 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
1771 (LOGMSGPFX + "Unexpected termination of the session that started"
1772 " redo log archiving. Stopping redo log archiving.")
1773 .c_str());
1774 if (redo_log_archive_stop(thd)) {
1775 /* return value must be used. */
1776 }
1777 }
1778 }
1779
1780 {
1781 IB_mutex_guard files_latch{&(log_sys->m_files_mutex), UT_LOCATION_HERE};
1782
1783 if (log_meb_consumer_session != session) {
1784 return;
1785 }
1786 }
1787
1788 ut_ad(log_meb_consumer_session == session);
1789
1790 ut_d(const bool ret =) redo_log_consumer_unregister(session);
1791
1792 ut_ad(!ret);
1793 ut_ad(log_meb_consumer_session == nullptr);
1794 }
1795
1796 /**
1797 Produce redo log blocks for the queue.
1798
1799 This function is called for every log write. So it must be as
1800 efficient as possible.
1801
1802 NOTE: This function must be called under the 'log_sys.writer_mutex'!
1803 */
1804 void redo_log_archive_produce(const byte *write_buf, const size_t write_size) {
1805 /* Execute the function body only if redo log archiving is active. */
1806 if (redo_log_archive_produce_blocks) {
1807 ut_ad(log_sys != nullptr);
1808 ut_ad(log_writer_mutex_own(*log_sys));
1809 ut_ad(write_buf != nullptr);
1810 ut_ad(write_size > 0);
1811
1812 /*
1813 Scan the redo log block in chunks of OS_FILE_LOG_BLOCK_SIZE (512) bytes.
1814 - If a chunk is empty or incomplete, parsing is stopped at this point.
1815 - If the temporary block becomes full, it is enqueued and it is
1816 cleared for storing further log records.
1817 */
1818 for (size_t i = 0; i < write_size; i += OS_FILE_LOG_BLOCK_SIZE) {
1819 if (redo_log_archive_tmp_block.full()) {
1820 redo_log_archive_queue.enqueue(redo_log_archive_tmp_block);
1821 redo_log_archive_tmp_block.reset();
1822 }
1823 if (!redo_log_archive_tmp_block.put_log_block(write_buf, i)) {
1824 break;
1825 }
1826 }
1827 }
1828 }
1829
1830 bool redo_log_archive_is_active() {
1831 DBUG_TRACE;
1832 /* During recovery, archiver may not be initialized yet. */
1833 if (!redo_log_archive_initialized.load()) {
1834 return false;
1835 }
1836
1837 mutex_enter(&redo_log_archive_admin_mutex);
1838 bool result = redo_log_archive_active;
1839 mutex_exit(&redo_log_archive_admin_mutex);
1840
1841 return result;
1842 }
1843
1844 /* This requires disk full testing */
1845 /* purecov: begin inspected */
1846 /**
1847 Handle a write error. Record an error message. Stop redo log archiving.
1848 @param[in] file_offset write offset
1849 */
1850 static void handle_write_error(uint64_t file_offset) {
1851 int os_errno = errno;
1852 char errbuf[MYSYS_STRERROR_SIZE];
1853 my_strerror(errbuf, sizeof(errbuf), os_errno);
1854 std::stringstream recorded_error_ss;
1855 recorded_error_ss << "Cannot write to file '"
1856 << redo_log_archive_file_pathname << "' at offset "
1857 << file_offset << " (OS errno: " << os_errno << " - "
1858 << errbuf << ")";
1859 if (!redo_log_archive_recorded_error.empty()) {
1860 redo_log_archive_recorded_error.append("; ");
1861 }
1862 redo_log_archive_recorded_error.append(recorded_error_ss.str());
1863 redo_log_archive_consume_complete = true;
1864 }
1865 /* purecov: end */
1866
1867 /**
1868 Dequeue blocks of size QUEUE_BLOCK_SIZE, enqueued by the producer.
1869 Write the blocks to the redo log archive file sequentially.
1870 */
1871 static void redo_log_archive_consumer() {
1872 DBUG_TRACE;
1873 /* Synchronize with with other threads while using global objects. */
1874 mutex_enter(&redo_log_archive_admin_mutex);
1875
1876 /*
1877 On error injection ensure, that the starting session has executed
1878 its timeout handling before the consumer sets its running state. But
1879 do not hang infinitely.
1880 */
1881 DBUG_EXECUTE_IF(
1882 "innodb_redo_log_archive_start_timeout",
1883 for (int count = 600; (count > 0) && !redo_log_archive_consume_complete;
1884 count--) {
1885 mutex_exit(&redo_log_archive_admin_mutex);
1886 my_sleep(100000); // 0.1s
1887 mutex_enter(&redo_log_archive_admin_mutex);
1888 });
1889
1890 if (redo_log_archive_consume_running) {
1891 /* Another consumer thread is still running. */
1892 /* purecov: begin inspected */
1893 if (!redo_log_archive_recorded_error.empty()) {
1894 redo_log_archive_recorded_error.append("; ");
1895 }
1896 redo_log_archive_recorded_error.append(
1897 "Consumer thread refuses to start - another one is running");
1898 if (redo_log_archive_consume_event != nullptr) {
1899 os_event_set(redo_log_archive_consume_event);
1900 }
1901 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
1902 (LOGMSGPFX + "Redo log archiving consumer thread refuses to start"
1903 " - another one is running")
1904 .c_str());
1905 mutex_exit(&redo_log_archive_admin_mutex);
1906 DBUG_PRINT("redo_log_archive", ("Other consumer is running"));
1907 return;
1908 /* purecov: end */
1909 }
1910
1911 /*
1912 A Guardian sets the 'running' status to true. When leaving the
1913 function (ending the thread), the Guardian's destructor sets it back
1914 to false again. The Guardian sets the event (if not NULL at that time)
1915 in both cases.
1916 */
1917 Guardian consumer_guardian(&redo_log_archive_consume_running,
1918 &redo_log_archive_consume_event,
1919 &redo_log_archive_admin_mutex);
1920
1921 /* Start might have timed out meanwhile. */
1922 if (redo_log_archive_consume_complete ||
1923 (redo_log_archive_consume_event == nullptr)) {
1924 if (!redo_log_archive_recorded_error.empty()) {
1925 redo_log_archive_recorded_error.append("; "); /* purecov: inspected */
1926 }
1927 redo_log_archive_recorded_error.append(
1928 "Consumer appears completed at start - terminating");
1929 if (redo_log_archive_consume_event != nullptr) {
1930 os_event_set(redo_log_archive_consume_event); /* purecov: inspected */
1931 }
1932 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
1933 (LOGMSGPFX +
1934 "Redo log archiving consumer thread sees completion at start"
1935 " - terminating")
1936 .c_str());
1937 mutex_exit(&redo_log_archive_admin_mutex);
1938 DBUG_PRINT("redo_log_archive", ("Consumer is already marked complete"));
1939 return;
1940 }
1941 mutex_exit(&redo_log_archive_admin_mutex);
1942
1943 /*
1944 Activate the producer outside of the redo_log_archive_admin_mutex
1945 and open a block, which defines the scope for the producer guardian.
1946 */
1947 {
1948 ut_ad(log_sys != nullptr);
1949 Guardian producer_guardian(&redo_log_archive_produce_blocks, nullptr,
1950 &log_sys->writer_mutex);
1951
1952 /* Prepare an I/O request with potential encryption. */
1953 IORequest request(IORequest::LOG | IORequest::WRITE);
1954
1955 if (srv_redo_log_encrypt) {
1956 IB_mutex_guard files_latch{&(log_sys->m_files_mutex), UT_LOCATION_HERE};
1957
1958 if (log_can_encrypt(*log_sys)) {
1959 request.get_encryption_info().set(log_sys->m_encryption_metadata);
1960 }
1961
1962 // Ensure, that the block written has a minimum size.
1963 // The encryption is skipped for offsets smaller than
1964 // `LOG_FILE_HDR_SIZE` (not only for offsets==0).
1965 static_assert(QUEUE_BLOCK_SIZE >= LOG_FILE_HDR_SIZE);
1966 }
1967 /*
1968 Offset inside the redo log archive file. The offset is incremented
1969 each time the consumer writes to the redo log archive file.
1970 */
1971 os_offset_t file_offset{0};
1972 Block temp_block;
1973
1974 mutex_enter(&redo_log_archive_admin_mutex);
1975 /*
1976 Write a log header (dummy) to file_offset zero.
1977 Writes to offset zero are not encrypted by os_file_write().
1978 */
1979 if (redo_log_archive_file_handle.m_file != OS_FILE_CLOSED) {
1980 dberr_t err = os_file_write(
1981 request, redo_log_archive_file_pathname.c_str(),
1982 redo_log_archive_file_handle, temp_block.get_queue_block(),
1983 file_offset, QUEUE_BLOCK_SIZE);
1984 if (err != DB_SUCCESS) {
1985 /* This requires disk full testing */
1986 /* purecov: begin inspected */
1987 handle_write_error(file_offset);
1988 /*
1989 handle_write_error() sets redo_log_archive_consume_complete,
1990 so that the below loop won't be entered.
1991 */
1992 /* purecov: end */
1993 } else {
1994 file_offset += QUEUE_BLOCK_SIZE;
1995 }
1996 }
1997
1998 while (!redo_log_archive_consume_complete) {
1999 /* Dequeue a log block from the queue outside of the mutex. */
2000 mutex_exit(&redo_log_archive_admin_mutex);
2001 redo_log_archive_queue.dequeue(temp_block);
2002 mutex_enter(&redo_log_archive_admin_mutex);
2003 /* Check the redo log archiving state. It could have changed meanwhile. */
2004 if (redo_log_archive_consume_complete) {
2005 /* purecov: begin inspected */
2006 DBUG_PRINT("redo_log_archive",
2007 ("Consume complete - Stopping consumer."));
2008 break;
2009 /* purecov: end */
2010 }
2011
2012 /*
2013 Write the dequeued block only if redo log archiving is in a good state.
2014 */
2015 if (redo_log_archive_active && redo_log_archive_recorded_error.empty() &&
2016 !redo_log_archive_file_pathname.empty() &&
2017 (redo_log_archive_file_handle.m_file != OS_FILE_CLOSED)) {
2018 dberr_t err = os_file_write(
2019 request, redo_log_archive_file_pathname.c_str(),
2020 redo_log_archive_file_handle, temp_block.get_queue_block(),
2021 file_offset, QUEUE_BLOCK_SIZE);
2022 /*
2023 An error during the write to the redo log archive file causes
2024 the consumer to terminate and record the error for the next
2025 redo_log_archive_stop() call.
2026 */
2027 if (err != DB_SUCCESS) {
2028 /* This requires disk full testing */
2029 /* purecov: begin inspected */
2030 handle_write_error(file_offset);
2031 break;
2032 /* purecov: end */
2033 }
2034 // If this is a flush block, do not update the file offset.
2035 // The next regular block shall overwrite this one.
2036 if (temp_block.m_is_flush_block) {
2037 redo_log_archive_consume_flushed = true;
2038 if (redo_log_archive_consume_event != nullptr) {
2039 os_event_set(redo_log_archive_consume_event);
2040 }
2041 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
2042 (LOGMSGPFX + "Flushed redo log archive").c_str());
2043 } else {
2044 file_offset += QUEUE_BLOCK_SIZE;
2045 }
2046 }
2047
2048 if (temp_block.get_is_final_block()) {
2049 DBUG_PRINT("redo_log_archive", ("Final Block - Stopping consumer."));
2050 redo_log_archive_consume_complete = true;
2051 }
2052 } /* end while loop */
2053 mutex_exit(&redo_log_archive_admin_mutex);
2054 } /* end producer_guardian block -> disable producer */
2055
2056 mutex_enter(&redo_log_archive_admin_mutex);
2057 if (redo_log_archive_consume_event != nullptr) {
2058 os_event_set(redo_log_archive_consume_event);
2059 }
2060 if (redo_log_archive_file_handle.m_file != OS_FILE_CLOSED) {
2061 os_file_close(redo_log_archive_file_handle);
2062 redo_log_archive_file_handle.m_file = OS_FILE_CLOSED;
2063 }
2064 if (!redo_log_archive_recorded_error.empty()) {
2065 /* We have to remove the file on error. */
2066 /* This requires disk full testing */
2067 /* purecov: begin inspected */
2068 if (!redo_log_archive_file_pathname.empty()) {
2069 os_file_delete_if_exists(redo_log_archive_file_key,
2070 redo_log_archive_file_pathname.c_str(), nullptr);
2071 /*
2072 Do not clear the filename here. Redo log archiving is not yet inactive.
2073 */
2074 }
2075 redo_log_archive_recorded_error.append(
2076 " - stopped redo log archiving and deleted the file.");
2077 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
2078 (LOGMSGPFX + redo_log_archive_recorded_error).c_str());
2079 /* purecov: end */
2080 }
2081 mutex_exit(&redo_log_archive_admin_mutex);
2082 DBUG_PRINT("redo_log_archive", ("Redo log archive log consumer stopped"));
2083 }
2084
2085 /**
2086 Initialize UDF innodb_redo_log_archive_start
2087
2088 See include/mysql/udf_registration_types.h
2089 */
2090 bool innodb_redo_log_archive_start_init(UDF_INIT *initid [[maybe_unused]],
2091 UDF_ARGS *args, char *message) {
2092 if ((args->arg_count < 1) || (args->arg_count > 2)) {
2093 snprintf(message, MYSQL_ERRMSG_SIZE, "Invalid number of arguments.");
2094 return true;
2095 }
2096 if (args->args[0] == nullptr) {
2097 snprintf(message, MYSQL_ERRMSG_SIZE, "First argument must not be null.");
2098 return true;
2099 }
2100 if (args->arg_type[0] != STRING_RESULT) {
2101 snprintf(message, MYSQL_ERRMSG_SIZE, "Invalid first argument type.");
2102 return true;
2103 }
2104 if ((args->arg_count == 2) && (args->arg_type[1] != STRING_RESULT)) {
2105 snprintf(message, MYSQL_ERRMSG_SIZE, "Invalid second argument type.");
2106 return true;
2107 }
2108 return false;
2109 }
2110
2111 /**
2112 Deinitialize UDF innodb_redo_log_archive_start
2113
2114 See include/mysql/udf_registration_types.h
2115 */
2116 void innodb_redo_log_archive_start_deinit(UDF_INIT *initid [[maybe_unused]]) {
2117 return;
2118 }
2119
2120 /**
2121 UDF innodb_redo_log_archive_start
2122
2123 The UDF is of type Udf_func_longlong returning INT_RESULT
2124
2125 See include/mysql/udf_registration_types.h
2126
2127 The UDF expects two or three arguments:
2128 - A thread context pointer, maybe NULL
2129 - A label from the server system variable innodb_redo_log_archive_dirs
2130 - An optional subdirectory inside the corresponding directory path from
2131 innodb_redo_log_archive_dirs. This must be a plain directory
2132 name. On Unix/Linux/Mac no slash ('/') is allowed in the
2133 argument. On Windows, no slash ('/'), backslash ('\'), nor
2134 colon (':') is allowed in the argument. Can be NULL or empty.
2135
2136 Returns zero on success, one otherwise.
2137 */
2138 long long innodb_redo_log_archive_start(UDF_INIT *initid [[maybe_unused]],
2139 UDF_ARGS *args,
2140 unsigned char *null_value
2141 [[maybe_unused]],
2142 unsigned char *error [[maybe_unused]]) {
2143 return static_cast<long long>(meb::redo_log_archive_start(
2144 current_thd, args->args[0],
2145 (args->arg_count == 2) ? args->args[1] : nullptr));
2146 }
2147
2148 /**
2149 Initialize UDF innodb_redo_log_archive_stop
2150
2151 See include/mysql/udf_registration_types.h
2152 */
2153 bool innodb_redo_log_archive_stop_init(UDF_INIT *initid [[maybe_unused]],
2154 UDF_ARGS *args, char *message) {
2155 if (args->arg_count != 0) {
2156 snprintf(message, MYSQL_ERRMSG_SIZE, "Invalid number of arguments.");
2157 return true;
2158 }
2159 return false;
2160 }
2161
2162 /**
2163 Deinitialize UDF innodb_redo_log_archive_stop
2164
2165 See include/mysql/udf_registration_types.h
2166 */
2167 void innodb_redo_log_archive_stop_deinit(UDF_INIT *initid [[maybe_unused]]) {
2168 return;
2169 }
2170
2171 /**
2172 UDF innodb_redo_log_archive_stop
2173
2174 The UDF is of type Udf_func_longlong returning INT_RESULT
2175
2176 See include/mysql/udf_registration_types.h
2177
2178 The UDF expects one argument:
2179 - A thread context pointer, maybe NULL
2180
2181 Returns zero on success, one otherwise.
2182 */
2183 long long innodb_redo_log_archive_stop(UDF_INIT *initid [[maybe_unused]],
2184 UDF_ARGS *args [[maybe_unused]],
2185 unsigned char *null_value
2186 [[maybe_unused]],
2187 unsigned char *error [[maybe_unused]]) {
2188 return static_cast<long long>(meb::redo_log_archive_stop(current_thd));
2189 }
2190
2191 /**
2192 Initialize UDF innodb_redo_log_archive_flush
2193
2194 See include/mysql/udf_registration_types.h
2195 */
2196 bool innodb_redo_log_archive_flush_init(UDF_INIT *initid [[maybe_unused]],
2197 UDF_ARGS *args, char *message) {
2198 if (args->arg_count != 0) {
2199 snprintf(message, MYSQL_ERRMSG_SIZE, "Invalid number of arguments.");
2200 return true;
2201 }
2202 return false;
2203 }
2204
2205 /**
2206 Deinitialize UDF innodb_redo_log_archive_flush
2207
2208 See include/mysql/udf_registration_types.h
2209 */
2210 void innodb_redo_log_archive_flush_deinit(UDF_INIT *initid [[maybe_unused]]) {
2211 return;
2212 }
2213
2214 /**
2215 UDF innodb_redo_log_archive_flush
2216
2217 The UDF is of type Udf_func_longlong returning INT_RESULT
2218
2219 See include/mysql/udf_registration_types.h
2220
2221 The UDF expects one argument:
2222 - A thread context pointer, maybe NULL
2223
2224 Returns zero on success, one otherwise.
2225 */
2226 long long innodb_redo_log_archive_flush(UDF_INIT *initid [[maybe_unused]],
2227 UDF_ARGS *args [[maybe_unused]],
2228 unsigned char *null_value
2229 [[maybe_unused]],
2230 unsigned char *error [[maybe_unused]]) {
2231 return static_cast<long long>(meb::redo_log_archive_flush(current_thd));
2232 }
2233
2234 /**
2235 Initialize UDF innodb_redo_log_sharp_checkpoint
2236
2237 See include/mysql/udf_registration_types.h
2238 */
2239 bool innodb_redo_log_sharp_checkpoint_init([[maybe_unused]] UDF_INIT *initid,
2240 UDF_ARGS *args, char *message) {
2241 if (args->arg_count != 0) {
2242 snprintf(message, MYSQL_ERRMSG_SIZE, "Invalid number of arguments.");
2243 return true;
2244 }
2245 return false;
2246 }
2247
2248 /**
2249 Deinitialize UDF innodb_redo_log_sharp_checkpoint
2250
2251 See include/mysql/udf_registration_types.h
2252 */
2253 void innodb_redo_log_sharp_checkpoint_deinit(
2254 [[maybe_unused]] UDF_INIT *initid) {
2255 return;
2256 }
2257
2258 /**
2259 UDF innodb_redo_log_sharp_checkpoint
2260
2261 The UDF is of type Udf_func_longlong returning INT_RESULT
2262
2263 See include/mysql/udf_registration_types.h
2264
2265 The UDF expects one argument:
2266 - A thread context pointer, maybe NULL
2267
2268 Returns zero on success, one otherwise.
2269 */
2270 long long innodb_redo_log_sharp_checkpoint(
2271 [[maybe_unused]] UDF_INIT *initid, [[maybe_unused]] UDF_ARGS *args,
2272 [[maybe_unused]] unsigned char *null_value,
2273 [[maybe_unused]] unsigned char *error) {
2274 /* Security measure: Require the backup admin privilege. */
2275 if (verify_privilege(current_thd, backup_admin_privilege)) {
2276 return 1;
2277 }
2278
2279 if (log_sys == nullptr) {
2280 my_error(ER_INVALID_USE_OF_NULL, MYF(0));
2281 return 1;
2282 }
2283 LogErr(INFORMATION_LEVEL, ER_INNODB_ERROR_LOGGER_MSG,
2284 "innodb_redo_log_sharp_checkpoint() making checkpoint");
2285 log_make_latest_checkpoint(*log_sys);
2286 return 0;
2287 }
2288
2289 /**
2290 Initialize UDF innodb_redo_log_consumer_register
2291
2292 See include/mysql/udf_registration_types.h
2293 */
2294 bool innodb_redo_log_consumer_register_init([[maybe_unused]] UDF_INIT *initid,
2295 UDF_ARGS *args, char *message) {
2296 if (args->arg_count != 0) {
2297 snprintf(message, MYSQL_ERRMSG_SIZE, "Invalid number of arguments.");
2298 return true;
2299 }
2300 return false;
2301 }
2302
2303 /**
2304 Deinitialize UDF innodb_redo_log_consumer_register
2305
2306 See include/mysql/udf_registration_types.h
2307 */
2308 void innodb_redo_log_consumer_register_deinit(
2309 [[maybe_unused]] UDF_INIT *initid) {}
2310
2311 /**
2312 UDF innodb_redo_log_consumer_register
2313
2314 The UDF is of type Udf_func_longlong returning INT_RESULT
2315 and expects no arguments.
2316
2317 See include/mysql/udf_registration_types.h
2318
2319 Returns zero on success, one otherwise.
2320 */
2321 long long innodb_redo_log_consumer_register(
2322 [[maybe_unused]] UDF_INIT *initid, [[maybe_unused]] UDF_ARGS *args,
2323 [[maybe_unused]] unsigned char *null_value,
2324 [[maybe_unused]] unsigned char *error) {
2325 if (current_thd == nullptr ||
2326 verify_privilege(current_thd, backup_admin_privilege)) {
2327 return 1;
2328 }
2329 return static_cast<long long>(
2330 meb::redo_log_consumer_register(thd_to_innodb_session(current_thd)));
2331 }
2332
2333 /**
2334 Initialize UDF innodb_redo_log_consumer_unregister
2335
2336 See include/mysql/udf_registration_types.h
2337 */
2338 bool innodb_redo_log_consumer_unregister_init([[maybe_unused]] UDF_INIT *initid,
2339 UDF_ARGS *args, char *message) {
2340 if (args->arg_count != 0) {
2341 snprintf(message, MYSQL_ERRMSG_SIZE, "Invalid number of arguments.");
2342 return true;
2343 }
2344 return false;
2345 }
2346
2347 /**
2348 Deinitialize UDF innodb_redo_log_consumer_unregister
2349
2350 See include/mysql/udf_registration_types.h
2351 */
2352 void innodb_redo_log_consumer_unregister_deinit(
2353 [[maybe_unused]] UDF_INIT *initid) {}
2354
2355 /**
2356 UDF innodb_redo_log_consumer_unregister
2357
2358 The UDF is of type Udf_func_longlong returning INT_RESULT
2359 and expects no arguments.
2360
2361 See include/mysql/udf_registration_types.h
2362
2363 Returns zero on success, one otherwise.
2364 */
2365 long long innodb_redo_log_consumer_unregister(
2366 [[maybe_unused]] UDF_INIT *initid, [[maybe_unused]] UDF_ARGS *args,
2367 [[maybe_unused]] unsigned char *null_value,
2368 [[maybe_unused]] unsigned char *error) {
2369 if (current_thd == nullptr) {
2370 return 1;
2371 }
2372 return static_cast<long long>(
2373 meb::redo_log_consumer_unregister(thd_to_innodb_session(current_thd)));
2374 }
2375
2376 /**
2377 Initialize UDF innodb_redo_log_consumer_advance
2378
2379 See include/mysql/udf_registration_types.h
2380 */
2381 bool innodb_redo_log_consumer_advance_init([[maybe_unused]] UDF_INIT *initid,
2382 UDF_ARGS *args, char *message) {
2383 if (args->arg_count != 1) {
2384 snprintf(message, MYSQL_ERRMSG_SIZE, "Invalid number of arguments.");
2385 return true;
2386 }
2387 if (args->arg_type[0] != INT_RESULT) {
2388 snprintf(message, MYSQL_ERRMSG_SIZE, "Invalid argument type.");
2389 return true;
2390 }
2391 return false;
2392 }
2393
2394 /**
2395 Deinitialize UDF innodb_redo_log_consumer_advance
2396
2397 See include/mysql/udf_registration_types.h
2398 */
2399 void innodb_redo_log_consumer_advance_deinit(
2400 [[maybe_unused]] UDF_INIT *initid) {}
2401
2402 /**
2403 UDF innodb_redo_log_consumer_advance
2404
2405 The UDF is of type Udf_func_longlong returning INT_RESULT
2406 and expects LSN argument which is the LSN up to which all
2407 redo log data has been consumed by the registered consumer.
2408
2409 Before calling this function the consumer must be registered
2410 by the innodb_redo_log_consumer_register UDF.
2411
2412 See include/mysql/udf_registration_types.h
2413
2414 Returns zero on success, one otherwise.
2415 */
2416 long long innodb_redo_log_consumer_advance(
2417 [[maybe_unused]] UDF_INIT *initid, UDF_ARGS *args,
2418 [[maybe_unused]] unsigned char *null_value,
2419 [[maybe_unused]] unsigned char *error) {
2420 if (current_thd == nullptr ||
2421 verify_privilege(current_thd, backup_admin_privilege)) {
2422 return 1;
2423 }
2424 return static_cast<long long>(meb::redo_log_consumer_advance(
2425 thd_to_innodb_session(current_thd), *((long long *)args->args[0])));
2426 }
2427 } /* namespace meb */