forked from mydumper/mydumper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mydumper.c
2949 lines (2595 loc) · 92.7 KB
/
mydumper.c
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
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Authors: Domas Mituzas, Facebook ( domas at fb dot com )
Mark Leith, Oracle Corporation (mark dot leith at oracle dot com)
Andrew Hutchings, SkySQL (andrew at skysql dot com)
Max Bubenick, Percona RDBA (max dot bubenick at percona dot com)
*/
#define _LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS 64
#include <mysql.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <glib.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <time.h>
#include <zlib.h>
#include <pcre.h>
#include <signal.h>
#include <glib/gstdio.h>
#include "config.h"
#ifdef WITH_BINLOG
#include "binlog.h"
#else
#include "mydumper.h"
#endif
#include "server_detect.h"
#include "common.h"
#include "g_unix_signal.h"
#include <math.h>
#include "getPassword.h"
char *regexstring=NULL;
const char DIRECTORY[]= "export";
#ifdef WITH_BINLOG
const char BINLOG_DIRECTORY[]= "binlog_snapshot";
const char DAEMON_BINLOGS[]= "binlogs";
#endif
static GMutex * init_mutex = NULL;
/* Program options */
gchar *output_directory= NULL;
guint statement_size= 1000000;
guint rows_per_file= 0;
guint chunk_filesize = 0;
int longquery= 60;
int build_empty_files= 0;
int skip_tz= 0;
int need_dummy_read= 0;
int need_dummy_toku_read = 0;
int compress_output= 0;
int killqueries= 0;
int detected_server= 0;
int lock_all_tables=0;
guint snapshot_interval= 60;
gboolean daemon_mode= FALSE;
gboolean have_snapshot_cloning= FALSE;
gchar *ignore_engines= NULL;
char **ignore= NULL;
gchar *tables_list= NULL;
char **tables= NULL;
GList *no_updated_tables=NULL;
#ifdef WITH_BINLOG
gboolean need_binlogs= FALSE;
gchar *binlog_directory= NULL;
gchar *daemon_binlog_directory= NULL;
#endif
gchar *logfile= NULL;
FILE *logoutfile= NULL;
gboolean no_schemas= FALSE;
gboolean no_data= FALSE;
gboolean no_locks= FALSE;
gboolean dump_triggers= FALSE;
gboolean dump_events= FALSE;
gboolean dump_routines= FALSE;
gboolean no_dump_views= FALSE;
gboolean less_locking = FALSE;
gboolean use_savepoints = FALSE;
gboolean success_on_1146 = FALSE;
gboolean no_backup_locks = FALSE;
GList *innodb_tables= NULL;
GList *non_innodb_table= NULL;
GList *table_schemas= NULL;
GList *view_schemas= NULL;
GList *schema_post= NULL;
gint non_innodb_table_counter= 0;
gint non_innodb_done= 0;
guint less_locking_threads = 0;
guint updated_since = 0;
guint trx_consistency_only = 0;
// For daemon mode, 0 or 1
guint dump_number= 0;
guint binlog_connect_id= 0;
gboolean shutdown_triggered= FALSE;
GAsyncQueue *start_scheduled_dump;
GMainLoop *m1;
static GCond * ll_cond = NULL;
static GMutex * ll_mutex = NULL;
int errors;
static GOptionEntry entries[] =
{
{ "database", 'B', 0, G_OPTION_ARG_STRING, &db, "Database to dump", NULL },
{ "tables-list", 'T', 0, G_OPTION_ARG_STRING, &tables_list, "Comma delimited table list to dump (does not exclude regex option)", NULL },
{ "outputdir", 'o', 0, G_OPTION_ARG_FILENAME, &output_directory, "Directory to output files to", NULL },
{ "statement-size", 's', 0, G_OPTION_ARG_INT, &statement_size, "Attempted size of INSERT statement in bytes, default 1000000", NULL},
{ "rows", 'r', 0, G_OPTION_ARG_INT, &rows_per_file, "Try to split tables into chunks of this many rows. This option turns off --chunk-filesize", NULL},
{ "chunk-filesize", 'F', 0, G_OPTION_ARG_INT, &chunk_filesize, "Split tables into chunks of this output file size. This value is in MB", NULL },
{ "compress", 'c', 0, G_OPTION_ARG_NONE, &compress_output, "Compress output files", NULL},
{ "build-empty-files", 'e', 0, G_OPTION_ARG_NONE, &build_empty_files, "Build dump files even if no data available from table", NULL},
{ "regex", 'x', 0, G_OPTION_ARG_STRING, ®exstring, "Regular expression for 'db.table' matching", NULL},
{ "ignore-engines", 'i', 0, G_OPTION_ARG_STRING, &ignore_engines, "Comma delimited list of storage engines to ignore", NULL },
{ "no-schemas", 'm', 0, G_OPTION_ARG_NONE, &no_schemas, "Do not dump table schemas with the data", NULL },
{ "no-data", 'd', 0, G_OPTION_ARG_NONE, &no_data, "Do not dump table data", NULL },
{ "triggers", 'G', 0, G_OPTION_ARG_NONE, &dump_triggers, "Dump triggers", NULL },
{ "events", 'E', 0, G_OPTION_ARG_NONE, &dump_events, "Dump events", NULL },
{ "routines", 'R', 0, G_OPTION_ARG_NONE, &dump_routines, "Dump stored procedures and functions", NULL },
{ "no-views", 'W', 0, G_OPTION_ARG_NONE, &no_dump_views, "Do not dump VIEWs", NULL },
{ "no-locks", 'k', 0, G_OPTION_ARG_NONE, &no_locks, "Do not execute the temporary shared read lock. WARNING: This will cause inconsistent backups", NULL },
{ "no-backup-locks", 0, 0, G_OPTION_ARG_NONE, &no_backup_locks, "Do not use Percona backup locks", NULL},
{ "less-locking", 0, 0, G_OPTION_ARG_NONE, &less_locking, "Minimize locking time on InnoDB tables.", NULL},
{ "long-query-guard", 'l', 0, G_OPTION_ARG_INT, &longquery, "Set long query timer in seconds, default 60", NULL },
{ "kill-long-queries", 'K', 0, G_OPTION_ARG_NONE, &killqueries, "Kill long running queries (instead of aborting)", NULL },
#ifdef WITH_BINLOG
{ "binlogs", 'b', 0, G_OPTION_ARG_NONE, &need_binlogs, "Get a snapshot of the binary logs as well as dump data", NULL },
#endif
{ "daemon", 'D', 0, G_OPTION_ARG_NONE, &daemon_mode, "Enable daemon mode", NULL },
{ "snapshot-interval", 'I', 0, G_OPTION_ARG_INT, &snapshot_interval, "Interval between each dump snapshot (in minutes), requires --daemon, default 60", NULL },
{ "logfile", 'L', 0, G_OPTION_ARG_FILENAME, &logfile, "Log file name to use, by default stdout is used", NULL },
{ "tz-utc", 0, 0, G_OPTION_ARG_NONE, NULL, "SET TIME_ZONE='+00:00' at top of dump to allow dumping of TIMESTAMP data when a server has data in different time zones or data is being moved between servers with different time zones, defaults to on use --skip-tz-utc to disable.", NULL },
{ "skip-tz-utc", 0, 0, G_OPTION_ARG_NONE, &skip_tz, "", NULL },
{ "use-savepoints", 0, 0, G_OPTION_ARG_NONE, &use_savepoints, "Use savepoints to reduce metadata locking issues, needs SUPER privilege", NULL },
{ "success-on-1146", 0, 0, G_OPTION_ARG_NONE, &success_on_1146, "Not increment error count and Warning instead of Critical in case of table doesn't exist", NULL},
{ "lock-all-tables", 0, 0, G_OPTION_ARG_NONE, &lock_all_tables, "Use LOCK TABLE for all, instead of FTWRL", NULL},
{ "updated-since", 'U', 0, G_OPTION_ARG_INT, &updated_since, "Use Update_time to dump only tables updated in the last U days", NULL},
{ "trx-consistency-only", 0, 0, G_OPTION_ARG_NONE, &trx_consistency_only, "Transactional consistency only", NULL},
{ NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL }
};
struct tm tval;
void dump_schema_data(MYSQL *conn, char *database, char *table, char *filename);
void dump_triggers_data(MYSQL *conn, char *database, char *table, char *filename);
void dump_view_data(MYSQL *conn, char *database, char *table, char *filename, char *filename2);
void dump_schema(MYSQL *conn, char *database, char *table, struct configuration *conf);
void dump_view(char *database, char *table, struct configuration *conf);
void dump_table(MYSQL *conn, char *database, char *table, struct configuration *conf, gboolean is_innodb);
void dump_tables(MYSQL *, GList *, struct configuration *);
void dump_schema_post(char *database, struct configuration *conf);
void restore_charset(GString* statement);
void set_charset(GString* statement, char *character_set, char *collation_connection);
void dump_schema_post_data(MYSQL *conn, char *database, char *filename);
guint64 dump_table_data(MYSQL *, FILE *, char *, char *, char *, char *);
void dump_database(MYSQL *, char *, FILE *, struct configuration *);
void dump_create_database(MYSQL *conn, char *database);
void get_tables(MYSQL * conn, struct configuration *);
void get_not_updated(MYSQL *conn);
GList * get_chunks_for_table(MYSQL *, char *, char*, struct configuration *conf);
guint64 estimate_count(MYSQL *conn, char *database, char *table, char *field, char *from, char *to);
void dump_table_data_file(MYSQL *conn, char *database, char *table, char *where, char *filename);
void create_backup_dir(char *directory);
gboolean write_data(FILE *,GString*);
gboolean check_regex(char *database, char *table);
void no_log(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data);
void set_verbose(guint verbosity);
#ifdef WITH_BINLOG
MYSQL *reconnect_for_binlog(MYSQL *thrconn);
void *binlog_thread(void *data);
#endif
void start_dump(MYSQL *conn);
MYSQL *create_main_connection();
void *exec_thread(void *data);
void write_log_file(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data);
void no_log(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) {
(void) log_domain;
(void) log_level;
(void) message;
(void) user_data;
}
void set_verbose(guint verbosity) {
if (logfile) {
logoutfile = g_fopen(logfile, "w");
if (!logoutfile) {
g_critical("Could not open log file '%s' for writing: %d", logfile, errno);
exit(EXIT_FAILURE);
}
}
switch (verbosity) {
case 0:
g_log_set_handler(NULL, (GLogLevelFlags)(G_LOG_LEVEL_MASK), no_log, NULL);
break;
case 1:
g_log_set_handler(NULL, (GLogLevelFlags)(G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE), no_log, NULL);
if (logfile)
g_log_set_handler(NULL, (GLogLevelFlags)(G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL), write_log_file, NULL);
break;
case 2:
g_log_set_handler(NULL, (GLogLevelFlags)(G_LOG_LEVEL_MESSAGE), no_log, NULL);
if (logfile)
g_log_set_handler(NULL, (GLogLevelFlags)(G_LOG_LEVEL_WARNING | G_LOG_LEVEL_ERROR | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL), write_log_file, NULL);
break;
default:
if (logfile)
g_log_set_handler(NULL, (GLogLevelFlags)(G_LOG_LEVEL_MASK), write_log_file, NULL);
break;
}
}
gboolean sig_triggered(gpointer user_data) {
(void) user_data;
g_message("Shutting down gracefully");
shutdown_triggered= TRUE;
g_main_loop_quit(m1);
return FALSE;
}
void clear_dump_directory()
{
GError *error= NULL;
char* dump_directory= g_strdup_printf("%s/%d", output_directory, dump_number);
GDir* dir= g_dir_open(dump_directory, 0, &error);
if (error) {
g_critical("cannot open directory %s, %s\n", dump_directory, error->message);
errors++;
return;
}
const gchar* filename= NULL;
while((filename= g_dir_read_name(dir))) {
gchar* path= g_build_filename(dump_directory, filename, NULL);
if (g_unlink(path) == -1) {
g_critical("error removing file %s (%d)\n", path, errno);
errors++;
return;
}
g_free(path);
}
g_dir_close(dir);
g_free(dump_directory);
}
gboolean run_snapshot(gpointer *data)
{
(void) data;
g_async_queue_push(start_scheduled_dump,GINT_TO_POINTER(1));
return (shutdown_triggered) ? FALSE : TRUE;
}
/* Check database.table string against regular expression */
gboolean check_regex(char *database, char *table) {
/* This is not going to be used in threads */
static pcre *re = NULL;
int rc;
int ovector[9]= {0};
const char *error;
int erroroffset;
char *p;
/* Let's compile the RE before we do anything */
if (!re) {
re = pcre_compile(regexstring,PCRE_CASELESS|PCRE_MULTILINE,&error,&erroroffset,NULL);
if(!re) {
g_critical("Regular expression fail: %s", error);
exit(EXIT_FAILURE);
}
}
p=g_strdup_printf("%s.%s",database,table);
rc = pcre_exec(re,NULL,p,strlen(p),0,0,ovector,9);
g_free(p);
return (rc>0)?TRUE:FALSE;
}
/* Write some stuff we know about snapshot, before it changes */
void write_snapshot_info(MYSQL *conn, FILE *file) {
MYSQL_RES *master=NULL, *slave=NULL, *mdb=NULL;
MYSQL_FIELD *fields;
MYSQL_ROW row;
char *masterlog=NULL;
char *masterpos=NULL;
char *mastergtid=NULL;
char *connname=NULL;
char *slavehost=NULL;
char *slavelog=NULL;
char *slavepos=NULL;
char *slavegtid=NULL;
guint isms;
guint i;
mysql_query(conn,"SHOW MASTER STATUS");
master=mysql_store_result(conn);
if (master && (row=mysql_fetch_row(master))) {
masterlog=row[0];
masterpos=row[1];
/* Oracle/Percona GTID */
if(mysql_num_fields(master) == 5) {
mastergtid=row[4];
} else {
/* Let's try with MariaDB 10.x */
mysql_query(conn, "SELECT @@gtid_current_pos");
mdb=mysql_store_result(conn);
if (mdb && (row=mysql_fetch_row(mdb))) {
mastergtid=row[0];
}
}
}
if (masterlog) {
fprintf(file, "SHOW MASTER STATUS:\n\tLog: %s\n\tPos: %s\n\tGTID:%s\n\n", masterlog, masterpos,mastergtid);
g_message("Written master status");
}
isms = 0;
mysql_query(conn,"SELECT @@default_master_connection");
MYSQL_RES *rest = mysql_store_result(conn);
if(rest != NULL && mysql_num_rows(rest)){
mysql_free_result(rest);
g_message("Multisource slave detected.");
isms = 1;
}
if (isms)
mysql_query(conn, "SHOW ALL SLAVES STATUS");
else
mysql_query(conn, "SHOW SLAVE STATUS");
slave=mysql_store_result(conn);
while (slave && (row=mysql_fetch_row(slave))) {
fields=mysql_fetch_fields(slave);
for (i=0; i<mysql_num_fields(slave);i++) {
if (isms && !strcasecmp("connection_name",fields[i].name))
connname=row[i];
if (!strcasecmp("exec_master_log_pos",fields[i].name)) {
slavepos=row[i];
} else if (!strcasecmp("relay_master_log_file", fields[i].name)) {
slavelog=row[i];
} else if (!strcasecmp("master_host",fields[i].name)) {
slavehost=row[i];
} else if (!strcasecmp("Executed_Gtid_Set",fields[i].name) || !strcasecmp("Gtid_Slave_Pos",fields[i].name)) {
slavegtid=row[i];
}
}
if (slavehost) {
fprintf(file, "SHOW SLAVE STATUS:");
if (isms)
fprintf(file, "\n\tConnection name: %s",connname);
fprintf(file, "\n\tHost: %s\n\tLog: %s\n\tPos: %s\n\tGTID:%s\n\n",slavehost, slavelog, slavepos,slavegtid);
g_message("Written slave status");
}
}
fflush(file);
if (master)
mysql_free_result(master);
if (slave)
mysql_free_result(slave);
if (mdb)
mysql_free_result(mdb);
}
void *process_queue(struct thread_data *td) {
struct configuration *conf= td->conf;
// mysql_init is not thread safe, especially in Connector/C
g_mutex_lock(init_mutex);
MYSQL *thrconn = mysql_init(NULL);
g_mutex_unlock(init_mutex);
if (defaults_file != NULL)
mysql_options(thrconn,MYSQL_READ_DEFAULT_FILE,defaults_file);
mysql_options(thrconn,MYSQL_READ_DEFAULT_GROUP,"mydumper");
if (compress_protocol)
mysql_options(thrconn,MYSQL_OPT_COMPRESS,NULL);
if (!mysql_real_connect(thrconn, hostname, username, password, NULL, port, socket_path, 0)) {
g_critical("Failed to connect to database: %s", mysql_error(thrconn));
exit(EXIT_FAILURE);
} else {
g_message("Thread %d connected using MySQL connection ID %lu", td->thread_id, mysql_thread_id(thrconn));
}
if(use_savepoints && mysql_query(thrconn, "SET SQL_LOG_BIN = 0")){
g_critical("Failed to disable binlog for the thread: %s",mysql_error(thrconn));
exit(EXIT_FAILURE);
}
if ((detected_server == SERVER_TYPE_MYSQL) && mysql_query(thrconn, "SET SESSION wait_timeout = 2147483")){
g_warning("Failed to increase wait_timeout: %s", mysql_error(thrconn));
}
if (mysql_query(thrconn, "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ")) {
g_critical("Failed to set isolation level: %s", mysql_error(thrconn));
exit(EXIT_FAILURE);
}
if (mysql_query(thrconn, "START TRANSACTION /*!40108 WITH CONSISTENT SNAPSHOT */")) {
g_critical("Failed to start consistent snapshot: %s",mysql_error(thrconn));
exit(EXIT_FAILURE);
}
if(!skip_tz && mysql_query(thrconn, "/*!40103 SET TIME_ZONE='+00:00' */")){
g_critical("Failed to set time zone: %s",mysql_error(thrconn));
}
/* Unfortunately version before 4.1.8 did not support consistent snapshot transaction starts, so we cheat */
if (need_dummy_read) {
mysql_query(thrconn,"SELECT /*!40001 SQL_NO_CACHE */ * FROM mysql.mydumperdummy");
MYSQL_RES *res=mysql_store_result(thrconn);
if (res)
mysql_free_result(res);
}
if(need_dummy_toku_read){
mysql_query(thrconn,"SELECT /*!40001 SQL_NO_CACHE */ * FROM mysql.tokudbdummy");
MYSQL_RES *res=mysql_store_result(thrconn);
if (res)
mysql_free_result(res);
}
mysql_query(thrconn, "/*!40101 SET NAMES binary*/");
g_async_queue_push(conf->ready,GINT_TO_POINTER(1));
struct job* job= NULL;
struct table_job* tj= NULL;
struct schema_job* sj= NULL;
struct view_job* vj= NULL;
struct schema_post_job* sp= NULL;
#ifdef WITH_BINLOG
struct binlog_job* bj= NULL;
#endif
/* if less locking we need to wait until that threads finish
progressively waking up these threads */
if(less_locking){
g_mutex_lock(ll_mutex);
while (less_locking_threads >= td->thread_id) {
g_cond_wait (ll_cond, ll_mutex);
}
g_mutex_unlock(ll_mutex);
}
for(;;) {
GTimeVal tv;
g_get_current_time(&tv);
g_time_val_add(&tv,1000*1000*1);
job=(struct job *)g_async_queue_pop(conf->queue);
if (shutdown_triggered && (job->type != JOB_SHUTDOWN)) {
continue;
}
switch (job->type) {
case JOB_DUMP:
tj=(struct table_job *)job->job_data;
if (tj->where)
g_message("Thread %d dumping data for `%s`.`%s` where %s", td->thread_id, tj->database, tj->table, tj->where);
else
g_message("Thread %d dumping data for `%s`.`%s`", td->thread_id, tj->database, tj->table);
if(use_savepoints && mysql_query(thrconn, "SAVEPOINT mydumper")){
g_critical("Savepoint failed: %s",mysql_error(thrconn));
}
dump_table_data_file(thrconn, tj->database, tj->table, tj->where, tj->filename);
if(use_savepoints && mysql_query(thrconn, "ROLLBACK TO SAVEPOINT mydumper")){
g_critical("Rollback to savepoint failed: %s",mysql_error(thrconn));
}
if(tj->database) g_free(tj->database);
if(tj->table) g_free(tj->table);
if(tj->where) g_free(tj->where);
if(tj->filename) g_free(tj->filename);
g_free(tj);
g_free(job);
break;
case JOB_DUMP_NON_INNODB:
tj=(struct table_job *)job->job_data;
if (tj->where)
g_message("Thread %d dumping data for `%s`.`%s` where %s", td->thread_id, tj->database, tj->table, tj->where);
else
g_message("Thread %d dumping data for `%s`.`%s`", td->thread_id, tj->database, tj->table);
if(use_savepoints && mysql_query(thrconn, "SAVEPOINT mydumper")){
g_critical("Savepoint failed: %s",mysql_error(thrconn));
}
dump_table_data_file(thrconn, tj->database, tj->table, tj->where, tj->filename);
if(use_savepoints && mysql_query(thrconn, "ROLLBACK TO SAVEPOINT mydumper")){
g_critical("Rollback to savepoint failed: %s",mysql_error(thrconn));
}
if(tj->database) g_free(tj->database);
if(tj->table) g_free(tj->table);
if(tj->where) g_free(tj->where);
if(tj->filename) g_free(tj->filename);
g_free(tj);
g_free(job);
if (g_atomic_int_dec_and_test(&non_innodb_table_counter) && g_atomic_int_get(&non_innodb_done)) {
g_async_queue_push(conf->unlock_tables, GINT_TO_POINTER(1));
}
break;
case JOB_SCHEMA:
sj=(struct schema_job *)job->job_data;
g_message("Thread %d dumping schema for `%s`.`%s`", td->thread_id, sj->database, sj->table);
dump_schema_data(thrconn, sj->database, sj->table, sj->filename);
if(sj->database) g_free(sj->database);
if(sj->table) g_free(sj->table);
if(sj->filename) g_free(sj->filename);
g_free(sj);
g_free(job);
break;
case JOB_VIEW:
vj=(struct view_job *)job->job_data;
g_message("Thread %d dumping view for `%s`.`%s`", td->thread_id, vj->database, vj->table);
dump_view_data(thrconn, vj->database, vj->table, vj->filename, vj->filename2);
if(vj->database) g_free(vj->database);
if(vj->table) g_free(vj->table);
if(vj->filename) g_free(vj->filename);
if(vj->filename2) g_free(vj->filename2);
g_free(vj);
g_free(job);
break;
case JOB_TRIGGERS:
sj=(struct schema_job *)job->job_data;
g_message("Thread %d dumping triggers for `%s`.`%s`", td->thread_id, sj->database, sj->table);
dump_triggers_data(thrconn, sj->database, sj->table, sj->filename);
if(sj->database) g_free(sj->database);
if(sj->table) g_free(sj->table);
if(sj->filename) g_free(sj->filename);
g_free(sj);
g_free(job);
break;
case JOB_SCHEMA_POST:
sp=(struct schema_post_job *)job->job_data;
g_message("Thread %d dumping SP and VIEWs for `%s`", td->thread_id, sp->database);
dump_schema_post_data(thrconn, sp->database, sp->filename);
if(sp->database) g_free(sp->database);
if(sp->filename) g_free(sp->filename);
g_free(sp);
g_free(job);
break;
#ifdef WITH_BINLOG
case JOB_BINLOG:
thrconn= reconnect_for_binlog(thrconn);
g_message("Thread %d connected using MySQL connection ID %lu (in binlog mode)", td->thread_id, mysql_thread_id(thrconn));
bj=(struct binlog_job *)job->job_data;
g_message("Thread %d dumping binary log file %s", td->thread_id, bj->filename);
get_binlog_file(thrconn, bj->filename, binlog_directory, bj->start_position, bj->stop_position, FALSE);
if(bj->filename)
g_free(bj->filename);
g_free(bj);
g_free(job);
break;
#endif
case JOB_SHUTDOWN:
g_message("Thread %d shutting down", td->thread_id);
if (thrconn)
mysql_close(thrconn);
g_free(job);
mysql_thread_end();
return NULL;
break;
default:
g_critical("Something very bad happened!");
exit(EXIT_FAILURE);
}
}
if (thrconn)
mysql_close(thrconn);
mysql_thread_end();
return NULL;
}
void *process_queue_less_locking(struct thread_data *td) {
struct configuration *conf= td->conf;
// mysql_init is not thread safe, especially in Connector/C
g_mutex_lock(init_mutex);
MYSQL *thrconn = mysql_init(NULL);
g_mutex_unlock(init_mutex);
if (defaults_file != NULL)
mysql_options(thrconn,MYSQL_READ_DEFAULT_FILE,defaults_file);
mysql_options(thrconn,MYSQL_READ_DEFAULT_GROUP,"mydumper");
if (compress_protocol)
mysql_options(thrconn,MYSQL_OPT_COMPRESS,NULL);
if (!mysql_real_connect(thrconn, hostname, username, password, NULL, port, socket_path, 0)) {
g_critical("Failed to connect to database: %s", mysql_error(thrconn));
exit(EXIT_FAILURE);
} else {
g_message("Thread %d connected using MySQL connection ID %lu", td->thread_id, mysql_thread_id(thrconn));
}
if ((detected_server == SERVER_TYPE_MYSQL) && mysql_query(thrconn, "SET SESSION wait_timeout = 2147483")){
g_warning("Failed to increase wait_timeout: %s", mysql_error(thrconn));
}
if(!skip_tz && mysql_query(thrconn, "/*!40103 SET TIME_ZONE='+00:00' */")){
g_critical("Failed to set time zone: %s",mysql_error(thrconn));
}
mysql_query(thrconn, "/*!40101 SET NAMES binary*/");
g_async_queue_push(conf->ready_less_locking,GINT_TO_POINTER(1));
struct job* job= NULL;
struct table_job* tj= NULL;
struct tables_job* mj=NULL;
struct schema_job* sj= NULL;
struct view_job* vj= NULL;
struct schema_post_job* sp= NULL;
#ifdef WITH_BINLOG
struct binlog_job* bj= NULL;
#endif
GList* glj;
int first = 1;
GString *query= g_string_sized_new(1024);
GString *prev_table = g_string_sized_new(100);
GString *prev_database = g_string_sized_new(100);
for(;;) {
GTimeVal tv;
g_get_current_time(&tv);
g_time_val_add(&tv,1000*1000*1);
job=(struct job *)g_async_queue_pop(conf->queue_less_locking);
if (shutdown_triggered && (job->type != JOB_SHUTDOWN)) {
continue;
}
switch (job->type) {
case JOB_LOCK_DUMP_NON_INNODB:
mj=(struct tables_job *)job->job_data;
glj = g_list_copy(mj->table_job_list);
for (glj= g_list_first(glj); glj; glj= g_list_next(glj)) {
tj = (struct table_job *)glj->data;
if(first){
g_string_printf(query, "LOCK TABLES `%s`.`%s` READ LOCAL",tj->database,tj->table);
first = 0;
}else{
if(g_ascii_strcasecmp(prev_database->str, tj->database) || g_ascii_strcasecmp(prev_table->str, tj->table)){
g_string_append_printf(query, ", `%s`.`%s` READ LOCAL",tj->database,tj->table);
}
}
g_string_printf(prev_table, "%s", tj->table);
g_string_printf(prev_database, "%s", tj->database);
}
first = 1;
if(mysql_query(thrconn,query->str)){
g_critical("Non Innodb lock tables fail: %s", mysql_error(thrconn));
exit(EXIT_FAILURE);
}
if (g_atomic_int_dec_and_test(&non_innodb_table_counter) && g_atomic_int_get(&non_innodb_done)) {
g_async_queue_push(conf->unlock_tables, GINT_TO_POINTER(1));
}
for (mj->table_job_list= g_list_first(mj->table_job_list); mj->table_job_list; mj->table_job_list= g_list_next(mj->table_job_list)) {
tj = (struct table_job *)mj->table_job_list->data;
if (tj->where)
g_message("Thread %d dumping data for `%s`.`%s` where %s", td->thread_id, tj->database, tj->table, tj->where);
else
g_message("Thread %d dumping data for `%s`.`%s`", td->thread_id, tj->database, tj->table);
dump_table_data_file(thrconn, tj->database, tj->table, tj->where, tj->filename);
if(tj->database) g_free(tj->database);
if(tj->table) g_free(tj->table);
if(tj->where) g_free(tj->where);
if(tj->filename) g_free(tj->filename);
g_free(tj);
}
mysql_query(thrconn, "UNLOCK TABLES /* Non Innodb */");
g_free(g_list_first(mj->table_job_list));
g_free(mj);
g_free(job);
break;
case JOB_SCHEMA:
sj=(struct schema_job *)job->job_data;
g_message("Thread %d dumping schema for `%s`.`%s`", td->thread_id, sj->database, sj->table);
dump_schema_data(thrconn, sj->database, sj->table, sj->filename);
if(sj->database) g_free(sj->database);
if(sj->table) g_free(sj->table);
if(sj->filename) g_free(sj->filename);
g_free(sj);
g_free(job);
break;
case JOB_VIEW:
vj=(struct view_job *)job->job_data;
g_message("Thread %d dumping view for `%s`.`%s`", td->thread_id, sj->database, sj->table);
dump_view_data(thrconn, vj->database, vj->table, vj->filename, vj->filename2);
if(vj->database) g_free(vj->database);
if(vj->table) g_free(vj->table);
if(vj->filename) g_free(vj->filename);
if(vj->filename2) g_free(vj->filename2);
g_free(vj);
g_free(job);
break;
case JOB_TRIGGERS:
sj=(struct schema_job *)job->job_data;
g_message("Thread %d dumping triggers for `%s`.`%s`", td->thread_id, sj->database, sj->table);
dump_triggers_data(thrconn, sj->database, sj->table, sj->filename);
if(sj->database) g_free(sj->database);
if(sj->table) g_free(sj->table);
if(sj->filename) g_free(sj->filename);
g_free(sj);
g_free(job);
break;
case JOB_SCHEMA_POST:
sp=(struct schema_post_job *)job->job_data;
g_message("Thread %d dumping SP and VIEWs for `%s`", td->thread_id, sp->database);
dump_schema_post_data(thrconn, sp->database, sp->filename);
if(sp->database) g_free(sp->database);
if(sp->filename) g_free(sp->filename);
g_free(sp);
g_free(job);
break;
#ifdef WITH_BINLOG
case JOB_BINLOG:
thrconn= reconnect_for_binlog(thrconn);
g_message("Thread %d connected using MySQL connection ID %lu (in binlog mode)", td->thread_id, mysql_thread_id(thrconn));
bj=(struct binlog_job *)job->job_data;
g_message("Thread %d dumping binary log file %s", td->thread_id, bj->filename);
get_binlog_file(thrconn, bj->filename, binlog_directory, bj->start_position, bj->stop_position, FALSE);
if(bj->filename)
g_free(bj->filename);
g_free(bj);
g_free(job);
break;
#endif
case JOB_SHUTDOWN:
g_message("Thread %d shutting down", td->thread_id);
g_mutex_lock(ll_mutex);
less_locking_threads--;
g_cond_broadcast(ll_cond);
g_mutex_unlock(ll_mutex);
if (thrconn)
mysql_close(thrconn);
g_free(job);
mysql_thread_end();
return NULL;
break;
default:
g_critical("Something very bad happened!");
exit(EXIT_FAILURE);
}
}
if (thrconn)
mysql_close(thrconn);
mysql_thread_end();
return NULL;
}
#ifdef WITH_BINLOG
MYSQL *reconnect_for_binlog(MYSQL *thrconn) {
if (thrconn) {
mysql_close(thrconn);
}
g_mutex_lock(init_mutex);
thrconn= mysql_init(NULL);
g_mutex_unlock(init_mutex);
if (compress_protocol)
mysql_options(thrconn,MYSQL_OPT_COMPRESS,NULL);
int timeout= 1;
mysql_options(thrconn, MYSQL_OPT_READ_TIMEOUT, (const char*)&timeout);
if (!mysql_real_connect(thrconn, hostname, username, password, NULL, port, socket_path, 0)) {
g_critical("Failed to re-connect to database: %s", mysql_error(thrconn));
exit(EXIT_FAILURE);
}
return thrconn;
}
#endif
int main(int argc, char *argv[])
{
GError *error = NULL;
GOptionContext *context;
g_thread_init(NULL);
init_mutex = g_mutex_new();
ll_mutex = g_mutex_new();
ll_cond = g_cond_new();
context = g_option_context_new("multi-threaded MySQL dumping");
GOptionGroup *main_group= g_option_group_new("main", "Main Options", "Main Options", NULL, NULL);
g_option_group_add_entries(main_group, entries);
g_option_group_add_entries(main_group, common_entries);
g_option_context_set_main_group(context, main_group);
if (!g_option_context_parse(context, &argc, &argv, &error)) {
g_print ("option parsing failed: %s, try --help\n", error->message);
exit (EXIT_FAILURE);
}
g_option_context_free(context);
//prompt for password if it's NULL
if ( sizeof(password) == 0 || ( password == NULL && askPassword ) ){
password = passwordPrompt();
}
//printf("your password is %s and the size is %d \n",password,sizeof(password));
if (program_version) {
g_print("mydumper %s, built against MySQL %s\n", VERSION, MYSQL_SERVER_VERSION);
exit (EXIT_SUCCESS);
}
set_verbose(verbose);
time_t t;
time(&t);localtime_r(&t,&tval);
//rows chunks have precedence over chunk_filesize
if (rows_per_file > 0 && chunk_filesize > 0){
chunk_filesize = 0;
g_warning("--chunk-filesize disabled by --rows option");
}
//until we have an unique option on lock types we need to ensure this
if(no_locks || trx_consistency_only)
less_locking = 0;
/* savepoints workaround to avoid metadata locking issues
doesnt work for chuncks */
if(rows_per_file && use_savepoints){
use_savepoints = FALSE;
g_warning("--use-savepoints disabled by --rows");
}
//clarify binlog coordinates with trx_consistency_only
if(trx_consistency_only)
g_warning("Using trx_consistency_only, binlog coordinates will not be accurate if you are writing to non transactional tables.");
if (!output_directory)
output_directory = g_strdup_printf("%s-%04d%02d%02d-%02d%02d%02d",DIRECTORY,
tval.tm_year+1900, tval.tm_mon+1, tval.tm_mday,
tval.tm_hour, tval.tm_min, tval.tm_sec);
create_backup_dir(output_directory);
if (daemon_mode) {
pid_t pid, sid;
pid= fork();
if (pid < 0)
exit(EXIT_FAILURE);
else if (pid > 0)
exit(EXIT_SUCCESS);
umask(0);
sid= setsid();
if (sid < 0)
exit(EXIT_FAILURE);
char *dump_directory= g_strdup_printf("%s/0", output_directory);
create_backup_dir(dump_directory);
g_free(dump_directory);
dump_directory= g_strdup_printf("%s/1", output_directory);
create_backup_dir(dump_directory);
g_free(dump_directory);
#ifdef WITH_BINLOG
daemon_binlog_directory= g_strdup_printf("%s/%s", output_directory, DAEMON_BINLOGS);
create_backup_dir(daemon_binlog_directory);
#endif
}
#ifdef WITH_BINLOG
if (need_binlogs) {
binlog_directory = g_strdup_printf("%s/%s", output_directory, BINLOG_DIRECTORY);
create_backup_dir(binlog_directory);
}
#endif
/* Give ourselves an array of engines to ignore */
if (ignore_engines)
ignore = g_strsplit(ignore_engines, ",", 0);
/* Give ourselves an array of tables to dump */
if (tables_list)
tables = g_strsplit(tables_list, ",", 0);
if (daemon_mode) {
GError* terror;
#ifdef WITH_BINLOG
GThread *bthread= g_thread_create(binlog_thread, GINT_TO_POINTER(1), FALSE, &terror);
if (bthread == NULL) {
g_critical("Could not create binlog thread: %s", terror->message);
g_error_free(terror);
exit(EXIT_FAILURE);
}
#endif
start_scheduled_dump= g_async_queue_new();
GThread *ethread= g_thread_create(exec_thread, GINT_TO_POINTER(1), FALSE, &terror);
if (ethread == NULL) {
g_critical("Could not create exec thread: %s", terror->message);
g_error_free(terror);
exit(EXIT_FAILURE);
}
// Run initial snapshot
run_snapshot(NULL);
#if GLIB_MINOR_VERSION < 14
g_timeout_add(snapshot_interval*60*1000, (GSourceFunc) run_snapshot, NULL);
#else
g_timeout_add_seconds(snapshot_interval*60, (GSourceFunc) run_snapshot, NULL);
#endif
guint sigsource= g_unix_signal_add(SIGINT, sig_triggered, NULL);
sigsource= g_unix_signal_add(SIGTERM, sig_triggered, NULL);
m1= g_main_loop_new(NULL, TRUE);
g_main_loop_run(m1);
g_source_remove(sigsource);
} else {
MYSQL *conn= create_main_connection();
start_dump(conn);
}
//sleep(5);
mysql_thread_end();
mysql_library_end();
g_free(output_directory);
g_strfreev(ignore);
g_strfreev(tables);
if (logoutfile) {
fclose(logoutfile);
}
exit(errors ? EXIT_FAILURE : EXIT_SUCCESS);
}
MYSQL *create_main_connection()
{
MYSQL *conn;
conn = mysql_init(NULL);
if (defaults_file != NULL)
mysql_options(conn,MYSQL_READ_DEFAULT_FILE,defaults_file);
mysql_options(conn,MYSQL_READ_DEFAULT_GROUP,"mydumper");
if (!mysql_real_connect(conn, hostname, username, password, db, port, socket_path, 0)) {
g_critical("Error connecting to database: %s", mysql_error(conn));
exit(EXIT_FAILURE);
}
detected_server= detect_server(conn);
if ((detected_server == SERVER_TYPE_MYSQL) && mysql_query(conn, "SET SESSION wait_timeout = 2147483")){
g_warning("Failed to increase wait_timeout: %s", mysql_error(conn));
}
if ((detected_server == SERVER_TYPE_MYSQL) && mysql_query(conn, "SET SESSION net_write_timeout = 2147483")){
g_warning("Failed to increase net_write_timeout: %s", mysql_error(conn));
}
switch (detected_server) {
case SERVER_TYPE_MYSQL:
g_message("Connected to a MySQL server");
break;
case SERVER_TYPE_DRIZZLE:
g_message("Connected to a Drizzle server");
break;
default:
g_critical("Cannot detect server type");
exit(EXIT_FAILURE);
break;
}
return conn;
}
void *exec_thread(void *data) {
(void) data;
while(1) {
g_async_queue_pop(start_scheduled_dump);
clear_dump_directory();
MYSQL *conn= create_main_connection();
start_dump(conn);