/
ConnectionImpl.java
2582 lines (2207 loc) · 78.7 KB
/
ConnectionImpl.java
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 (c) 2015-2016 Apcera Inc. All rights reserved. This program and the accompanying
* materials are made available under the terms of the MIT License (MIT) which accompanies this
* distribution, and is available at http://opensource.org/licenses/MIT
*/
package io.nats.client;
import static io.nats.client.Nats.ConnState;
import static io.nats.client.Nats.ConnState.CLOSED;
import static io.nats.client.Nats.ConnState.CONNECTED;
import static io.nats.client.Nats.ConnState.CONNECTING;
import static io.nats.client.Nats.ConnState.DISCONNECTED;
import static io.nats.client.Nats.ConnState.RECONNECTING;
import static io.nats.client.Nats.ERR_BAD_SUBJECT;
import static io.nats.client.Nats.ERR_BAD_SUBSCRIPTION;
import static io.nats.client.Nats.ERR_BAD_TIMEOUT;
import static io.nats.client.Nats.ERR_CONNECTION_CLOSED;
import static io.nats.client.Nats.ERR_CONNECTION_READ;
import static io.nats.client.Nats.ERR_MAX_PAYLOAD;
import static io.nats.client.Nats.ERR_NO_INFO_RECEIVED;
import static io.nats.client.Nats.ERR_NO_SERVERS;
import static io.nats.client.Nats.ERR_RECONNECT_BUF_EXCEEDED;
import static io.nats.client.Nats.ERR_SECURE_CONN_REQUIRED;
import static io.nats.client.Nats.ERR_SECURE_CONN_WANTED;
import static io.nats.client.Nats.ERR_SLOW_CONSUMER;
import static io.nats.client.Nats.ERR_STALE_CONNECTION;
import static io.nats.client.Nats.ERR_TCP_FLUSH_FAILED;
import static io.nats.client.Nats.ERR_TIMEOUT;
import static io.nats.client.Nats.PERMISSIONS_ERR;
import static io.nats.client.Nats.TLS_SCHEME;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class ConnectionImpl implements Connection {
private final Logger logger = LoggerFactory.getLogger(ConnectionImpl.class);
private String version = null;
private static final String INBOX_PREFIX = "_INBOX.";
private ConnState status = DISCONNECTED;
protected static final String STALE_CONNECTION = "Stale Connection";
// Default language string for CONNECT message
protected static final String LANG_STRING = "java";
// The size of the read buffer in readLoop.
protected static final int DEFAULT_BUF_SIZE = 65536;
// The size of the BufferedInputStream and BufferedOutputStream on top of the socket.
protected static final int DEFAULT_STREAM_BUF_SIZE = 65536;
// The buffered size of the flush "kick" channel
protected static final int FLUSH_CHAN_SIZE = 1;
// The number of msec the flusher will wait between flushes
private long flushTimerInterval = 1;
private TimeUnit flushTimerUnit = TimeUnit.MICROSECONDS;
protected static final String CRLF = "\r\n";
protected static final String _EMPTY_ = "";
protected static final String _SPC_ = " ";
protected static final String _PUB_P_ = "PUB ";
// Operations
protected static final String _OK_OP_ = "+OK";
protected static final String _ERR_OP_ = "-ERR";
protected static final String _MSG_OP_ = "MSG";
protected static final String _PING_OP_ = "PING";
protected static final String _PONG_OP_ = "PONG";
protected static final String _INFO_OP_ = "INFO";
// Message Prototypes
protected static final String CONN_PROTO = "CONNECT %s" + CRLF;
protected static final String PING_PROTO = "PING" + CRLF;
protected static final String PONG_PROTO = "PONG" + CRLF;
protected static final String PUB_PROTO = "PUB %s %s %d" + CRLF;
protected static final String SUB_PROTO = "SUB %s%s %d" + CRLF;
protected static final String UNSUB_PROTO = "UNSUB %d %s" + CRLF;
protected static final String OK_PROTO = _OK_OP_ + CRLF;
enum ClientProto {
CLIENT_PROTO_ZERO(0), // CLIENT_PROTO_ZERO is the original client protocol from 2009.
CLIENT_PROTO_INFO(1); // clientProtoInfo signals a client can receive more then the original
// INFO block. This can be used to update clients on other cluster
// members, etc.
private final int value;
ClientProto(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
private ConnectionImpl nc = null;
final Lock mu = new ReentrantLock();
// protected final Lock mu = new AlternateDeadlockDetectingLock(true, true);
private final AtomicLong sidCounter = new AtomicLong(0L);
private URI url = null;
private Options opts = null;
private TcpConnectionFactory tcf = null;
private TcpConnection conn = null;
// Prepare protocol messages for efficiency
private ByteBuffer pubProtoBuf = null;
// we have a buffered reader for writing, and reading.
// This is for both performance, and having to work around
// interlinked read/writes (supported by the underlying network
// stream, but not the BufferedStream).
private OutputStream bw = null;
private InputStream br = null;
private ByteArrayOutputStream pending = null;
private Map<Long, SubscriptionImpl> subs = new ConcurrentHashMap<Long, SubscriptionImpl>();
private List<Srv> srvPool = null;
private Map<String, URI> urls = null;
private Exception lastEx = null;
private ServerInfo info = null;
private int pout;
private Parser parser = new Parser(this);
private static final byte[] pingProtoBytes = PING_PROTO.getBytes();
private static final int pingProtoBytesLen = pingProtoBytes.length;
private static final byte[] pongProtoBytes = PONG_PROTO.getBytes();
private static final int pongProtoBytesLen = pongProtoBytes.length;
private static final byte[] pubPrimBytes = _PUB_P_.getBytes();
private static final int pubPrimBytesLen = pubPrimBytes.length;
private static final byte[] crlfProtoBytes = CRLF.getBytes();
private static final int crlfProtoBytesLen = crlfProtoBytes.length;
private Statistics stats = null;
private List<BlockingQueue<Boolean>> pongs;
private static final int NUM_CORE_THREADS = 4;
// The main executor service for core threads and timers
private ScheduledExecutorService exec;
static final String EXEC_NAME = "jnats-exec";
// Executor for subscription threads
private ExecutorService subexec;
static final String SUB_EXEC_NAME = "jnats-subscriptions";
// Executor for async connection callbacks
private ExecutorService cbexec;
static final String CB_EXEC_NAME = "jnats-callbacks";
// The ping timer task
private ScheduledFuture<?> ptmr = null;
static final String PINGTIMER = "pingtimer";
static final String READLOOP = "readloop";
static final String FLUSHER = "flusher";
private final Map<String, Future<?>> tasks = new HashMap<>();
private static final int NUM_WATCHER_THREADS = 2;
private CountDownLatch socketWatchersStartLatch = new CountDownLatch(NUM_WATCHER_THREADS);
private CountDownLatch socketWatchersDoneLatch = null;
// The flusher signalling channel
private BlockingQueue<Boolean> fch;
// ConnectionImpl() {
// }
ConnectionImpl(Options opts) {
Properties props = this.getProperties(Nats.PROP_PROPERTIES_FILENAME);
version = props.getProperty(Nats.PROP_CLIENT_VERSION);
this.nc = this;
this.opts = opts;
this.stats = new Statistics();
if (opts.getFactory() != null) {
tcf = opts.getFactory();
} else {
tcf = new TcpConnectionFactory();
}
}
ScheduledExecutorService createScheduler() {
ScheduledThreadPoolExecutor sexec = (ScheduledThreadPoolExecutor)
Executors.newScheduledThreadPool(NUM_CORE_THREADS,
new NatsThreadFactory(EXEC_NAME));
sexec.setRemoveOnCancelPolicy(true);
return sexec;
}
ExecutorService createSubscriptionScheduler() {
return Executors.newCachedThreadPool(new NatsThreadFactory(SUB_EXEC_NAME));
}
ExecutorService createCallbackScheduler() {
return Executors.newSingleThreadExecutor(new NatsThreadFactory(CB_EXEC_NAME));
}
void setup() {
exec = createScheduler();
cbexec = createCallbackScheduler();
subexec = createSubscriptionScheduler();
fch = createFlushChannel();
pongs = createPongs();
subs.clear();
// predefine the start of the publish protocol message.
buildPublishProtocolBuffer(Parser.MAX_CONTROL_LINE_SIZE);
}
Properties getProperties(InputStream inputStream) {
Properties rv = new Properties();
try {
if (inputStream == null) {
rv = null;
} else {
rv.load(inputStream);
}
} catch (IOException e) {
logger.warn("nats: error loading properties from InputStream", e);
rv = null;
}
return rv;
}
Properties getProperties(String resourceName) {
InputStream is = getClass().getClassLoader().getResourceAsStream(resourceName);
return getProperties(is);
}
private void buildPublishProtocolBuffer(int size) {
pubProtoBuf = ByteBuffer.allocate(size);
pubProtoBuf.put(pubPrimBytes, 0, pubPrimBytesLen);
pubProtoBuf.mark();
}
/*
* Create the server pool using the options given. We will place a Url option first, followed by
* any Srv Options. We will randomize the server pool (except Url) unless the NoRandomize flag
* is set.
*/
void setupServerPool() {
final URI url;
if (opts.getUrl() != null) {
url = URI.create(opts.getUrl());
} else {
url = null;
}
List<URI> servers = opts.getServers();
srvPool = new ArrayList<Srv>();
urls = new ConcurrentHashMap<String, URI>();
if (servers != null) {
for (URI s : servers) {
addUrlToPool(s, false);
}
}
if (!opts.isNoRandomize()) {
// Randomize the order
Collections.shuffle(srvPool, new Random(System.nanoTime()));
}
/*
* Insert the supplied url, if not null or empty, at the beginning of the list. Normally, if
* this is set, then opts.servers should NOT be set, and vice versa. However, we always
* allowed both to be set before, so we'll continue to do so.
*/
if (url != null) {
srvPool.add(0, new Srv(url, false));
urls.put(url.getAuthority(), url);
}
// If the pool is empty, add the default URL
if (srvPool.isEmpty()) {
addUrlToPool(Nats.DEFAULT_URL, false);
}
/*
* At this point, srvPool being empty would be programmer error.
*/
// Return the first server in the list
this.setUrl(srvPool.get(0).url);
}
/* Add a string URL to the server pool */
void addUrlToPool(String srvUrl, boolean implicit) {
URI uri = URI.create(srvUrl);
srvPool.add(new Srv(uri, implicit));
urls.put(uri.getAuthority(), uri);
}
/* Add a URL to the server pool */
void addUrlToPool(URI uri, boolean implicit) {
srvPool.add(new Srv(uri, implicit));
urls.put(uri.getAuthority(), uri);
}
Srv currentServer() {
Srv rv = null;
for (Srv s : srvPool) {
if (s.url.equals(this.getUrl())) {
rv = s;
break;
}
}
return rv;
}
Srv selectNextServer() throws IOException {
Srv srv = currentServer();
if (srv == null) {
throw new IOException(ERR_NO_SERVERS);
}
/*
* Pop the current server and put onto the end of the list. Select head of list as long as
* number of reconnect attempts under MaxReconnect.
*/
srvPool.remove(srv);
/*
* if the maxReconnect is unlimited, or the number of reconnect attempts is less than
* maxReconnect, move the current server to the end of the list.
*
*/
int maxReconnect = opts.getMaxReconnect();
if ((maxReconnect < 0) || (srv.reconnects < maxReconnect)) {
srvPool.add(srv);
}
if (srvPool.isEmpty()) {
this.setUrl(null);
throw new IOException(ERR_NO_SERVERS);
}
return srvPool.get(0);
}
Connection connect() throws IOException {
// Create actual socket connection
// For first connect we walk all servers in the pool and try
// to connect immediately.
IOException returnedErr = null;
setupServerPool();
mu.lock();
try {
for (Srv srv : srvPool) {
this.setUrl(srv.url);
try {
logger.debug("Connecting to {}", this.getUrl());
createConn();
logger.debug("Connected to {}", this.getUrl());
this.setup();
try {
processConnectInit();
srv.reconnects = 0;
returnedErr = null;
break;
} catch (IOException e) {
returnedErr = e;
mu.unlock();
close(DISCONNECTED, false);
mu.lock();
this.setUrl(null);
} catch (InterruptedException e) {
returnedErr = new IOException(e);
mu.unlock();
close(DISCONNECTED, false);
mu.lock();
this.setUrl(null);
}
} catch (IOException e) { // createConn failed
// Cancel out default connection refused, will trigger the
// No servers error conditional
if (e.getMessage() != null && e.getMessage().contains("Connection refused")) {
setLastError(null);
}
}
} // for
if ((returnedErr == null) && (this.status != CONNECTED)) {
returnedErr = new IOException(ERR_NO_SERVERS);
}
if (returnedErr != null) {
throw (returnedErr);
}
cbexec = createCallbackScheduler();
return this;
} finally {
mu.unlock();
}
}
/*
* createConn will connect to the server and wrap the appropriate bufio structures. A new
* connection is always created.
*/
void createConn() throws IOException {
if (opts.getConnectionTimeout() < 0) {
logger.warn("{}: {}", ERR_BAD_TIMEOUT, opts.getConnectionTimeout());
throw new IOException(ERR_BAD_TIMEOUT);
}
Srv srv = currentServer();
if (srv == null) {
throw new IOException(ERR_NO_SERVERS);
} else {
srv.updateLastAttempt();
}
try {
logger.debug("Opening {}", srv.url);
conn = tcf.createConnection();
conn.open(srv.url.toString(), opts.getConnectionTimeout());
logger.trace("Opened {} as TcpConnection ({})", srv.url, conn);
} catch (IOException e) {
logger.debug("Couldn't establish connection to {}: {}", srv.url, e.getMessage());
throw (e);
}
if ((pending != null) && (bw != null)) {
try {
bw.flush();
} catch (IOException e) {
logger.warn(ERR_TCP_FLUSH_FAILED);
}
}
bw = conn.getOutputStream(DEFAULT_STREAM_BUF_SIZE);
br = conn.getInputStream(DEFAULT_STREAM_BUF_SIZE);
}
BlockingQueue<Message> createMsgChannel() {
return createMsgChannel(Integer.MAX_VALUE);
}
BlockingQueue<Message> createMsgChannel(int size) {
int theSize = size;
if (theSize <= 0) {
theSize = 1;
}
return new LinkedBlockingQueue<Message>(theSize);
}
BlockingQueue<Boolean> createBooleanChannel() {
return new LinkedBlockingQueue<Boolean>();
}
BlockingQueue<Boolean> createBooleanChannel(int size) {
int theSize = size;
if (theSize <= 0) {
theSize = 1;
}
return new LinkedBlockingQueue<Boolean>(theSize);
}
BlockingQueue<Boolean> createFlushChannel() {
return new LinkedBlockingQueue<Boolean>(FLUSH_CHAN_SIZE);
// return new SynchronousQueue<Boolean>();
}
// This will clear any pending flush calls and release pending calls.
// Lock is assumed to be held by the caller.
void clearPendingFlushCalls() {
// Clear any queued pongs, e.g. pending flush calls.
if (pongs == null) {
return;
}
for (BlockingQueue<Boolean> ch : pongs) {
if (ch != null) {
ch.clear();
// Signal other waiting threads that we're done
ch.add(false);
}
}
pongs.clear();
pongs = null;
}
@Override
public void close() {
close(CLOSED, true);
}
/*
* Low level close call that will do correct cleanup and set desired status. Also controls
* whether user defined callbacks will be triggered. The lock should not be held entering this
* method. This method will handle the locking manually.
*/
private void close(ConnState closeState, boolean doCBs) {
logger.debug("close({}, {})", closeState, String.valueOf(doCBs));
final ConnectionImpl nc = this;
mu.lock();
try {
if (closed()) {
this.status = closeState;
return;
}
this.status = CLOSED;
// Kick the Flusher routine so it falls out.
kickFlusher();
} finally {
mu.unlock();
}
mu.lock();
try {
// Clear any queued pongs, e.g. pending flush calls.
clearPendingFlushCalls();
// Go ahead and make sure we have flushed the outbound
if (conn != null) {
try {
if (bw != null) {
bw.flush();
}
} catch (IOException e) {
/* NOOP */
}
}
// Close sync subscribers and release any pending nextMsg() calls.
for (Map.Entry<Long, SubscriptionImpl> entry : subs.entrySet()) {
SubscriptionImpl sub = entry.getValue();
// for (Long key : subs.keySet()) {
// SubscriptionImpl sub = subs.get(key);
sub.lock();
try {
sub.closeChannel();
// Mark as invalid, for signaling to deliverMsgs
sub.closed = true;
// Mark connection closed in subscription
sub.connClosed = true;
// Terminate thread exec
sub.close();
} finally {
sub.unlock();
}
}
subs.clear();
// perform appropriate callback if needed for a disconnect;
if (doCBs) {
if (opts.getDisconnectedCallback() != null && conn != null) {
cbexec.submit(new Runnable() {
@Override
public void run() {
opts.getDisconnectedCallback().onDisconnect(new ConnectionEvent(nc));
logger.trace("executed DisconnectedCB");
}
});
}
if (opts.getClosedCallback() != null) {
cbexec.submit(new Runnable() {
@Override
public void run() {
opts.getClosedCallback().onClose(new ConnectionEvent(nc));
logger.trace("executed ClosedCB");
}
});
}
if (cbexec != null) {
cbexec.shutdown();
}
}
this.status = closeState;
if (conn != null) {
conn.close();
}
if (exec != null) {
shutdownAndAwaitTermination(exec, EXEC_NAME);
}
if (subexec != null) {
shutdownAndAwaitTermination(subexec, SUB_EXEC_NAME);
}
} finally {
mu.unlock();
}
}
void shutdownAndAwaitTermination(ExecutorService pool, String name) {
try {
pool.shutdownNow();
if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
logger.error("{} did not terminate", name);
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
void processConnectInit() throws IOException, InterruptedException {
// Set our status to connecting.
status = CONNECTING;
// Process the INFO protocol that we should be receiving
processExpectedInfo();
// Send the CONNECT and PING protocol, and wait for the PONG.
sendConnect();
// Reset the number of PINGs sent out
this.setActualPingsOutstanding(0);
// Start the readLoop and flusher threads
spinUpSocketWatchers();
}
// This will check to see if the connection should be
// secure. This can be dictated from either end and should
// only be called after the INIT protocol has been received.
void checkForSecure() throws IOException {
// Check to see if we need to engage TLS
// Check for mismatch in setups
if (opts.isSecure() && !info.isTlsRequired()) {
throw new IOException(ERR_SECURE_CONN_WANTED);
} else if (info.isTlsRequired() && !opts.isSecure()) {
throw new IOException(ERR_SECURE_CONN_REQUIRED);
}
// Need to rewrap with bufio
if (opts.isSecure() || TLS_SCHEME.equals(this.getUrl().getScheme())) {
makeTlsConn();
}
}
// makeSecureConn will wrap an existing Conn using TLS
void makeTlsConn() throws IOException {
conn.setTlsDebug(opts.isTlsDebug());
conn.makeTls(opts.getSslContext());
bw = conn.getOutputStream(DEFAULT_STREAM_BUF_SIZE);
br = conn.getInputStream(DEFAULT_STREAM_BUF_SIZE);
}
void processExpectedInfo() throws IOException, InterruptedException {
Control control;
try {
// Read the protocol
control = readOp();
} catch (IOException e) {
processOpError(e);
return;
}
// The nats protocol should send INFO first always.
if (!control.op.equals(_INFO_OP_)) {
throw new IOException(ERR_NO_INFO_RECEIVED);
}
// Parse the protocol
processInfo(control.args);
checkForSecure();
}
// processPing will send an immediate pong protocol response to the
// server. The server uses this mechanism to detect dead clients.
void processPing() {
try {
sendProto(pongProtoBytes, pongProtoBytesLen);
} catch (IOException e) {
setLastError(e);
// e.printStackTrace();
}
}
// processPong is used to process responses to the client's ping
// messages. We use pings for the flush mechanism as well.
void processPong() throws InterruptedException {
BlockingQueue<Boolean> ch = null;
mu.lockInterruptibly();
try {
if (pongs != null && pongs.size() > 0) {
ch = pongs.get(0);
pongs.remove(0);
}
setActualPingsOutstanding(0);
} finally {
mu.unlock();
}
if (ch != null) {
ch.add(true);
}
}
// processOK is a placeholder for processing OK messages.
void processOk() {
// NOOP;
}
// processInfo is used to parse the info messages sent
// from the server.
void processInfo(String infoString) {
if ((infoString == null) || infoString.isEmpty()) {
return;
}
setConnectedServerInfo(ServerInfo.createFromWire(infoString));
boolean updated = false;
if (info.getConnectUrls() != null) {
for (String s : info.getConnectUrls()) {
if (!urls.containsKey(s)) {
this.addUrlToPool(String.format("nats://%s", s), true);
updated = true;
}
}
if (updated && !opts.isNoRandomize()) {
Collections.shuffle(srvPool);
}
}
}
// processAsyncInfo does the same as processInfo, but is called
// from the parser. Calls processInfo under connection's lock
// protection.
void processAsyncInfo(byte[] asyncInfo, int offset, int length) {
mu.lock();
try {
String theInfo = new String(asyncInfo, offset, length);
// Ignore errors, we will simply not update the server pool...
processInfo(theInfo);
} finally {
mu.unlock();
}
}
// processOpError handles errors from reading or parsing the protocol.
// This is where disconnect/reconnect is initially handled.
// The lock should not be held entering this function.
void processOpError(Exception err) throws InterruptedException {
mu.lockInterruptibly();
try {
if (connecting() || closed() || reconnecting()) {
return;
}
logger.debug("Connection terminated: {}", err.getMessage());
if (opts.isReconnectAllowed() && status == CONNECTED) {
// Set our new status
status = RECONNECTING;
if (ptmr != null) {
ptmr.cancel(true);
tasks.remove(ptmr);
}
if (this.conn != null) {
try {
bw.flush();
} catch (IOException e1) {
logger.warn("I/O error during flush");
}
conn.close();
}
if (fch != null && !fch.offer(false)) {
logger.debug("Coudn't shut down flusher following connection error");
}
// Create a new pending buffer to underpin the buffered output
// stream while we are reconnecting.
setPending(new ByteArrayOutputStream(opts.getReconnectBufSize()));
setOutputStream(getPending());
if (exec.isShutdown()) {
exec = createScheduler();
}
exec.submit(new Runnable() {
public void run() {
Thread.currentThread().setName("reconnect");
try {
doReconnect();
} catch (InterruptedException e) {
logger.warn("nats: interrupted while reonnecting");
}
}
});
if (cbexec.isShutdown()) {
cbexec = createCallbackScheduler();
}
} else {
processDisconnect();
setLastError(err);
close();
}
} finally {
mu.unlock();
}
}
protected void processDisconnect() {
logger.debug("processDisconnect()");
status = DISCONNECTED;
}
@Override
public boolean isReconnecting() {
mu.lock();
try {
return reconnecting();
} finally {
mu.unlock();
}
}
boolean reconnecting() {
return (status == RECONNECTING);
}
@Override
public boolean isConnected() {
mu.lock();
try {
return connected();
} finally {
mu.unlock();
}
}
boolean connected() {
return (status == CONNECTED);
}
@Override
public boolean isClosed() {
mu.lock();
try {
return closed();
} finally {
mu.unlock();
}
}
boolean closed() {
return (status == CLOSED);
}
// flushReconnectPending will push the pending items that were
// gathered while we were in a RECONNECTING state to the socket.
void flushReconnectPendingItems() {
if (pending == null) {
return;
}
if (pending.size() > 0) {
try {
bw.write(pending.toByteArray(), 0, pending.size());
bw.flush();
} catch (IOException e) {
logger.error("Error flushing pending items", e);
}
}
pending = null;
}
// Try to reconnect using the option parameters.
// This function assumes we are allowed to reconnect.
void doReconnect() throws InterruptedException {
logger.trace("doReconnect()");
// We want to make sure we have the other watchers shutdown properly
// here before we proceed past this point
waitForExits();
logger.trace("Old threads have exited, proceeding with reconnect");
// FIXME(dlc) - We have an issue here if we have
// outstanding flush points (pongs) and they were not
// sent out, but are still in the pipe.
// Hold the lock manually and release where needed below.
mu.lockInterruptibly();
try {
// Clear any queued pongs, e.g. pending flush calls.
nc.clearPendingFlushCalls();
// Clear any errors.
setLastError(null);
// Perform appropriate callback if needed for a disconnect
if (opts.getDisconnectedCallback() != null) {
logger.trace("Spawning disconnectCB from doReconnect()");
cbexec.submit(new Runnable() {
public void run() {
opts.getDisconnectedCallback().onDisconnect(new ConnectionEvent(nc));
}
});
logger.trace("Spawned disconnectCB from doReconnect()");
}
while (!srvPool.isEmpty()) {
Srv cur;
try {
cur = selectNextServer();
this.setUrl(cur.url);
} catch (IOException nse) {
setLastError(nse);
break;
}
long sleepTime = 0L;
// Sleep appropriate amount of time before the
// connection attempt if connecting to same server
// we just got disconnected from.
long timeSinceLastAttempt = cur.timeSinceLastAttempt();
if (timeSinceLastAttempt < opts.getReconnectWait()) {
sleepTime = opts.getReconnectWait() - timeSinceLastAttempt;
}
if (sleepTime > 0) {
mu.unlock();
Thread.sleep(sleepTime);
mu.lockInterruptibly();
}
// Check if we have been closed first.
if (isClosed()) {
logger.debug("Connection has been closed while in doReconnect()");
break;
}
// Mark that we tried a reconnect
cur.reconnects++;
// try to create a new connection
try {
// conn.teardown();