forked from Qihoo360/Atlas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy-plugin.c
More file actions
2653 lines (2149 loc) · 79.2 KB
/
proxy-plugin.c
File metadata and controls
2653 lines (2149 loc) · 79.2 KB
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
/* $%BEGINLICENSE%$
Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the
License.
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, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/**
* @page page-plugin-proxy Proxy plugin
*
* The MySQL Proxy implements the MySQL Protocol in its own way.
*
* -# connect @msc
* client, proxy, backend;
* --- [ label = "connect to backend" ];
* client->proxy [ label = "INIT" ];
* proxy->backend [ label = "CONNECT_SERVER", URL="\ref proxy_connect_server" ];
* @endmsc
* -# auth @msc
* client, proxy, backend;
* --- [ label = "authenticate" ];
* backend->proxy [ label = "READ_HANDSHAKE", URL="\ref proxy_read_handshake" ];
* proxy->client [ label = "SEND_HANDSHAKE" ];
* client->proxy [ label = "READ_AUTH", URL="\ref proxy_read_auth" ];
* proxy->backend [ label = "SEND_AUTH" ];
* backend->proxy [ label = "READ_AUTH_RESULT", URL="\ref proxy_read_auth_result" ];
* proxy->client [ label = "SEND_AUTH_RESULT" ];
* @endmsc
* -# query @msc
* client, proxy, backend;
* --- [ label = "query result phase" ];
* client->proxy [ label = "READ_QUERY", URL="\ref proxy_read_query" ];
* proxy->backend [ label = "SEND_QUERY" ];
* backend->proxy [ label = "READ_QUERY_RESULT", URL="\ref proxy_read_query_result" ];
* proxy->client [ label = "SEND_QUERY_RESULT", URL="\ref proxy_send_query_result" ];
* @endmsc
*
* - network_mysqld_proxy_connection_init()
* -# registers the callbacks
* - proxy_connect_server() (CON_STATE_CONNECT_SERVER)
* -# calls the connect_server() function in the lua script which might decide to
* -# send a handshake packet without contacting the backend server (CON_STATE_SEND_HANDSHAKE)
* -# closing the connection (CON_STATE_ERROR)
* -# picking a active connection from the connection pool
* -# pick a backend to authenticate against
* -# do nothing
* -# by default, pick a backend from the backend list on the backend with the least active connctions
* -# opens the connection to the backend with connect()
* -# when done CON_STATE_READ_HANDSHAKE
* - proxy_read_handshake() (CON_STATE_READ_HANDSHAKE)
* -# reads the handshake packet from the server
* - proxy_read_auth() (CON_STATE_READ_AUTH)
* -# reads the auth packet from the client
* - proxy_read_auth_result() (CON_STATE_READ_AUTH_RESULT)
* -# reads the auth-result packet from the server
* - proxy_send_auth_result() (CON_STATE_SEND_AUTH_RESULT)
* - proxy_read_query() (CON_STATE_READ_QUERY)
* -# reads the query from the client
* - proxy_read_query_result() (CON_STATE_READ_QUERY_RESULT)
* -# reads the query-result from the server
* - proxy_send_query_result() (CON_STATE_SEND_QUERY_RESULT)
* -# called after the data is written to the client
* -# if scripts wants to close connections, goes to CON_STATE_ERROR
* -# if queries are in the injection queue, goes to CON_STATE_SEND_QUERY
* -# otherwise goes to CON_STATE_READ_QUERY
* -# does special handling for COM_BINLOG_DUMP (go to CON_STATE_READ_QUERY_RESULT)
*/
#ifdef HAVE_SYS_FILIO_H
/**
* required for FIONREAD on solaris
*/
#include <sys/filio.h>
#endif
#ifndef _WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>
#include <stdio.h>
#include <execinfo.h>
#include <errno.h>
#include <glib.h>
#ifdef HAVE_LUA_H
/**
* embedded lua support
*/
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#endif
/* for solaris 2.5 and NetBSD 1.3.x */
#ifndef HAVE_SOCKLEN_T
typedef int socklen_t;
#endif
#include <mysqld_error.h> /** for ER_UNKNOWN_ERROR */
#include <math.h>
#include <openssl/evp.h>
#include "network-mysqld.h"
#include "network-mysqld-proto.h"
#include "network-mysqld-packet.h"
#include "network-mysqld-lua.h"
#include "network-conn-pool.h"
#include "network-conn-pool-lua.h"
#include "sys-pedantic.h"
#include "network-injection.h"
#include "network-injection-lua.h"
#include "network-backend.h"
#include "glib-ext.h"
#include "lua-env.h"
#include "proxy-plugin.h"
#include "lua-load-factory.h"
#include "chassis-timings.h"
#include "chassis-gtimeval.h"
#include "lib/sql-tokenizer.h"
#include "chassis-event-thread.h"
#define C(x) x, sizeof(x) - 1
#define S(x) x->str, x->len
#define HASH_INSERT(hash, key, expr) \
do { \
GString *hash_value; \
if ((hash_value = g_hash_table_lookup(hash, key))) { \
expr; \
} else { \
hash_value = g_string_new(NULL); \
expr; \
g_hash_table_insert(hash, g_strdup(key), hash_value); \
} \
} while(0);
#define CRASHME() do { char *_crashme = NULL; *_crashme = 0; } while(0);
static gboolean online = TRUE;
static gchar op = COM_QUERY;
typedef struct {
gchar* table_name;
gchar* column_name;
guint table_num;
} db_table_t;
typedef enum {
OFF,
ON,
REALTIME
} SQL_LOG_TYPE;
SQL_LOG_TYPE sql_log_type = OFF;
char* charset[64] = {NULL, "big5", NULL, NULL, NULL, NULL, NULL, NULL, "latin1", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "gb2312", NULL, NULL, NULL, "gbk", NULL, NULL, NULL, NULL, "utf8", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "utf8mb4", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "binary"};
struct chassis_plugin_config {
gchar *address; /**< listening address of the proxy */
gchar **backend_addresses; /**< read-write backends */
gchar **read_only_backend_addresses; /**< read-only backends */
gint fix_bug_25371; /**< suppress the second ERR packet of bug #25371 */
gint profiling; /**< skips the execution of the read_query() function */
gchar *lua_script; /**< script to load at the start the connection */
gint pool_change_user; /**< don't reset the connection, when a connection is taken from the pool
- this safes a round-trip, but we also don't cleanup the connection
- another name could be "fast-pool-connect", but that's too friendly
*/
gint start_proxy;
gchar **client_ips;
GHashTable *ip_table[2];
gint ip_table_index;
gchar **lvs_ips;
GHashTable *lvs_table;
gchar **tables;
GHashTable *dt_table;
gchar **pwds;
GHashTable *pwd_table[2];
gint pwd_table_index;
network_mysqld_con *listen_con;
FILE *sql_log;
gchar *sql_log_type;
gint sql_log_slow_ms;
gchar *charset;
};
chassis_plugin_config *config = NULL;
guint get_table_index(GPtrArray* tokens, gint* d, gint* t) {
*d = *t = -1;
sql_token** ts = (sql_token**)(tokens->pdata);
guint len = tokens->len;
if (len <= 1) { return 0; }
guint i = 1, j;
while (ts[i]->token_id == TK_COMMENT && ++i < len);
if (i >= len) { return 0; } // sql contains TK_COMMENT only.
sql_token_id token_id = ts[i]->token_id;
if (token_id == TK_SQL_SELECT || token_id == TK_SQL_DELETE) {
for (; i < len; ++i) {
if (ts[i]->token_id == TK_SQL_FROM) {
for (j = i+1; j < len; ++j) {
if (ts[j]->token_id == TK_SQL_WHERE) break;
if (ts[j]->token_id == TK_LITERAL) {
if (j + 2 < len && ts[j+1]->token_id == TK_DOT) {
*d = j;
*t = j + 2;
} else {
*t = j;
}
break;
}
}
break;
}
}
return 1;
} else if (token_id == TK_SQL_UPDATE) {
for (; i < len; ++i) {
if (ts[i]->token_id == TK_SQL_SET) break;
if (ts[i]->token_id == TK_LITERAL) {
if (i + 2 < len && ts[i+1]->token_id == TK_DOT) {
*d = i;
*t = i + 2;
} else {
*t = i;
}
break;
}
}
return 2;
} else if (token_id == TK_SQL_INSERT || token_id == TK_SQL_REPLACE) {
for (; i < len; ++i) {
gchar* str = ts[i]->text->str;
if (strcasecmp(str, "VALUES") == 0 || strcasecmp(str, "VALUE") == 0) break;
sql_token_id token_id = ts[i]->token_id;
if (token_id == TK_LITERAL && i + 2 < len && ts[i+1]->token_id == TK_DOT) {
*d = i;
*t = i + 2;
break;
} else if (token_id == TK_LITERAL || token_id == TK_FUNCTION) {
if (i == len - 1) {
*t = i;
break;
} else {
str = ts[i+1]->text->str;
token_id = ts[i+1]->token_id;
if (strcasecmp(str, "VALUES") == 0 || strcasecmp(str, "VALUE") == 0 || token_id == TK_OBRACE || token_id == TK_SQL_SET) {
*t = i;
break;
}
}
}
}
return 3;
}
return 0;
}
GArray* get_column_index(GPtrArray* tokens, gchar* table_name, gchar* column_name, guint sql_type, gint start) {
GArray* columns = g_array_new(FALSE, FALSE, sizeof(guint));
sql_token** ts = (sql_token**)(tokens->pdata);
guint len = tokens->len;
guint i, j, k;
if (sql_type == 1) {
for (i = start; i < len; ++i) {
if (ts[i]->token_id == TK_SQL_WHERE) {
for (j = i+1; j < len-2; ++j) {
if (ts[j]->token_id == TK_LITERAL && strcasecmp(ts[j]->text->str, column_name) == 0) {
if (ts[j+1]->token_id == TK_EQ) {
if (ts[j-1]->token_id != TK_DOT || strcasecmp(ts[j-2]->text->str, table_name) == 0) {
k = j + 2;
g_array_append_val(columns, k);
break;
}
} else if (j + 3 < len && strcasecmp(ts[j+1]->text->str, "IN") == 0 && ts[j+2]->token_id == TK_OBRACE) {
k = j + 3;
g_array_append_val(columns, k);
while ((k += 2) < len && ts[k-1]->token_id != TK_CBRACE) {
g_array_append_val(columns, k);
}
break;
}
}
}
break;
}
}
} else if (sql_type == 2) {
for (i = start; i < len; ++i) {
if (ts[i]->token_id == TK_SQL_WHERE) {
for (j = i+1; j < len-2; ++j) {
if (ts[j]->token_id == TK_LITERAL && strcasecmp(ts[j]->text->str, column_name) == 0) {
if (ts[j+1]->token_id == TK_EQ) {
if (ts[j-1]->token_id != TK_DOT || strcasecmp(ts[j-2]->text->str, table_name) == 0) {
k = j + 2;
g_array_append_val(columns, k);
break;
}
} else if (j + 3 < len && strcasecmp(ts[j+1]->text->str, "IN") == 0 && ts[j+2]->token_id == TK_OBRACE) {
k = j + 3;
g_array_append_val(columns, k);
while ((k += 2) < len && ts[k-1]->token_id != TK_CBRACE) {
g_array_append_val(columns, k);
}
break;
}
}
}
break;
}
}
} else if (sql_type == 3) {
sql_token_id token_id = ts[start]->token_id;
if (token_id == TK_SQL_SET) {
for (i = start+1; i < len-2; ++i) {
if (ts[i]->token_id == TK_LITERAL && strcasecmp(ts[i]->text->str, column_name) == 0) {
k = i + 2;
g_array_append_val(columns, k);
break;
}
}
} else {
k = 2;
if (token_id == TK_OBRACE) {
gint found = -1;
for (j = start+1; j < len; ++j) {
token_id = ts[j]->token_id;
if (token_id == TK_CBRACE) break;
if (token_id == TK_LITERAL && strcasecmp(ts[j]->text->str, column_name) == 0) {
if (ts[j-1]->token_id != TK_DOT || strcasecmp(ts[j-2]->text->str, table_name) == 0) {
found = j;
break;
}
}
}
k = found - start + 1;
}
for (i = start; i < len-1; ++i) {
gchar* str = ts[i]->text->str;
if ((strcasecmp(str, "VALUES") == 0 || strcasecmp(str, "VALUE") == 0) && ts[i+1]->token_id == TK_OBRACE) {
k += i;
if (k < len) g_array_append_val(columns, k);
break;
}
}
}
}
return columns;
}
GPtrArray* combine_sql(GPtrArray* tokens, gint table, GArray* columns, guint num) {
GPtrArray* sqls = g_ptr_array_new();
sql_token** ts = (sql_token**)(tokens->pdata);
guint len = tokens->len;
guint i;
if (columns->len == 1) {
GString* sql = g_string_new(&op);
if (ts[1]->token_id == TK_COMMENT) {
g_string_append_printf(sql, "/*%s*/", ts[1]->text->str);
} else {
g_string_append(sql, ts[1]->text->str);
}
for (i = 2; i < len; ++i) {
sql_token_id token_id = ts[i]->token_id;
if (token_id != TK_OBRACE) g_string_append_c(sql, ' ');
if (i == table) {
g_string_append_printf(sql, "%s_%u", ts[i]->text->str, atoi(ts[g_array_index(columns, guint, 0)]->text->str) % num);
} else if (token_id == TK_STRING) {
g_string_append_printf(sql, "'%s'", ts[i]->text->str);
} else if (token_id == TK_COMMENT) {
g_string_append_printf(sql, "/*%s*/", ts[i]->text->str);
} else {
g_string_append(sql, ts[i]->text->str);
}
}
g_ptr_array_add(sqls, sql);
} else {
GArray* mt[num];
for (i = 0; i < num; ++i) mt[i] = g_array_new(FALSE, FALSE, sizeof(guint));
guint clen = columns->len;
for (i = 0; i < clen; ++i) {
guint column_value = atoi(ts[g_array_index(columns, guint, i)]->text->str);
g_array_append_val(mt[column_value%num], column_value);
}
guint property_index = g_array_index(columns, guint, 0) - 3;
guint start_skip_index = property_index + 1;
guint end_skip_index = property_index + (clen + 1) * 2;
guint m;
for (m = 0; m < num; ++m) {
if (mt[m]->len > 0) {
GString* tmp = g_string_new(" IN(");
g_string_append_printf(tmp, "%u", g_array_index(mt[m], guint, 0));
guint k;
for (k = 1; k < mt[m]->len; ++k) {
g_string_append_printf(tmp, ",%u", g_array_index(mt[m], guint, k));
}
g_string_append_c(tmp, ')');
GString* sql = g_string_new(&op);
if (ts[1]->token_id == TK_COMMENT) {
g_string_append_printf(sql, "/*%s*/", ts[1]->text->str);
} else {
g_string_append(sql, ts[1]->text->str);
}
for (i = 2; i < len; ++i) {
if (i < start_skip_index || i > end_skip_index) {
if (ts[i]->token_id != TK_OBRACE) g_string_append_c(sql, ' ');
if (i == table) {
g_string_append_printf(sql, "%s_%u", ts[i]->text->str, m);
} else if (i == property_index) {
g_string_append_printf(sql, "%s%s", ts[i]->text->str, tmp->str);
} else if (ts[i]->token_id == TK_STRING) {
g_string_append_printf(sql, "'%s'", ts[i]->text->str);
} else if (ts[i]->token_id == TK_COMMENT) {
g_string_append_printf(sql, "/*%s*/", ts[i]->text->str);
} else {
g_string_append(sql, ts[i]->text->str);
}
}
}
g_string_free(tmp, TRUE);
g_ptr_array_add(sqls, sql);
}
g_array_free(mt[m], TRUE);
}
}
return sqls;
}
GPtrArray* sql_parse(network_mysqld_con* con, GPtrArray* tokens) {
//1. 解析库名和表名
gint db, table;
guint sql_type = get_table_index(tokens, &db, &table);
if (table == -1) return NULL;
//2. 解析列
gchar* table_name = NULL;
if (db == -1) {
table_name = g_strdup_printf("%s.%s", con->client->default_db->str, ((sql_token*)tokens->pdata[table])->text->str);
} else {
table_name = g_strdup_printf("%s.%s", ((sql_token*)tokens->pdata[db])->text->str, ((sql_token*)tokens->pdata[table])->text->str);
}
db_table_t* dt = g_hash_table_lookup(config->dt_table, table_name);
if (dt == NULL) {
g_free(table_name);
return NULL;
}
GArray* columns = get_column_index(tokens, table_name, dt->column_name, sql_type, table+1);
g_free(table_name);
if (columns->len == 0) {
g_array_free(columns, TRUE);
return NULL;
}
//3. 拼接SQL
GPtrArray* sqls = combine_sql(tokens, table, columns, dt->table_num);
g_array_free(columns, TRUE);
return sqls;
}
int idle_rw(network_mysqld_con* con) {
int ret = -1;
guint i;
network_backends_t* backends = con->srv->backends;
guint count = network_backends_count(backends);
for (i = 0; i < count; ++i) {
network_backend_t* backend = network_backends_get(backends, i);
if (backend == NULL) continue;
if (chassis_event_thread_pool(backend) == NULL) continue;
if (backend->type == BACKEND_TYPE_RW && backend->state == BACKEND_STATE_UP) {
ret = i;
break;
}
}
return ret;
}
int idle_ro(network_mysqld_con* con) {
int max_conns = -1;
guint i;
network_backends_t* backends = con->srv->backends;
guint count = network_backends_count(backends);
for(i = 0; i < count; ++i) {
network_backend_t* backend = network_backends_get(backends, i);
if (backend == NULL) continue;
if (chassis_event_thread_pool(backend) == NULL) continue;
if (backend->type == BACKEND_TYPE_RO && backend->state == BACKEND_STATE_UP) {
if (max_conns == -1 || backend->connected_clients < max_conns) {
max_conns = backend->connected_clients;
}
}
}
return max_conns;
}
int wrr_ro(network_mysqld_con *con) {
guint i;
network_backends_t* backends = con->srv->backends;
g_wrr_poll* rwsplit = backends->global_wrr;
guint ndx_num = network_backends_count(backends);
// set max weight if no init
if (rwsplit->max_weight == 0) {
for(i = 0; i < ndx_num; ++i) {
network_backend_t* backend = network_backends_get(backends, i);
if (backend == NULL) continue;
if (rwsplit->max_weight < backend->weight) {
rwsplit->max_weight = backend->weight;
rwsplit->cur_weight = backend->weight;
}
}
}
guint max_weight = rwsplit->max_weight;
guint cur_weight = rwsplit->cur_weight;
guint next_ndx = rwsplit->next_ndx;
// get backend index by slave wrr
gint ndx = -1;
for(i = 0; i < ndx_num; ++i) {
network_backend_t* backend = network_backends_get(backends, next_ndx);
if (backend == NULL) goto next;
if (chassis_event_thread_pool(backend) == NULL) goto next;
if (backend->type == BACKEND_TYPE_RO && backend->weight >= cur_weight && backend->state == BACKEND_STATE_UP) ndx = next_ndx;
next:
if (next_ndx >= ndx_num - 1) {
--cur_weight;
next_ndx = 0;
if (cur_weight == 0) cur_weight = max_weight;
} else {
++next_ndx;
}
if (ndx != -1) break;
}
rwsplit->cur_weight = cur_weight;
rwsplit->next_ndx = next_ndx;
return ndx;
}
/**
* call the lua function to intercept the handshake packet
*
* @return PROXY_SEND_QUERY to send the packet from the client
* PROXY_NO_DECISION to pass the server packet unmodified
*/
static network_mysqld_lua_stmt_ret proxy_lua_read_handshake(network_mysqld_con *con) {
network_mysqld_lua_stmt_ret ret = PROXY_NO_DECISION; /* send what the server gave us */
#ifdef HAVE_LUA_H
network_mysqld_con_lua_t *st = con->plugin_con_state;
lua_State *L;
/* call the lua script to pick a backend
ignore the return code from network_mysqld_con_lua_register_callback, because we cannot do anything about it,
it would always show up as ERROR 2013, which is not helpful.
*/
(void)network_mysqld_con_lua_register_callback(con, config->lua_script);
if (!st->L) return ret;
L = st->L;
g_assert(lua_isfunction(L, -1));
lua_getfenv(L, -1);
g_assert(lua_istable(L, -1));
lua_getfield_literal(L, -1, C("read_handshake"));
if (lua_isfunction(L, -1)) {
/* export
*
* every thing we know about it
* */
if (lua_pcall(L, 0, 1, 0) != 0) {
g_critical("(read_handshake) %s", lua_tostring(L, -1));
lua_pop(L, 1); /* errmsg */
/* the script failed, but we have a useful default */
} else {
if (lua_isnumber(L, -1)) {
ret = lua_tonumber(L, -1);
}
lua_pop(L, 1);
}
switch (ret) {
case PROXY_NO_DECISION:
break;
case PROXY_SEND_QUERY:
g_warning("%s.%d: (read_handshake) return proxy.PROXY_SEND_QUERY is deprecated, use PROXY_SEND_RESULT instead",
__FILE__, __LINE__);
ret = PROXY_SEND_RESULT;
case PROXY_SEND_RESULT:
/**
* proxy.response.type = ERR, RAW, ...
*/
if (network_mysqld_con_lua_handle_proxy_response(con, config->lua_script)) {
/**
* handling proxy.response failed
*
* send a ERR packet
*/
network_mysqld_con_send_error(con->client, C("(lua) handling proxy.response failed, check error-log"));
}
break;
default:
ret = PROXY_NO_DECISION;
break;
}
} else if (lua_isnil(L, -1)) {
lua_pop(L, 1); /* pop the nil */
} else {
g_message("%s.%d: %s", __FILE__, __LINE__, lua_typename(L, lua_type(L, -1)));
lua_pop(L, 1); /* pop the ... */
}
lua_pop(L, 1); /* fenv */
g_assert(lua_isfunction(L, -1));
#endif
return ret;
}
/**
* parse the hand-shake packet from the server
*
*
* @note the SSL and COMPRESS flags are disabled as we can't
* intercept or parse them.
*/
NETWORK_MYSQLD_PLUGIN_PROTO(proxy_read_handshake) {
network_packet packet;
network_socket *recv_sock, *send_sock;
network_mysqld_auth_challenge *challenge;
GString *challenge_packet;
guint8 status = 0;
int err = 0;
send_sock = con->client;
recv_sock = con->server;
packet.data = g_queue_peek_tail(recv_sock->recv_queue->chunks);
packet.offset = 0;
err = err || network_mysqld_proto_skip_network_header(&packet);
if (err) return NETWORK_SOCKET_ERROR;
err = err || network_mysqld_proto_peek_int8(&packet, &status);
if (err) return NETWORK_SOCKET_ERROR;
/* handle ERR packets directly */
if (status == 0xff) {
/* move the chunk from one queue to the next */
guint16 errcode;
gchar *errmsg = NULL;
// get error message from packet
packet.offset += 1; // skip 0xff
err = err || network_mysqld_proto_get_int16(&packet, &errcode);
if (packet.offset < packet.data->len) {
err = err || network_mysqld_proto_get_string_len(&packet, &errmsg, packet.data->len - packet.offset);
}
g_warning("[%s]: error packet from server (%s -> %s): %s(%d)", G_STRLOC, recv_sock->dst->name->str, recv_sock->src->name->str, errmsg, errcode);
if (errmsg) g_free(errmsg);
network_mysqld_queue_append_raw(send_sock, send_sock->send_queue, g_queue_pop_tail(recv_sock->recv_queue->chunks));
network_mysqld_con_lua_t *st = con->plugin_con_state;
if (st->backend->state != BACKEND_STATE_OFFLINE) st->backend->state = BACKEND_STATE_DOWN;
// chassis_gtime_testset_now(&st->backend->state_since, NULL);
network_socket_free(con->server);
con->server = NULL;
return NETWORK_SOCKET_ERROR; /* it sends what is in the send-queue and hangs up */
}
challenge = network_mysqld_auth_challenge_new();
if (network_mysqld_proto_get_auth_challenge(&packet, challenge)) {
g_string_free(g_queue_pop_tail(recv_sock->recv_queue->chunks), TRUE);
network_mysqld_auth_challenge_free(challenge);
return NETWORK_SOCKET_ERROR;
}
con->server->challenge = challenge;
/* we can't sniff compressed packets nor do we support SSL */
challenge->capabilities &= ~(CLIENT_COMPRESS);
challenge->capabilities &= ~(CLIENT_SSL);
switch (proxy_lua_read_handshake(con)) {
case PROXY_NO_DECISION:
break;
case PROXY_SEND_RESULT:
/* the client overwrote and wants to send its own packet
* it is already in the queue */
g_string_free(g_queue_pop_tail(recv_sock->recv_queue->chunks), TRUE);
return NETWORK_SOCKET_ERROR;
default:
g_error("%s.%d: ...", __FILE__, __LINE__);
break;
}
challenge_packet = g_string_sized_new(packet.data->len); /* the packet we generate will be likely as large as the old one. should save some reallocs */
network_mysqld_proto_append_auth_challenge(challenge_packet, challenge);
network_mysqld_queue_sync(send_sock, recv_sock);
network_mysqld_queue_append(send_sock, send_sock->send_queue, S(challenge_packet));
g_string_free(challenge_packet, TRUE);
g_string_free(g_queue_pop_tail(recv_sock->recv_queue->chunks), TRUE);
/* copy the pack to the client */
con->state = CON_STATE_SEND_HANDSHAKE;
return NETWORK_SOCKET_SUCCESS;
}
static network_mysqld_lua_stmt_ret proxy_lua_read_auth(network_mysqld_con *con) {
network_mysqld_lua_stmt_ret ret = PROXY_NO_DECISION;
#ifdef HAVE_LUA_H
network_mysqld_con_lua_t *st = con->plugin_con_state;
lua_State *L;
/* call the lua script to pick a backend
ignore the return code from network_mysqld_con_lua_register_callback, because we cannot do anything about it,
it would always show up as ERROR 2013, which is not helpful.
*/
(void)network_mysqld_con_lua_register_callback(con, config->lua_script);
if (!st->L) return 0;
L = st->L;
g_assert(lua_isfunction(L, -1));
lua_getfenv(L, -1);
g_assert(lua_istable(L, -1));
lua_getfield_literal(L, -1, C("read_auth"));
if (lua_isfunction(L, -1)) {
/* export
*
* every thing we know about it
* */
if (lua_pcall(L, 0, 1, 0) != 0) {
g_critical("(read_auth) %s", lua_tostring(L, -1));
lua_pop(L, 1); /* errmsg */
/* the script failed, but we have a useful default */
} else {
if (lua_isnumber(L, -1)) {
ret = lua_tonumber(L, -1);
}
lua_pop(L, 1);
}
switch (ret) {
case PROXY_NO_DECISION:
break;
case PROXY_SEND_RESULT:
/* answer directly */
if (network_mysqld_con_lua_handle_proxy_response(con, config->lua_script)) {
/**
* handling proxy.response failed
*
* send a ERR packet
*/
network_mysqld_con_send_error(con->client, C("(lua) handling proxy.response failed, check error-log"));
}
break;
case PROXY_SEND_QUERY:
/* something is in the injection queue, pull it from there and replace the content of
* original packet */
if (st->injected.queries->length) {
ret = PROXY_SEND_INJECTION;
} else {
ret = PROXY_NO_DECISION;
}
break;
default:
ret = PROXY_NO_DECISION;
break;
}
/* ret should be a index into */
} else if (lua_isnil(L, -1)) {
lua_pop(L, 1); /* pop the nil */
} else {
g_message("%s.%d: %s", __FILE__, __LINE__, lua_typename(L, lua_type(L, -1)));
lua_pop(L, 1); /* pop the ... */
}
lua_pop(L, 1); /* fenv */
g_assert(lua_isfunction(L, -1));
#endif
return ret;
}
NETWORK_MYSQLD_PLUGIN_PROTO(proxy_read_auth) {
/* read auth from client */
network_packet packet;
network_socket *recv_sock, *send_sock;
network_mysqld_auth_response *auth;
int err = 0;
gboolean free_client_packet = TRUE;
network_mysqld_con_lua_t *st = con->plugin_con_state;
recv_sock = con->client;
send_sock = con->server;
packet.data = g_queue_pop_tail(recv_sock->recv_queue->chunks);
packet.offset = 0;
err = err || network_mysqld_proto_skip_network_header(&packet);
if (err) return NETWORK_SOCKET_ERROR;
auth = network_mysqld_auth_response_new();
err = err || network_mysqld_proto_get_auth_response(&packet, auth);
g_string_free(packet.data, TRUE);
if (err) {
network_mysqld_auth_response_free(auth);
return NETWORK_SOCKET_ERROR;
}
if (!(auth->capabilities & CLIENT_PROTOCOL_41)) {
/* should use packet-id 0 */
network_mysqld_queue_append(con->client, con->client->send_queue, C("\xff\xd7\x07" "4.0 protocol is not supported"));
network_mysqld_auth_response_free(auth);
return NETWORK_SOCKET_ERROR;
}
con->client->response = auth;
// g_string_assign_len(con->client->default_db, S(auth->database));
con->state = CON_STATE_SEND_AUTH_RESULT;
GString *hashed_password = g_hash_table_lookup(config->pwd_table[config->pwd_table_index], auth->username->str);
if (hashed_password) {
GString *expected_response = g_string_sized_new(20);
network_mysqld_proto_password_scramble(expected_response, S(con->challenge), S(hashed_password));
if (g_string_equal(expected_response, auth->response)) {
g_string_assign_len(recv_sock->default_db, S(auth->database));
char *client_charset = NULL;
if (config->charset == NULL) client_charset = charset[auth->charset];
else client_charset = config->charset;
g_string_assign(recv_sock->charset_client, client_charset);
g_string_assign(recv_sock->charset_results, client_charset);
g_string_assign(recv_sock->charset_connection, client_charset);
network_mysqld_con_send_ok(recv_sock);
} else {
GString *error = g_string_sized_new(64);
g_string_printf(error, "Access denied for user '%s'@'%s' (using password: YES)", auth->username->str, recv_sock->src->name->str);
network_mysqld_con_send_error_full(recv_sock, S(error), ER_ACCESS_DENIED_ERROR, "28000");
g_string_free(error, TRUE);
}
g_string_free(expected_response, TRUE);
} else {
GString *error = g_string_sized_new(64);
g_string_printf(error, "Access denied for user '%s'@'%s' (using password: YES)", auth->username->str, recv_sock->src->name->str);
network_mysqld_con_send_error_full(recv_sock, S(error), ER_ACCESS_DENIED_ERROR, "28000");
g_string_free(error, TRUE);
}
return NETWORK_SOCKET_SUCCESS;
}
NETWORK_MYSQLD_PLUGIN_PROTO(proxy_read_auth_result) {
GString *packet;
GList *chunk;
network_socket *recv_sock, *send_sock;
recv_sock = con->server;
send_sock = con->client;