-
Notifications
You must be signed in to change notification settings - Fork 21
/
controller.py
1573 lines (1454 loc) · 82.1 KB
/
controller.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2019 Aiven, Helsinki, Finland. https://aiven.io/
import contextlib
import datetime
import enum
import json
import logging
import math
import os
import threading
import time
import pymysql
from pghoard.rohmu import get_transfer
from pghoard.rohmu.compressor import DecompressSink
from pghoard.rohmu.encryptor import DecryptSink
from .backup_stream import BackupStream
from .binlog_scanner import BinlogScanner
from .errors import BadRequest
from .restore_coordinator import RestoreCoordinator
from .state_manager import StateManager
from .util import (
are_gtids_in_executed_set,
change_master_to,
DEFAULT_MYSQL_TIMEOUT,
ERR_TIMEOUT,
make_gtid_range_string,
mysql_cursor,
parse_fs_metadata,
relay_log_name,
)
ERR_CANNOT_CONNECT = 2003
class Controller(threading.Thread):
"""Main logic controller for the service. This drives the individual handlers like
BackupStream, BinlogScanner and RestoreCoordinator as well as provides state info
that can be made available by other components like an HTTP server."""
@enum.unique
class Mode(str, enum.Enum):
# Actively back up the system and perform related auxiliary operations
active = "active"
# Waiting for command to determine which state to enter
idle = "idle"
# Observe backup progress by other nodes and perform related auxiliary operations
observe = "observe"
# Promote current server into active one
promote = "promote"
# Restore system to given backup
restore = "restore"
BACKUP_REFRESH_INTERVAL_BASE = 120
# We don't expect anyone but the single active MyHoard to make any changes to backups but we still want
# to sometimes check there aren't some unexpected changes. The "sometimes" can be pretty infrequently
BACKUP_REFRESH_ACTIVE_MULTIPLIER = 10
ITERATION_SLEEP = 1
def __init__(
self,
*,
backup_settings,
backup_sites,
binlog_purge_settings,
mysql_binlog_prefix,
mysql_client_params,
mysql_config_file_name,
mysql_data_directory,
mysql_relay_log_index_file,
mysql_relay_log_prefix,
restart_mysqld_callback,
restore_max_binlog_bytes,
server_id,
state_dir,
stats,
temp_dir,
):
super().__init__()
self.backup_refresh_interval_base = self.BACKUP_REFRESH_INTERVAL_BASE
self.backup_settings = backup_settings
self.backup_sites = backup_sites
self.backup_streams = []
self.backup_streams_initialized = False
self.binlog_not_caught_log_counter = 0
self.binlog_purge_settings = binlog_purge_settings
scanner_state_file = os.path.join(state_dir, "binlog_scanner_state.json")
self.binlog_scanner = BinlogScanner(
binlog_prefix=mysql_binlog_prefix,
server_id=server_id,
state_file=scanner_state_file,
stats=stats,
)
self.is_running = True
self.iteration_sleep = self.ITERATION_SLEEP
self.lock = threading.RLock()
self.log = logging.getLogger(self.__class__.__name__)
self.max_binlog_bytes = None
self.mysql_client_params = mysql_client_params
self.mysql_config_file_name = mysql_config_file_name
self.mysql_data_directory = mysql_data_directory
self.mysql_relay_log_index_file = mysql_relay_log_index_file
self.mysql_relay_log_prefix = mysql_relay_log_prefix
self.restart_mysqld_callback = restart_mysqld_callback
self.restore_max_binlog_bytes = restore_max_binlog_bytes
self.restore_coordinator = None
self.seen_basebackup_infos = {}
self.server_id = server_id
self.site_transfers = {}
self.state = {
"backup_request": {},
"backups": [],
"backups_fetched_at": 0,
"binlogs_purged_at": 0,
"errors": 0,
"force_promote": False,
"last_binlog_purge": time.time(),
"last_binlog_rotation": time.time(),
"last_could_have_purged": time.time(),
"mode": self.Mode.idle,
"owned_stream_ids": [],
"promote_details": {},
"promote_on_restore_completion": False,
"replication_state": {},
"restore_options": {},
"server_uuid": None,
"uploaded_binlogs": [],
}
self.state_dir = state_dir
state_file = os.path.join(state_dir, "myhoard_controller_state.json")
self.state_manager = StateManager(lock=self.lock, state=self.state, state_file=state_file)
self.stats = stats
self.temp_dir = temp_dir
self.wakeup_event = threading.Event()
self._get_upload_backup_site()
self._update_mode_tag()
def is_log_backed_up(self, *, log_index):
return all(
# Only consider streams that are actively backing up binlogs
not backup_stream.is_streaming_binlogs() or backup_stream.is_log_backed_up(log_index=log_index)
for backup_stream in self.backup_streams
)
def is_safe_to_reload(self):
restore_coordinator = self.restore_coordinator
if restore_coordinator and restore_coordinator.phase == RestoreCoordinator.Phase.restoring_basebackup:
return False
with self.lock:
for stream in self.backup_streams:
if stream.active_phase == BackupStream.ActivePhase.basebackup:
return False
return True
def mark_backup_requested(self, *, backup_reason, normalized_backup_time=None):
normalized_backup_time = normalized_backup_time or self._current_normalized_backup_timestamp()
new_request = {"backup_reason": backup_reason, "normalized_backup_time": normalized_backup_time}
with self.lock:
old = self.state["backup_request"]
if old:
if (
old == new_request or normalized_backup_time < old["normalized_backup_time"]
# Prefer storing "scheduled" as backup reason since that reduces chance of trying to correct
# backup schedule too quickly in case of backup time has been changed and manual backup is created
or (
normalized_backup_time == old["normalized_backup_time"]
and old["backup_reason"] == BackupStream.BackupReason.scheduled
)
):
return
self.state_manager.update_state(backup_request=new_request)
@property
def mode(self):
return self.state["mode"]
def restore_backup(self, *, site, stream_id, target_time=None, target_time_approximate_ok=None):
with self.lock:
if self.mode != self.Mode.idle:
# Could consider allowing restore request also when mode is `restore`
raise ValueError("Current mode is {}, restore only allowed while in idle mode".format(self.mode))
for backup in list(self.state["backups"]):
if backup["stream_id"] != stream_id or backup["site"] != site:
continue
if not backup["basebackup_info"]:
raise ValueError("Backup {!r} cannot be restored".format(backup))
if target_time:
if target_time < backup["basebackup_info"]["end_ts"]:
raise ValueError(
"Requested target time {} predates backup completion: {!r}".format(target_time, backup)
)
# Caller must make sure they pick a backup that contains the requested target time. If this backup
# has been closed (will not get any further updates) at a time that is before the requested target
# time it is not possible to satisfy the request
if backup["closed_at"] and target_time > backup["closed_at"]:
raise ValueError("Requested target time {} is after backup close: {!r}".format(target_time, backup))
break
else:
raise ValueError(f"Requested backup {stream_id!r} for site {site!r} not found")
self.log.info(
"Restoring backup stream %r, target time %r%s", stream_id, target_time,
" (approximate time)" if target_time_approximate_ok else ""
)
self.state_manager.update_state(
mode=self.Mode.restore,
restore_options={
"binlog_streams": [{
"site": site,
"stream_id": stream_id,
}],
"pending_binlogs_state_file": self._get_restore_coordinator_pending_state_file_and_remove_old(),
"state_file": self._get_restore_coordinator_state_file_and_remove_old(),
"stream_id": stream_id,
"site": site,
"target_time": target_time,
"target_time_approximate_ok": target_time_approximate_ok,
}
)
self._update_mode_tag()
self.wakeup_event.set()
def rotate_and_back_up_binlog(self):
local_log_index = self._rotate_binlog()
self.wakeup_event.set()
return local_log_index
def run(self):
self.log.info("Controller running")
while self.is_running:
try:
if self.mode == self.Mode.idle:
self._handle_mode_idle()
elif self.mode == self.Mode.restore:
self._handle_mode_restore()
elif self.mode == self.Mode.active:
self._handle_mode_active()
elif self.mode == self.Mode.observe:
self._handle_mode_observe()
elif self.mode == self.Mode.promote:
self._handle_mode_promote()
else:
assert False, "Invalid mode {}".format(self.mode)
self.wakeup_event.wait(self._get_iteration_sleep())
self.wakeup_event.clear()
except Exception as ex: # pylint: disable=broad-except
self.log.exception("Unexpected exception in mode %s", self.mode)
self.stats.unexpected_exception(ex=ex, where="Controller.run")
self.state_manager.increment_counter(name="errors")
self.stats.increase("myhoard.generic_errors")
time.sleep(self.iteration_sleep)
self.is_running = False
def stop(self):
self.log.info("Stopping controller")
self.is_running = False
self.wakeup_event.set()
with contextlib.suppress(Exception):
self.join()
if self.restore_coordinator:
self.restore_coordinator.stop()
for stream in self.backup_streams:
stream.stop()
self.log.info("Controller stopped")
def switch_to_active_mode(self, *, force=False):
"""Requests switching from idle, observe or restore mode to active mode. This does
not immediately switch mode to active but instead switches to promote mode first, which
automatically switches to active mode once promotion flow has been successfully completed"""
with self.lock:
# If current mode is promote and some binlogs are being applied, set a flag indicating that
# promotion should be considered complete even if applying the binary logs has not completed
if self.mode == self.Mode.promote and force and self.state["promote_details"].get("binlogs_applying"):
self.state_manager.update_state(force_promote=True)
return
elif self.mode == self.Mode.restore:
if not force:
self._fail_if_restore_is_not_complete()
else:
if not self.restore_coordinator:
raise ValueError("Cannot switch mode, current restoration state is indeterminate")
self.restore_coordinator.force_completion()
self.state_manager.update_state(force_promote=True, promote_on_restore_completion=True)
return
elif force:
raise BadRequest("Can only force promotion while waiting for binlogs to be applied")
elif self.mode in {self.Mode.active, self.Mode.promote}:
self.log.info("Already in %s mode when switch to active mode was requested", self.mode)
return
elif self.mode == self.Mode.observe:
self._fail_if_observe_to_active_switch_is_not_allowed()
self.state_manager.update_state(
# Ensure latest backup list is fetched before promotion so that we
# start working with appropriate backup streams
backups_fetched_at=0,
mode=self.Mode.promote,
restore_options={},
)
self._update_mode_tag()
self.wakeup_event.set()
def switch_to_observe_mode(self):
"""Request switching from idle or restore mode to observe mode"""
with self.lock:
if self.mode == self.Mode.observe:
self.log.info("Requested switch to observe mode but currently mode is already that")
return
elif self.mode in {self.Mode.active, self.Mode.promote}:
# Master (or almost master) cannot become a standby
raise ValueError(f"Switch from {self.mode} to observe mode is not allowed")
elif self.mode == self.Mode.restore:
self._fail_if_restore_is_not_complete()
self._fail_if_not_read_only()
self.state_manager.update_state(
backups_fetched_at=0,
mode=self.Mode.observe,
restore_options={},
)
self._update_mode_tag()
@classmethod
def collect_binlogs_to_purge(
cls, *, backup_streams, binlogs, exclude_uuid=None, log, mode, purge_settings, replication_state
):
only_binlogs_without_gtids = None
binlogs_to_purge = []
binlogs_to_maybe_purge = []
for binlog in binlogs:
binlog_age = time.time() - binlog["processed_at"]
min_age = purge_settings["min_binlog_age_before_purge"]
if binlog_age < min_age:
log.info(
"Binlog %s was processed %s seconds ago and min age before purging is %s seconds, not purging",
binlog["local_index"], math.ceil(binlog_age), min_age
)
break
if mode == cls.Mode.active:
# In active mode we want all streams to say purging a binlog is safe
can_purge = all(
stream.is_binlog_safe_to_delete(binlog, exclude_uuid=exclude_uuid) for stream in backup_streams
)
if not can_purge:
log.info("Binlog %s reported not safe to delete by some backup streams", binlog["local_index"])
elif purge_settings["purge_when_observe_no_streams"] and not backup_streams:
log.info("No backup streams and purging is allowed, assuming purging %s is safe", binlog["local_index"])
can_purge = True
else:
# Any stream that has basebackup info (is resumable) must say purging is safe and there must
# be at least one such stream. For other streams we don't care.
at_least_one_safe_stream = False
at_least_one_unsafe_stream = False
for stream in backup_streams:
if stream.state["basebackup_info"]:
if stream.is_binlog_safe_to_delete( # pylint: disable=simplifiable-if-statement
binlog, exclude_uuid=exclude_uuid
):
at_least_one_safe_stream = True
else:
at_least_one_unsafe_stream = True
can_purge = at_least_one_safe_stream and not at_least_one_unsafe_stream
if can_purge:
log.info(
"Binlog %s is reported safe to delete by at least one stream and not as unsafe by any",
binlog["local_index"]
)
else:
log.info(
"Binlog %s either reported as unsafe to delete (%s) by some stream or not reported as safe to "
"delete by any (%s)", binlog["local_index"], at_least_one_unsafe_stream, at_least_one_safe_stream
)
if not can_purge:
break
# If we haven't been informed of any replication state assume purging is safe for any backed up binlog
if not replication_state:
log.info("No replication state set, assuming purging binlog %s is safe", binlog["local_index"])
binlogs_to_purge.append(binlog)
elif not binlog["gtid_ranges"]:
if only_binlogs_without_gtids is None:
only_binlogs_without_gtids = True
if mode == cls.Mode.observe:
binlogs_to_purge.append(binlog)
else:
# Maybe purge this. We cannot tell based on the information we have whether deleting is safe because
# we only have replication GTID info available but not info about which files each server has
# replicated. If we delete a file that is after any server's current position, even if the file is
# empty, replication will break. We know this is safe to purge when we encounter at least one binlog
# with GTIDs after this one and those GTIDs have all been replicated.
binlogs_to_maybe_purge.append(binlog)
else:
only_binlogs_without_gtids = False
for server_name, gtid_executed in replication_state.items():
if not are_gtids_in_executed_set(gtid_executed, binlog["gtid_ranges"], exclude_uuid=exclude_uuid):
log.info(
"Binlog %s not yet replicated to server %r, not purging", binlog["local_index"], server_name
)
can_purge = False
break
if can_purge:
log.info("Binlog %s has been replicated to all servers, purging", binlog["local_index"])
binlogs_to_purge.extend(binlogs_to_maybe_purge)
binlogs_to_maybe_purge = []
binlogs_to_purge.append(binlog)
else:
break
return binlogs_to_purge, only_binlogs_without_gtids
@staticmethod
def get_backup_list(backup_sites, *, seen_basebackup_infos=None, site_transfers=None):
if seen_basebackup_infos is None:
seen_basebackup_infos = {}
if site_transfers is None:
site_transfers = {}
backups = []
for site_name, site_config in backup_sites.items():
file_storage = site_transfers.get(site_name)
if file_storage is None:
file_storage = get_transfer(site_config["object_storage"])
site_transfers[site_name] = file_storage
streams = list(file_storage.list_prefixes(site_name))
for site_and_stream_id in streams:
basebackup_compressed_size = None
basebackup_info = None
closed_info = None
completed_info = None
for info in file_storage.list_iter(site_and_stream_id):
file_name = info["name"].rsplit("/", 1)[-1]
if file_name == "basebackup.xbstream":
basebackup_compressed_size = info["size"]
elif file_name == "basebackup.json":
# The basebackup info json contents never change after creation so we can use cached
# value if available to avoid re-fetching the same content over and over again
basebackup_info = seen_basebackup_infos.get(site_and_stream_id)
if basebackup_info is None:
info_str, _ = file_storage.get_contents_to_string(info["name"])
basebackup_info = json.loads(info_str.decode("utf-8"))
seen_basebackup_infos[site_and_stream_id] = basebackup_info
elif file_name == "closed.json":
closed_info = parse_fs_metadata(info["metadata"])
elif file_name == "completed.json":
completed_info = parse_fs_metadata(info["metadata"])
if basebackup_info and basebackup_compressed_size:
basebackup_info = dict(basebackup_info, compressed_size=basebackup_compressed_size)
resumable = basebackup_info and basebackup_compressed_size
completed = resumable and completed_info
closed = completed and closed_info
backups.append({
"basebackup_info": basebackup_info,
"closed_at": closed_info["closed_at"] if closed else None,
"completed_at": completed_info["completed_at"] if completed else None,
"recovery_site": site_config.get("recovery_only", False),
"stream_id": site_and_stream_id.rsplit("/", 1)[-1],
"resumable": bool(resumable),
"site": site_name,
})
return backups
def _apply_downloaded_remote_binlogs(self):
to_apply = self.state["promote_details"].get("binlogs_to_apply")
if self.state["promote_details"].get("binlogs_applying") or not to_apply:
return
expected_ranges = []
with mysql_cursor(**self.mysql_client_params) as cursor:
# Stop IO and SQL slaves so that we can flush relay logs and retain the old log files. This allows
# us to replace the empty files with ones that have actual content and make the SQL thread apply
# them. Same as with regular restoration.
cursor.execute("STOP SLAVE")
# Get current slave status so that we know which relay logs to reuse
cursor.execute("SHOW SLAVE STATUS")
slave_status = cursor.fetchone()
first_name = slave_status["Relay_Log_File"]
if not first_name:
first_name = "relay.000001"
if not self.state["promote_details"].get("relay_index_updated"):
first_index = int(first_name.split(".")[-1])
if (
first_index == 1 and not slave_status["Relay_Master_Log_File"]
and not slave_status["Exec_Master_Log_Pos"] and not slave_status["Retrieved_Gtid_Set"]
):
# FLUSH RELAY LOGS does nothing if RESET SLAVE has been called since last call to CHANGE MASTER TO
self.log.info(
"Slave status is empty, assuming RESET SLAVE has been executed and writing relay index manually"
)
with open(self.mysql_relay_log_index_file, "wb") as index_file:
names = [self._relay_log_name(index=i + 1, full_path=False) for i in range(len(to_apply))]
index_file.write(("\n".join(names) + "\n").encode("utf-8"))
self.log.info("Wrote names: %s", names)
else:
for _ in to_apply:
cursor.execute("FLUSH RELAY LOGS")
self.state_manager.update_state(
promote_details={
**self.state["promote_details"],
"relay_index_updated": True,
}
)
for idx, binlog in enumerate(to_apply):
if not self.state["promote_details"].get("relay_logs_renamed"):
os.rename(binlog["local_prefetch_name"], self._relay_log_name(index=first_index + idx))
self.log.info(
"Renamed %r to %r", binlog["local_prefetch_name"], self._relay_log_name(index=first_index + idx)
)
expected_ranges.extend(binlog["gtid_ranges"])
if not self.state["promote_details"].get("relay_logs_renamed"):
self.state_manager.update_state(
promote_details={
**self.state["promote_details"],
"relay_logs_renamed": True,
}
)
# Make SQL thread replay relay logs starting from where we have replaced empty / old logs with
# new ones that have actual valid binlogs from previous master
options = {
"MASTER_AUTO_POSITION": 0,
"MASTER_HOST": "dummy",
"RELAY_LOG_FILE": first_name,
"RELAY_LOG_POS": 4,
}
change_master_to(cursor=cursor, options=options)
cursor.execute("START SLAVE SQL_THREAD")
expected_file = self._relay_log_name(index=first_index + len(to_apply), full_path=False)
expected_ranges = make_gtid_range_string(expected_ranges)
self.log.info(
"Started SQL thread, waiting for file %r and GTID range %r to be reached", expected_file, expected_ranges
)
self.state_manager.update_state(
promote_details={
**self.state["promote_details"],
"binlogs_applying": to_apply,
"binlogs_to_apply": [],
"expected_file": expected_file,
"expected_ranges": expected_ranges,
}
)
def _binlog_uploaded(self, *, local_index, remote_key, stream):
# Do the actual update calls from main controller thread to avoid any other binlog updates
# happening to be ongoing at the same time that could cause hard to debug random failures
with self.lock:
binlog_info = {
"exclude_stream_id": stream.stream_id,
"local_index": local_index,
"remote_key": remote_key,
}
self.state_manager.update_state(uploaded_binlogs=self.state["uploaded_binlogs"] + [binlog_info])
def _build_backup_stream(self, backup):
stream_id = backup["stream_id"]
backup_site = self.backup_sites[backup["site"]]
# Some of the values being passed here like backup_reason will be set correctly either based on
# data stored in local state file if available or in backup file storage if local state is not available
return BackupStream(
backup_reason=None,
compression=backup_site.get("compression"),
file_storage_setup_fn=lambda: get_transfer(backup_site["object_storage"]),
file_uploaded_callback=self._binlog_uploaded,
# Always create in observe mode, will be switched to
# active mode later if needed
mode=BackupStream.Mode.observe,
mysql_client_params=self.mysql_client_params,
mysql_config_file_name=self.mysql_config_file_name,
mysql_data_directory=self.mysql_data_directory,
normalized_backup_time=None,
rsa_public_key_pem=backup_site["encryption_keys"]["public"],
server_id=self.server_id,
state_file=self._state_file_from_stream_id(stream_id),
site=backup["site"],
stats=self.stats,
stream_id=stream_id,
temp_dir=self.temp_dir,
)
def _cache_server_uuid_if_missing(self):
if self.state["server_uuid"]:
return
with mysql_cursor(**self.mysql_client_params) as cursor:
cursor.execute("SELECT @@GLOBAL.server_uuid AS server_uuid")
server_uuid = cursor.fetchone()["server_uuid"]
self.state_manager.update_state(server_uuid=server_uuid)
def _check_binlog_apply_status(self):
binlogs = self.state["promote_details"].get("binlogs_applying")
if not binlogs:
return
expected_file = self.state["promote_details"].get("expected_file")
expected_ranges = self.state["promote_details"].get("expected_ranges")
with mysql_cursor(**self.mysql_client_params) as cursor:
cursor.execute("SHOW SLAVE STATUS")
slave_status = cursor.fetchone()
current_file = slave_status["Relay_Log_File"]
reached_target = True
if current_file != expected_file:
reached_target = False
elif expected_ranges:
cursor.execute("SELECT GTID_SUBSET(%s, @@GLOBAL.gtid_executed) AS executed", [expected_ranges])
if not cursor.fetchone()["executed"]:
reached_target = False
if not reached_target:
if self.state["force_promote"]:
self.log.warning("Promotion target state not reached but forced promotion requested")
else:
sql_thread_running = slave_status["Slave_SQL_Running"]
if sql_thread_running != "Yes":
self.log.warning("Expected SQL thread to be running state is %s, starting it", sql_thread_running)
cursor.execute("START SLAVE SQL_THREAD")
return
else:
self.log.info("Expected relay log (%r) and GTIDs reached (%r)", expected_file, expected_ranges)
cursor.execute("STOP SLAVE")
promote_details = {
**self.state["promote_details"],
"binlogs_applying": [],
"expected_file": None,
"expected_ranges": None,
}
if not reached_target and self.state["force_promote"]:
promote_details["binlogs_to_apply"] = []
promote_details["binlogs_to_fetch"] = []
self.state_manager.update_state(promote_details=promote_details)
def _create_new_backup_stream_if_requested_and_max_streams_not_exceeded(self):
# Only ever have two open backup streams. Uploading binlogs to more streams than that is
# unlikely to improve the system behavior. We'll create new backup stream once the latter
# one catches up with the first, the first is marked as closed, and removed from our list.
if len(self.backup_streams) >= 2:
return
with self.lock:
request = self.state["backup_request"]
if request:
self._start_new_backup(
backup_reason=request["backup_reason"],
normalized_backup_time=request["normalized_backup_time"],
)
def _create_restore_coordinator_if_missing(self):
if self.restore_coordinator:
return
options = self.state["restore_options"]
backup_site = self.backup_sites[options["site"]]
storage_config = backup_site["object_storage"]
self.log.info("Creating new restore coordinator")
self.restore_coordinator = RestoreCoordinator(
binlog_streams=options["binlog_streams"],
file_storage_config=storage_config,
max_binlog_bytes=self.restore_max_binlog_bytes,
mysql_client_params=self.mysql_client_params,
mysql_config_file_name=self.mysql_config_file_name,
mysql_data_directory=self.mysql_data_directory,
mysql_relay_log_index_file=self.mysql_relay_log_index_file,
mysql_relay_log_prefix=self.mysql_relay_log_prefix,
pending_binlogs_state_file=options["pending_binlogs_state_file"],
restart_mysqld_callback=self.restart_mysqld_callback,
rsa_private_key_pem=backup_site["encryption_keys"]["private"],
site=options["site"],
state_file=options["state_file"],
stats=self.stats,
stream_id=options["stream_id"],
target_time=options["target_time"],
target_time_approximate_ok=options["target_time_approximate_ok"],
temp_dir=self.temp_dir,
)
if not self.restore_coordinator.is_complete():
self.log.info("Starting restore coordinator")
self.restore_coordinator.start()
else:
self.log.info("Newly created restore coordinator is already in completed state")
def _current_normalized_backup_timestamp(self):
"""Returns the closest historical backup time that current time matches to (or current time if it matches).
E.g. if backup hour is 13, backup minute is 50, current time is 15:40 and backup interval is 60 minutes,
the return value is 14:50 today. If backup hour and minute are as before, backup interval is 1440 and
current time is 13:45 the return value is 13:50 yesterday."""
now = datetime.datetime.now(datetime.timezone.utc)
normalized = now
backup_interval_minutes = self.backup_settings["backup_interval_minutes"]
backup_hour = self.backup_settings["backup_hour"]
backup_minute = self.backup_settings["backup_minute"]
if normalized.hour < backup_hour or (normalized.hour == backup_hour and normalized.minute < backup_minute):
normalized = normalized - datetime.timedelta(days=1)
normalized = normalized.replace(hour=backup_hour, minute=backup_minute, second=0, microsecond=0)
while normalized + datetime.timedelta(minutes=backup_interval_minutes) < now:
normalized = normalized + datetime.timedelta(minutes=backup_interval_minutes)
return normalized.isoformat()
def _determine_unapplied_remote_binlogs(self, stream):
"""Finds out if given stream contains any remote binlogs that have GTIDs that have not
yet been applied locally. Possibly found binlogs are stored in state so that they get
downloaded and applied."""
missing_checked_key = f"{stream.stream_id}.missing_checked"
if self.state["promote_details"].get(missing_checked_key) or self.state["force_promote"]:
return
already_processed_remote_indexes = set()
for key in {"binlogs_to_fetch", "binlogs_to_apply", "binlogs_applying"}:
for binlog in self.state["promote_details"].get(key, []):
already_processed_remote_indexes.add(binlog["remote_index"])
missing_binlogs = []
missing_gtids = False
with mysql_cursor(**self.mysql_client_params) as cursor:
for binlog in stream.iterate_remote_binlogs(reverse=True):
if binlog["remote_index"] in already_processed_remote_indexes:
break
if not binlog["gtid_ranges"]:
missing_binlogs.insert(0, binlog)
else:
gtid_str = make_gtid_range_string(binlog["gtid_ranges"])
cursor.execute("SELECT GTID_SUBSET(%s, @@GLOBAL.gtid_executed) AS executed", [gtid_str])
executed = cursor.fetchone()["executed"]
if executed:
break
missing_binlogs.insert(0, binlog)
missing_gtids = True
binlogs_to_fetch = self.state["promote_details"].get("binlogs_to_fetch", [])
# No point in applying binlogs that don't have any GTIDs in them (we shouldn't even have such binlogs)
# as we don't know whether those really are applied or not and applying them doesn't change things anyway
if missing_gtids:
# New binlogs must be after the earlier binlogs because we skipped any that had already been seen
site = self._get_site_for_stream_id(stream.stream_id)
missing_binlogs = [{**binlog, "site": site} for binlog in missing_binlogs]
binlogs_to_fetch = binlogs_to_fetch + missing_binlogs
self.state_manager.update_state(
promote_details={
**self.state["promote_details"],
missing_checked_key: True,
"binlogs_to_fetch": binlogs_to_fetch,
}
)
def _download_unapplied_remote_binlogs(self):
"""Download any binlogs that master has uploaded to file storage but we haven't applied.
In normal situation there shouldn't be any and in abnormal situation there should only be
one or two so don't bother with any multiprocess complexity."""
# Make a copy in case the array gets modified
binlogs_to_fetch = self.state["promote_details"].get("binlogs_to_fetch", [])[:]
for binlog in binlogs_to_fetch:
remote_index = binlog["remote_index"]
# Prefetch name doesn't matter, we'll anyway use whatever indexes the server
# is currently using
local_name = self._relay_log_name(index=remote_index)
prefetch_name = f"{local_name}.prefetch"
binlog["local_prefetch_name"] = prefetch_name
start_time = time.monotonic()
with contextlib.suppress(OSError):
os.remove(prefetch_name)
with open(prefetch_name, "wb") as output_file:
output_obj = DecompressSink(output_file, binlog["compression_algorithm"])
site = binlog["site"]
backup_site = self.backup_sites[site]
output_obj = DecryptSink(output_obj, binlog["remote_file_size"], backup_site["encryption_keys"]["private"])
transfer = self.site_transfers.get(site)
if transfer is None:
transfer = get_transfer(backup_site["object_storage"])
self.site_transfers[site] = transfer
transfer.get_contents_to_fileobj(binlog["remote_key"], output_obj)
self.log.info(
"%r successfully saved as %r in %.2f seconds", binlog["remote_key"], prefetch_name,
time.monotonic() - start_time
)
# Try to keep objects in state mostly immutable to avoid weird issues due to changes from different
# threads when other one has a reference to the same object
binlogs_to_fetch = binlogs_to_fetch[1:]
binlogs_to_apply = self.state["promote_details"].get("binlogs_to_apply", []) + [binlog]
self.state_manager.update_state(
promote_details={
**self.state["promote_details"],
"binlogs_to_apply": binlogs_to_apply,
"binlogs_to_fetch": binlogs_to_fetch,
},
)
def _extend_binlog_stream_list(self):
"""If we're currently restoring a backup to most recent point in time, checks for new available
backup streams and if there is one adds that to the list of streams from which to apply binlogs.
The reasoning for this logic is that if restoring binary logs takes a long time the current master
could fail while we're restoring data but before failing it could've created new backup stream and
uploaded some files there but not in the backup we're restoring, causing data loss when this node
gets promoted after backup restoration completes and there's no available master."""
if not self.restore_coordinator.can_add_binlog_streams():
return
backups = sorted(
(backup for backup in self.state["backups"] if backup["completed_at"]), key=lambda backup: backup["completed_at"]
)
# If most recent current backup is not in the list of backups being restored then we're probably
# restoring some old backup and don't want to automatically get latest changes
if not any(bs["stream_id"] == backups[-1]["stream_id"] for bs in self.restore_coordinator.binlog_streams):
return
old_backups = [{"site": backup["site"], "stream_id": backup["stream_id"]} for backup in backups]
self._refresh_backups_list()
backups = sorted(
(backup for backup in self.state["backups"] if backup["completed_at"]), key=lambda backup: backup["completed_at"]
)
new_backups = [{"site": backup["site"], "stream_id": backup["stream_id"]} for backup in backups]
if old_backups == new_backups:
return
active_stream_found = False
new_binlog_streams = []
for backup in new_backups:
if backup["stream_id"] == self.restore_coordinator.stream_id:
active_stream_found = True
elif active_stream_found:
if backup not in self.restore_coordinator.binlog_streams:
new_binlog_streams.append(backup)
if new_binlog_streams:
if self.restore_coordinator.add_new_binlog_streams(new_binlog_streams):
options = self.state["restore_options"]
options = dict(options, binlog_streams=options["binlog_streams"] + new_binlog_streams)
self.state_manager.update_state(restore_options=options)
self.log.info("Added new binlog streams %r", new_binlog_streams)
def _fail_if_not_read_only(self):
with mysql_cursor(**self.mysql_client_params) as cursor:
cursor.execute("SELECT @@GLOBAL.read_only AS read_only")
if not cursor.fetchone()["read_only"]:
raise Exception("System expected to be in read-only mode but isn't")
def _fail_if_observe_to_active_switch_is_not_allowed(self):
"""Verifies that the MySQL server is in read-only mode with IO and SQL threads stopped"""
with mysql_cursor(**self.mysql_client_params) as cursor:
cursor.execute("SELECT @@GLOBAL.read_only AS read_only")
if not cursor.fetchone()["read_only"]:
raise Exception("System expected to be in read-only mode but isn't")
cursor.execute("SHOW SLAVE STATUS")
info = cursor.fetchone()
if info is None:
# None happens if RESET SLAVE has been performed or if the slave never was running, e.g.
# because there were no binary logs to restore.
self.log.warning("SHOW SLAVE STATUS returned no results.")
return
if info["Slave_IO_Running"] == "Yes":
raise Exception("Slave IO thread expected to be stopped but is running")
if info["Slave_SQL_Running"] == "Yes":
if info["Slave_SQL_Running_State"] != "Slave has read all relay log; waiting for more updates":
raise Exception("Expected SQL thread to be stopped or finished processing updates")
cursor.execute("STOP SLAVE SQL_THREAD")
def _fail_if_restore_is_not_complete(self):
if not self.restore_coordinator:
# Edge case, shouldn't happen
raise ValueError("Cannot switch mode, current restoration state is indeterminate")
if not self.restore_coordinator.is_complete():
raise ValueError("Cannot switch mode, ongoing restoration is not complete")
def _get_iteration_sleep(self):
# Sleep less when in promote mode because this should complete as soon as
# possible to reduce downtime
if self.mode == self.Mode.promote:
return self.iteration_sleep / 10.0
else:
return self.iteration_sleep
def _get_long_timeout_params(self, *, multiplier=1):
connect_params = dict(self.mysql_client_params)
connect_params["timeout"] = DEFAULT_MYSQL_TIMEOUT * 5 * multiplier
return connect_params
def _get_upload_backup_site(self):
non_recovery_sites = {id: values for id, values in self.backup_sites.items() if not values.get("recovery_only")}
if not non_recovery_sites:
raise Exception("No non-recovery sites defined")
if not self.backup_settings.get("upload_site"):
if len(non_recovery_sites) > 1:
raise Exception("No upload site defined but multiple non-recovery sites exist")
return list(non_recovery_sites.items())[0]
site_id = self.backup_settings["upload_site"]
if site_id not in non_recovery_sites:
raise Exception("Defined upload site not present in list of non-recovery backup sites")
return site_id, non_recovery_sites[site_id]
def _get_site_for_stream_id(self, stream_id):
for backup in self.state["backups"]:
if backup["stream_id"] == stream_id:
return backup["site"]
raise KeyError(f"Stream {stream_id} not found in backups")
def _get_restore_coordinator_state_file_and_remove_old(self):
state_file_name = os.path.join(self.state_dir, "restore_coordinator_state.json")
# If we're retrying restoration there could be an old state file, make sure to delete it
# so that obsolete state doesn't get reused
with contextlib.suppress(Exception):
os.remove(state_file_name)
return state_file_name
def _get_restore_coordinator_pending_state_file_and_remove_old(self):
state_file_name = os.path.join(self.state_dir, "restore_coordinator_state.pending_binlogs")
# If we're retrying restoration there could be an old state file, make sure to delete it
# so that obsolete state doesn't get reused
with contextlib.suppress(Exception):
os.remove(state_file_name)
return state_file_name
def _handle_mode_active(self):
self._cache_server_uuid_if_missing()
self._set_uploaded_binlog_references()
self._refresh_backups_list_and_streams()
self._mark_periodic_backup_requested_if_interval_exceeded()
self._create_new_backup_stream_if_requested_and_max_streams_not_exceeded()
self._update_stream_completed_and_closed_statuses()
self._rotate_binlog_if_threshold_exceeded()
self._purge_old_backups()
self._purge_old_binlogs()
self._process_local_binlog_updates()
self._send_binlog_stats()
def _handle_mode_idle(self):
self._refresh_backups_list()
def _handle_mode_observe(self):
self._cache_server_uuid_if_missing()
self._refresh_backups_list_and_streams()
self._purge_old_binlogs()
self._process_local_binlog_updates()
def _handle_mode_promote(self):
self._refresh_backups_list_and_streams()
# It is possible to have a netsplit where clients can talk to old master and old master
# can talk to file storage but it cannot talk to standby and other decision making nodes
# so it gets replaced. In such a situation we want to manually apply any binlogs the old
# master has managed to upload to storage before making this node applicable for actual
# promotion.
if self._prepare_streams_for_promotion() == len(self.backup_streams):
self.log.info("Switching controller to active mode (1)")
self.state_manager.update_state(mode=self.Mode.active, promote_details={})
self._update_mode_tag()
return
self._download_unapplied_remote_binlogs()
self._apply_downloaded_remote_binlogs()
self._check_binlog_apply_status()
has_pending = any(
self.state["promote_details"].get(key) for key in {"binlogs_to_fetch", "binlogs_to_apply", "binlogs_applying"}
)
if not has_pending:
for stream in self.backup_streams:
if stream.mode == BackupStream.Mode.promoted:
stream.activate()
if self._prepare_streams_for_promotion() == len(self.backup_streams):
self.log.info("Switching controller to active mode (2)")
self.state_manager.update_state(mode=self.Mode.active, promote_details={})
self._update_mode_tag()
def _handle_mode_restore(self):
self._create_restore_coordinator_if_missing()
if self.state["server_uuid"] is None and self.restore_coordinator.server_uuid:
self.state_manager.update_state(server_uuid=self.restore_coordinator.server_uuid)
# Need to purge binlogs also during restoration because generating binlogs from relay logs should be enabled
# also during restoration. The binlogs created during restoration could be required e.g. if an old master has
# managed to upload binlogs that have not been replicated to a read replica; when the old master gets replaced
# read replica connects to the new server and must be able to download missing binlogs from there
self._purge_old_binlogs(mysql_maybe_not_running=True)
self._process_local_binlog_updates()
self._extend_binlog_stream_list()
if self.restore_coordinator.phase == RestoreCoordinator.Phase.failed_basebackup:
self._switch_basebackup_if_possible()
if self.state["promote_on_restore_completion"] and self.restore_coordinator.is_complete():
self.state_manager.update_state(
# Ensure latest backup list is fetched before promotion so that we
# start working with appropriate backup streams
backups_fetched_at=0,
force_promote=True,
mode=self.Mode.promote,
restore_options={},
)
def _mark_periodic_backup_requested_if_interval_exceeded(self):
normalized_backup_time = self._current_normalized_backup_timestamp()
last_normalized_backup_time = None
most_recent_scheduled = None
if self.backup_streams:
last_normalized_backup_time = max(stream.state["normalized_backup_time"] for stream in self.backup_streams)
scheduled_streams = [
stream for stream in self.backup_streams
if stream.state["backup_reason"] == BackupStream.BackupReason.scheduled
]
if scheduled_streams:
most_recent_scheduled = max(stream.created_at for stream in scheduled_streams)
# Don't create new backup unless at least half of interval has elapsed since scheduled last backup. Otherwise
# we would end up creating a new backup each time when backup hour/minute changes, which is typically undesired.
# With the "half of interval" check the backup time will quickly drift towards the selected time without backup
# spamming in case of repeated setting changes.
half_backup_interval_s = self.backup_settings["backup_interval_minutes"] * 60 / 2