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
| #include <ncursesw/ncurses.h>
#include <ncursesw/panel.h>
#include <mysql_connection.h>
#include <string.h>
#include <sstream>
#include <fstream>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <errno.h>
#include "sql_tablework.h"
#include "sql_connector.h"
#include "logtime.h"
#define FIFO_FILE1 "/tmp/.idfifo1"
#define FIFO_FILE2 "/tmp/.idfifo2"
#define FIFO_FILE3 "/tmp/.idfifo3"
#define BUFF_SIZE 64
using namespace std;
using namespace sql;
sql_tablework::sql_tablework(const char *conffile) {//конструктор класса
unlink(FIFO_FILE1);
unlink(FIFO_FILE2);
unlink(FIFO_FILE3);
sql_connector *conn = new sql_connector(conffile);
logtime *cDate = new logtime();
this->sqlconffile = conffile;
this->address = conn->getFolder().c_str();
this->user = conn->getUser().c_str();
this->password = conn->getPassword().c_str();
this->con = conn->db_ident();
this->dbasedump = conn->getDbdump();
this->currtime = cDate->getFname(); //Фиксируем время
delete conn;
delete cDate;
}
string sql_tablework::int_to_string(int in) {//Преобразую целочисленный тип к string. Внутренняя реализация.
stringstream output;
output << in;
if (in < 10 && in >= 0) {
string out = "0" + output.str();
return out;
} else {
return output.str();
}
return "0";
}
void sql_tablework::dbdump() {//Тут дамп нужной мне таблицы БД
this->out_error = 0;
ofstream logs("/var/log/sqservice/sqsrv.log", ios::app);
if (logs.is_open()) {
Statement *stmt = NULL;
logtime *cDate = new logtime();
sql_connector *conn = new sql_connector(this->sqlconffile);
this->con = conn->db_ident();
//Запрос отключен в тестовом режиме.
//string query = "SELECT * INTO OUTFILE '" + this->dbasedump + this->currtime + ".csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' FROM sq_traffic";
if (this->con->isValid()) {//Если соединение существует
try {
stmt = this->con->createStatement();
stmt->execute(query);
} catch (SQLException &e) {//Обрабатываем исключение
this->out_error = 4;
logs << cDate->getTime() + " #ОШБ(dbdump()): " << e.what() << endl;
logs << cDate->getTime() + " (MySQL Код ошибки: " << e.getErrorCode();
logs << ", SQLСтатус: " << e.getSQLState() << " )" << endl;
}
delete stmt;
}
logs << cDate->getTime() + " #ИНФ: Дамп таблицы завершен." << endl;
delete cDate;
delete conn;
logs.close();
} else this->out_error = 2;
}
const char *sql_tablework::get_mfile_size(const char* addr) {//Получаю текущий размер файла в нужном мне формате
int tmp = 0;
string out = "0б";
long long _result = 0;
ifstream file(addr, ios_base::in | ios_base::ate);
if (file.is_open()) {
file.seekg(0,file.end);
_result = file.tellg();
file.seekg(0,file.beg);
if (_result > 1024 && _result < 1024000) {
tmp = _result / 1024;
out = this->int_to_string(tmp) + "кб ";
} else if (_result > 1024000 && _result < 1024000000) {
tmp = _result / 1024000;
out = this->int_to_string(tmp) + "Мб ";
} else if (_result > 1024000000) {
tmp = _result / 1024000000;
out = this->int_to_string(tmp) + "Гб ";
} else {
out = "0б";
}
file.close();
}
return out.c_str();
}
string sql_tablework::read_data(const char* f_name) {//Читаем из канала
string result = "";
int i = 0;
int fd;
char buff[BUFF_SIZE];
memset(buff, '\0', (BUFF_SIZE - 1));
if ((fd = open(f_name, O_RDONLY)) >= 0) {
if (read(fd, &buff, BUFF_SIZE) >= 0) {
while (buff[i] != '\0') {
result.append(1, buff[i]);
i++;
}
} else {
ofstream logs("/var/log/sqservice/sqsrv.log", ios::app); //Хранение логов
if (logs.is_open()) {
logtime *cDate = new logtime();
logs << cDate->getTime() + " #ОШБ(read_data()): Ошибка чтения канала:" << f_name << " " << " Ошибка(read()): " << errno << endl;
logs.close();
delete cDate;
}
}
close(fd);
} else {
ofstream logs("/var/log/sqservice/sqsrv.log", ios::app); //Хранение логов
if (logs.is_open()) {
logtime *cDate = new logtime();
logs << cDate->getTime() + " #ОШБ(read_data()): Невозможно открыть канал " + *f_name + " для чтения" << " Ошибка(open()): " << errno << endl;
logs.close();
delete cDate;
}
}
return result;
}
void sql_tablework::write_data(const char* f_name, const char* message) {//Пишем в канал
int fd;
if ((fd = open(f_name, O_WRONLY)) >= 0) {
if (write(fd, message, BUFF_SIZE) > 0) {
fsync(fd); //На всякий случай.Write не гарантирует запись.
} else {
if (errno != EPIPE) {
ofstream logs("/var/log/sqservice/sqsrv.log", ios::app); //Хранение логов
if (logs.is_open()) {
logtime *cDate = new logtime();
logs << cDate->getTime() + " #ОШБ(write_data()): Ошибка записи в канал:" << f_name << " Ошибка(write()): " << errno << endl;
logs.close();
delete cDate;
}
}
}
close(fd);
} else {
ofstream logs("/var/log/sqservice/sqsrv.log", ios::app); //Хранение логов
if (logs.is_open()) {
logtime *cDate = new logtime();
logs << cDate->getTime() + " #ОШБ(write_data()): Невозможно открыть канал: " + *f_name + " для записи" << " Ошибка(write()): " << errno << endl;
logs.close();
delete cDate;
}
}
}
void sql_tablework::arch_table() {//Основной функционал
this->out_error = 0;
ofstream logs("/var/log/sqservice/sqsrv.log", ios::app); //Хранение логов
if (logs.is_open()) {
int status;
pid_t forkid[3];
logtime *cDate = new logtime();
if (((mkfifo(FIFO_FILE1, 0777)) != 0) || ((mkfifo(FIFO_FILE2, 0777)) != 0) || ((mkfifo(FIFO_FILE3, 0777)) != 0)) {
logs << cDate->getTime() + " #ОШБ(arch_table()): Ошибка создания каналов межпроцессной связи" << endl;
exit(EXIT_FAILURE);
}
if ((forkid[0] = fork()) < 0) {
logs << cDate->getTime() + " #ОШБ(arch_table()): Ошибка создания процесса архивации" << endl;
exit(EXIT_FAILURE);
}
if (forkid[0] == 0) {//Первый процесс архивация
this->dbdump();
string inFile = this->dbasedump + this->currtime + ".csv";
string outFile = this->dbasedump + this->currtime + ".csv.bz2";
logs << cDate->getTime() + " #ИНФ: Запущен процесс архивации" << endl;
execl("/usr/local/bin/sql_arch.sh", " ", outFile.c_str(), inFile.c_str(), NULL);
//execl("/bin/tar", " ", "-c", "-j", "-f", "/home/andrew/Загрузки/tst.iso.tar.bz2", "/home/andrew/Загрузки/tst.iso", NULL);
exit(EXIT_FAILURE); //Если все хорошо, сюда реализация не заглянет
} else if (forkid[0] > 0) {//Второй процесс
if ((forkid[1] = fork()) < 0) {
logs << cDate->getTime() + " #ОШБ(arch_table()): Ошибка создания процесса ручной отмены операции" << endl;
exit(EXIT_FAILURE);
}
if (forkid[1] == 0) {
char ch;
nodelay(stdscr, TRUE); //Переводим getch в неблокирующий режим
while (1) {
write_data(FIFO_FILE2, "rdy");
ch = getch();
if ((ch == 'q') || (ch == 'Q')) break;
}
sleep(1);//Надо дать возможность считать данные иначе блокировка записи не позволит исполниться коду дальше
write_data(FIFO_FILE2, "off");//Корректно завершаем работу модуля
nodelay(stdscr, FALSE);
exit(0);
} else if (forkid[1] > 0) {
if ((forkid[2] = fork()) < 0) {
logs << cDate->getTime() + " #ОШБ(arch_table()): Ошибка создания процесса интерфейса" << endl;
exit(EXIT_FAILURE);
}
if (forkid[2] == 0) {//Третий процесс визуализация
string inFile = this->dbasedump + this->currtime + ".csv";
string outFile = this->dbasedump + this->currtime + ".csv.bz2";
string title = ("Псевдографическая утилита для конфигурирования прокси-сервера SQUID");
string bkgName = "Архивирование таблицы БД";
string f_message = "Текущий размер файла: " + this->currtime + ".csv";
string s_message = "Текущий размер файла: " + this->currtime + ".csv.bz2";
int y = 0;
int x = 0;
noecho();
curs_set(0);
init_pair(1, COLOR_BLUE, COLOR_YELLOW);
init_pair(2, COLOR_GREEN, COLOR_YELLOW);
init_pair(3, COLOR_BLACK, COLOR_YELLOW);
init_pair(4, COLOR_WHITE, COLOR_BLUE);
init_pair(5, COLOR_GREEN, COLOR_BLACK);
getmaxyx(stdscr, y, x);
int height = y - 3; //Насколько окно меньше терминала
int width = x - 6;
int ycurr = (LINES - height) / 2; //Теперь это насколько делим дабы поставить окно посередине
int xcurr = (COLS - width) / 2;
int c = (width / 2) - (bkgName.length() / 3); //Центр экрана для заглолвка
attron(COLOR_PAIR(5));
mvwprintw(stdscr, 0, xcurr, "%s", title.c_str());
attroff(COLOR_PAIR(5));
WINDOW *Frnt = newwin(height, width, ycurr + 1, xcurr); //Подложка
WINDOW *Wnd = newwin(6, 46, (y - (y / 2)) - 3, (x - (x / 2)) - 23); //Рабочее окно
WINDOW *Shad = newwin(6, 46, (y - (y / 2)) - 2, (x - (x / 2)) - 22); //Рабочее окно
PANEL *PnlW = new_panel(Wnd);
PANEL *PnlF = new_panel(Frnt);
PANEL *PnlS = new_panel(Shad);
wbkgd(Frnt, COLOR_PAIR(4));
wbkgd(Shad, COLOR_BLACK);
wbkgd(Wnd, COLOR_PAIR(3));
wborder(Frnt, ACS_VLINE, ACS_VLINE, ACS_HLINE, ACS_HLINE, ACS_ULCORNER,
ACS_URCORNER, ACS_LLCORNER, ACS_LRCORNER);
attron(COLOR_PAIR(5));
mvwprintw(Frnt, 0, c, "%s", bkgName.c_str());
attroff(COLOR_PAIR(5));
wborder(Wnd, ACS_VLINE, ACS_VLINE, ACS_HLINE, ACS_HLINE, ACS_ULCORNER,
ACS_URCORNER, ACS_LLCORNER, ACS_LRCORNER);
mvwprintw(Frnt, height - 2, 3, "ОТМЕНА/НАЗАД В МЕНЮ(q или Q)");
mvwprintw(Wnd, 1, 1, "%s", f_message.c_str());
mvwprintw(Wnd, 3, 1, "%s", s_message.c_str());
top_panel(PnlW);
while (1) {
if (read_data(FIFO_FILE1) == "off") break;
mvwprintw(Wnd, 0, 1, "%s", read_data(FIFO_FILE3).c_str());
wattron(Wnd, COLOR_PAIR(1) | A_BOLD);
mvwprintw(Wnd, 2, 1, "%s", get_mfile_size(inFile.c_str()));
wattroff(Wnd, COLOR_PAIR(1));
wattron(Wnd, COLOR_PAIR(2) | A_BOLD);
mvwprintw(Wnd, 4, 1, "%s", get_mfile_size(outFile.c_str()));
wattroff(Wnd, COLOR_PAIR(2));
update_panels();
doupdate();
}
mvwprintw(Wnd, 2, 1, "%s", "ВОЗВРАТ В МЕНЮ ");
update_panels();
doupdate();
del_panel(PnlW);
del_panel(PnlF);
del_panel(PnlS);
delwin(Frnt);
delwin(Shad);
delwin(Wnd);
exit(0);
} else if (forkid[2] > 0) { //Родитель третьего процесса
while (read_data(FIFO_FILE2) != "off") {
write_data(FIFO_FILE1, "rdy"); //Постоянно шлем сигнал готовности иначе циклы будут заблокированы
if (waitpid(forkid[0], &status, WNOHANG) == -1) {//Неблокирующий режим контроля детей.
write_data(FIFO_FILE3, "Завершено ");
} else {
write_data(FIFO_FILE3, "Обработка");
}
}
write_data(FIFO_FILE1, "off");
kill(forkid[0], SIGKILL); //Прибиваем на всякий случай
kill(forkid[1], SIGKILL);
nodelay(stdscr, FALSE);
sleep(1);
waitpid(forkid[2], &status, WNOHANG);
}
waitpid(forkid[1], &status, WNOHANG);
}
waitpid(forkid[0], &status, WNOHANG);
}
unlink(FIFO_FILE1);//программа завершается разлинковываем каналы
unlink(FIFO_FILE2);
unlink(FIFO_FILE3);
delete cDate;
logs.close();
} else this->out_error = 2; // Проблемы открытия лог файла
}
sql_tablework::~sql_tablework() {
} |