forked from Tencent/phxsql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio_channel.cpp
395 lines (337 loc) · 13.3 KB
/
io_channel.cpp
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
/*
Tencent is pleased to support the open source community by making PhxSQL available.
Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the GNU General Public License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
https://opensource.org/licenses/GPL-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/poll.h>
#include <unistd.h>
#include <string.h>
#include <mysql.h>
#include "io_channel.h"
#include "phxcomm/phx_log.h"
#include "phxsqlproxyutil.h"
#include "co_routine.h"
#include "routineutil.h"
#include "monitor_plugin.h"
#include "requestfilter_plugin.h"
namespace phxsqlproxy {
#define PRETTY_LOG(log, fmt, ...) \
log("%s:%d requniqid %llu " fmt, __func__, __LINE__, req_uniq_id_, ## __VA_ARGS__)
#define LOG_ERR(...) PRETTY_LOG(phxsql::LogError, __VA_ARGS__)
#define LOG_WARN(...) PRETTY_LOG(phxsql::LogWarning, __VA_ARGS__)
#define LOG_DEBUG(...) PRETTY_LOG(phxsql::LogVerbose, __VA_ARGS__)
IOChannel::IOChannel(PHXSqlProxyConfig * config,
WorkerConfig_t * worker_config,
GroupStatusCache * group_status_cache) :
config_(config),
worker_config_(worker_config),
group_status_cache_(group_status_cache) {
Clear();
}
IOChannel::~IOChannel() {
}
void IOChannel::SetReqUniqID(uint64_t req_uniq_id) {
req_uniq_id_ = req_uniq_id;
}
void IOChannel::Clear() {
req_uniq_id_ = 0;
client_fd_ = -1;
sqlsvr_fd_ = -1;
connect_dest_ = "";
connect_port_ = 0;
is_authed_ = false;
db_name_ = "";
last_read_fd_ = -1;
last_received_request_timestamp_ = 0;
client_ip_ = "";
}
int IOChannel::TransMsg(int client_fd, int sqlsvr_fd) {
client_fd_ = client_fd;
sqlsvr_fd_ = sqlsvr_fd;
int ret = GetPeerName(sqlsvr_fd, connect_dest_, connect_port_);
if (ret != 0) {
LOG_ERR("get dest ip port failed, ret %d sqlsvr_fd %d", ret, sqlsvr_fd);
return 0;
}
// get client_ip_ for FakeClientIPInAuthBuf, forward compatibility
int t_port;
ret = GetPeerName(client_fd, client_ip_, t_port);
if (ret != 0) {
LOG_ERR("get client ip failed, ret %d client_fd %d", ret, client_fd);
return 0;
}
int byte_size_tot = 0;
for (;;) {
struct pollfd pf[2];
memset(pf, 0, sizeof(pf));
pf[0].fd = client_fd;
pf[0].events = (POLLIN | POLLERR | POLLHUP);
pf[1].fd = sqlsvr_fd;
pf[1].events = (POLLIN | POLLERR | POLLHUP);
uint64_t begin = GetTimestampMS();
int return_fd_count = co_poll(co_get_epoll_ct(), pf, 2, 1000);
if (return_fd_count < 0) {
LOG_ERR("poll fd client_fd %d sqlsvr_fd %d failed,ret %d", client_fd, sqlsvr_fd, return_fd_count);
break;
}
uint64_t cost_in_epoll = GetTimestampMS() - begin;
if (cost_in_epoll < 1000 && cost_in_epoll > 30) {
LOG_DEBUG("epollcost2 %llu", cost_in_epoll);
}
int byte_size = TransMsgDirect(client_fd, sqlsvr_fd, pf, 2);
if (byte_size < 0) {
break;
}
byte_size_tot += byte_size;
ByteFromMysqlClient(byte_size);
int byte_size2 = TransMsgDirect(sqlsvr_fd, client_fd, pf, 2);
if (byte_size2 < 0) {
break;
}
byte_size_tot += byte_size2;
ByteFromConnectDestSvr(byte_size2);
if (byte_size || byte_size2) {
MonitorPluginEntry::GetDefault()->GetMonitorPlugin()->Epocost(GetTimestampMS() - begin);
}
}
return byte_size_tot;
}
int IOChannel::WriteToDest(int dest_fd, const char * buf, int write_size) {
MonitorPluginEntry::GetDefault()->GetMonitorPlugin()->WriteNetwork(write_size);
//for debug
//
if (config_->OpenDebugMode()) {
std::string debug_str;
GetMysqlBufDebugString(buf, write_size, debug_str);
LOG_DEBUG("dest %d command [%s]", dest_fd, debug_str.c_str());
}
//for debug end
int written_once = 0;
int total_written = 0;
while (total_written < write_size) {
written_once = RoutineWriteWithTimeout(dest_fd, buf + total_written, write_size - total_written,
config_->WriteTimeoutMs());
if (written_once < 0) {
LOG_ERR("write to %d buf size [%d] failed, ret %d, errno (%d:%s)",
dest_fd, write_size, written_once, errno, strerror(errno));
MonitorPluginEntry::GetDefault()->GetMonitorPlugin()->WriteNetworkFail(write_size);
return -__LINE__;
}
total_written += written_once;
}
return total_written;
}
int IOChannel::TransMsgDirect(int source_fd, int dest_fd, struct pollfd pf[], int nfds) {
int byte_size = 0;
int read_once = 0;
int written = 0;
for (int i = 0; i < nfds; ++i) {
char buf[1024 * 16];
if (pf[i].fd == source_fd) {
if (pf[i].revents & POLLIN) {
if ((read_once = read(source_fd, buf, sizeof(buf))) <= 0) {
if (read_once < 0) {
MonitorPluginEntry::GetDefault()->GetMonitorPlugin()->ReadNetworkFail();
}
LOG_ERR("clientfd %d svrfd %d source %d dest %d read failed, ret %d, errno (%d:%s)",
client_fd_, sqlsvr_fd_, source_fd, dest_fd, read_once, errno, strerror(errno));
return -1;
}
if (source_fd == client_fd_) {
if (!is_authed_) {
GetDBNameFromAuthBuf(buf, read_once);
is_authed_ = true;
} else {
GetDBNameFromReqBuf(buf, read_once);
}
if (!CanExecute(buf, read_once)) {
LOG_ERR("request [cmd:%d] can't execute here", (int) buf[4]);
return -1;
}
}
written = WriteToDest(dest_fd, buf, read_once);
if (written < 0) {
return -__LINE__;
}
byte_size += written;
//LOG_DEBUG("last read clientfd %d svrfd %d source %d dest %d ret %d read ret %d",
// client_fd_, sqlsvr_fd_, source_fd, dest_fd, read_once, byte_size);
} else if (pf[i].revents & POLLHUP) {
LOG_DEBUG("source %d dest %d read events POLLHUP", source_fd, dest_fd);
} else if (pf[i].revents & POLLERR) {
return -__LINE__;
}
}
}
return byte_size;
}
int IOChannel::FakeClientIPInAuthBuf(char * buf, size_t buf_len) {
if (buf_len < 36) {
LOG_ERR("buf len less than 36");
return -__LINE__;
}
char * reserverd_begin = buf + 14;
char ip_buf[INET6_ADDRSTRLEN] = { 0 };
uint32_t ip = 0;
memcpy(&ip, reserverd_begin, sizeof(uint32_t));
if (ip) {
if (inet_ntop(AF_INET, reserverd_begin, ip_buf, INET6_ADDRSTRLEN) != NULL) {
if (!group_status_cache_->IsMember(client_ip_)) {
LOG_ERR("receive fake ip package from [%s], fake ip [%s]", client_ip_.c_str(), ip_buf);
return -__LINE__;
}
} else
return -__LINE__;
} else {
int ret = inet_pton(AF_INET, client_ip_.c_str(), reserverd_begin);
if (ret <= 0) {
LOG_ERR("ret %d errno (%d:%s)", ret, errno, strerror(errno));
return -__LINE__;
}
}
return 0;
}
void IOChannel::GetDBNameFromAuthBuf(const char * buf, int buf_size) {
if (buf_size < 36) {
return;
}
uint32_t client_property = 0;
memcpy(&client_property, buf + 4, 4);
if (client_property & CLIENT_CONNECT_WITH_DB) {
const char * offset = buf + 36;
//skip username
offset += strlen(offset) + 1;
//skip authorize data
int len_field_size = 0;
uint64_t len = DecodedLengthBinary(offset, buf_size - (offset - buf), len_field_size);
if (len == (uint64_t)(-1LL))
return;
offset += len_field_size + len;
//this is the db's name
if (strlen(offset)) {
db_name_ = std::string(offset, strlen(offset));
}
LOG_DEBUG("client property %u CLIENT_CONNECT_WITH_DB %d ret db [%s]",
client_property, (int) CLIENT_CONNECT_WITH_DB, db_name_.c_str());
}
}
void IOChannel::GetDBNameFromReqBuf(const char * buf, int buf_size) {
if (buf_size > 5) {
char cmd = buf[4];
if (cmd == COM_INIT_DB) {
int buf_len = 0;
memcpy(&buf_len, buf, 3);
db_name_ = std::string(buf + 5, buf_len - 1);
LOG_DEBUG("bufsize %d buflen %d ret [%s]", buf_size, buf_len, db_name_.c_str());
}
}
}
void IOChannel::ByteFromConnectDestSvr(uint32_t byte_size) {
if (byte_size != 0) {
MonitorPluginEntry::GetDefault()->GetMonitorPlugin()->ReceiveByteFromConnectDestSvr(byte_size);
//mysql client stat
if (connect_port_ == config_->GetMysqlPort()) {
MonitorPluginEntry::GetDefault()->GetMonitorPlugin()->ReceiveByteFromMysql(byte_size);
}
if (last_read_fd_ != sqlsvr_fd_) {
MonitorPluginEntry::GetDefault()->GetMonitorPlugin()->DestSvrRespPacket();
last_read_fd_ = sqlsvr_fd_;
if (last_received_request_timestamp_) {
uint64_t cost = GetTimestampMS() - last_received_request_timestamp_;
if (connect_port_ == config_->GetMysqlPort()) {
//LOG_DEBUG("recieve mysql resp cost %llu", cost);
MonitorPluginEntry::GetDefault()->GetMonitorPlugin()->MysqlQueryCost(cost);
}
//LOG_DEBUG("request exec cost %llu", cost);
MonitorPluginEntry::GetDefault()->GetMonitorPlugin()->RequestExecuteCost(cost);
}
}
}
}
void IOChannel::ByteFromMysqlClient(uint32_t byte_size) {
if (byte_size != 0) {
MonitorPluginEntry::GetDefault()->GetMonitorPlugin()->ReceiveByteFromMysqlClient(byte_size);
//mysql client stat
if (connect_port_ == config_->GetMysqlPort()) {
MonitorPluginEntry::GetDefault()->GetMonitorPlugin()->MysqlClientConnect(byte_size);
}
if (last_read_fd_ != client_fd_) {
MonitorPluginEntry::GetDefault()->GetMonitorPlugin()->ClientReqPacket();
last_read_fd_ = client_fd_;
last_received_request_timestamp_ = GetTimestampMS();
}
}
}
MasterIOChannel::MasterIOChannel(PHXSqlProxyConfig * config,
WorkerConfig_t * worker_config,
GroupStatusCache * group_status_cache) :
IOChannel(config, worker_config, group_status_cache) {
}
MasterIOChannel::~MasterIOChannel() {
}
bool MasterIOChannel::CanExecute(const char * buf, int size) {
std::string master_ip;
int ret = group_status_cache_->GetMaster(master_ip);
if (ret != 0) {
LOG_ERR("getmaster failed, ret %d", ret);
return false;
}
bool can_execute = false;
if (connect_dest_ == "127.0.0.1") {
if (master_ip == worker_config_->listen_ip_) {
can_execute = true;
}
} else {
if (master_ip == connect_dest_) {
//allowed only if my connect destination is master
can_execute = true;
}
}
if (can_execute && connect_port_ == config_->GetMysqlPort()) {
can_execute = RequestFilterPluginEntry::GetDefault()->GetRequestFilterPlugin()
->CanExecute(true, db_name_, buf, size);
}
if (can_execute == false) {
LOG_ERR("find sql [%s] can't execute in this connection, port [%d]",
std::string(buf + 5, size - 5).c_str(), worker_config_->port_);
}
return can_execute;
}
SlaveIOChannel::SlaveIOChannel(PHXSqlProxyConfig * config,
WorkerConfig_t * worker_config,
GroupStatusCache * group_status_cache) :
IOChannel(config, worker_config, group_status_cache) {
}
SlaveIOChannel::~SlaveIOChannel() {
}
bool SlaveIOChannel::CanExecute(const char * buf, int size) {
std::string master_ip;
int ret = group_status_cache_->GetMaster(master_ip);
if (ret != 0) {
LOG_ERR("getmaster failed, ret %d", ret);
return false;
}
if (!config_->MasterEnableReadPort()) {
if (master_ip == connect_dest_) {
LOG_ERR("connected to master %s, stop query", master_ip.c_str());
return false;
}
}
bool can_execute = true;
if (connect_port_ == config_->GetMysqlPort()) {
can_execute = RequestFilterPluginEntry::GetDefault()->GetRequestFilterPlugin()
->CanExecute(false, db_name_, buf, size);
}
if (can_execute == false) {
LOG_ERR("find sql [%s] can't execute in this connection, port [%d]",
std::string(buf + 5, size - 5).c_str(), worker_config_->port_);
}
return can_execute;
}
}