-
Notifications
You must be signed in to change notification settings - Fork 41
/
pyxbackup
4105 lines (3281 loc) · 146 KB
/
pyxbackup
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
#!/usr/bin/python
# pyxbackup - Robust Xtrabackup based MySQL Backups Manager
#
# @author Jervin Real <jervin.real@percona.com>
import sys, traceback, os, errno, signal, socket
import time, calendar, shutil, re, pwd
import smtplib, MySQLdb, base64
from datetime import datetime, timedelta
from ConfigParser import ConfigParser, NoOptionError
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT, CalledProcessError
from struct import unpack
XB_BIN_NAME = 'pyxbackup'
xb_opt_config = None
xb_opt_config_section = None
xb_opt_stor_dir = ''
xb_opt_work_dir = ''
xb_opt_mysql_user = None
xb_opt_mysql_pass = None
xb_opt_mysql_host = 'localhost'
xb_opt_mysql_port = 3306
xb_opt_mysql_sock = None
xb_opt_mysql_cnf = None
xb_opt_retention_binlogs = False
xb_opt_compress = False
xb_opt_compress_with = 'gzip'
xb_opt_apply_log = False
xb_opt_prepare_memory = 128
xb_opt_retention_sets = 2
xb_opt_retention_months = 0
xb_opt_retention_weeks = 0
xb_opt_debug = False
xb_opt_quiet = False
xb_opt_status_format = None
xb_opt_command = 'status'
xb_opt_restore_backup = None
xb_opt_restore_dir = None
xb_opt_remote_stor_dir = None
xb_opt_remote_host = None
xb_opt_remote_push_only = None
xb_opt_remote_script = XB_BIN_NAME
xb_opt_remote_nc_port = 0
xb_opt_remote_nc_port_min = 0
xb_opt_remote_nc_port_max = 0
xb_opt_ssh_opts = ''
xb_opt_ssh_user = None
xb_opt_notify_by_email = None
xb_opt_notify_on_success = None
xb_opt_meta_item = None
xb_opt_wipeout = False
xb_opt_first_binlog = False
xb_opt_binlog_binary = None
xb_opt_binlog_from_master = False
xb_opt_binlog_resume = 0
xb_opt_encrypt = False
xb_opt_encrypt_key_file = None
xb_opt_extra_ibx_options = None
xb_opt_purge_bitmaps = None
xb_hostname = None
xb_user = None
xb_stor_full = None
xb_stor_incr = None
xb_stor_weekly = None
xb_stor_monthly = None
xb_stor_binlogs = None
xb_curdate = None
xb_cfg = None
xb_cwd = None
xb_lang = None
xb_version = 0.5
xb_ibx_opts = ''
xb_ibx_bin = 'innobackupex'
xb_zip_bin = 'gzip'
xb_xbs_bin = 'xbstream'
xb_this_backup = None
xb_this_backup_remote = None
xb_this_binlog = None
xb_this_master_binlog = None
xb_this_last_lsn = None
xb_last_full = None
xb_last_incr = None
xb_full_list = None
xb_incr_list = None
xb_weekly_list = None
xb_monthly_list = None
xb_last_backup = None
xb_last_backup_is = None
xb_stor_start_binlog = None
xb_stor_end_binlog = None
xb_binlogs_list = None
xb_binlog_name = None
xb_exit_code = 0
xb_prepared_backup = ''
xb_backup_is_success = False
xb_prepare_is_success = False
xb_backup_in_progress = None
xb_info_bkp_start = None
xb_info_bkp_end = None
xb_info_prep_start = None
xb_info_prep_end = None
xb_log_file = ''
xb_log_fd = None
xb_is_last_day_of_week = False
xb_is_last_day_of_month = False
xb_mysqldb = None
xb_backup_summary = None
xb_server_version = None
xb_server_type = 'mysql'
XB_CMD_INCR = 'incr'
XB_CMD_FULL = 'full'
XB_CMD_LIST = 'list'
XB_CMD_STAT = 'status'
XB_CMD_PREP = 'restore-set'
XB_CMD_APPL = 'apply-last'
XB_CMD_PRUNE = 'prune'
XB_CMD_META = 'meta'
XB_CMD_BINLOGS = 'binlog-stream'
XB_CMD_WIPE = 'wipeout'
XB_TAG_FILE = 'xtrabackup_checkpoints'
XB_CKP_FILE = 'xtrabackup_checkpoints'
XB_LOG_FILE = 'xtrabackup_logfile'
XB_LCK_FILE = ''
XB_META_FILE = 'backup.meta'
XB_BKP_LOG = 'innobackupex-backup.log'
XB_APPLY_LOG = 'innobackupex-prepare.log'
XB_LOG_NAME = XB_BIN_NAME + '.log'
XB_SSH_TMPFILE = '/tmp/' + XB_BIN_NAME + '-ssh-result'
XB_SIGTERM_CAUGHT = False
XB_VERSION_MAJOR = 0
XB_VERSION_MINOR = 0
XB_VERSION_REV = 0
XB_VERSION = None
XB_EXIT_COMPRESS_FAIL = 1
XB_EXIT_REMOTE_PUSH_FAIL = 2
XB_EXIT_EXTRACT_FAIL = 4
XB_EXIT_BITMAP_PURGE_FAIL = 8
XB_EXIT_NO_FULL = 16
XB_EXIT_DECRYPT_FAIL = 32
XB_EXIT_APPLY_FAIL = 64
XB_EXIT_INNOBACKUP_FAIL = 65
XB_EXIT_BINLOG_STREAM_FAIL = 66
XB_EXIT_REMOTE_CMD_FAIL = 96
XB_EXIT_BY_DEATH = 128
XB_EXIT_EXCEPTION = 255
# What commands does not need a log or lock file
cmd_no_log = [
XB_CMD_LIST, XB_CMD_STAT, XB_CMD_META, XB_CMD_BINLOGS,
XB_CMD_PRUNE]
cmd_no_lock = cmd_no_log
cmd_backups = [XB_CMD_FULL, XB_CMD_INCR]
class PyxLanguage(object):
dictionary = {
'rotate_to_monthly': "Rotating backup %s to monthly",
'binlog_start_from': "Maintaing binary logs from %s"
}
def __init__(self):
pass
def say(self, key, params=None):
return self.dictionary[key] % params
def date(unixtime, format = '%m/%d/%Y %H:%M:%S'):
d = datetime.fromtimestamp(unixtime)
return d.strftime(format)
def _xb_version(verstr = None, tof = False):
global XB_VERSION_MAJOR
global XB_VERSION_MINOR
global XB_VERSION_REV
global XB_VERSION
global xb_ibx_bin
if verstr is None:
if XB_VERSION is not None:
if tof: return float("%d.%d" % (XB_VERSION_MAJOR, XB_VERSION_MINOR))
else: return True
if xb_server_type == 'mariadb':
xb_ibx_bin = 'mariabackup'
else:
xb_ibx_bin = 'xtrabackup'
p = Popen([xb_ibx_bin, "--version"], stdout=PIPE, stderr=PIPE)
# weird, xtrabackup outputs version
# string on STDERR instead of STDOUT
out, err = p.communicate()
ver = re.search('[version|server] ([\d\.]+)', err)
major, minor, rev = ver.group(1).split('.')
XB_VERSION_MAJOR = int(major) if major else 0
XB_VERSION_MINOR = int(minor) if minor else 0
XB_VERSION_REV = int(rev) if rev else 0
XB_VERSION = "%d.%d.%d" % (
XB_VERSION_MAJOR, XB_VERSION_MINOR, XB_VERSION_REV)
if XB_VERSION_MAJOR == 0:
_error(
"Invalid xtrabackup version or unable to determine valid "
"version string or binary version non-GA release")
_error("Version string was \"%s\"" % err)
_die("Exiting")
if float('%d.%d' % (XB_VERSION_MAJOR, XB_VERSION_MINOR)) >= 2.3 and xb_server_type != 'mariadb':
xb_ibx_bin = 'xtrabackup'
_debug("Found xtrabackup version %d.%d.%d" % (
XB_VERSION_MAJOR, XB_VERSION_MINOR, XB_VERSION_REV))
else:
major, minor, rev = verstr.split('.')
major = int(major) if major else 0
minor = int(minor) if minor else 0
rev = int(rev) if rev else 0
if tof:
return float("%d.%d" % (major, minor))
else: return [major, minor, rev]
return True
def _out(tag, *msgs):
s = ''
if not msgs:
return
for msg in msgs:
s += str(msg)
out = "[%s] %s: %s" % (date(time.time()), tag, s)
if xb_log_fd is not None:
os.write(xb_log_fd, "%s\n" % out)
if not xb_opt_quiet: print out
def _say(*msgs):
_out('INFO', *msgs)
def _warn(*msgs):
_out('WARN', *msgs)
def _error(*msgs):
_out('ERROR', *msgs)
def _die(*msgs):
_out('FATAL', *msgs)
if not xb_exit_code: _exit_code(XB_EXIT_BY_DEATH)
raise Exception(str(msgs))
def _debug(*msgs):
if xb_opt_debug: _out("** DEBUG **", *msgs)
def _which(file):
for path in os.environ["PATH"].split(os.pathsep):
if os.path.exists(path + os.path.sep + file):
return path + os.path.sep + file
return None
def _parse_port_param(param):
"""
Parses and assign given port range values
i.e.
remote_nc_port = 9999
remote_nc_port = 9999,1000
"""
global xb_opt_remote_nc_port_min
global xb_opt_remote_nc_port_max
if not param: return False
if param.isdigit():
xb_opt_remote_nc_port_min = int(param)
xb_opt_remote_nc_port_max = xb_opt_remote_nc_port_min
return True
elif param.count(',') == 1:
pmin, pmax = param.split(',')
pmin = pmin.strip()
pmax = pmax.strip()
if not pmin.isdigit() or not pmax.isdigit(): return False
xb_opt_remote_nc_port_min = int(pmin)
xb_opt_remote_nc_port_max = int(pmax)
if xb_opt_remote_nc_port_min > xb_opt_remote_nc_port_max:
pmin = xb_opt_remote_nc_port_max
xb_opt_remote_nc_port_max = xb_opt_remote_nc_port_min
xb_opt_remote_nc_port_min = pmin
return True
return False
def _read_magic_chunk(bfile, size):
"""
This is a more reliable way of reading some files format
XBCRYP for xbcrypt files
XBSTCK for xbstream files
"""
if not os.path.isfile(bfile):
return None
return open(bfile, 'rb').read(size)
def _check_binary(name):
bin = _which(name)
if bin is None:
_die("%s script is not found in $PATH" % name)
return bin
def _check_mariadb_binaries():
global xb_xbs_bin
if xb_opt_command in [XB_CMD_FULL, XB_CMD_INCR, XB_CMD_PREP, XB_CMD_APPL]:
_check_binary('mariabackup')
if xb_opt_remote_nc_port_min:
_check_binary('nc')
_check_binary('netstat')
if xb_opt_encrypt or xb_opt_encrypt_key_file:
_exit_code(XB_EXIT_BY_DEATH)
raise Exception("This script does not support MariaDB backup encryption yet")
if xb_opt_compress:
_check_binary('mbstream')
if xb_opt_compress_with == 'qpress':
_exit_code(XB_EXIT_BY_DEATH)
raise Exception("MariaDB deprecated builtin compression, this is upcoming feature")
elif xb_opt_compress_with == 'gzip':
_check_binary('gzip')
xb_xbs_bin = 'mbstream'
# store xtrabackup version numbers
if xb_opt_command not in [XB_CMD_WIPE, XB_CMD_LIST]:
_xb_version()
def _check_mysql_binaries():
if xb_opt_command in [XB_CMD_FULL, XB_CMD_INCR, XB_CMD_PREP, XB_CMD_APPL]:
_check_binary('innobackupex')
_check_binary('xtrabackup')
if xb_opt_remote_nc_port_min:
_check_binary('nc')
_check_binary('netstat')
if xb_opt_encrypt or xb_opt_encrypt_key_file:
_check_binary('xbcrypt')
if xb_opt_compress:
_check_binary('xbstream')
if xb_opt_compress_with == 'qpress':
_check_binary('qpress')
# store xtrabackup version numbers
if xb_opt_command not in [XB_CMD_WIPE, XB_CMD_LIST]:
_xb_version()
def _exit_code(code):
global xb_exit_code
c = int(code)
if c > xb_exit_code: xb_exit_code = c
def _destroy_lock_file():
if (xb_opt_command == XB_CMD_FULL or xb_opt_command == XB_CMD_INCR) \
and os.path.isfile(XB_LCK_FILE):
if xb_backup_in_progress is None:
os.remove(XB_LCK_FILE)
def _create_lock_file():
if (xb_opt_command == XB_CMD_FULL or xb_opt_command == XB_CMD_INCR):
lck = open(XB_LCK_FILE, 'w')
lck.write("backup = %s\n" % xb_curdate)
lck.write("type = %s\n" % xb_opt_command)
if xb_opt_command == XB_CMD_INCR:
lck.write("full = %s\n" % xb_last_full)
lck.write("pid = %s\n" % str(os.getpid()))
lck.close()
def _xb_logfile_copy(bkp):
log_file = None
# When backup is not compressed we need to preserve the
# xtrabackup_logfile since preparing directly from the
# stor_dir will touch the logfile and we cannot use it
# again
# We do this to make the process faster instead of copying
# the whole incremental backup
if xb_ibx_bin == 'mariabackup':
log_file = 'ib_logfile0'
else:
log_file = XB_LOG_FILE
_say("Preserving %s from %s" % (log_file, bkp))
xb_from = "%s/%s" % (bkp, log_file)
xb_to = "%s/%s.101" % (bkp, log_file)
shutil.copy(xb_from, xb_to)
def _xb_logfile_restore(bkp):
log_file = None
if xb_ibx_bin == 'mariabackup':
log_file = 'ib_logfile0'
else:
log_file = XB_LOG_FILE
_say("Restoring %s from %s" % (log_file, bkp))
xb_from = "%s/%s.101" % (bkp, log_file)
xb_to = "%s/%s" % (bkp, log_file)
if os.path.isfile(xb_to): os.remove(xb_to)
shutil.move(xb_from, xb_to)
def _sigterm_handler(signal, frame):
global XB_SIGTERM_CAUGHT
_say("Got TERM signal, cleaning up ...")
XB_SIGTERM_CAUGHT = True
def _check_in_progress():
global xb_backup_in_progress
ret = False
is_backup = False
if xb_opt_command in [XB_CMD_FULL, XB_CMD_INCR]:
is_backup = True
if os.path.isfile(XB_LCK_FILE):
_debug("%s lock file exists and is_backup is %s" % (XB_LCK_FILE, str(is_backup)))
cfp = _parse_raw_config(XB_LCK_FILE)
pid = int(cfp.get(XB_BIN_NAME, 'pid'))
xb_backup_in_progress = cfp
ret = True
if is_backup:
try:
os.kill(pid, 0)
except OSError, e:
if e.errno == errno.ESRCH:
_die("%s lock file exists but process is not running" % XB_LCK_FILE)
elif e.errno == errno.EPERM:
_die('Permission denied while checking backup process')
else:
_warn('Could not determine backup process state')
else:
_die("Another backup process in progress with PID %d" % pid)
return ret
def _write_backup_info():
global xb_backup_summary
if (xb_opt_command == XB_CMD_FULL or xb_opt_command == XB_CMD_INCR):
inf = open("%s/%s" % (xb_this_backup, XB_META_FILE), 'w')
inf.write("backup = %s\n" % xb_curdate)
inf.write("type = %s\n" % xb_opt_command)
if xb_opt_command == XB_CMD_INCR:
inf.write("full = %s\n" % xb_last_full)
inf.write("start_backup = %s\n" % xb_curdate)
inf.write("end_backup = %s\n" % xb_info_bkp_end)
inf.write("start_prepare = %s\n" % xb_info_prep_start)
inf.write("end_prepare = %s\n" % xb_info_prep_end)
inf.write("compress = %d\n" % int(xb_opt_compress))
inf.write("compress_with = %s\n" % xb_opt_compress_with)
inf.write("log_bin = %s\n" % xb_this_binlog)
inf.write("master_log_bin = %s\n" % xb_this_master_binlog)
inf.write("last_lsn = %s\n" % xb_this_last_lsn)
inf.write("source_version = %d.%d.%d\n" % (
XB_VERSION_MAJOR, XB_VERSION_MINOR, XB_VERSION_REV))
inf.write("source_server_type = %s\n" % xb_server_type)
inf.write("source_server_version = %s\n" % xb_server_version)
inf.close()
if xb_opt_notify_on_success:
xb_backup_summary = "Backup summary: \n\n"
xb_backup_summary += "Backup: %s\n" % xb_curdate
xb_backup_summary += "Type: %s\n" % xb_opt_command
if xb_opt_command == XB_CMD_INCR:
xb_backup_summary += "Full: %s\n" % xb_last_full
xb_backup_summary += "Backup started: %s\n" % xb_curdate
xb_backup_summary += "Backup ended: %s\n" % xb_info_bkp_end
xb_backup_summary += "Prepare started: %s\n" % xb_info_prep_start
xb_backup_summary += "Prepare ended: %s\n" % xb_info_prep_end
xb_backup_summary += "Compressed: %s\n" % bool(xb_opt_compress)
xb_backup_summary += "Compressed with: %s\n" % xb_opt_compress_with
xb_backup_summary += "Binary log name: %s\n" % xb_this_binlog
xb_backup_summary += "Master binary log name: %s\n" % xb_this_master_binlog
xb_backup_summary += "Source xtrabackup version %d.%d.%d\n" % (
XB_VERSION_MAJOR, XB_VERSION_MINOR, XB_VERSION_REV)
xb_backup_summary += "Source server version: %s\n" % xb_server_version
xb_backup_summary += "Source server type: %s\n" % xb_server_type
def _parse_raw_config(ckpnt_f):
if not os.path.isfile(ckpnt_f):
_warn("Config file not found, ", ckpnt_f, "!")
return False
with open(ckpnt_f) as ckp:
defaults = dict([line.replace(' ','').rstrip("\n").split('=') for line in ckp])
cfp = ConfigParser(defaults)
cfp.add_section(XB_BIN_NAME)
return cfp
def _read_backup_metadata(bkp):
meta_path = os.path.join(bkp, XB_META_FILE)
# For backwards compatibility
if not os.path.isfile(meta_path):
meta_path = os.path.join(bkp, 'xbackup.meta')
meta = _parse_raw_config(meta_path)
if not meta:
_die("Unable to read backup meta information, ",
"%s corrupt?" % meta_path)
return meta
def _rotate_xtrabackup_info(dirname):
# We do this when using mbstream because of the bug
# https://jira.mariadb.org/browse/MDEV-18438
if xb_xbs_bin != 'mbstream':
return True
xb_info_file = os.path.join(dirname, 'xtrabackup_info')
xb_info_file0 = os.path.join(dirname, 'xtrabackup_info0')
if os.path.isfile(xb_info_file):
if os.path.isfile(xb_info_file0):
os.remove(xb_info_file0)
shutil.move(xb_info_file, xb_info_file0)
return True
def _apply_log(bkp, incrdir=None, final=False):
if not os.path.isdir(bkp):
_warn("Directory not found, ", bkp, " will not prepare")
return False
cfp = _parse_raw_config("%s/xtrabackup_checkpoints" % bkp)
if not cfp:
_die('Could not parse xtrabackup_checkpoints file')
ibx_cmd = ''
ibx_log = "%s/%s-innobackupex-prepare.log" % (xb_opt_work_dir, xb_curdate)
tee_cmd = "tee %s" % ibx_log
ibx_opts = ""
if xb_ibx_bin != 'innobackupex':
ibx_opts = '--prepare '
else: ibx_opts = '--apply-log '
ibx_opts += "--use-memory=%dM" % xb_opt_prepare_memory
log_fd = None
p_tee = None
if not final:
if xb_ibx_bin != 'innobackupex': ibx_opts += " --apply-log-only"
else: ibx_opts += " --redo-only"
if cfp.get(XB_BIN_NAME,'backup_type') == 'incremental':
_say('Preparing incremental backup: ', bkp)
if xb_ibx_bin != 'innobackupex':
ibx_opts += " --incremental-dir %s --target-dir %s" % (bkp, incrdir)
else: ibx_opts += " --incremental-dir %s %s" % (bkp, incrdir)
else:
_say('Preparing full backup: ', bkp)
if xb_ibx_bin != 'innobackupex': ibx_opts += " --target-dir %s" % bkp
else: ibx_opts += " %s" % bkp
ibx_cmd = "%s %s" % (xb_ibx_bin, ibx_opts)
_say("Running prepare command: ", ibx_cmd)
try:
if not xb_opt_debug:
log_fd = os.open(ibx_log, os.O_WRONLY|os.O_CREAT)
p_ibx = Popen(ibx_cmd, shell=True, stdout=PIPE, stderr=log_fd)
else:
p_ibx = Popen(ibx_cmd, shell=True, stdout=PIPE, stderr=PIPE)
p_tee = Popen(tee_cmd, shell=True, stdin=p_ibx.stderr)
r = p_ibx.poll()
while r is None:
time.sleep(2)
r = p_ibx.poll()
if p_tee is not None: p_tee.wait()
if log_fd is not None:
os.close(log_fd)
if r != 0: raise Exception("Non-zero exit of innobackupex command!")
if cfp.get(XB_BIN_NAME,'backup_type') == 'incremental':
shutil.move(ibx_log,
"%s/%s-innobackupex-prepare.log" % (incrdir, xb_curdate))
else:
shutil.move(ibx_log,
"%s/%s-innobackupex-prepare.log" % (bkp, xb_curdate))
return True
except Exception, e:
_error("Command was: ", ibx_cmd.replace(xb_opt_mysql_pass,"*******"))
_error("Error: process exited with status %s" % str(e))
_error("Please check innobackupex log file at %s" % ibx_log)
_exit_code(XB_EXIT_APPLY_FAIL)
return False
def _prepare_backup(bkp, prep, final=False):
prepare_success = False
meta = _read_backup_metadata(bkp)
if not meta:
_die("Unable to read backup meta information, ",
"%s corrupt?" % meta_f)
is_cmp = bool(int(meta.get(XB_BIN_NAME, 'compress')))
is_of_type = meta.get(XB_BIN_NAME, 'type')
this_bkp = meta.get(XB_BIN_NAME, 'backup')
# If the backup is compressed, we extract to the prepare path
if is_cmp:
prep_tmp = os.path.join(os.path.dirname(prep), this_bkp)
if is_of_type == XB_CMD_FULL:
if not os.path.isdir(prep): os.mkdir(prep, 0755)
cmp_to = prep
else:
if not os.path.isdir(prep_tmp): os.mkdir(prep_tmp, 0755)
cmp_to = prep_tmp
for fmt in ['xbs.gz', 'tar.gz', 'xbs.qp', 'xbs.qp.xbcrypt', 'qp', 'qp.xbcrypt']:
bkp_file = "%s/backup.%s" % (bkp, fmt)
if os.path.isfile(bkp_file):
break
_say("Decompressing %s" % bkp_file)
if not _decompress(bkp_file, cmp_to, meta):
_die("An error occurred while extracting %s to %s" % (bkp_file, cmp_to))
if is_of_type == XB_CMD_FULL:
_say("Applying log on %s" % prep)
prepare_success = _apply_log(prep, prep, final)
else:
_say("Applying log on %s with %s" % (prep, prep_tmp))
prepare_success = _apply_log(prep_tmp, prep, final)
shutil.rmtree(prep_tmp)
else:
if is_of_type == XB_CMD_FULL:
_say("Copying %s to %s" % (bkp, prep))
shutil.copytree(bkp, prep)
_say("Applying log to %s" % prep)
prepare_success = _apply_log(prep, prep, final)
else:
_xb_logfile_copy(bkp)
_say("Applying log on %s with %s" % (prep, bkp))
prepare_success = _apply_log(bkp, prep, final)
_xb_logfile_restore(bkp)
return prepare_success
def _compress(bkp, archive):
global xb_exit_code
if not os.path.isdir(bkp):
_warn("Directory not found, ", bkp, " cannot compress")
return False
if xb_opt_compress_with == 'gzip':
return _compress_tgz(bkp, archive)
elif xb_opt_compress_with == 'qpress':
return _compress_qp(bkp, archive)
def _compress_qp(bkp, xbs):
global xb_exit_code
cwd = os.getcwd()
os.chdir(bkp)
# *.tar.gz tar+gzip compress either via innobackupex --stream=tar or
# tar czvf . -
# *.qp cmopressed with qpress i.e. qpress -rvT4 .
# *.xbs.qp for streamed qpress i.e. innobackupex --stream --compress
# *.xbs.qp.xbcrypt for streamed qpress, encrypted
# i.e. innobackupex --stream --compress --encrypt
xbc_cmd = None
qp = None
xbc = None
FNULL = None
if xb_opt_debug:
qp_cmd = 'qpress -rvT4'
else:
qp_cmd = 'qpress -rT4'
if xb_opt_encrypt:
qp_cmd += 'o .'
xbc_cmd = 'xbcrypt --encrypt-algo=%s --encrypt-key-file=%s --output=%s.qp.xbcrypt' % (
xb_opt_encrypt, xb_opt_encrypt_key_file, xbs)
_debug("Encrypting with command: %s" % xbc_cmd)
else:
qp_cmd += ' . %s.qp' % xbs
_debug("Compressing with command: %s" % qp_cmd)
if not xb_opt_debug:
FNULL = open(os.devnull, 'w')
if xb_opt_encrypt:
qp = Popen(qp_cmd, shell=True, stdout=PIPE, stderr=FNULL)
xbc = Popen(xbc_cmd, shell=True, stdin=qp.stdout, stdout=FNULL, stderr=FNULL)
else:
qp = Popen(qp_cmd, shell=True, stdout=FNULL, stderr=STDOUT)
else:
if xb_opt_encrypt:
qp = Popen(qp_cmd, shell=True, stdout=PIPE)
xbc = Popen(xbc_cmd, shell=True, stdin=qp.stdout)
else:
qp = Popen(qp_cmd, shell=True)
r = qp.poll()
while r is None:
time.sleep(5)
r = qp.poll()
if xbc is not None:
x = xbc.poll()
if x is None: xbc.wait()
x = xbc.poll()
if FNULL is not None:
FNULL.close()
if r != 0:
_error("Compressing ", bkp, " to ", xbs, " failed.")
_error("qpress command was: ", qp_cmd)
_error("qpress returned exit code was: ", str(r))
if xb_opt_encrypt:
_error("xbcrypt command was: ", xbc_cmd)
_error("xbcrypt returned exit code was: ", str(x))
_exit_code(XB_EXIT_COMPRESS_FAIL)
return False
os.chdir(cwd)
return True
def _compress_tgz(bkp, tgz):
global xb_exit_code
tgz = "%s.tar.gz" % tgz
if os.path.isfile(tgz):
_warn("Destination archive already exists, ", tgz, " aborting compression")
return False
cwd = os.getcwd()
os.chdir(bkp)
run_cmd = "tar c"
run_cmd += 'z'
if xb_opt_debug:
run_cmd += 'v'
run_cmd += "f %s %s" % (tgz, './')
FNULL = None
_debug("Running compress command: %s" % run_cmd)
if not xb_opt_debug:
FNULL = open(os.devnull, 'w')
p1 = Popen(run_cmd, shell=True, stdout=FNULL, stderr=STDOUT)
else:
p1 = Popen(run_cmd, shell=True)
r = p1.poll()
while r is None:
time.sleep(5)
r = p1.poll()
if FNULL is not None:
FNULL.close()
os.chdir(cwd)
if r != 0:
_error("Compressing ", bkp, " to ", tgz, " failed.")
_error("tar command was: ", run_cmd)
_error("tar returned exit code was: ", str(r))
_exit_code(XB_EXIT_COMPRESS_FAIL)
return False
return True
def _extract_tgz(tgz, dest):
run_cmd = "tar xi"
if xb_opt_compress_with == 'gzip':
run_cmd += 'z'
if xb_opt_debug:
run_cmd += 'v'
run_cmd += "f %s -C %s" % (tgz, dest)
FNULL = None
if not xb_opt_debug:
FNULL = open(os.devnull, 'w')
p1 = Popen(run_cmd, shell=True, stdout=FNULL, stderr=STDOUT)
else:
p1 = Popen(run_cmd, shell=True)
r = p1.poll()
while r is None:
time.sleep(5)
r = p1.poll()
if FNULL is not None:
FNULL.close()
if r != 0:
_error("Extracting ", tgz, " to ", dest, " failed.")
_error("tar command was: ", run_cmd)
_error("tar returned exit code was: ", str(r))
_exit_code(XB_EXIT_EXTRACT_FAIL)
return False
return True
def _extract_xgz(xgz, dest):
gz_cmd = "gzip -cd"
#if xb_opt_debug:
# gz_cmd += ' -v'
gz_cmd += " %s" % xgz
FNULL = None
xbs_cmd = "%s -x -C %s" % (xb_xbs_bin, dest)
_rotate_xtrabackup_info(os.path.dirname(xgz))
_debug("Running gzip command: %s" % gz_cmd)
_debug("Running xbstream command: %s" % xbs_cmd)
if not os.path.isdir(dest): os.mkdir(dest, 0755)
if not xb_opt_debug:
FNULL = open(os.devnull, 'w')
gz = Popen(gz_cmd, shell=True, stdout=PIPE, stderr=FNULL)
xbs = Popen(xbs_cmd, shell=True, stderr=FNULL, stdin=gz.stdout)
else:
gz = Popen(gz_cmd, shell=True, stdout=PIPE)
xbs = Popen(xbs_cmd, shell=True, stdin=gz.stdout)
r = gz.poll()
while r is None:
time.sleep(5)
r = gz.poll()
x = xbs.poll()
if x is None: xbs.wait()
x = xbs.poll()
if FNULL is not None:
FNULL.close()
if r != 0:
_error("Extracting ", xgz, " to ", dest, " failed.")
_error("Extract command was: %s | %s" % (gz_cmd, xbs_cmd))
_error("Extract returned exit codes were: %s and %s" % (str(r), str(x)))
_exit_code(XB_EXIT_EXTRACT_FAIL)
return False
return True
def _extract_xbs(xbs, dest, meta = None):
xbs_cmd = "%s -x -C %s" % (xb_xbs_bin, dest)
xbc_cmd = 'cat %s' % xbs
_rotate_xtrabackup_info(os.path.dirname(xbs))
if not os.path.isdir(dest): os.mkdir(dest, 0755)
_say("Extracting from xbstream format: %s" % xbs)
FNULL = None
if not xb_opt_debug:
FNULL = open(os.devnull, 'w')
xbc = Popen(xbc_cmd, shell=True, stdout=PIPE, stderr=FNULL)
xbs = Popen(xbs_cmd, shell=True, stderr=FNULL, stdin=xbc.stdout)
else:
xbc = Popen(xbc_cmd, shell=True, stdout=PIPE)
xbs = Popen(xbs_cmd, shell=True, stdin=xbc.stdout)
r = xbc.poll()
while r is None:
time.sleep(5)
r = xbc.poll()
x = xbs.poll()
if x is None: xbs.wait()
x = xbs.poll()
if FNULL is not None:
FNULL.close()
if r != 0:
_error("Extracting ", xbs, " to ", dest, " failed.")
_error("Extract command was: %s | %s" % (xbc_cmd, xbs_cmd))
_error("Extract returned exit codes were: %s and %s" % (str(r), str(x)))
_exit_code(XB_EXIT_EXTRACT_FAIL)
_die("Decompress of xbstream file %s failed." % xbs)
return True
def _extract_xbcrypt(dest, meta = None):
""" Decrypt a backup set encrypted with xbcrypt
if xrabackup version is < 2.3 we use xtrabackup --decrypt
via _extract_xbcrypt_file which decrypts the files one
at a timedelta
"""
if _xb_version(tof = True) < 2.3:
_say(
"You are running an older xtrabackup version "
"that do not have --decrypt support, "
"switching manual decompresssion")
return _extract_xbcrypt_file(dest)
# Now we decompress *.xbcrypt files
ibx_cmd = '%s --decrypt=%s --encrypt-key-file=%s --target-dir=%s' % (
xb_ibx_bin, xb_opt_encrypt, xb_opt_encrypt_key_file, dest)
FNULL = None
if not xb_opt_debug:
FNULL = open(os.devnull, 'w')
ibx = Popen(ibx_cmd, shell=True, stdout=FNULL, stderr=FNULL)
else:
ibx = Popen(ibx_cmd, shell=True)
r = ibx.poll()
while r is None:
time.sleep(5)
r = ibx.poll()
if FNULL is not None:
FNULL.close()
if r != 0:
_error("Decrypt of backup failed.")
_error("Decrypt command was: %s" % ibx_cmd)
_error("Decrypt returned exit code was: %s" % str(r))
_exit_code(XB_EXIT_DECRYPT_FAIL)
_die("Decrypt of backup %s failed." % dest)
_cleanup_files_by_ext(dest, 'xbcrypt')
return True
def _extract_xbcrypt_file(cfile):
""" cfile is encrypted file or folder, this method
traverses individual xbcrypt files if --decrypt option is
not available
"""
if os.path.isdir(cfile):