forked from mongodb/mongo-java-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDBTCPConnector.java
More file actions
656 lines (562 loc) · 22.2 KB
/
Copy pathDBTCPConnector.java
File metadata and controls
656 lines (562 loc) · 22.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
/*
* Copyright (c) 2008-2014 MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static com.mongodb.ClusterConnectionMode.Multiple;
import static com.mongodb.ClusterConnectionMode.Single;
import static com.mongodb.ClusterType.ReplicaSet;
import static com.mongodb.ClusterType.Sharded;
import static com.mongodb.ClusterType.Unknown;
import static com.mongodb.MongoAuthority.Type.Set;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.bson.util.Assertions.isTrue;
/**
* @deprecated This class is NOT part of the public API. It will be dropped in 3.x releases.
*/
@Deprecated
public class DBTCPConnector implements DBConnector {
private static final AtomicInteger NEXT_CLUSTER_ID = new AtomicInteger(1);
private volatile boolean _closed;
private final Mongo _mongo;
private Cluster cluster;
private final MyPort _myPort = new MyPort();
private final ClusterConnectionMode connectionMode;
private ClusterType type = ClusterType.Unknown;
private MongosHAServerSelector mongosHAServerSelector;
/**
* @param mongo the Mongo instance
* @throws MongoException
*/
public DBTCPConnector( Mongo mongo ) {
_mongo = mongo;
connectionMode = _mongo.getAuthority().getType() == Set || _mongo.getMongoOptions().getRequiredReplicaSetName() != null ?
Multiple : Single;
}
public void start() {
isTrue("open", !_closed);
MongoOptions options = _mongo.getMongoOptions();
String clusterId = Integer.toString(NEXT_CLUSTER_ID.getAndIncrement());
cluster =
Clusters.create(clusterId,
ClusterSettings.builder()
.hosts(_mongo.getAuthority().getServerAddresses())
.mode(connectionMode)
.requiredReplicaSetName(_mongo.getMongoOptions().getRequiredReplicaSetName())
.build(),
ServerSettings.builder()
.heartbeatFrequency(options.heartbeatFrequencyMS, MILLISECONDS)
.heartbeatConnectRetryFrequency(options.heartbeatConnectRetryFrequencyMS, MILLISECONDS)
.heartbeatSocketSettings(SocketSettings.builder()
.connectTimeout(options.heartbeatConnectTimeoutMS,
MILLISECONDS)
.readTimeout(options.heartbeatReadTimeoutMS, MILLISECONDS)
.socketFactory(_mongo.getMongoOptions().getSocketFactory())
.build())
.build(),
null, _mongo);
}
/**
* Start a "request".
*
* A "request" is a group of operations in which order matters. Examples
* include inserting a document and then performing a query which expects
* that document to have been inserted, or performing an operation and
* then using com.mongodb.Mongo.getLastError to perform error-checking
* on that operation. When a thread performs operations in a "request", all
* operations will be performed on the same socket, so they will be
* correctly ordered.
*/
@Override
public void requestStart(){
isTrue("open", !_closed);
_myPort.requestStart();
}
/**
* End the current "request", if this thread is in one.
*
* By ending a request when it is safe to do so the built-in connection-
* pool is allowed to reassign requests to different sockets in order to
* more effectively balance load. See requestStart for more information.
*/
@Override
public void requestDone(){
isTrue("open", !_closed);
_myPort.requestDone();
}
/**
* @throws MongoException
*/
@Override
public void requestEnsureConnection(){
isTrue("open", !_closed);
_myPort.requestEnsureConnection();
}
private WriteResult _checkWriteError( DB db, DBPort port , WriteConcern concern )
throws IOException{
CommandResult e = port.runCommand( db , concern.getCommand() );
e.throwOnError();
return new WriteResult( e , concern );
}
/**
* @param db
* @param m
* @param concern
* @return
* @throws MongoException
*/
@Override
public WriteResult say( DB db , OutMessage m , WriteConcern concern ){
isTrue("open", !_closed);
return say( db , m , concern , (ServerAddress) null);
}
/**
* @param db
* @param m
* @param concern
* @param hostNeeded
* @return
* @throws MongoException
*/
@Override
public WriteResult say( DB db , OutMessage m , WriteConcern concern , ServerAddress hostNeeded ){
isTrue("open", !_closed);
DBPort port = _myPort.get(true, ReadPreference.primary(), hostNeeded);
try {
return say(db, m, concern, port);
}
finally {
_myPort.done(port);
}
}
WriteResult say(final DB db, final OutMessage m, final WriteConcern concern, final DBPort port){
isTrue("open", !_closed);
if (concern == null) {
throw new IllegalArgumentException("Write concern is null");
}
try {
return doOperation(db, port, new DBPort.Operation<WriteResult>() {
@Override
public WriteResult execute() throws IOException {
port.say(m);
if (concern.callGetLastError()) {
return _checkWriteError(db, port, concern);
} else {
return new WriteResult(db, port, concern);
}
}
});
} catch (MongoException.Network e) {
if ( concern.raiseNetworkErrors() )
throw e;
CommandResult res = new CommandResult(port.serverAddress());
res.put( "ok" , false );
res.put( "$err" , "NETWORK ERROR" );
return new WriteResult( res , concern );
} finally {
m.doneWithMessage();
}
}
<T> T doOperation(final DB db, final DBPort port, final DBPort.Operation<T> operation){
isTrue("open", !_closed);
try {
port.checkAuth( db.getMongo() );
return operation.execute();
}
catch ( MongoException re ){
throw re;
}
catch ( IOException ioe ){
_myPort.error(port, ioe);
throw new MongoException.Network("Operation on server " + port.getAddress() + " failed" , ioe );
}
catch ( RuntimeException re ){
_myPort.error(port, re);
throw re;
}
}
/**
* @param db
* @param coll
* @param m
* @param hostNeeded
* @param decoder
* @return
* @throws MongoException
*/
@Override
public Response call( DB db , DBCollection coll , OutMessage m, ServerAddress hostNeeded, DBDecoder decoder ){
isTrue("open", !_closed);
return call( db , coll , m , hostNeeded , 2, null, decoder );
}
/**
* @param db
* @param coll
* @param m
* @param hostNeeded
* @param retries
* @return
* @throws MongoException
*/
@Override
public Response call( DB db , DBCollection coll , OutMessage m , ServerAddress hostNeeded , int retries ){
isTrue("open", !_closed);
return call(db, coll, m, hostNeeded, retries, null, null);
}
/**
* @param db
* @param coll
* @param m
* @param hostNeeded
* @param readPref
* @param decoder
* @return
* @throws MongoException
*/
@Override
public Response call( DB db, DBCollection coll, OutMessage m, ServerAddress hostNeeded, int retries,
ReadPreference readPref, DBDecoder decoder ){
isTrue("open", !_closed);
try {
return innerCall(db, coll, m, hostNeeded, retries, readPref, decoder);
} finally {
m.doneWithMessage();
}
}
// This method is recursive. It calls itself to implement query retry logic.
private Response innerCall(final DB db, final DBCollection coll, final OutMessage m, final ServerAddress hostNeeded,
final int remainingRetries, ReadPreference readPref, final DBDecoder decoder) {
if (readPref == null)
readPref = ReadPreference.primary();
if (readPref == ReadPreference.primary() && m.hasOption( Bytes.QUERYOPTION_SLAVEOK ))
readPref = ReadPreference.secondaryPreferred();
final DBPort port = _myPort.get(false, readPref, hostNeeded);
Response res = null;
boolean retry = false;
try {
port.checkAuth( db.getMongo() );
res = port.call( m , coll, decoder );
if ( res._responseTo != m.getId() )
throw new MongoException( "ids don't match" );
}
catch ( IOException ioe ){
_myPort.error(port, ioe);
retry = shouldRetryQuery(readPref, coll, ioe, remainingRetries);
if ( !retry ){
throw new MongoException.Network("Read operation to server " + port.host() + " failed on database " + db , ioe );
}
}
catch ( RuntimeException re ){
_myPort.error(port, re);
throw re;
} finally {
_myPort.done(port);
}
if (retry)
return innerCall( db , coll , m , hostNeeded , remainingRetries - 1 , readPref, decoder );
ServerError err = res.getError();
if ( err != null && err.isNotMasterError() ){
if ( remainingRetries <= 0 ){
throw new MongoException( "not talking to master and retries used up" );
}
return innerCall( db , coll , m , hostNeeded , remainingRetries -1, readPref, decoder );
}
return res;
}
public ServerAddress getAddress() {
isTrue("open", !_closed);
ClusterDescription clusterDescription = getClusterDescription();
if (connectionMode == Single) {
return clusterDescription.getAny().get(0).getAddress();
}
if (clusterDescription.getPrimaries().isEmpty()) {
return null;
}
return clusterDescription.getPrimaries().get(0).getAddress();
}
/**
* Gets the list of seed server addresses
* @return
*/
public List<ServerAddress> getAllAddress() {
isTrue("open", !_closed);
return _mongo._authority.getServerAddresses();
}
/**
* Gets the list of server addresses currently seen by the connector.
* This includes addresses auto-discovered from a replica set.
* @return
* @throws MongoException
*/
public List<ServerAddress> getServerAddressList() {
isTrue("open", !_closed);
List<ServerAddress> serverAddressList = new ArrayList<ServerAddress>();
ClusterDescription clusterDescription = getClusterDescription();
for (ServerDescription serverDescription : clusterDescription.getAll()) {
serverAddressList.add(serverDescription.getAddress());
}
return serverAddressList;
}
public ReplicaSetStatus getReplicaSetStatus() {
isTrue("open", !_closed);
return getType() == ReplicaSet && connectionMode == Multiple ? new ReplicaSetStatus(getClusterDescription()) : null;
}
// This call can block if it's not yet known.
boolean isMongosConnection() {
isTrue("open", !_closed);
return getType() == Sharded;
}
public String getConnectPoint(){
isTrue("open", !_closed);
ServerAddress master = getAddress();
return master != null ? master.toString() : null;
}
private boolean shouldRetryQuery(ReadPreference readPreference, final DBCollection coll, final IOException ioe, final int remainingRetries) {
if (remainingRetries == 0) {
return false;
}
if (coll._name.equals("$cmd")) {
return false;
}
if (ioe instanceof SocketTimeoutException) {
return false;
}
if (readPreference.equals(ReadPreference.primary())) {
return false;
}
return connectionMode == Multiple && getType() == ReplicaSet;
}
private ClusterDescription getClusterDescription() {
return cluster.getDescription(getClusterWaitTimeMS(), MILLISECONDS);
}
private int getClusterWaitTimeMS() {
return Math.min(_mongo.getMongoOptions().maxWaitTime, _mongo.getMongoOptions().connectTimeout);
}
private int getConnectionWaitTimeMS() {
return _mongo.getMongoOptions().maxWaitTime;
}
DBPort getPrimaryPort() {
isTrue("open", !_closed);
return _myPort.get(true, ReadPreference.primary(), null);
}
void releasePort(final DBPort port) {
isTrue("open", !_closed);
_myPort.done(port);
}
ServerDescription getServerDescription(final ServerAddress address) {
isTrue("open", !_closed);
return getClusterDescription().getByServerAddress(address);
}
class MyPort {
DBPort get( boolean keep , ReadPreference readPref, ServerAddress hostNeeded ){
DBPort pinnedRequestPort = getPinnedRequestPortForThread();
if ( hostNeeded != null ) {
if (pinnedRequestPort != null && pinnedRequestPort.serverAddress().equals(hostNeeded)) {
return pinnedRequestPort;
}
// asked for a specific host
return getConnection(new ServerAddressSelector(hostNeeded));
}
if ( pinnedRequestPort != null ){
// we are within a request, and have a port, should stick to it
if ( portIsAPrimary(pinnedRequestPort) || !keep ) {
// if keep is false, it's a read, so we use port even if primary changed
return pinnedRequestPort;
}
// it's write and primary has changed
// we fall back on new primary and try to go on with request
// this may not be best behavior if spec of request is to stick with same server
pinnedRequestPort.getProvider().release(pinnedRequestPort);
setPinnedRequestPortForThread(null);
}
DBPort port = getConnection(createServerSelector(readPref));
// if within request, remember port to stick to same server
if (threadHasPinnedRequest()) {
setPinnedRequestPortForThread(port);
}
return port;
}
private boolean portIsAPrimary(final DBPort pinnedRequestPort) {
for (ServerDescription cur : getClusterDescription().getPrimaries()) {
if (cur.getAddress().equals(pinnedRequestPort.serverAddress())) {
return true;
}
}
return false;
}
void done( DBPort port ) {
Connection requestPort = getPinnedRequestPortForThread();
// keep request port
if (port != requestPort) {
port.getProvider().release(port);
}
}
/**
* call this method when there is an IOException or other low level error on port.
* @param port
* @param e
*/
void error( DBPort port , Exception e ){
if (!(e instanceof InterruptedIOException)) {
getServer(new ServerAddressSelector(port.getAddress())).invalidate();
}
port.close();
pinnedRequestStatusThreadLocal.remove();
}
void requestEnsureConnection(){
if ( !threadHasPinnedRequest() )
return;
if ( getPinnedRequestPortForThread() != null )
return;
setPinnedRequestPortForThread(getConnection(createServerSelector(ReadPreference.primary())));
}
private DBPort getConnection(final ServerSelector serverSelector) {
return (DBPort) getServer(serverSelector).getConnection(getConnectionWaitTimeMS(), MILLISECONDS);
}
void requestStart() {
PinnedRequestStatus current = getPinnedRequestStatusForThread();
if (current == null) {
pinnedRequestStatusThreadLocal.set(new PinnedRequestStatus());
}
else {
current.nestedBindings++;
}
}
void requestDone(){
PinnedRequestStatus current = getPinnedRequestStatusForThread();
if (current != null) {
if (current.nestedBindings > 0) {
current.nestedBindings--;
}
else {
pinnedRequestStatusThreadLocal.remove();
if (current.requestPort != null)
current.requestPort.getProvider().release(current.requestPort);
}
}
}
PinnedRequestStatus getPinnedRequestStatusForThread() {
return pinnedRequestStatusThreadLocal.get();
}
boolean threadHasPinnedRequest() {
return pinnedRequestStatusThreadLocal.get() != null;
}
DBPort getPinnedRequestPortForThread() {
return threadHasPinnedRequest() ? pinnedRequestStatusThreadLocal.get().requestPort : null;
}
void setPinnedRequestPortForThread(final DBPort port) {
pinnedRequestStatusThreadLocal.get().requestPort = port;
}
private final ThreadLocal<PinnedRequestStatus> pinnedRequestStatusThreadLocal = new ThreadLocal<PinnedRequestStatus>();
}
private ServerSelector createServerSelector(final ReadPreference readPreference) {
if (connectionMode == Multiple) {
List<ServerSelector> serverSelectorList = new ArrayList<ServerSelector>();
if (getType() == Sharded) {
serverSelectorList.add(getMongosHAServerSelector());
} else if (getType() == ReplicaSet) {
serverSelectorList.add(new ReadPreferenceServerSelector(readPreference));
} else {
serverSelectorList.add(new AnyServerSelector());
}
serverSelectorList.add(new LatencyMinimizingServerSelector(_mongo.getMongoOptions().acceptableLatencyDifferenceMS,
MILLISECONDS));
return new CompositeServerSelector(serverSelectorList);
} else {
return new AnyServerSelector();
}
}
private synchronized ClusterType getType() {
if (type == Unknown) {
type = getClusterDescription().getType();
}
return type;
}
// There needs to be just one instance of this because it's stateful between requests
private synchronized MongosHAServerSelector getMongosHAServerSelector() {
if (mongosHAServerSelector == null) {
mongosHAServerSelector = new MongosHAServerSelector();
}
return mongosHAServerSelector;
}
static class PinnedRequestStatus {
DBPort requestPort;
public int nestedBindings;
}
public String debugString(){
return getClusterDescription().getShortDescription();
}
public void close(){
_closed = true;
if (cluster != null) {
cluster.close();
cluster = null;
}
}
/**
* Assigns a new DBPortPool for a given ServerAddress.
* This is used to obtain a new pool when the resolved IP of a host changes, for example.
* User application should not have to call this method directly.
* @param addr
*/
public void updatePortPool(ServerAddress addr) {
}
/**
* Gets the DBPortPool associated with a ServerAddress.
* @param addr
* @return
*/
public DBPortPool getDBPortPool(ServerAddress addr) {
throw new UnsupportedOperationException();
}
public boolean isOpen(){
return !_closed;
}
@Override
public CommandResult authenticate(MongoCredential credentials) {
final DBPort port = _myPort.get(false, ReadPreference.primaryPreferred(), null);
try {
CommandResult result = port.authenticate(_mongo, credentials);
_mongo.getAuthority().getCredentialsStore().add(credentials);
return result;
} finally {
_myPort.done(port);
}
}
/**
* Gets the maximum size for a BSON object supported by the current master server.
* Note that this value may change over time depending on which server is master.
* @return the maximum size, or 0 if not obtained from servers yet.
*/
public int getMaxBsonObjectSize() {
ClusterDescription clusterDescription = getClusterDescription();
if (clusterDescription.getPrimaries().isEmpty()) {
return Bytes.MAX_OBJECT_SIZE;
}
return clusterDescription.getPrimaries().get(0).getMaxDocumentSize();
}
// expose for unit testing
MyPort getMyPort() {
return _myPort;
}
private Server getServer(final ServerSelector serverSelector) {
return cluster.getServer(serverSelector, getClusterWaitTimeMS(), MILLISECONDS);
}
}