/
net_box.c
3323 lines (3134 loc) · 99.6 KB
/
net_box.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
/*
* Copyright 2010-2016, Tarantool AUTHORS, please see AUTHORS file.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "net_box.h"
#include <assert.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/socket.h>
#include <sys/types.h>
#include "box/authentication.h"
#include "box/errcode.h"
#include "box/iproto_constants.h"
#include "box/iproto_features.h"
#include "box/lua/tuple.h" /* luamp_convert_tuple() / luamp_convert_key() */
#include "box/lua/tuple_format.h"
#include "box/xrow.h"
#include "box/tuple.h"
#include "box/execute.h"
#include "box/error.h"
#include "box/schema_def.h"
#include "box/mp_box_ctx.h"
#include "box/mp_tuple.h"
#include "coio.h"
#include "fiber.h"
#include "fiber_cond.h"
#include "iostream.h"
#include "lua/fiber.h"
#include "lua/fiber_cond.h"
#include "lua/msgpack.h"
#include "lua/uri.h"
#include "lua/utils.h"
#include "msgpuck.h"
#include "small/ibuf.h"
#include "small/region.h"
#include "mpstream/mpstream.h"
#include "uri/uri.h"
#include "version.h"
#define cfg luaL_msgpack_default
enum {
/**
* connect() timeout used by default, in seconds.
*/
NETBOX_DEFAULT_CONNECT_TIMEOUT = 10,
/**
* Send and receive buffers readahead.
*/
NETBOX_READAHEAD = 16320,
/**
* IPROTO protocol version supported by the netbox connector.
*/
NETBOX_IPROTO_VERSION = 7,
};
/**
* IPROTO protocol features supported by the netbox connector.
*/
static struct iproto_features NETBOX_IPROTO_FEATURES;
#define NETBOX_METHODS(_) \
_(PING) \
_(CALL) \
_(EVAL) \
_(INSERT) \
_(REPLACE) \
_(DELETE) \
_(UPDATE) \
_(UPSERT) \
_(SELECT) \
_(SELECT_WITH_POS) \
_(EXECUTE) \
_(PREPARE) \
_(UNPREPARE) \
_(GET) \
_(MIN) \
_(MAX) \
_(COUNT) \
_(BEGIN) \
_(COMMIT) \
_(ROLLBACK) \
_(WATCH_ONCE) \
_(INJECT) \
#define NETBOX_METHOD_MEMBER(s) \
NETBOX_ ## s,
enum netbox_method {
NETBOX_METHODS(NETBOX_METHOD_MEMBER)
netbox_method_MAX
};
#define NETBOX_METHOD_STRS_MEMBER(s) \
[NETBOX_ ## s] = #s,
static const char *netbox_method_strs[netbox_method_MAX] = {
NETBOX_METHODS(NETBOX_METHOD_STRS_MEMBER)
};
enum netbox_state {
NETBOX_INITIAL = 0,
NETBOX_AUTH = 1,
NETBOX_FETCH_SCHEMA = 2,
NETBOX_ACTIVE = 3,
NETBOX_ERROR = 4,
NETBOX_ERROR_RECONNECT = 5,
NETBOX_CLOSED = 6,
NETBOX_GRACEFUL_SHUTDOWN = 7,
netbox_state_MAX,
};
static const char *netbox_state_str[] = {
[NETBOX_INITIAL] = "initial",
[NETBOX_AUTH] = "auth",
[NETBOX_FETCH_SCHEMA] = "fetch_schema",
[NETBOX_ACTIVE] = "active",
[NETBOX_ERROR] = "error",
[NETBOX_ERROR_RECONNECT] = "error_reconnect",
[NETBOX_CLOSED] = "closed",
[NETBOX_GRACEFUL_SHUTDOWN] = "graceful_shutdown",
};
struct netbox_options {
/** Remote server URI. Nil if this connection was created from fd. */
struct uri uri;
/** Connection fd. -1 if this connection was created from URI. */
int fd;
/** Authentication method. NULL if unspecified. */
const struct auth_method *auth_method;
/** User credentials. */
char *user;
char *password;
/**
* Lua reference to the transport callback function
* (see the comment to netbox_transport).
*/
int callback_ref;
/** connect() timeout, in seconds. */
double connect_timeout;
/**
* Timeout to wait after a connection failure before trying to
* reconnect, in seconds. Reconnect is disabled if it's 0.
*/
double reconnect_after;
/**
* Flag that determines is it required to fetch server schema or not.
*/
bool fetch_schema;
};
/**
* Basically, *transport* is a TCP connection speaking the Tarantool
* network protocol (IPROTO). This is a low-level interface.
* Primary features:
* * concurrent perform_request()-s benefit from multiplexing
* support in the protocol;
* * schema-aware - snoops responses and initiates schema reload
* when a response has a new schema version;
* * delivers transport events via the callback.
*
* Transport state machine:
*
* State machine starts in 'initial' state. Start method
* spawns a worker fiber, which will establish a connection.
* Stop method sets the state to 'closed' and kills the worker.
* If the transport is already in 'error' state stop() does
* nothing.
*
* State chart:
*
* initial -> auth -> fetch_schema <-> active
*
* fetch_schema, active -> graceful_shutdown
*
* (any state, on error) -> error_reconnect -> auth -> ...
* \
* -> error
* (any state, but 'error') -> closed
*
* State machine is switched to 'graceful_shutdown' state when it
* receives a 'box.shutdown' event from the remote host. In this state,
* no new requests are allowed, and once all in-progress requests
* have completed, the state machine will be switched to 'error' or
* 'error_reconnect' state, depending on whether reconnect_after is
* set.
*
* State change events can be delivered to the transport user via
* the optional 'callback' argument:
*
* The callback functions needs to have the following signature:
*
* callback(event_name, ...)
*
* The following events are delivered, with arguments:
*
* 'state_changed', state, error
* 'handshake', greeting, version, features
* 'did_fetch_schema', schema_version, spaces, indices, collations
* 'event', key, value
* 'shutdown'
*/
struct netbox_transport {
/** Connection options. Not modified after initialization. */
struct netbox_options opts;
/** Greeting received from the remote host. */
struct greeting greeting;
/** Features supported by the server as reported by IPROTO_ID. */
struct iproto_features features;
/** Default authentication method reported by IPROTO_ID. */
const struct auth_method *auth_method_default;
/** Connection state. */
enum netbox_state state;
/**
* The connection is closing. No new requests are allowed.
* The connection will be closed as soon as all pending requests
* have been sent.
*/
bool is_closing;
/** Error that caused the last connection failure or NULL. */
struct error *last_error;
/** Fiber doing I/O and dispatching responses. */
struct fiber *worker;
/** Signalled when the worker is stopped. */
struct fiber_cond on_worker_stop;
/**
* Lua reference to the Lua state used by the worker fiber or
* LUA_NOREF if the worker fiber isn't running.
*/
int coro_ref;
/**
* Lua reference to self or LUA_NOREF. Needed to prevent garbage
* collection of this transport object while the worker fiber is
* running.
*/
int self_ref;
/** Connection I/O stream context. */
struct iostream_ctx io_ctx;
/** Connection I/O stream. */
struct iostream io;
/** Connection send buffer. */
struct ibuf send_buf;
/** Connection receive buffer. */
struct ibuf recv_buf;
/** Size of the last received message. */
size_t last_msg_size;
/** Signalled when send_buf becomes empty. */
struct fiber_cond on_send_buf_empty;
/** Next request id. */
uint64_t next_sync;
/** sync -> netbox_request */
struct mh_i64ptr_t *requests;
/**
* Number of requests to which the server hasn't responded yet.
* Note, it may be greater than the number of entries in the request
* map, because a request is removed from the map when it's discarded
* by the user.
*/
int64_t inprogress_request_count;
};
struct netbox_request {
enum netbox_method method;
/**
* Unique identifier needed for matching the request with its response.
* Used as a key in netbox_transport::requests.
*/
uint64_t sync;
/**
* The transport this request belongs to or NULL if the request has
* been completed.
*/
struct netbox_transport *transport;
/** Format used for decoding the response (ref incremented). */
struct tuple_format *format;
/** Signaled when the response is received. */
struct fiber_cond cond;
/**
* A user-provided buffer to which the response body should be copied.
* If NULL, the response will be decoded to Lua stack.
*/
struct ibuf *buffer;
/**
* Lua reference to the buffer. Used to prevent garbage collection in
* case the user discards the request.
*/
int buffer_ref;
/**
* Whether to skip MessagePack map header and IPROTO_DATA key when
* copying the response body to a user-provided buffer. Ignored if
* buffer is not set.
*/
bool skip_header;
/**
* If this flag is set, the response data won't be decoded - instead,
* a msgpack object will be returned to the caller.
*/
bool return_raw;
/** Lua references to on_push trigger and its context. */
int on_push_ref;
int on_push_ctx_ref;
/**
* Lua reference to a table with user-defined fields.
* We allow the user to attach extra information to a future object,
* e.g. a reference to a connection or the invoked method name/args.
* All the information is stored in this table, which is created
* lazily, on the first __newindex invocation. Until then, it's
* LUA_NOREF.
*/
int index_ref;
/**
* Lua reference to the request result or LUA_NOREF if the response
* hasn't been received yet. If the response was decoded to a
* user-provided buffer (see buffer_ref), result_ref stores a Lua
* reference to an integer value that contains the length of the
* decoded data.
*/
int result_ref;
/**
* Error if the request failed (ref incremented). NULL on success or if
* the response hasn't been received yet.
*/
struct error *error;
/**
* Lua reference to the connection object if the request is asynchronous
* or LUA_NOREF if the request is synchronous. Used to prevent garbage
* collection in case the user discards the connection.
*/
int remote_ref;
};
/*
* Context for encoding a netbox method.
*/
struct netbox_method_encode_ctx {
/* MsgPack stream to which the method is encoded. */
struct mpstream *stream;
/* Current transport's IPROTO sync. */
uint64_t sync;
/* Current transport's IPROTO stream identifier. */
uint64_t stream_id;
/*
* Whether box tuples should be encoded to MsgPack as MP_TUPLE
* extension.
*/
bool box_tuple_arg_as_ext;
};
static const char netbox_transport_typename[] = "net.box.transport";
static const char netbox_request_typename[] = "net.box.request";
/**
* We keep a reference to each C function that is frequently called with
* lua_call so as not to create a new Lua object each time we call it.
*/
static int luaT_netbox_request_iterator_next_ref = LUA_NOREF;
static void
netbox_request_destroy(struct netbox_request *request)
{
assert(request->transport == NULL);
if (request->format != NULL)
tuple_format_unref(request->format);
fiber_cond_destroy(&request->cond);
luaL_unref(tarantool_L, LUA_REGISTRYINDEX, request->buffer_ref);
luaL_unref(tarantool_L, LUA_REGISTRYINDEX, request->on_push_ref);
luaL_unref(tarantool_L, LUA_REGISTRYINDEX, request->on_push_ctx_ref);
luaL_unref(tarantool_L, LUA_REGISTRYINDEX, request->result_ref);
luaL_unref(tarantool_L, LUA_REGISTRYINDEX, request->index_ref);
if (request->error != NULL)
error_unref(request->error);
luaL_unref(tarantool_L, LUA_REGISTRYINDEX, request->remote_ref);
}
/**
* Adds a request to a transport. There must not be a request with the same id
* (sync) in the transport.
*/
static void
netbox_request_register(struct netbox_request *request,
struct netbox_transport *transport)
{
struct mh_i64ptr_t *h = transport->requests;
struct mh_i64ptr_node_t node = { request->sync, request };
struct mh_i64ptr_node_t *old_node = NULL;
mh_i64ptr_put(h, &node, &old_node, NULL);
assert(old_node == NULL);
request->transport = transport;
}
/**
* Unregisters a previously registered request. Does nothing if the request has
* already been unregistered or has never been registered.
*/
static void
netbox_request_unregister(struct netbox_request *request)
{
struct netbox_transport *transport = request->transport;
if (transport == NULL)
return;
request->transport = NULL;
struct mh_i64ptr_t *h = transport->requests;
mh_int_t k = mh_i64ptr_find(h, request->sync, NULL);
assert(k != mh_end(h));
assert(mh_i64ptr_node(h, k)->val == request);
mh_i64ptr_del(h, k, NULL);
}
static inline bool
netbox_request_is_ready(const struct netbox_request *request)
{
return request->transport == NULL;
}
static inline void
netbox_request_signal(struct netbox_request *request)
{
fiber_cond_broadcast(&request->cond);
}
static inline void
netbox_request_complete(struct netbox_request *request)
{
netbox_request_unregister(request);
netbox_request_signal(request);
}
/**
* Waits on netbox_request::cond. Subtracts the wait time from the timeout.
* Returns false on timeout or if the fiber was cancelled.
*/
static inline bool
netbox_request_wait(struct netbox_request *request, double *timeout)
{
/*
* Waiting for a request completion in the net.box worker fiber
* would result in a dead lock.
*/
assert(request->transport != NULL &&
request->transport->worker != fiber());
if (*timeout == 0)
return false;
double ts = ev_monotonic_now(loop());
int rc = fiber_cond_wait_timeout(&request->cond, *timeout);
*timeout -= ev_monotonic_now(loop()) - ts;
return rc == 0;
}
static inline void
netbox_request_set_result(struct netbox_request *request, int result_ref)
{
assert(request->result_ref == LUA_NOREF);
request->result_ref = result_ref;
}
static inline void
netbox_request_set_error(struct netbox_request *request, struct error *error)
{
assert(request->error == NULL);
request->error = error;
error_ref(error);
}
/**
* Pushes the result or error to Lua stack. See the comment to request.result()
* for more information about the values pushed.
*/
static int
netbox_request_push_result(struct netbox_request *request, struct lua_State *L)
{
if (!netbox_request_is_ready(request)) {
diag_set(ClientError, ER_PROC_LUA, "Response is not ready");
return luaT_push_nil_and_error(L);
}
if (request->error != NULL) {
assert(request->result_ref == LUA_NOREF);
diag_set_error(diag_get(), request->error);
return luaT_push_nil_and_error(L);
} else {
assert(request->result_ref != LUA_NOREF);
lua_rawgeti(L, LUA_REGISTRYINDEX, request->result_ref);
}
return 1;
}
static void
netbox_options_create(struct netbox_options *opts)
{
memset(opts, 0, sizeof(*opts));
uri_create(&opts->uri, NULL);
opts->fd = -1;
opts->auth_method = NULL;
opts->callback_ref = LUA_NOREF;
opts->connect_timeout = NETBOX_DEFAULT_CONNECT_TIMEOUT;
opts->fetch_schema = true;
}
static void
netbox_options_destroy(struct netbox_options *opts)
{
uri_destroy(&opts->uri);
free(opts->user);
free(opts->password);
luaL_unref(tarantool_L, LUA_REGISTRYINDEX, opts->callback_ref);
}
static void
netbox_transport_create(struct netbox_transport *transport)
{
netbox_options_create(&transport->opts);
memset(&transport->greeting, 0, sizeof(transport->greeting));
iproto_features_create(&transport->features);
transport->auth_method_default = AUTH_METHOD_DEFAULT;
transport->state = NETBOX_INITIAL;
transport->is_closing = false;
transport->last_error = NULL;
transport->worker = NULL;
fiber_cond_create(&transport->on_worker_stop);
transport->coro_ref = LUA_NOREF;
transport->self_ref = LUA_NOREF;
iostream_ctx_clear(&transport->io_ctx);
iostream_clear(&transport->io);
ibuf_create(&transport->send_buf, &cord()->slabc, NETBOX_READAHEAD);
ibuf_create(&transport->recv_buf, &cord()->slabc, NETBOX_READAHEAD);
transport->last_msg_size = 0;
fiber_cond_create(&transport->on_send_buf_empty);
transport->next_sync = 1;
transport->requests = mh_i64ptr_new();
transport->inprogress_request_count = 0;
}
static void
netbox_transport_destroy(struct netbox_transport *transport)
{
netbox_options_destroy(&transport->opts);
if (transport->last_error != NULL)
error_unref(transport->last_error);
assert(transport->worker == NULL);
fiber_cond_destroy(&transport->on_worker_stop);
assert(transport->coro_ref == LUA_NOREF);
assert(transport->self_ref == LUA_NOREF);
iostream_ctx_destroy(&transport->io_ctx);
assert(!iostream_is_initialized(&transport->io));
assert(ibuf_used(&transport->send_buf) == 0);
assert(ibuf_used(&transport->recv_buf) == 0);
fiber_cond_destroy(&transport->on_send_buf_empty);
struct mh_i64ptr_t *h = transport->requests;
assert(mh_size(h) == 0);
mh_i64ptr_delete(h);
assert(transport->inprogress_request_count == 0);
}
/**
* Looks up a request by id (sync). Returns NULL if not found.
*/
static inline struct netbox_request *
netbox_transport_lookup_request(struct netbox_transport *transport,
uint64_t sync)
{
struct mh_i64ptr_t *h = transport->requests;
mh_int_t k = mh_i64ptr_find(h, sync, NULL);
if (k == mh_end(h))
return NULL;
return mh_i64ptr_node(h, k)->val;
}
/**
* Sets transport->last_error to the last error set in the diagnostics area
* and aborts all pending requests.
*/
static void
netbox_transport_set_error(struct netbox_transport *transport)
{
/* Set last error. */
assert(!diag_is_empty(diag_get()));
struct error *error = diag_last_error(diag_get());
if (transport->last_error != NULL)
error_unref(transport->last_error);
transport->last_error = error;
error_ref(error);
/* Reset buffers. */
ibuf_reinit(&transport->send_buf);
ibuf_reinit(&transport->recv_buf);
transport->last_msg_size = 0;
fiber_cond_broadcast(&transport->on_send_buf_empty);
/* Complete requests and clean up the hash. */
struct mh_i64ptr_t *h = transport->requests;
mh_int_t k;
mh_foreach(h, k) {
struct netbox_request *request = mh_i64ptr_node(h, k)->val;
request->transport = NULL;
netbox_request_set_error(request, error);
netbox_request_signal(request);
}
mh_i64ptr_clear(h);
transport->inprogress_request_count = 0;
}
static inline size_t
netbox_begin_encode(struct mpstream *stream, uint64_t sync,
enum iproto_type type, uint64_t stream_id)
{
/* Remember initial size of ibuf (see netbox_end_encode()) */
struct ibuf *ibuf = stream->ctx;
size_t used = ibuf_used(ibuf);
/* Reserve and skip space for fixheader */
size_t fixheader_size = mp_sizeof_uint(UINT32_MAX);
mpstream_reserve(stream, fixheader_size);
mpstream_advance(stream, fixheader_size);
/* encode header */
mpstream_encode_map(stream, 1 + (sync != 0) + (stream_id != 0));
if (sync != 0) {
mpstream_encode_uint(stream, IPROTO_SYNC);
mpstream_encode_uint(stream, sync);
}
mpstream_encode_uint(stream, IPROTO_REQUEST_TYPE);
mpstream_encode_uint(stream, type);
if (stream_id != 0) {
mpstream_encode_uint(stream, IPROTO_STREAM_ID);
mpstream_encode_uint(stream, stream_id);
}
/* Caller should remember how many bytes was used in ibuf */
return used;
}
static inline void
netbox_end_encode(struct mpstream *stream, size_t initial_size)
{
mpstream_flush(stream);
struct ibuf *ibuf = (struct ibuf *) stream->ctx;
/*
* Calculation the start position in ibuf by getting current size
* and then substracting initial size. Since we don't touch
* ibuf->rpos during encoding this approach should always work
* even on realloc or memmove inside ibuf.
*/
size_t fixheader_size = mp_sizeof_uint(UINT32_MAX);
size_t used = ibuf_used(ibuf);
assert(initial_size + fixheader_size <= used);
size_t total_size = used - initial_size;
char *fixheader = ibuf->wpos - total_size;
assert(fixheader >= ibuf->rpos);
/* patch skipped len */
*(fixheader++) = 0xce;
/* fixheader size is not included */
mp_store_u32(fixheader, total_size - fixheader_size);
}
/**
* Encode an `IPROTO_PING` request and write it to the provided MsgPack stream.
*/
static int
netbox_encode_ping(lua_State *L, int idx, struct netbox_method_encode_ctx *ctx)
{
(void)L;
(void)idx;
size_t svp = netbox_begin_encode(ctx->stream, ctx->sync, IPROTO_PING,
ctx->stream_id);
netbox_end_encode(ctx->stream, svp);
return 0;
}
/**
* Encodes an id request and writes it to the provided buffer.
* Raises a Lua error on memory allocation failure.
*/
static void
netbox_encode_id(struct lua_State *L, struct ibuf *ibuf, uint64_t sync,
bool fetch_schema)
{
struct iproto_features features = NETBOX_IPROTO_FEATURES;
if (fetch_schema) {
iproto_features_clear(&features,
IPROTO_FEATURE_DML_TUPLE_EXTENSION);
}
#ifndef NDEBUG
struct errinj *errinj = errinj(ERRINJ_NETBOX_FLIP_FEATURE, ERRINJ_INT);
if (errinj->iparam >= 0 && errinj->iparam < iproto_feature_id_MAX) {
int feature_id = errinj->iparam;
if (iproto_features_test(&features, feature_id))
iproto_features_clear(&features, feature_id);
else
iproto_features_set(&features, feature_id);
}
#endif
struct mpstream stream;
mpstream_init(&stream, ibuf, ibuf_reserve_cb, ibuf_alloc_cb,
luamp_error, L);
size_t svp = netbox_begin_encode(&stream, sync, IPROTO_ID, 0);
mpstream_encode_map(&stream, 2);
mpstream_encode_uint(&stream, IPROTO_VERSION);
mpstream_encode_uint(&stream, NETBOX_IPROTO_VERSION);
mpstream_encode_uint(&stream, IPROTO_FEATURES);
size_t size = mp_sizeof_iproto_features(&features);
char *data = mpstream_reserve(&stream, size);
mp_encode_iproto_features(data, &features);
mpstream_advance(&stream, size);
netbox_end_encode(&stream, svp);
}
/**
* Encodes an authorization request and writes it to the provided buffer.
* Raises a Lua error on memory allocation failure.
*/
static void
netbox_encode_auth(struct lua_State *L, struct ibuf *ibuf, uint64_t sync,
const struct auth_method *method, const char *user,
const char *password, const char *salt, uint32_t salt_len)
{
assert(salt_len >= AUTH_SALT_SIZE);
(void)salt_len;
if (password == NULL)
password = "";
struct region *region = &fiber()->gc;
size_t region_svp = region_used(region);
const char *auth_request, *auth_request_end;
auth_request_prepare(method, password, strlen(password), salt,
&auth_request, &auth_request_end);
struct mpstream stream;
mpstream_init(&stream, ibuf, ibuf_reserve_cb, ibuf_alloc_cb,
luamp_error, L);
size_t svp = netbox_begin_encode(&stream, sync, IPROTO_AUTH, 0);
mpstream_encode_map(&stream, 2);
mpstream_encode_uint(&stream, IPROTO_USER_NAME);
mpstream_encode_strn(&stream, user, strlen(user));
mpstream_encode_uint(&stream, IPROTO_TUPLE);
mpstream_encode_array(&stream, 2);
mpstream_encode_str(&stream, method->name);
mpstream_memcpy(&stream, auth_request, auth_request_end - auth_request);
netbox_end_encode(&stream, svp);
region_truncate(region, region_svp);
}
/**
* Encodes a SELECT(*) request and writes it to the provided buffer.
* Raises a Lua error on memory allocation failure.
*/
static void
netbox_encode_select_all(struct lua_State *L, struct ibuf *ibuf, uint64_t sync,
uint32_t space_id)
{
struct mpstream stream;
mpstream_init(&stream, ibuf, ibuf_reserve_cb, ibuf_alloc_cb,
luamp_error, L);
size_t svp = netbox_begin_encode(&stream, sync, IPROTO_SELECT, 0);
mpstream_encode_map(&stream, 3);
mpstream_encode_uint(&stream, IPROTO_SPACE_ID);
mpstream_encode_uint(&stream, space_id);
mpstream_encode_uint(&stream, IPROTO_LIMIT);
mpstream_encode_uint(&stream, UINT32_MAX);
mpstream_encode_uint(&stream, IPROTO_KEY);
mpstream_encode_array(&stream, 0);
netbox_end_encode(&stream, svp);
}
/*
* Encode the arguments of call or eval netbox methods.
*/
static int
netbox_encode_call_or_eval_args(lua_State *L, int idx, struct mpstream *stream,
bool box_tuple_arg_as_ext)
{
mpstream_encode_uint(stream, IPROTO_TUPLE);
struct mp_box_ctx ctx;
mp_box_ctx_create(&ctx, NULL, NULL);
if (luamp_encode_tuple_with_ctx(L, cfg, stream, idx,
box_tuple_arg_as_ext ?
(struct mp_ctx *)&ctx : NULL) != 0) {
mp_ctx_destroy((struct mp_ctx *)&ctx);
return -1;
}
mpstream_encode_uint(stream, IPROTO_TUPLE_FORMATS);
tuple_format_map_to_mpstream(&ctx.tuple_format_map, stream);
mp_ctx_destroy((struct mp_ctx *)&ctx);
return 0;
}
/**
* Encode an `IPROTO_CALL` request and write it to the provided MsgPack stream.
*/
static int
netbox_encode_call(lua_State *L, int idx, struct netbox_method_encode_ctx *ctx)
{
/* Lua stack at idx: function_name, args */
size_t svp = netbox_begin_encode(ctx->stream, ctx->sync, IPROTO_CALL,
ctx->stream_id);
mpstream_encode_map(ctx->stream, 3);
/* encode proc name */
size_t name_len;
const char *name = lua_tolstring(L, idx, &name_len);
mpstream_encode_uint(ctx->stream, IPROTO_FUNCTION_NAME);
mpstream_encode_strn(ctx->stream, name, name_len);
if (netbox_encode_call_or_eval_args(L, idx + 1, ctx->stream,
ctx->box_tuple_arg_as_ext) != 0)
return -1;
netbox_end_encode(ctx->stream, svp);
return 0;
}
/**
* Encode an `IPROTO_EVAL` request and write it to the provided MsgPack stream.
*/
static int
netbox_encode_eval(lua_State *L, int idx, struct netbox_method_encode_ctx *ctx)
{
/* Lua stack at idx: expr, args */
size_t svp = netbox_begin_encode(ctx->stream, ctx->sync, IPROTO_EVAL,
ctx->stream_id);
mpstream_encode_map(ctx->stream, 3);
/* encode expr */
size_t expr_len;
const char *expr = lua_tolstring(L, idx, &expr_len);
mpstream_encode_uint(ctx->stream, IPROTO_EXPR);
mpstream_encode_strn(ctx->stream, expr, expr_len);
if (netbox_encode_call_or_eval_args(L, idx + 1, ctx->stream,
ctx->box_tuple_arg_as_ext) != 0)
return -1;
netbox_end_encode(ctx->stream, svp);
return 0;
}
/*
* Depending on the type of the argument (see also net.box space metatable)
* encode either a space identifier or a space name.
*/
static void
netbox_encode_space_id_or_name(lua_State *L, int idx, struct mpstream *stream)
{
if (lua_type(L, idx) == LUA_TNUMBER) {
uint32_t space_id = lua_tonumber(L, idx);
mpstream_encode_uint(stream, IPROTO_SPACE_ID);
mpstream_encode_uint(stream, space_id);
} else {
size_t len;
const char *space_name = lua_tolstring(L, idx, &len);
mpstream_encode_uint(stream, IPROTO_SPACE_NAME);
mpstream_encode_strn(stream, space_name, len);
}
}
/*
* Depending on the type of the argument (see also net.box index metatable)
* encode either a index identifier or an index name.
*/
static void
netbox_encode_index_id_or_name(lua_State *L, int idx, struct mpstream *stream)
{
if (lua_type(L, idx) == LUA_TNUMBER) {
uint32_t space_id = lua_tonumber(L, idx);
mpstream_encode_uint(stream, IPROTO_INDEX_ID);
mpstream_encode_uint(stream, space_id);
} else {
size_t len;
const char *space_name = lua_tolstring(L, idx, &len);
mpstream_encode_uint(stream, IPROTO_INDEX_NAME);
mpstream_encode_strn(stream, space_name, len);
}
}
/* Encode select request. */
static int
netbox_encode_select(lua_State *L, int idx,
struct netbox_method_encode_ctx *ctx)
{
/*
* Lua stack at idx: space_id, index_id, iterator, offset, limit, key,
* after, fetch_pos.
*/
size_t svp = netbox_begin_encode(ctx->stream, ctx->sync, IPROTO_SELECT,
ctx->stream_id);
uint32_t map_size = 6;
bool have_after = !lua_isnil(L, idx + 6);
if (have_after)
map_size++;
bool fetch_pos = lua_toboolean(L, idx + 7);
if (fetch_pos)
map_size++;
mpstream_encode_map(ctx->stream, map_size);
int iterator = lua_tointeger(L, idx + 2);
uint32_t offset = lua_tonumber(L, idx + 3);
uint32_t limit = lua_tonumber(L, idx + 4);
netbox_encode_space_id_or_name(L, idx, ctx->stream);
netbox_encode_index_id_or_name(L, idx + 1, ctx->stream);
/* encode iterator */
mpstream_encode_uint(ctx->stream, IPROTO_ITERATOR);
mpstream_encode_uint(ctx->stream, iterator);
/* encode offset */
mpstream_encode_uint(ctx->stream, IPROTO_OFFSET);
mpstream_encode_uint(ctx->stream, offset);
/* encode limit */
mpstream_encode_uint(ctx->stream, IPROTO_LIMIT);
mpstream_encode_uint(ctx->stream, limit);
/* encode key */
mpstream_encode_uint(ctx->stream, IPROTO_KEY);
if (luamp_convert_key(L, cfg, ctx->stream, idx + 5) != 0)
return -1;
/* encode after */
if (have_after) {
if (lua_isstring(L, idx + 6)) {
mpstream_encode_uint(ctx->stream,
IPROTO_AFTER_POSITION);
size_t size;
const char *pos = lua_tolstring(L, idx + 6, &size);
mpstream_encode_strn(ctx->stream, pos, size);
} else {
assert(luaT_istuple(L, idx + 6) != NULL ||
lua_istable(L, idx + 6));
mpstream_encode_uint(ctx->stream, IPROTO_AFTER_TUPLE);
if (luamp_encode_tuple(L, cfg, ctx->stream, idx + 6) != 0)
return -1;
}
}
/* encode fetch_pos */
if (fetch_pos) {
mpstream_encode_uint(ctx->stream, IPROTO_FETCH_POSITION);
mpstream_encode_bool(ctx->stream, fetch_pos);
}
netbox_end_encode(ctx->stream, svp);
return 0;
}
static int
netbox_encode_insert_or_replace(lua_State *L, int idx, struct mpstream *stream,
uint64_t sync, enum iproto_type type,
uint64_t stream_id)
{
/* Lua stack at idx: space_id, tuple */
size_t svp = netbox_begin_encode(stream, sync, type, stream_id);
mpstream_encode_map(stream, 2);
netbox_encode_space_id_or_name(L, idx, stream);
/* encode args */
mpstream_encode_uint(stream, IPROTO_TUPLE);
if (luamp_encode_tuple(L, cfg, stream, idx + 1) != 0)
return -1;
netbox_end_encode(stream, svp);
return 0;
}