-
Notifications
You must be signed in to change notification settings - Fork 377
/
net_box.lua
1575 lines (1463 loc) · 54.8 KB
/
net_box.lua
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
-- net_box.lua (internal file)
local log = require('log')
local ffi = require('ffi')
local buffer = require('buffer')
local socket = require('socket')
local fiber = require('fiber')
local msgpack = require('msgpack')
local errno = require('errno')
local urilib = require('uri')
local internal = require('net.box.lib')
local trigger = require('internal.trigger')
local band = bit.band
local max = math.max
local fiber_clock = fiber.clock
local fiber_self = fiber.self
local decode = msgpack.decode_unchecked
local decode_map_header = msgpack.decode_map_header
local table_new = require('table.new')
local check_iterator_type = box.internal.check_iterator_type
local check_index_arg = box.internal.check_index_arg
local check_space_arg = box.internal.check_space_arg
local check_primary_index = box.internal.check_primary_index
local communicate = internal.communicate
local encode_auth = internal.encode_auth
local encode_select = internal.encode_select
local decode_greeting = internal.decode_greeting
local TIMEOUT_INFINITY = 500 * 365 * 86400
local VSPACE_ID = 281
local VINDEX_ID = 289
local VCOLLATION_ID = 277
local DEFAULT_CONNECT_TIMEOUT = 10
local IPROTO_STATUS_KEY = 0x00
local IPROTO_ERRNO_MASK = 0x7FFF
local IPROTO_SYNC_KEY = 0x01
local IPROTO_SCHEMA_VERSION_KEY = 0x05
local IPROTO_METADATA_KEY = 0x32
local IPROTO_SQL_INFO_KEY = 0x42
local SQL_INFO_ROW_COUNT_KEY = 0
local IPROTO_FIELD_NAME_KEY = 0
local IPROTO_DATA_KEY = 0x30
local IPROTO_ERROR_KEY = 0x31
local IPROTO_GREETING_SIZE = 128
local IPROTO_CHUNK_KEY = 128
local IPROTO_OK_KEY = 0
-- select errors from box.error
local E_UNKNOWN = box.error.UNKNOWN
local E_NO_CONNECTION = box.error.NO_CONNECTION
local E_TIMEOUT = box.error.TIMEOUT
local E_PROC_LUA = box.error.PROC_LUA
-- utility tables
local is_final_state = {closed = 1, error = 1}
local function decode_nil(raw_data, raw_data_end)
return nil, raw_data_end
end
local function decode_data(raw_data)
local response, raw_end = decode(raw_data)
return response[IPROTO_DATA_KEY], raw_end
end
local function decode_tuple(raw_data, raw_data_end, format)
local response, raw_end = internal.decode_select(raw_data, nil, format)
return response[1], raw_end
end
local function decode_get(raw_data, raw_data_end, format)
local body, raw_end = internal.decode_select(raw_data, nil, format)
if body[2] then
return nil, raw_end, box.error.MORE_THAN_ONE_TUPLE
end
return body[1], raw_end
end
local function decode_count(raw_data)
local response, raw_end = decode(raw_data)
return response[IPROTO_DATA_KEY][1], raw_end
end
local function decode_push(raw_data)
local response, raw_end = decode(raw_data)
return response[IPROTO_DATA_KEY][1], raw_end
end
local function version_id(major, minor, patch)
return bit.bor(bit.lshift(major, 16), bit.lshift(minor, 8), patch)
end
local function version_at_least(peer_version_id, major, minor, patch)
return peer_version_id >= version_id(major, minor, patch)
end
local method_encoder = {
ping = internal.encode_ping,
call_16 = internal.encode_call_16,
call_17 = internal.encode_call,
eval = internal.encode_eval,
insert = internal.encode_insert,
replace = internal.encode_replace,
delete = internal.encode_delete,
update = internal.encode_update,
upsert = internal.encode_upsert,
select = internal.encode_select,
execute = internal.encode_execute,
get = internal.encode_select,
min = internal.encode_select,
max = internal.encode_select,
count = internal.encode_call,
-- inject raw data into connection, used by console and tests
inject = function(buf, id, bytes)
local ptr = buf:reserve(#bytes)
ffi.copy(ptr, bytes, #bytes)
buf.wpos = ptr + #bytes
end
}
local method_decoder = {
ping = decode_nil,
call_16 = internal.decode_select,
call_17 = decode_data,
eval = decode_data,
insert = decode_tuple,
replace = decode_tuple,
delete = decode_tuple,
update = decode_tuple,
upsert = decode_nil,
select = internal.decode_select,
execute = internal.decode_execute,
get = decode_get,
min = decode_get,
max = decode_get,
count = decode_count,
inject = decode_data,
push = decode_push,
}
local function next_id(id) return band(id + 1, 0x7FFFFFFF) end
--
-- Connect to a remote server, do handshake.
-- @param host Hostname.
-- @param port TCP port.
-- @param timeout Timeout to connect and receive greeting.
--
-- @retval nil, err Error occured. The reason is returned.
-- @retval two non-nils A connected socket and a decoded greeting.
--
local function establish_connection(host, port, timeout)
local timeout = timeout or DEFAULT_CONNECT_TIMEOUT
local begin = fiber.clock()
local s = socket.tcp_connect(host, port, timeout)
if not s then
return nil, errno.strerror(errno())
end
local msg = s:read({chunk = IPROTO_GREETING_SIZE},
timeout - (fiber.clock() - begin))
if not msg then
local err = s:error()
s:close()
return nil, err
end
local greeting, err = decode_greeting(msg)
if not greeting then
s:close()
return nil, err
end
return s, greeting
end
--
-- Default action on push during a synchronous request -
-- ignore.
--
local function on_push_sync_default(...) end
--
-- Basically, *transport* is a TCP connection speaking one of
-- Tarantool network protocols. This is a low-level interface.
-- Primary features:
-- * implements protocols; concurrent perform_request()-s benefit from
-- multiplexing support in the protocol;
-- * schema-aware (optional) - 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. New_sm method
-- accepts an established connection and spawns a worker fiber.
-- Stop method sets the state to 'closed' and kills the worker.
-- If the transport is already in 'error' state stop() does
-- nothing.
--
-- State chart:
--
-- connecting -> initial +-> active
-- \
-- +-> auth -> fetch_schema <-> active
--
-- (any state, on error) -> error_reconnect -> connecting -> ...
-- \
-- -> [error]
-- (any_state, but [error]) -> [closed]
--
--
-- 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, errno, error
-- 'handshake', greeting -> nil (accept) / errno, error (reject)
-- 'will_fetch_schema' -> true (approve) / false (skip fetch)
-- 'did_fetch_schema', schema_version, spaces, indices
-- 'reconnect_timeout' -> get reconnect timeout if set and > 0,
-- else nil is returned.
--
-- Suggestion for callback writers: sleep a few secs before approving
-- reconnect.
--
local function create_transport(host, port, user, password, callback,
connection, greeting)
-- check / normalize credentials
if user == nil and password ~= nil then
box.error(E_PROC_LUA, 'net.box: user is not defined')
end
if user ~= nil and password == nil then password = '' end
-- Current state machine's state.
local state = 'initial'
local last_errno
local last_error
local state_cond = fiber.cond() -- signaled when the state changes
-- Async requests currently 'in flight', keyed by a request
-- id. Value refs are weak hence if a client dies
-- unexpectedly, GC cleans the mess.
-- Async request can not be timed out completely. Instead a
-- user must decide when he does not want to wait for
-- response anymore.
-- Sync requests are implemented as async call + immediate
-- wait for a result.
local requests = setmetatable({}, { __mode = 'v' })
local next_request_id = 1
local worker_fiber
local send_buf = buffer.ibuf(buffer.READAHEAD)
local recv_buf = buffer.ibuf(buffer.READAHEAD)
--
-- Async request metamethods.
--
local request_index = {}
--
-- When an async request is finalized (with ok or error - no
-- matter), its 'id' field is nullified by a response
-- dispatcher.
--
function request_index:is_ready()
return self.id == nil or worker_fiber == nil
end
--
-- When a request is finished, a result can be got from a
-- future object anytime.
-- @retval result, nil Success, the response is returned.
-- @retval nil, error Error occured.
--
function request_index:result()
if self.errno then
return nil, box.error.new({code = self.errno,
reason = self.response})
elseif not self.id then
return self.response
elseif not worker_fiber then
return nil, box.error.new(E_NO_CONNECTION)
else
return nil, box.error.new(box.error.PROC_LUA,
'Response is not ready')
end
end
--
-- Get the next message or the final result.
-- @param iterator Iterator object.
-- @param i Index to get a next message from.
--
-- @retval nil, nil The request is finished.
-- @retval i + 1, object A message/response and its index.
-- @retval box.NULL, error An error occured. When this
-- function is called in 'for k, v in future:pairs()',
-- `k` becomes box.NULL, and `v` becomes error object.
-- On error the key becomes exactly box.NULL instead
-- of nil, because nil is treated by Lua as iteration
-- end marker. Nil does not participate in iteration,
-- and does not allow to continue it.
--
local function request_iterator_next(iterator, i)
if i == box.NULL then
return nil, nil
else
i = i + 1
end
local request = iterator.request
local messages = request.on_push_ctx
::retry::
if i <= #messages then
return i, messages[i]
end
if request:is_ready() then
-- After all the messages are iterated, `i` is equal
-- to #messages + 1. After response reading `i`
-- becomes #messages + 2. It is the trigger to finish
-- the iteration.
if i > #messages + 1 then
return nil, nil
end
local response, err = request:result()
if err then
return box.NULL, err
end
return i, response
end
local old_message_count = #messages
local timeout = iterator.timeout
repeat
local ts = fiber_clock()
request.cond:wait(timeout)
timeout = timeout - (fiber_clock() - ts)
if request:is_ready() or old_message_count ~= #messages then
goto retry
end
until timeout <= 0
return box.NULL, box.error.new(E_TIMEOUT)
end
--
-- Iterate over all messages, received by a request. @Sa
-- request_iterator_next for details what to expect in `for`
-- key/value pairs.
-- @param timeout One iteration timeout.
-- @retval next() callback, iterator, zero key.
--
function request_index:pairs(timeout)
if timeout then
if type(timeout) ~= 'number' or timeout < 0 then
error('Usage: future:pairs(timeout)')
end
else
timeout = TIMEOUT_INFINITY
end
local iterator = {request = self, timeout = timeout}
return request_iterator_next, iterator, 0
end
--
-- Wait for a response or error max timeout seconds.
-- @param timeout Max seconds to wait.
-- @retval result, nil Success, the response is returned.
-- @retval nil, error Error occured.
--
function request_index:wait_result(timeout)
if timeout then
if type(timeout) ~= 'number' or timeout < 0 then
error('Usage: future:wait_result(timeout)')
end
else
timeout = TIMEOUT_INFINITY
end
if not self:is_ready() then
-- When a response is ready before timeout, the
-- waiting client is waked up prematurely.
while timeout > 0 and not self:is_ready() do
local ts = fiber.clock()
self.cond:wait(timeout)
timeout = timeout - (fiber.clock() - ts)
end
if not self:is_ready() then
return nil, box.error.new(E_TIMEOUT)
end
end
return self:result()
end
--
-- Make a connection forget about the response. When it will
-- be received, it will be ignored. It reduces size of
-- requests table speeding up other requests.
--
function request_index:discard()
if self.id then
requests[self.id] = nil
self.id = nil
self.errno = box.error.PROC_LUA
self.response = 'Response is discarded'
end
end
local request_mt = { __index = request_index }
-- STATE SWITCHING --
local function set_state(new_state, new_errno, new_error)
state = new_state
last_errno = new_errno
last_error = new_error
callback('state_changed', new_state, new_errno, new_error)
state_cond:broadcast()
if state == 'error' or state == 'error_reconnect' or
state == 'closed' then
for _, request in pairs(requests) do
request.id = nil
request.errno = new_errno
request.response = new_error
request.cond:broadcast()
end
requests = {}
end
end
-- FYI: [] on a string is valid
local function wait_state(target_state, timeout)
local deadline = fiber_clock() + (timeout or TIMEOUT_INFINITY)
repeat until state == target_state or target_state[state] or
is_final_state[state] or
not state_cond:wait(max(0, deadline - fiber_clock()))
return state == target_state or target_state[state] or false
end
-- START/STOP --
local protocol_sm
local function start()
if state ~= 'initial' then return not is_final_state[state] end
fiber.create(function()
local ok, err, timeout
worker_fiber = fiber_self()
fiber.name(string.format('%s:%s (net.box)', host, port), {truncate=true})
if not connection then
goto do_connect
end
::handle_connection::
ok, err = pcall(protocol_sm)
if not (ok or is_final_state[state]) then
set_state('error', E_UNKNOWN, err)
end
if connection then
connection:close()
connection = nil
end
timeout = callback('reconnect_timeout')
::do_reconnect::
if not timeout or state ~= 'error_reconnect' then
goto stop
end
fiber.sleep(timeout)
timeout = callback('reconnect_timeout')
if not timeout or state ~= 'error_reconnect' then
goto stop
end
::do_connect::
connection, greeting =
establish_connection(host, port, callback('fetch_connect_timeout'))
if connection then
goto handle_connection
end
timeout = callback('reconnect_timeout')
if not timeout then
set_state('error', E_NO_CONNECTION, greeting)
goto stop
end
set_state('error_reconnect', E_NO_CONNECTION, greeting)
goto do_reconnect
::stop::
send_buf:recycle()
recv_buf:recycle()
worker_fiber = nil
end)
end
local function stop()
if not is_final_state[state] then
set_state('closed', E_NO_CONNECTION, 'Connection closed')
end
if worker_fiber then
worker_fiber:cancel()
worker_fiber = nil
end
end
--
-- Send a request and do not wait for response.
-- @retval nil, error Error occured.
-- @retval not nil Future object.
--
local function perform_async_request(buffer, skip_header, method, on_push,
on_push_ctx, request_ctx, ...)
if state ~= 'active' and state ~= 'fetch_schema' then
return nil, box.error.new({code = last_errno or E_NO_CONNECTION,
reason = last_error})
end
-- alert worker to notify it of the queued outgoing data;
-- if the buffer wasn't empty, assume the worker was already alerted
if send_buf:size() == 0 then
worker_fiber:wakeup()
end
local id = next_request_id
method_encoder[method](send_buf, id, ...)
next_request_id = next_id(id)
-- Request in most cases has maximum 10 members:
-- method, buffer, skip_header, id, cond, errno, response,
-- on_push, on_push_ctx and ctx.
local request = setmetatable(table_new(0, 10), request_mt)
request.method = method
request.buffer = buffer
request.skip_header = skip_header
request.id = id
request.cond = fiber.cond()
requests[id] = request
request.on_push = on_push
request.on_push_ctx = on_push_ctx
request.ctx = request_ctx
return request
end
--
-- Send a request and wait for response.
-- @retval nil, error Error occured.
-- @retval not nil Response object.
--
local function perform_request(timeout, buffer, skip_header, method,
on_push, on_push_ctx, request_ctx, ...)
local request, err =
perform_async_request(buffer, skip_header, method, on_push,
on_push_ctx, request_ctx, ...)
if not request then
return nil, err
end
return request:wait_result(timeout)
end
local function dispatch_response_iproto(hdr, body_rpos, body_end)
local id = hdr[IPROTO_SYNC_KEY]
local request = requests[id]
if request == nil then -- nobody is waiting for the response
return
end
local status = hdr[IPROTO_STATUS_KEY]
local body, body_end_check
if status > IPROTO_CHUNK_KEY then
-- Handle errors
requests[id] = nil
request.id = nil
body, body_end_check = decode(body_rpos)
assert(body_end == body_end_check, "invalid xrow length")
request.errno = band(status, IPROTO_ERRNO_MASK)
request.response = body[IPROTO_ERROR_KEY]
request.cond:broadcast()
return
end
local buffer = request.buffer
if buffer ~= nil then
-- Copy xrow.body to user-provided buffer
local body_len = body_end - body_rpos
if request.skip_header then
-- Skip {[IPROTO_DATA_KEY] = ...} wrapper.
local map_len, key
map_len, body_rpos = decode_map_header(body_rpos, body_len)
assert(map_len == 1)
key, body_rpos = decode(body_rpos)
assert(key == IPROTO_DATA_KEY)
body_len = body_end - body_rpos
end
local wpos = buffer:alloc(body_len)
ffi.copy(wpos, body_rpos, body_len)
body_len = tonumber(body_len)
if status == IPROTO_OK_KEY then
request.response = body_len
requests[id] = nil
request.id = nil
else
request.on_push(request.on_push_ctx, body_len)
end
request.cond:broadcast()
return
end
local real_end
-- Decode xrow.body[DATA] to Lua objects
if status == IPROTO_OK_KEY then
request.response, real_end, request.errno =
method_decoder[request.method](body_rpos, body_end, request.ctx)
assert(real_end == body_end, "invalid body length")
requests[id] = nil
request.id = nil
else
local msg
msg, real_end, request.errno =
method_decoder.push(body_rpos, body_end)
assert(real_end == body_end, "invalid body length")
request.on_push(request.on_push_ctx, msg)
end
request.cond:broadcast()
end
local function new_request_id()
local id = next_request_id;
next_request_id = next_id(id)
return id
end
-- IO (WORKER FIBER) --
local function send_and_recv(limit_or_boundary, timeout)
return communicate(connection:fd(), send_buf, recv_buf,
limit_or_boundary, timeout)
end
local function send_and_recv_iproto(timeout)
local data_len = recv_buf.wpos - recv_buf.rpos
local required = 0
if data_len < 5 then
required = 5
else
-- PWN! insufficient input validation
local bufpos = recv_buf.rpos
local len, rpos = decode(bufpos)
required = (rpos - bufpos) + len
if data_len >= required then
local body_end = rpos + len
local hdr, body_rpos = decode(rpos)
recv_buf.rpos = body_end
return nil, hdr, body_rpos, body_end
end
end
local deadline = fiber_clock() + (timeout or TIMEOUT_INFINITY)
local err, extra = send_and_recv(required, timeout)
if err then
return err, extra
end
return send_and_recv_iproto(max(0, deadline - fiber_clock()))
end
local function send_and_recv_console(timeout)
local delim = '\n...\n'
local err, delim_pos = send_and_recv(delim, timeout)
if err then
return err, delim_pos
else
local response = ffi.string(recv_buf.rpos, delim_pos + #delim)
recv_buf.rpos = recv_buf.rpos + delim_pos + #delim
return nil, response
end
end
-- PROTOCOL STATE MACHINE (WORKER FIBER) --
--
-- The sm is implemented as a collection of functions performing
-- tail-recursive calls to each other. Yep, Lua optimizes
-- such calls, and yep, this is the canonical way to implement
-- a state machine in Lua.
local console_sm, iproto_auth_sm, iproto_schema_sm, iproto_sm, error_sm
--
-- Protocol_sm is a core function of netbox. It calls all
-- other ..._sm() functions, and explicitly or implicitly
-- holds Lua referece on a connection object. It means, that
-- until it works, the connection can not be garbage
-- collected. See gh-3164, where because of reconnect sleeps
-- in this function, a connection could not be deleted.
--
protocol_sm = function()
assert(connection)
assert(greeting)
local err, msg = callback('handshake', greeting)
if err then
return error_sm(err, msg)
end
-- @deprecated since 1.10
if greeting.protocol == 'Lua console' then
log.warn("Netbox text protocol support is deprecated since 1.10, "..
"please use require('console').connect() instead")
local setup_delimiter = 'require("console").delimiter("$EOF$")\n'
method_encoder.inject(send_buf, nil, setup_delimiter)
local err, response = send_and_recv_console()
if err then
return error_sm(err, response)
elseif response ~= '---\n...\n' then
return error_sm(E_NO_CONNECTION, 'Unexpected response')
end
local rid = next_request_id
set_state('active')
return console_sm(rid)
elseif greeting.protocol == 'Binary' then
return iproto_auth_sm(greeting.salt)
else
return error_sm(E_NO_CONNECTION,
'Unknown protocol: '..greeting.protocol)
end
end
console_sm = function(rid)
local delim = '\n...\n'
local err, response = send_and_recv_console()
if err then
return error_sm(err, response)
else
local request = requests[rid]
if request == nil then -- nobody is waiting for the response
return
end
request.id = nil
requests[rid] = nil
request.response = response
request.cond:broadcast()
return console_sm(next_id(rid))
end
end
iproto_auth_sm = function(salt)
set_state('auth')
if not user or not password then
set_state('fetch_schema')
return iproto_schema_sm()
end
encode_auth(send_buf, new_request_id(), user, password, salt)
local err, hdr, body_rpos, body_end = send_and_recv_iproto()
if err then
return error_sm(err, hdr)
end
if hdr[IPROTO_STATUS_KEY] ~= 0 then
local body
body, body_end = decode(body_rpos)
return error_sm(E_NO_CONNECTION, body[IPROTO_ERROR_KEY])
end
set_state('fetch_schema')
return iproto_schema_sm(hdr[IPROTO_SCHEMA_VERSION_KEY])
end
iproto_schema_sm = function(schema_version)
if not callback('will_fetch_schema') then
set_state('active')
return iproto_sm(schema_version)
end
-- _vcollation view was added in 2.2.0-389-g3e3ef182f
local peer_has_vcollation = version_at_least(greeting.version_id,
2, 2, 1)
local select1_id = new_request_id()
local select2_id = new_request_id()
local select3_id
local response = {}
-- fetch everything from space _vspace, 2 = ITER_ALL
encode_select(send_buf, select1_id, VSPACE_ID, 0, 2, 0, 0xFFFFFFFF, nil)
-- fetch everything from space _vindex, 2 = ITER_ALL
encode_select(send_buf, select2_id, VINDEX_ID, 0, 2, 0, 0xFFFFFFFF, nil)
-- fetch everything from space _vcollation, 2 = ITER_ALL
if peer_has_vcollation then
select3_id = new_request_id()
encode_select(send_buf, select3_id, VCOLLATION_ID, 0, 2, 0,
0xFFFFFFFF, nil)
end
schema_version = nil -- any schema_version will do provided that
-- it is consistent across responses
repeat
local err, hdr, body_rpos, body_end = send_and_recv_iproto()
if err then return error_sm(err, hdr) end
dispatch_response_iproto(hdr, body_rpos, body_end)
local id = hdr[IPROTO_SYNC_KEY]
-- trick: omit check for peer_has_vcollation: id is
-- not nil
if id == select1_id or id == select2_id or id == select3_id then
-- response to a schema query we've submitted
local status = hdr[IPROTO_STATUS_KEY]
local response_schema_version = hdr[IPROTO_SCHEMA_VERSION_KEY]
if status ~= 0 then
local body
body, body_end = decode(body_rpos)
return error_sm(E_NO_CONNECTION, body[IPROTO_ERROR_KEY])
end
if schema_version == nil then
schema_version = response_schema_version
elseif schema_version ~= response_schema_version then
-- schema changed while fetching schema; restart loader
return iproto_schema_sm()
end
local body
body, body_end = decode(body_rpos)
response[id] = body[IPROTO_DATA_KEY]
end
until response[select1_id] and response[select2_id] and
(not peer_has_vcollation or response[select3_id])
-- trick: response[select3_id] is nil when the key is nil
callback('did_fetch_schema', schema_version, response[select1_id],
response[select2_id], response[select3_id])
set_state('active')
return iproto_sm(schema_version)
end
iproto_sm = function(schema_version)
local err, hdr, body_rpos, body_end = send_and_recv_iproto()
if err then return error_sm(err, hdr) end
dispatch_response_iproto(hdr, body_rpos, body_end)
local status = hdr[IPROTO_STATUS_KEY]
local response_schema_version = hdr[IPROTO_SCHEMA_VERSION_KEY]
if response_schema_version > 0 and
response_schema_version ~= schema_version then
-- schema_version has been changed - start to load a new version.
-- Sic: self.schema_version will be updated only after reload.
local body
body, body_end = decode(body_rpos)
set_state('fetch_schema')
return iproto_schema_sm(schema_version)
end
return iproto_sm(schema_version)
end
error_sm = function(err, msg)
if connection then connection:close(); connection = nil end
send_buf:recycle()
recv_buf:recycle()
if state ~= 'closed' then
if callback('reconnect_timeout') then
set_state('error_reconnect', err, msg)
else
set_state('error', err, msg)
end
end
end
return {
stop = stop,
start = start,
wait_state = wait_state,
perform_request = perform_request,
perform_async_request = perform_async_request,
}
end
-- Wrap create_transport, adding auto-stop-on-GC feature.
-- All the GC magic is neatly encapsulated!
-- The tricky part is the callback:
-- * callback (typically) references the transport (indirectly);
-- * worker fiber references the callback;
-- * fibers are GC roots - i.e. transport is never GC-ed!
-- We solve the issue by making the worker->callback ref weak.
-- Now it is necessary to have a strong ref to callback somewhere or
-- it is GC-ed prematurely. We wrap stop() method, stashing the
-- ref in an upvalue (stop() performance doesn't matter much.)
local create_transport = function(host, port, user, password, callback,
connection, greeting)
local weak_refs = setmetatable({callback = callback}, {__mode = 'v'})
local function weak_callback(...)
local callback = weak_refs.callback
if callback then return callback(...) end
end
local transport = create_transport(host, port, user, password,
weak_callback, connection, greeting)
local transport_stop = transport.stop
local gc_hook = ffi.gc(ffi.new('char[1]'), function()
pcall(transport_stop)
end)
transport.stop = function()
-- dummy gc_hook, callback refs prevent premature GC
return transport_stop(gc_hook, callback)
end
return transport
end
local function parse_connect_params(host_or_uri, ...) -- self? host_or_uri port? opts?
local port, opts = ...
if type(host_or_uri) == 'table' then host_or_uri, port, opts = ... end
if type(port) == 'table' then opts = port; port = nil end
if opts == nil then opts = {} else
local copy = {}
for k, v in pairs(opts) do copy[k] = v end
opts = copy
end
local host = host_or_uri
if port == nil then
local url = urilib.parse(tostring(host))
if url == nil or url.service == nil then
box.error(E_PROC_LUA,
"usage: connect(uri[, opts] | host, port[, opts])")
end
host, port = url.host, url.service
if opts.user == nil and opts.password == nil then
opts.user, opts.password = url.login, url.password
end
end
return host, port, opts
end
local function remote_serialize(self)
return {
host = self.host,
port = self.port,
opts = next(self.opts) and self.opts,
state = self.state,
error = self.error,
protocol = self.protocol,
schema_version = self.schema_version,
peer_uuid = self.peer_uuid,
peer_version_id = self.peer_version_id
}
end
local remote_methods = {}
local remote_mt = {
__index = remote_methods, __serialize = remote_serialize,
__metatable = false
}
local console_methods = {}
local console_mt = {
__index = console_methods, __serialize = remote_serialize,
__metatable = false
}
local space_metatable, index_metatable
local function new_sm(host, port, opts, connection, greeting)
local user, password = opts.user, opts.password; opts.password = nil
local last_reconnect_error
local remote = {host = host, port = port, opts = opts, state = 'initial'}
local function callback(what, ...)
if what == 'state_changed' then
local state, errno, err = ...
if (remote.state == 'active' or remote.state == 'fetch_schema') and
(state == 'error' or state == 'closed' or
state == 'error_reconnect') then
remote._on_disconnect:run(remote)
end
if remote.state ~= 'error' and remote.state ~= 'error_reconnect' and
state == 'active' then
remote._on_connect:run(remote)
end
remote.state, remote.error = state, err
if state == 'error_reconnect' then
-- Repeat the same error in verbose log only.
-- Else the error clogs the log. See gh-3175.
if err ~= last_reconnect_error then
log.warn('%s:%s: %s', host or "", port or "", err)
last_reconnect_error = err
else
log.verbose('%s:%s: %s', host or "", port or "", err)
end
end
elseif what == 'handshake' then
local greeting = ...
if not opts.console and greeting.protocol ~= 'Binary' then
return E_NO_CONNECTION,
'Unsupported protocol: '..greeting.protocol
end
remote.protocol = greeting.protocol
remote.peer_uuid = greeting.uuid
remote.peer_version_id = greeting.version_id
elseif what == 'will_fetch_schema' then
return not opts.console
elseif what == 'fetch_connect_timeout' then
return opts.connect_timeout or DEFAULT_CONNECT_TIMEOUT
elseif what == 'did_fetch_schema' then
remote:_install_schema(...)
elseif what == 'reconnect_timeout' then
if type(opts.reconnect_after) == 'number' and
opts.reconnect_after > 0 then
return opts.reconnect_after
end
end
end
-- @deprecated since 1.10
if opts.console then
log.warn("Netbox console API is deprecated since 1.10, please use "..
"require('console').connect() instead")
setmetatable(remote, console_mt)
else
setmetatable(remote, remote_mt)
-- @deprecated since 1.7.4
remote._deadlines = setmetatable({}, {__mode = 'k'})
remote._space_mt = space_metatable(remote)
remote._index_mt = index_metatable(remote)
if opts.call_16 then
remote.call = remote.call_16
remote.eval = remote.eval_16
end
end
remote._on_schema_reload = trigger.new("on_schema_reload")
remote._on_disconnect = trigger.new("on_disconnect")
remote._on_connect = trigger.new("on_connect")
remote._transport = create_transport(host, port, user, password, callback,
connection, greeting)
remote._transport.start()
if opts.wait_connected ~= false then
remote._transport.wait_state('active', tonumber(opts.wait_connected))
end
return remote
end