|
@@ -0,0 +1,87 @@
|
|
1
|
+//
|
|
2
|
+// Created by robin on 8/9/15.
|
|
3
|
+//
|
|
4
|
+
|
|
5
|
+#include <stdlib.h>
|
|
6
|
+#include <string.h>
|
|
7
|
+#include <unistd.h>
|
|
8
|
+#include <fstream>
|
|
9
|
+#include "MySql.h"
|
|
10
|
+
|
|
11
|
+#define tmpTemplate "/tmp/pdns-slave.XXXXXX"
|
|
12
|
+
|
|
13
|
+MySql::MySql(const SqlConfiguration &masterConfig, const SqlConfiguration &slaveConfig)
|
|
14
|
+ : _masterConfig(masterConfig)
|
|
15
|
+ , _slaveConfig(slaveConfig)
|
|
16
|
+{
|
|
17
|
+}
|
|
18
|
+
|
|
19
|
+MySql::~MySql()
|
|
20
|
+{
|
|
21
|
+ clean();
|
|
22
|
+}
|
|
23
|
+
|
|
24
|
+BResult MySql::dump()
|
|
25
|
+{
|
|
26
|
+ BResult res;
|
|
27
|
+ _dumpFilePath = getTempFile();
|
|
28
|
+ int status = system(std::string("mysqldump --routines '-h" + _masterConfig.getHost() + "'"
|
|
29
|
+ + " '-u" + _masterConfig.getUser() + "'"
|
|
30
|
+ + " '-p" + _masterConfig.getPassword() + "'"
|
|
31
|
+ + " " + _masterConfig.getDatabase()
|
|
32
|
+ + " > " + _dumpFilePath).c_str());
|
|
33
|
+ if (status == 0)
|
|
34
|
+ return res.ok(true);
|
|
35
|
+ return res.error("mysqldump exited with code " + std::to_string(status));
|
|
36
|
+}
|
|
37
|
+
|
|
38
|
+const std::string MySql::getTempFile()
|
|
39
|
+{
|
|
40
|
+ char tmp[sizeof(tmpTemplate)];
|
|
41
|
+ strcpy(tmp, tmpTemplate);
|
|
42
|
+ mkstemp(tmp);
|
|
43
|
+ return std::string(tmp);
|
|
44
|
+}
|
|
45
|
+
|
|
46
|
+void MySql::clean()
|
|
47
|
+{
|
|
48
|
+ if (!_dumpFilePath.empty())
|
|
49
|
+ {
|
|
50
|
+ unlink(_dumpFilePath.c_str());
|
|
51
|
+ _dumpFilePath = "";
|
|
52
|
+ }
|
|
53
|
+ if (!_overrideFilePath.empty())
|
|
54
|
+ {
|
|
55
|
+ unlink(_overrideFilePath.c_str());
|
|
56
|
+ _overrideFilePath = "";
|
|
57
|
+ }
|
|
58
|
+}
|
|
59
|
+
|
|
60
|
+BResult MySql::insert()
|
|
61
|
+{
|
|
62
|
+ _dumpFilePath = getTempFile();
|
|
63
|
+ return insertSlave(_dumpFilePath);
|
|
64
|
+}
|
|
65
|
+
|
|
66
|
+BResult MySql::override(const std::string &sql)
|
|
67
|
+{
|
|
68
|
+ _overrideFilePath = getTempFile();
|
|
69
|
+ std::ofstream file(_overrideFilePath);
|
|
70
|
+ if (!file)
|
|
71
|
+ return BResult().error("Could not open temp file " + _overrideFilePath);
|
|
72
|
+ file << sql;
|
|
73
|
+ file.close();
|
|
74
|
+ return insertSlave(_overrideFilePath);
|
|
75
|
+}
|
|
76
|
+
|
|
77
|
+BResult MySql::insertSlave(const std::string &file)
|
|
78
|
+{
|
|
79
|
+ BResult res;
|
|
80
|
+ int status = system(std::string("cat " + file + " | mysql '-h" + _slaveConfig.getHost() + "'"
|
|
81
|
+ + " '-u" + _slaveConfig.getUser() + "'"
|
|
82
|
+ + " '-p" + _slaveConfig.getPassword() + "'"
|
|
83
|
+ + " " + _slaveConfig.getDatabase()).c_str());
|
|
84
|
+ if (status == 0)
|
|
85
|
+ return res.ok(true);
|
|
86
|
+ return res.error("mysql exited with code " + std::to_string(status));
|
|
87
|
+}
|