@@ -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, connection supports server graceful
144
+ // shutdown. In this case, server will wait until all client requests will be
145
+ // finished and client disconnects before going down (server also may go down
146
+ // by timeout). Client reconnect will happen if connection options enable
147
+ // reconnect. Beware that graceful shutdown event initialization is asynchronous.
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 {
@@ -589,10 +610,20 @@ func (conn *Connection) dial() (err error) {
589
610
conn .lockShards ()
590
611
conn .c = connection
591
612
atomic .StoreUint32 (& conn .state , connConnected )
613
+ conn .cond .Broadcast ()
592
614
conn .unlockShards ()
593
615
go conn .writer (w , connection )
594
616
go conn .reader (r , connection )
595
617
618
+ // Subscribe shutdown event to process graceful shutdown.
619
+ if conn .shutdownWatcher == nil && conn .isFeatureInSlice (WatchersFeature , conn .serverProtocolInfo .Features ) {
620
+ watcher , werr := conn .newWatcherImpl (shutdownEventKey , shutdownEventCallback )
621
+ if werr != nil {
622
+ return werr
623
+ }
624
+ conn .shutdownWatcher = watcher
625
+ }
626
+
596
627
return
597
628
}
598
629
@@ -762,10 +793,17 @@ func (conn *Connection) closeConnection(neterr error, forever bool) (err error)
762
793
if conn .state != connClosed {
763
794
close (conn .control )
764
795
atomic .StoreUint32 (& conn .state , connClosed )
796
+ conn .cond .Broadcast ()
797
+ // Free the resources.
798
+ if conn .shutdownWatcher != nil {
799
+ go conn .shutdownWatcher .Unregister ()
800
+ conn .shutdownWatcher = nil
801
+ }
765
802
conn .notify (Closed )
766
803
}
767
804
} else {
768
805
atomic .StoreUint32 (& conn .state , connDisconnected )
806
+ conn .cond .Broadcast ()
769
807
conn .notify (Disconnected )
770
808
}
771
809
if conn .c != nil {
@@ -784,9 +822,7 @@ func (conn *Connection) closeConnection(neterr error, forever bool) (err error)
784
822
return
785
823
}
786
824
787
- func (conn * Connection ) reconnect (neterr error , c net.Conn ) {
788
- conn .mutex .Lock ()
789
- defer conn .mutex .Unlock ()
825
+ func (conn * Connection ) reconnectImpl (neterr error , c net.Conn ) {
790
826
if conn .opts .Reconnect > 0 {
791
827
if c == conn .c {
792
828
conn .closeConnection (neterr , false )
@@ -799,6 +835,13 @@ func (conn *Connection) reconnect(neterr error, c net.Conn) {
799
835
}
800
836
}
801
837
838
+ func (conn * Connection ) reconnect (neterr error , c net.Conn ) {
839
+ conn .mutex .Lock ()
840
+ defer conn .mutex .Unlock ()
841
+ conn .reconnectImpl (neterr , c )
842
+ conn .cond .Broadcast ()
843
+ }
844
+
802
845
func (conn * Connection ) lockShards () {
803
846
for i := range conn .shard {
804
847
conn .shard [i ].rmut .Lock ()
@@ -1026,6 +1069,15 @@ func (conn *Connection) newFuture(ctx context.Context) (fut *Future) {
1026
1069
fut .done = nil
1027
1070
shard .rmut .Unlock ()
1028
1071
return
1072
+ case connShutdown :
1073
+ fut .err = ClientError {
1074
+ ErrConnectionShutdown ,
1075
+ "server shutdown in progress" ,
1076
+ }
1077
+ fut .ready = nil
1078
+ fut .done = nil
1079
+ shard .rmut .Unlock ()
1080
+ return
1029
1081
}
1030
1082
pos := (fut .requestId / conn .opts .Concurrency ) & (requestsMap - 1 )
1031
1083
if ctx != nil {
@@ -1082,22 +1134,32 @@ func (conn *Connection) contextWatchdog(fut *Future, ctx context.Context) {
1082
1134
}
1083
1135
1084
1136
func (conn * Connection ) send (req Request , streamId uint64 ) * Future {
1137
+ atomic .AddInt64 (& conn .requestCnt , int64 (1 ))
1138
+
1085
1139
fut := conn .newFuture (req .Ctx ())
1086
1140
if fut .ready == nil {
1141
+ atomic .AddInt64 (& conn .requestCnt , int64 (- 1 ))
1087
1142
return fut
1088
1143
}
1144
+
1089
1145
if req .Ctx () != nil {
1090
1146
select {
1091
1147
case <- req .Ctx ().Done ():
1092
1148
conn .cancelFuture (fut , fmt .Errorf ("context is done" ))
1149
+ // future here does not belong to any shard yet,
1150
+ // so cancelFuture don't call markDone.
1151
+ atomic .AddInt64 (& conn .requestCnt , int64 (- 1 ))
1093
1152
return fut
1094
1153
default :
1095
1154
}
1096
1155
}
1156
+
1097
1157
conn .putFuture (fut , req , streamId )
1158
+
1098
1159
if req .Ctx () != nil {
1099
1160
go conn .contextWatchdog (fut , req .Ctx ())
1100
1161
}
1162
+
1101
1163
return fut
1102
1164
}
1103
1165
@@ -1164,6 +1226,10 @@ func (conn *Connection) markDone(fut *Future) {
1164
1226
if conn .rlimit != nil {
1165
1227
<- conn .rlimit
1166
1228
}
1229
+
1230
+ if atomic .AddInt64 (& conn .requestCnt , int64 (- 1 )) == 0 {
1231
+ conn .cond .Broadcast ()
1232
+ }
1167
1233
}
1168
1234
1169
1235
func (conn * Connection ) peekFuture (reqid uint32 ) (fut * Future ) {
@@ -1458,6 +1524,15 @@ func subscribeWatchChannel(conn *Connection, key string) (chan watchState, error
1458
1524
return st , nil
1459
1525
}
1460
1526
1527
+ func (conn * Connection ) isFeatureInSlice (expected ProtocolFeature , actualSlice []ProtocolFeature ) bool {
1528
+ for _ , actual := range actualSlice {
1529
+ if expected == actual {
1530
+ return true
1531
+ }
1532
+ }
1533
+ return false
1534
+ }
1535
+
1461
1536
// NewWatcher creates a new Watcher object for the connection.
1462
1537
//
1463
1538
// You need to require WatchersFeature to use watchers, see examples for the
@@ -1496,20 +1571,16 @@ func (conn *Connection) NewWatcher(key string, callback WatchCallback) (Watcher,
1496
1571
// asynchronous. We do not expect any response from a Tarantool instance
1497
1572
// That's why we can't just check the Tarantool response for an unsupported
1498
1573
// 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 {
1574
+ if ! conn .isFeatureInSlice (WatchersFeature , conn .opts .RequiredProtocolInfo .Features ) {
1508
1575
err := fmt .Errorf ("the feature %s must be required by connection " +
1509
1576
"options to create a watcher" , WatchersFeature )
1510
1577
return nil , err
1511
1578
}
1512
1579
1580
+ return conn .newWatcherImpl (key , callback )
1581
+ }
1582
+
1583
+ func (conn * Connection ) newWatcherImpl (key string , callback WatchCallback ) (Watcher , error ) {
1513
1584
st , err := subscribeWatchChannel (conn , key )
1514
1585
if err != nil {
1515
1586
return nil , err
@@ -1563,7 +1634,11 @@ func (conn *Connection) NewWatcher(key string, callback WatchCallback) (Watcher,
1563
1634
1564
1635
if state .cnt == 0 {
1565
1636
// The last one sends IPROTO_UNWATCH.
1566
- conn .Do (newUnwatchRequest (key )).Get ()
1637
+ if ! conn .ClosedNow () {
1638
+ // conn.ClosedNow() check is a workaround for calling
1639
+ // Unregister from connectionClose().
1640
+ conn .Do (newUnwatchRequest (key )).Get ()
1641
+ }
1567
1642
conn .watchMap .Delete (key )
1568
1643
close (state .unready )
1569
1644
}
@@ -1666,3 +1741,51 @@ func (conn *Connection) ServerProtocolInfo() ProtocolInfo {
1666
1741
func (conn * Connection ) ClientProtocolInfo () ProtocolInfo {
1667
1742
return clientProtocolInfo .Clone ()
1668
1743
}
1744
+
1745
+ func shutdownEventCallback (event WatchEvent ) {
1746
+ // Receives "true" on server shutdown.
1747
+ // See https://www.tarantool.io/en/doc/latest/dev_guide/internals/iproto/graceful_shutdown/
1748
+ // step 2.
1749
+ val , ok := event .Value .(bool )
1750
+ if ok && val {
1751
+ go event .Conn .shutdown ()
1752
+ }
1753
+ }
1754
+
1755
+ func (conn * Connection ) shutdown () {
1756
+ // Forbid state changes.
1757
+ conn .mutex .Lock ()
1758
+ defer conn .mutex .Unlock ()
1759
+
1760
+ if ! atomic .CompareAndSwapUint32 (& (conn .state ), connConnected , connShutdown ) {
1761
+ return
1762
+ }
1763
+ conn .cond .Broadcast ()
1764
+ conn .notify (Shutdown )
1765
+
1766
+ c := conn .c
1767
+ for {
1768
+ if (atomic .LoadUint32 (& conn .state ) != connShutdown ) || (c != conn .c ) {
1769
+ return
1770
+ }
1771
+ if atomic .LoadInt64 (& conn .requestCnt ) == 0 {
1772
+ break
1773
+ }
1774
+ // Use cond var on conn.mutex since request execution may
1775
+ // call reconnect(). It is ok if state changes as part of
1776
+ // reconnect since Tarantool server won't allow to reconnect
1777
+ // in the middle of shutting down.
1778
+ conn .cond .Wait ()
1779
+ }
1780
+
1781
+ // Start to reconnect based on common rules, same as in net.box.
1782
+ // Reconnect also closes the connection: server waits until all
1783
+ // subscribed connections are terminated.
1784
+ // See https://www.tarantool.io/en/doc/latest/dev_guide/internals/iproto/graceful_shutdown/
1785
+ // step 3.
1786
+ conn .reconnectImpl (
1787
+ ClientError {
1788
+ ErrConnectionClosed ,
1789
+ "connection closed after server shutdown" ,
1790
+ }, conn .c )
1791
+ }
0 commit comments