@@ -25,14 +25,17 @@ const ignoreStreamId = 0
25
25
const (
26
26
connDisconnected = 0
27
27
connConnected = 1
28
- connClosed = 2
28
+ connShutdown = 2
29
+ connClosed = 3
29
30
)
30
31
31
32
const (
32
33
connTransportNone = ""
33
34
connTransportSsl = "ssl"
34
35
)
35
36
37
+ const shutdownEventKey = "box.shutdown"
38
+
36
39
type ConnEventKind int
37
40
type ConnLogKind int
38
41
@@ -45,6 +48,8 @@ const (
45
48
ReconnectFailed
46
49
// Either reconnect attempts exhausted, or explicit Close is called.
47
50
Closed
51
+ // Shutdown signals that shutdown callback is processing.
52
+ Shutdown
48
53
49
54
// LogReconnectFailed is logged when reconnect attempt failed.
50
55
LogReconnectFailed ConnLogKind = iota + 1
@@ -134,10 +139,19 @@ func (d defaultLogger) Report(event ConnLogKind, conn *Connection, v ...interfac
134
139
// always returns array of array (array of tuples for space related methods).
135
140
// For Eval* and Call* Tarantool always returns array, but does not forces
136
141
// array of arrays.
142
+ //
143
+ // If connected to Tarantool 2.10 or newer and WatchersFeature is required,
144
+ // connection supports server graceful shutdown. In this case, server will
145
+ // wait until all client requests will be finished and client disconnects
146
+ // before going down (server also may go down by timeout). Client reconnect will
147
+ // happen if connection options enable reconnect.
148
+ //
149
+ // More on graceful shutdown: https://www.tarantool.io/en/doc/latest/dev_guide/internals/iproto/graceful_shutdown/
137
150
type Connection struct {
138
151
addr string
139
152
c net.Conn
140
153
mutex sync.Mutex
154
+ cond * sync.Cond
141
155
// Schema contains schema loaded on connection.
142
156
Schema * Schema
143
157
// requestId contains the last request ID for requests with nil context.
@@ -162,6 +176,11 @@ type Connection struct {
162
176
serverProtocolInfo ProtocolInfo
163
177
// watchMap is a map of key -> chan watchState.
164
178
watchMap sync.Map
179
+
180
+ // shutdownWatcher is the "box.shutdown" event watcher.
181
+ shutdownWatcher Watcher
182
+ // requestCnt is a counter of active requests.
183
+ requestCnt int64
165
184
}
166
185
167
186
var _ = Connector (& Connection {}) // Check compatibility with connector interface.
@@ -385,6 +404,8 @@ func Connect(addr string, opts Opts) (conn *Connection, err error) {
385
404
conn .opts .Logger = defaultLogger {}
386
405
}
387
406
407
+ conn .cond = sync .NewCond (& conn .mutex )
408
+
388
409
if err = conn .createConnection (false ); err != nil {
389
410
ter , ok := err .(Error )
390
411
if conn .opts .Reconnect <= 0 {
@@ -421,6 +442,16 @@ func Connect(addr string, opts Opts) (conn *Connection, err error) {
421
442
}
422
443
}
423
444
445
+ // Subscribe shutdown event to process graceful shutdown.
446
+ if conn .isWatchersRequired () {
447
+ watcher , werr := conn .NewWatcher (shutdownEventKey , shutdownEventCallback )
448
+ if werr != nil {
449
+ conn .closeConnection (werr , true )
450
+ return nil , werr
451
+ }
452
+ conn .shutdownWatcher = watcher
453
+ }
454
+
424
455
return conn , err
425
456
}
426
457
@@ -589,6 +620,7 @@ func (conn *Connection) dial() (err error) {
589
620
conn .lockShards ()
590
621
conn .c = connection
591
622
atomic .StoreUint32 (& conn .state , connConnected )
623
+ conn .cond .Broadcast ()
592
624
conn .unlockShards ()
593
625
go conn .writer (w , connection )
594
626
go conn .reader (r , connection )
@@ -762,10 +794,17 @@ func (conn *Connection) closeConnection(neterr error, forever bool) (err error)
762
794
if conn .state != connClosed {
763
795
close (conn .control )
764
796
atomic .StoreUint32 (& conn .state , connClosed )
797
+ conn .cond .Broadcast ()
798
+ // Free the resources.
799
+ if conn .shutdownWatcher != nil {
800
+ go conn .shutdownWatcher .Unregister ()
801
+ conn .shutdownWatcher = nil
802
+ }
765
803
conn .notify (Closed )
766
804
}
767
805
} else {
768
806
atomic .StoreUint32 (& conn .state , connDisconnected )
807
+ conn .cond .Broadcast ()
769
808
conn .notify (Disconnected )
770
809
}
771
810
if conn .c != nil {
@@ -784,9 +823,7 @@ func (conn *Connection) closeConnection(neterr error, forever bool) (err error)
784
823
return
785
824
}
786
825
787
- func (conn * Connection ) reconnect (neterr error , c net.Conn ) {
788
- conn .mutex .Lock ()
789
- defer conn .mutex .Unlock ()
826
+ func (conn * Connection ) reconnectImpl (neterr error , c net.Conn ) {
790
827
if conn .opts .Reconnect > 0 {
791
828
if c == conn .c {
792
829
conn .closeConnection (neterr , false )
@@ -799,6 +836,13 @@ func (conn *Connection) reconnect(neterr error, c net.Conn) {
799
836
}
800
837
}
801
838
839
+ func (conn * Connection ) reconnect (neterr error , c net.Conn ) {
840
+ conn .mutex .Lock ()
841
+ defer conn .mutex .Unlock ()
842
+ conn .reconnectImpl (neterr , c )
843
+ conn .cond .Broadcast ()
844
+ }
845
+
802
846
func (conn * Connection ) lockShards () {
803
847
for i := range conn .shard {
804
848
conn .shard [i ].rmut .Lock ()
@@ -1026,6 +1070,15 @@ func (conn *Connection) newFuture(ctx context.Context) (fut *Future) {
1026
1070
fut .done = nil
1027
1071
shard .rmut .Unlock ()
1028
1072
return
1073
+ case connShutdown :
1074
+ fut .err = ClientError {
1075
+ ErrConnectionShutdown ,
1076
+ "server shutdown in progress" ,
1077
+ }
1078
+ fut .ready = nil
1079
+ fut .done = nil
1080
+ shard .rmut .Unlock ()
1081
+ return
1029
1082
}
1030
1083
pos := (fut .requestId / conn .opts .Concurrency ) & (requestsMap - 1 )
1031
1084
if ctx != nil {
@@ -1086,6 +1139,7 @@ func (conn *Connection) send(req Request, streamId uint64) *Future {
1086
1139
if fut .ready == nil {
1087
1140
return fut
1088
1141
}
1142
+
1089
1143
if req .Ctx () != nil {
1090
1144
select {
1091
1145
case <- req .Ctx ().Done ():
@@ -1094,10 +1148,17 @@ func (conn *Connection) send(req Request, streamId uint64) *Future {
1094
1148
default :
1095
1149
}
1096
1150
}
1151
+
1152
+ if conn .shutdownWatcher != nil {
1153
+ atomic .AddInt64 (& (conn .requestCnt ), int64 (1 ))
1154
+ }
1155
+
1097
1156
conn .putFuture (fut , req , streamId )
1157
+
1098
1158
if req .Ctx () != nil {
1099
1159
go conn .contextWatchdog (fut , req .Ctx ())
1100
1160
}
1161
+
1101
1162
return fut
1102
1163
}
1103
1164
@@ -1164,6 +1225,12 @@ func (conn *Connection) markDone(fut *Future) {
1164
1225
if conn .rlimit != nil {
1165
1226
<- conn .rlimit
1166
1227
}
1228
+
1229
+ if conn .shutdownWatcher != nil {
1230
+ if atomic .AddInt64 (& (conn .requestCnt ), int64 (- 1 )) == 0 {
1231
+ conn .cond .Broadcast ()
1232
+ }
1233
+ }
1167
1234
}
1168
1235
1169
1236
func (conn * Connection ) peekFuture (reqid uint32 ) (fut * Future ) {
@@ -1458,6 +1525,15 @@ func subscribeWatchChannel(conn *Connection, key string) (chan watchState, error
1458
1525
return st , nil
1459
1526
}
1460
1527
1528
+ func (conn * Connection ) isWatchersRequired () bool {
1529
+ for _ , feature := range conn .opts .RequiredProtocolInfo .Features {
1530
+ if feature == WatchersFeature {
1531
+ return true
1532
+ }
1533
+ }
1534
+ return false
1535
+ }
1536
+
1461
1537
// NewWatcher creates a new Watcher object for the connection.
1462
1538
//
1463
1539
// You need to require WatchersFeature to use watchers, see examples for the
@@ -1496,15 +1572,7 @@ func (conn *Connection) NewWatcher(key string, callback WatchCallback) (Watcher,
1496
1572
// asynchronous. We do not expect any response from a Tarantool instance
1497
1573
// That's why we can't just check the Tarantool response for an unsupported
1498
1574
// request error.
1499
- watchersRequired := false
1500
- for _ , feature := range conn .opts .RequiredProtocolInfo .Features {
1501
- if feature == WatchersFeature {
1502
- watchersRequired = true
1503
- break
1504
- }
1505
- }
1506
-
1507
- if ! watchersRequired {
1575
+ if ! conn .isWatchersRequired () {
1508
1576
err := fmt .Errorf ("the feature %s must be required by connection " +
1509
1577
"options to create a watcher" , WatchersFeature )
1510
1578
return nil , err
@@ -1563,7 +1631,11 @@ func (conn *Connection) NewWatcher(key string, callback WatchCallback) (Watcher,
1563
1631
1564
1632
if state .cnt == 0 {
1565
1633
// The last one sends IPROTO_UNWATCH.
1566
- conn .Do (newUnwatchRequest (key )).Get ()
1634
+ if ! conn .ClosedNow () {
1635
+ // conn.ClosedNow() check is a workaround for calling
1636
+ // Unregister from connectionClose().
1637
+ conn .Do (newUnwatchRequest (key )).Get ()
1638
+ }
1567
1639
conn .watchMap .Delete (key )
1568
1640
close (state .unready )
1569
1641
}
@@ -1666,3 +1738,52 @@ func (conn *Connection) ServerProtocolInfo() ProtocolInfo {
1666
1738
func (conn * Connection ) ClientProtocolInfo () ProtocolInfo {
1667
1739
return clientProtocolInfo .Clone ()
1668
1740
}
1741
+
1742
+ func shutdownEventCallback (event WatchEvent ) {
1743
+ // Receives "true" on server shutdown.
1744
+ // See https://www.tarantool.io/en/doc/latest/dev_guide/internals/iproto/graceful_shutdown/
1745
+ // step 2.
1746
+ val , ok := event .Value .(bool )
1747
+ if ok && val {
1748
+ go event .Conn .processShutdown ()
1749
+ }
1750
+ }
1751
+
1752
+ func (conn * Connection ) processShutdown () {
1753
+ // Forbid state changes.
1754
+ conn .mutex .Lock ()
1755
+ defer conn .mutex .Unlock ()
1756
+
1757
+ if ! atomic .CompareAndSwapUint32 (& (conn .state ), connConnected , connShutdown ) {
1758
+ return
1759
+ }
1760
+ conn .notify (Shutdown )
1761
+
1762
+ c := conn .c
1763
+ for (atomic .LoadUint32 (& (conn .state )) == connShutdown ) &&
1764
+ (atomic .LoadInt64 (& (conn .requestCnt )) != 0 ) &&
1765
+ (c == conn .c ) {
1766
+ // Use cond var on conn.mutex since request execution may
1767
+ // call reconnect(). It is ok if state changes as part of
1768
+ // reconnect since Tarantool server won't allow to reconnect
1769
+ // in the middle of shutting down.
1770
+ conn .cond .Wait ()
1771
+ }
1772
+ // Do not unregister task explicitly here since connection teardown
1773
+ // has the same effect. To clean up connection resources,
1774
+ // unregister on full close.
1775
+
1776
+ if (atomic .LoadUint32 (& (conn .state )) == connShutdown ) &&
1777
+ (c == conn .c ) {
1778
+ // Start to reconnect based on common rules, same as in net.box.
1779
+ // Reconnect also closes the connection: server waits until all
1780
+ // subscribed connections are terminated.
1781
+ // See https://www.tarantool.io/en/doc/latest/dev_guide/internals/iproto/graceful_shutdown/
1782
+ // step 3.
1783
+ conn .reconnectImpl (
1784
+ ClientError {
1785
+ ErrConnectionClosed ,
1786
+ "connection closed after server shutdown" ,
1787
+ }, conn .c )
1788
+ }
1789
+ }
0 commit comments