aboutsummaryrefslogtreecommitdiffstats
path: root/jrt/src/com/yahoo/jrt/Connection.java
blob: db9dc629aeba75f490f226ac14ba69e559e99ff4 (plain) (blame)
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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;

import com.yahoo.security.tls.ConnectionAuthContext;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;


class Connection extends Target {

    private static final Logger log = Logger.getLogger(Connection.class.getName());

    private static final int READ_SIZE  = 16*1024;
    private static final int READ_REDO  = 10;
    private static final int WRITE_SIZE = 16*1024;
    private static final int WRITE_REDO = 10;

    private static final int INITIAL    = 0;
    private static final int CONNECTING = 1;
    private static final int CONNECTED  = 2;
    private static final int CLOSED     = 3;

    private int state = INITIAL;
    private final Queue  queue   = new Queue();
    private final Queue  myQueue = new Queue();
    private final Buffer input   = new Buffer(0); // Start off with empty buffer.
    private final Buffer output  = new Buffer(0); // Start off with empty buffer.
    private final int maxInputSize;
    private final int maxOutputSize;
    private final boolean dropEmptyBuffers;
    private final boolean tcpNoDelay;
    private final Map<Integer, ReplyHandler> replyMap = new HashMap<>();
    private final Map<TargetWatcher, TargetWatcher> watchers = new IdentityHashMap<>();
    private int writeWork  = 0;
    private boolean pendingHandshakeWork = false;
    private final TransportThread parent;
    private final Supervisor owner;
    private final Spec spec;
    private CryptoSocket socket;
    private int readSize = READ_SIZE;
    private final boolean server;
    private final AtomicLong requestId = new AtomicLong(0);
    private SelectionKey selectionKey;
    private Exception lostReason = null;

    private void setState(int state) {
        if (state <= this.state) {
            log.log(Level.WARNING, "Bogus state transition: " + this.state + "->" + state);
            return;
        }
        boolean live = (state == CONNECTED);
        boolean down = (state == CLOSED);
        boolean pendingWrite;
        synchronized (this) {
            this.state = state;
            pendingWrite = (writeWork > 0);
        }
        if (live) {
            enableRead();
            if (pendingWrite) {
                enableWrite();
            } else {
                disableWrite();
            }
        }
        if (down) {
            for (ReplyHandler rh : replyMap.values()) {
                rh.handleConnectionDown();
            }
            for (TargetWatcher watcher : watchers.values()) {
                watcher.notifyTargetInvalid(this);
            }
        }
    }

    public Connection(TransportThread parent, Supervisor owner,
                      SocketChannel channel, boolean tcpNoDelay) {

        this.parent = parent;
        this.owner = owner;
        this.socket = parent.transport().createServerCryptoSocket(channel);
        this.spec = null;
        this.tcpNoDelay = tcpNoDelay;
        maxInputSize = owner.getMaxInputBufferSize();
        maxOutputSize = owner.getMaxOutputBufferSize();
        dropEmptyBuffers = owner.getDropEmptyBuffers();
        server = true;
    }

    public Connection(TransportThread parent, Supervisor owner, Spec spec, Object context, boolean tcpNoDelay) {
        super(context);
        this.parent = parent;
        this.owner = owner;
        this.spec = spec;
        this.tcpNoDelay = tcpNoDelay;
        maxInputSize = owner.getMaxInputBufferSize();
        maxOutputSize = owner.getMaxOutputBufferSize();
        dropEmptyBuffers = owner.getDropEmptyBuffers();
        server = false;
    }

    public TransportThread transportThread() {
        return parent;
    }

    public int allocateKey() {
        long v = requestId.getAndIncrement();
        v = v*2 + (server ? 1 : 0);
        return (int)(v & 0x7fffffff);
    }

    public synchronized boolean cancelReply(ReplyHandler handler) {
        if (state == CLOSED) {
            return false;
        }
        ReplyHandler stored = replyMap.remove(handler.key());
        if (stored != handler) {
            if (stored != null) {
                replyMap.put(handler.key(), stored);
            }
            return false;
        }
        return true;
    }

    public boolean postPacket(Packet packet, ReplyHandler handler) {
        boolean accepted = false;
        boolean enableWrite = false;
        synchronized (this) {
            if (state <= CONNECTED) {
                enableWrite = (writeWork == 0 && state == CONNECTED);
                queue.enqueue(packet);
                writeWork++;
                accepted = true;
                if (handler != null) {
                    replyMap.put(handler.key(), handler);
                }
            }
        }
        if (enableWrite) {
            parent.enableWrite(this);
        }
        return accepted;
    }

    public boolean postPacket(Packet packet) {
        return postPacket(packet, null);
    }

    public Connection connect() {
        if (spec == null || spec.malformed()) {
            setLostReason(new IllegalArgumentException("jrt: malformed or missing spec"));
            return this;
        }
        try {
            socket = parent.transport().createClientCryptoSocket(SocketChannel.open(spec.resolveAddress()), spec);
        } catch (Exception e) {
            setLostReason(e);
        }
        return this;
    }

    public boolean init(Selector selector) {
        if (!hasSocket()) {
            return false;
        }
        try {
            socket.channel().configureBlocking(false);
            socket.channel().socket().setTcpNoDelay(tcpNoDelay);
            selectionKey = socket.channel().register(selector,
                    SelectionKey.OP_READ | SelectionKey.OP_WRITE,
                    this);
        } catch (Exception e) {
            log.log(Level.WARNING, "Error initializing connection", e);
            setLostReason(e);
            return false;
        }
        setState(CONNECTING);
        return true;
    }

    public void enableRead() {
        selectionKey.interestOps(selectionKey.interestOps()
                                 | SelectionKey.OP_READ);
    }

    public void disableRead() {
        selectionKey.interestOps(selectionKey.interestOps()
                                 & ~SelectionKey.OP_READ);
    }

    public void enableWrite() {
        selectionKey.interestOps(selectionKey.interestOps()
                                 | SelectionKey.OP_WRITE);
    }

    public void disableWrite() {
        selectionKey.interestOps(selectionKey.interestOps()
                                 & ~SelectionKey.OP_WRITE);
    }

    private void handshake() throws IOException {
        if (pendingHandshakeWork) {
            return;
        }
        switch (socket.handshake()) {
        case DONE:
            if (socket.getMinimumReadBufferSize() > readSize) {
                readSize = socket.getMinimumReadBufferSize();
            }
            setState(CONNECTED);
            while (socket.drain(input.getWritable(readSize)) > 0) {
                handlePackets();
            }
            break;
        case NEED_READ:
            enableRead();
            disableWrite();
            break;
        case NEED_WRITE:
            disableRead();
            enableWrite();
            break;
        case NEED_WORK:
            disableRead();
            disableWrite();
            pendingHandshakeWork = true;
            parent.transport().doHandshakeWork(this);
            break;
        }
    }

    public void doHandshakeWork() {
       socket.doHandshakeWork();
    }

    public void handleHandshakeWorkDone() throws IOException {
        if (!pendingHandshakeWork) {
            throw new IllegalStateException("jrt: got unwanted handshake work done event");
        }
        pendingHandshakeWork = false;
        if (state == CONNECTING) {
            handshake();
        } else {
            throw new IOException("jrt: got handshake work done event in incompatible state: " + state);
        }
    }

    private void handlePackets() throws IOException {
        ByteBuffer rb = input.getReadable();
        while (true) {
            PacketInfo info = PacketInfo.getPacketInfo(rb);
            if (info == null || info.packetLength() > rb.remaining()) {
                break;
            }
            owner.readPacket(info);
            Packet packet;
            try {
                packet = info.decodePacket(rb);
            } catch (RuntimeException e) {
                log.log(Level.WARNING, "got garbage; closing connection: " + this);
                throw new IOException("jrt: decode error", e);
            }
            ReplyHandler handler;
            synchronized (this) {
                handler = replyMap.remove(packet.requestId());
            }
            if (handler != null) {
                handler.handleReply(packet);
            } else {
                owner.handlePacket(this, packet);
            }
        }
    }

    private void read() throws IOException {
        boolean doneRead = false;
        for (int i = 0; !doneRead && i < READ_REDO; i++) {
            ByteBuffer wb = input.getWritable(readSize);
            if (socket.read(wb) == -1) {
                throw new IOException("jrt: Connection closed by peer");
            }
            doneRead = (wb.remaining() > 0);
            handlePackets();
        }
        while (socket.drain(input.getWritable(readSize)) > 0) {
            handlePackets();
        }
        if (dropEmptyBuffers) {
            socket.dropEmptyBuffers();
            input.shrink(0);
        }
        if (maxInputSize > 0) {
            input.shrink(maxInputSize);
        }
    }

    public void handleReadEvent() throws IOException {
        if (state == CONNECTED) {
            read();
        } else if (state == CONNECTING) {
            handshake();
        } else {
            throw new IOException("jrt: got read event in incompatible state: " + state);
        }
    }

    private void write() throws IOException {
        synchronized (this) {
            queue.flush(myQueue);
        }
        for (int i = 0; i < WRITE_REDO; i++) {
            while (output.bytes() < WRITE_SIZE) {
                Packet packet = (Packet) myQueue.dequeue();
                if (packet == null) {
                    break;
                }
                PacketInfo info = packet.getPacketInfo();
                ByteBuffer wb = output.getWritable(info.packetLength());
                owner.writePacket(info);
                info.encodePacket(packet, wb);
            }
            ByteBuffer rb = output.getReadable();
            if (rb.remaining() == 0) {
                break;
            }
            socket.write(rb);
            if (rb.remaining() > 0) {
                break;
            }
        }
        int myWriteWork = 0;
        if (output.bytes() > 0) {
            myWriteWork++;
        }
        if (socket.flush() == CryptoSocket.FlushResult.NEED_WRITE) {
            myWriteWork++;
        }
        boolean disableWrite;
        synchronized (this) {
            writeWork = queue.size()
                        + myQueue.size()
                        + myWriteWork;
            disableWrite = (writeWork == 0);
        }
        if (disableWrite) {
            disableWrite();
        }
        if (dropEmptyBuffers) {
            socket.dropEmptyBuffers();
            output.shrink(0);
        }
        if (maxOutputSize > 0) {
            output.shrink(maxOutputSize);
        }
    }

    public void handleWriteEvent() throws IOException {
        if (state == CONNECTED) {
            write();
        } else if (state == CONNECTING) {
            handshake();
        } else {
            throw new IOException("jrt: got write event in incompatible state: " + state);
        }
    }

    public void fini() {
        setState(CLOSED);
        if (selectionKey != null) {
            selectionKey.cancel();
        }
    }

    public boolean isClosed() {
        return (state == CLOSED);
    }

    public synchronized boolean isConnected() {
        return (state == CONNECTED);
    }

    public boolean hasSocket() {
        return ((socket != null) && (socket.channel() != null));
    }

    public void closeSocket() {
        if (hasSocket()) {
            try {
                socket.channel().socket().close();
            } catch (Exception e) {
                log.log(Level.WARNING, "Error closing connection", e);
            }
        }
    }

    public void setLostReason(Exception e) {
        if (lostReason == null) {
            lostReason = e;
        }
    }

    public TieBreaker startRequest() {
        return new TieBreaker();
    }

    public boolean completeRequest(TieBreaker done) {
        synchronized (this) {
            if (!done.first()) {
                return false;
            }
        }

        return true;
    }

    ///////////////////////////////////////////////////////////////////////////
    // Methods defined in the Target superclass
    ///////////////////////////////////////////////////////////////////////////

    public boolean isValid() {
        return (state != CLOSED);
    }

    public Exception getConnectionLostReason() {
        return lostReason;
    }

    @Override
    public ConnectionAuthContext connectionAuthContext() {
        if (socket == null) throw new IllegalStateException("Not connected");
        return socket.connectionAuthContext();
    }

    @Override
    public Spec peerSpec() {
        if (socket == null) throw new IllegalStateException("Not connected");
        InetSocketAddress addr = (InetSocketAddress) socket.channel().socket().getRemoteSocketAddress();
        return new Spec(addr.getHostString(), addr.getPort());
    }

    public boolean isClient() {
        return !server;
    }

    public boolean isServer() {
        return server;
    }

    public void invokeSync(Request req, double timeout) {
        SingleRequestWaiter waiter = new SingleRequestWaiter();
        invokeAsync(req, timeout, waiter);
        waiter.waitDone();
    }

    public void invokeAsync(Request req, double timeout, RequestWaiter waiter) {
        if (timeout < 0.0) {
            timeout = 0.0;
        }
        new InvocationClient(this, req, timeout, waiter).invoke();
    }

    public boolean invokeVoid(Request req) {
        return postPacket(new RequestPacket(Packet.FLAG_NOREPLY,
                                            allocateKey(),
                                            req.methodName(),
                                            req.parameters()));
    }

    public synchronized boolean addWatcher(TargetWatcher watcher) {
        if (state == CLOSED) {
            return false;
        }
        watchers.put(watcher, watcher);
        return true;
    }

    public synchronized boolean removeWatcher(TargetWatcher watcher) {
        if (state == CLOSED) {
            return false;
        }
        watchers.remove(watcher);
        return true;
    }

    public void close() {
        parent.closeConnection(this);
    }

    public String toString() {
        if (hasSocket()) {
            return "Connection { " + socket.channel().socket() + " }";
        }
        return "Connection { no socket, spec " + spec + " }";
    }
}