aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/fs4/mplex/FS4Connection.java
blob: 11e7d4e3d353dea144d112ad6055a13c558c0775 (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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

package com.yahoo.fs4.mplex;


import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.yahoo.fs4.BasicPacket;
import com.yahoo.fs4.BufferTooSmallException;
import com.yahoo.fs4.PacketDecoder;
import com.yahoo.fs4.PacketListener;
import com.yahoo.io.Connection;
import com.yahoo.io.Listener;
import com.yahoo.log.LogLevel;
import com.yahoo.search.Query;

/**
 *
 * This class is used to represent a connection to an fdispatch
 *
 * @author  <a href="mailto:borud@yahoo-inc.com">Bjorn Borud</a>
 */
public class FS4Connection implements Connection
{
    private static Logger log = Logger.getLogger(FS4Connection.class.getName());
    private Backend backend;
    private Listener listener;
    private SocketChannel channel;

    private boolean shouldWrite = false;

    private static int idCounter = 1;
    private int idNumber;
    private int maxInitialSize = 1024;

    // outbound data
    private ByteBuffer writeBuffer;
    private LinkedList<ByteBuffer> writeBufferList = new LinkedList<>();

    // inbound data
    private ByteBuffer fixedReadBuffer = ByteBuffer.allocateDirect(256 * 1024);
    private ByteBuffer readBuffer = fixedReadBuffer;

    private volatile boolean valid = true;

    private final PacketListener packetListener;


    /**
     * Create an FS4 Connection.
     */
    public FS4Connection (SocketChannel channel, Listener listener, Backend backend, PacketListener packetListener) {
        this.backend = backend;
        this.listener = listener;
        this.channel = channel;
        this.idNumber = idCounter++;
        this.packetListener = packetListener;

        log.log(Level.FINER, "new: "+this+", id="+idNumber + ", address=" + backend.getAddress());
    }


    /**
     * Packet sending interface.
     */
    public void sendPacket (BasicPacket packet, Integer channelId) throws IOException {
        ByteBuffer buffer = packet.grantEncodingBuffer(channelId.intValue(), maxInitialSize);
        ByteBuffer viewForPacketListener = buffer.slice();
        synchronized (this) {
            if (!(valid && channel.isOpen())) {
                throw new IllegalStateException("Connection is not valid. " +
                        "Address = " + backend.getAddress()  +
                        ", valid = " + valid +
                        ", isOpen = " + channel.isOpen());
            }

            if (buffer.capacity() > maxInitialSize) {
                maxInitialSize = buffer.limit();
            }
            if (writeBuffer == null) {
                writeBuffer = buffer;
            } else {
                writeBufferList.addLast(buffer);
                enableWrite();
            }
            write();
        }

        if (packetListener != null)
            packetListener.packetSent(backend.getChannel(channelId), packet, viewForPacketListener);
    }


    /**
     * The write event handler.  This can be called both from the client
     * thread and from the IO thread, so it needs to be synchronized.  It
     * assumes that IO is nonblocking, and will attempt to keep writing
     * data until the system won't accept more data.
     *
     */
    public synchronized void write () throws IOException {
        if (! channel.isOpen()) {
            throw new IllegalStateException("Channel not open in write(), address=" + backend.getAddress());
        }

        try {
            int bytesWritten = 0;
            boolean isFinished = false;
            do {
                // if writeBuffer is not set we need to fetch the next buffer
                if (writeBuffer == null) {

                    // if the list is empty, signal the selector we do not need
                    // to do any writing for a while yet and bail
                    if (writeBufferList.isEmpty()) {
                        disableWrite();
                        isFinished = true;
                        break;
                    }
                    writeBuffer = writeBufferList.removeFirst();
                }

                // invariants: we have a writeBuffer
                bytesWritten = channel.write(writeBuffer);

                // buffer drained so we forget it and see what happens when we
                // go around.  if indeed we go around
                if (!writeBuffer.hasRemaining()) {
                    writeBuffer = null;
                }
            } while (bytesWritten > 0);
            if (!isFinished) {
                enableWrite();
            }
        } catch (IOException e) {
            log.log(LogLevel.DEBUG, "Failed writing to channel for backend "  + backend.getAddress() +
                    ". Closing channel", e);
            try {
                close();
            } catch (IOException ignored) {}

            throw e;
        }
    }


    private void disableWrite() {
        if (shouldWrite) {
            listener.modifyInterestOpsBatch(this, SelectionKey.OP_WRITE, false);
            shouldWrite = false;
        }
    }


    private void enableWrite() {
        if (!shouldWrite) {
            listener.modifyInterestOps(this, SelectionKey.OP_WRITE, true);
            shouldWrite = true;
        }
    }



    public void read () throws IOException {
        if (! channel.isOpen()) {
            throw new IOException("Channel not open in read(), address=" + backend.getAddress());
        }

        int bytesRead = 0;

        do {
            try {
                if (readBuffer == fixedReadBuffer) {
                    bytesRead = channel.read(readBuffer);
                } else {
                    fixedReadBuffer.clear();
                    if (readBuffer.remaining() < fixedReadBuffer.capacity()) {
                        fixedReadBuffer.limit(readBuffer.remaining());
                    }
                    bytesRead = channel.read(fixedReadBuffer);
                    fixedReadBuffer.flip();
                    readBuffer.put(fixedReadBuffer);
                    fixedReadBuffer.clear();
                }
            }
            catch (IOException e) {
                // this is the "normal" way that connection closes.
                log.log(Level.FINER, "Read exception address=" + backend.getAddress() + " id="+idNumber+": "+
                        e.getClass().getName()+" / ", e);
                bytesRead = -1;
            }

            // end of file
            if (bytesRead == -1) {
                log.log(LogLevel.DEBUG, "Dispatch closed connection"
                        + " (id="+idNumber+", address=" + backend.getAddress() + ")");
                try {
                    close();
                } catch (Exception e) {
                    log.log(Level.WARNING, "Close failed, address=" + backend.getAddress(), e);
                }
            }

            // no more read
            if (bytesRead == 0) {
                // buffer too small?
                if (! readBuffer.hasRemaining()) {
                    log.fine("Buffer possibly too small, extending");
                    readBuffer.flip();
                    extendReadBuffer(readBuffer.capacity() * 2);
                }
            }

        } while (bytesRead > 0);

        readBuffer.flip();

        // hand off packet extraction
        extractPackets(readBuffer);
    }

    private void extractPackets(ByteBuffer readBuffer) {
        for (;;) {
            PacketDecoder.DecodedPacket packet = null;
            try {
                FS4Channel receiver = null;
                int queryId = PacketDecoder.sniffChannel(readBuffer);
                if (queryId == 0) {
                    if (PacketDecoder.isPongPacket(readBuffer))
                        receiver = backend.getPingChannel();
                }
                else {
                    receiver = backend.getChannel(Integer.valueOf(queryId));
                }
                packet = PacketDecoder.extractPacket(readBuffer);

                if (packet != null)
                    packetListener.packetReceived(receiver, packet.packet, packet.consumedBytes);
            }
            catch (BufferTooSmallException e) {
                log.fine("Unable to decode, extending readBuffer");
                extendReadBuffer(PacketDecoder.packetLength(readBuffer));
                return;
            }

            // break out of loop if we did not get a packet out of the
            // buffer so we can select and read some more
            if (packet == null) {

                // if the buffer has been cleared, we can do a reset
                // of the readBuffer
                if ((readBuffer.position() == 0)
                    && (readBuffer.limit() == readBuffer.capacity()))
                {
                    resetReadBuffer();
                }
                break;
            }

            backend.receivePacket(packet.packet);
        }
    }

    /**
     * This is called when we close the connection to do any
     * pending cleanup work.  Closing a connection marks it as
     * not valid.
     */
    public void close () throws IOException {
        valid = false;
        channel.close();
        log.log(Level.FINER, "invalidated id="+idNumber + " address=" + backend.getAddress());
    }

    /**
     * Upon asynchronous connect completion this method is called by
     * the Listener.
     */
    public void connect() throws IOException {
        throw new RuntimeException("connect() was called, address=" + backend.getAddress() + ".  "
                                   + "asynchronous connect in NIO is flawed!");
    }

    /**
     * Since we are performing an asynchronous connect we are initially
     * only interested in the <code>OP_CONNECT</code> event.
     */
    public int selectOps () {
        return SelectionKey.OP_READ;
    }

    /**
     * Return the underlying SocketChannel used by this connection.
     */
    public SocketChannel socketChannel() {
        return channel;
    }


    public String toString () {
        return FS4Connection.class.getName() + "/" + channel;
    }


    //============================================================
    //==== readbuffer management
    //============================================================


    /**
     * Extend the readBuffer.  Make a new buffer of the requested size
     * copy the contents of the readBuffer into it and assign reference
     * to readBuffer instance variable.
     *
     * <P>
     * <b>The readBuffer needs to be in "readable" (flipped) state before
     * this is called and it will be in the "writeable" state when it
     * returns.</b>
     */
    private void extendReadBuffer (int size) {
        // we specifically check this because packetLength() can return -1
        // and someone might alter the code so that we do in fact get -1
        // ...which never happens as the code is now
        //
        if (size == -1) {
            throw new RuntimeException("Invalid buffer size requested: -1");
        }

        // if we get a size that is smaller than the current
        // readBuffer capacity we just double it.  not sure how wise this
        // might be.
        //
        if (size < readBuffer.capacity()) {
            size = readBuffer.capacity() * 2;
        }

        ByteBuffer tmp = ByteBuffer.allocate(size);
        tmp.put(readBuffer);
        log.fine("Extended readBuffer to " + size + " bytes"
                 + "from " + readBuffer.capacity() + " bytes");
        readBuffer = tmp;
    }

    /**
     * Clear the readBuffer, and if temporarily allocated bigger
     * buffer is in use: ditch it and reset the reference to the
     * fixed readBuffer.
     */
    private void resetReadBuffer () {
        fixedReadBuffer.clear();
        if (readBuffer == fixedReadBuffer) {
            return;
        }
        log.fine("Resetting readbuffer");
        readBuffer = fixedReadBuffer;
    }

    /**
     * This method is used to determine whether the connection is still
     * viable or not.  All connections are initially valid, but they
     * become invalid if we close the connection or something bad happens
     * and the connection needs to be ditched.
     */
    public boolean isValid() {
        return valid;
    }

}