ClientHandler.java 17.7 KB
Newer Older
H
He Wang 已提交
1 2 3 4 5 6 7 8 9 10 11 12
/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
oblogclient is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

package com.oceanbase.clogproxy.client.connection;

13

H
He Wang 已提交
14
import com.google.protobuf.InvalidProtocolBufferException;
15
import com.oceanbase.clogproxy.client.config.ClientConf;
H
He Wang 已提交
16 17 18 19 20 21 22
import com.oceanbase.clogproxy.client.enums.ErrorCode;
import com.oceanbase.clogproxy.client.exception.LogProxyClientException;
import com.oceanbase.clogproxy.common.packet.CompressType;
import com.oceanbase.clogproxy.common.packet.HeaderType;
import com.oceanbase.clogproxy.common.packet.ProtocolVersion;
import com.oceanbase.clogproxy.common.packet.protocol.LogProxyProto;
import com.oceanbase.clogproxy.common.util.NetworkUtil;
23
import com.oceanbase.oms.logmessage.LogMessage;
H
He Wang 已提交
24 25 26 27 28 29 30
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.ByteToMessageDecoder.Cumulator;
import io.netty.handler.timeout.IdleStateEvent;
31
import java.util.concurrent.BlockingQueue;
H
He Wang 已提交
32 33 34 35 36 37
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4FastDecompressor;
import org.apache.commons.lang3.Conversion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

38
/** This is an implementation class of {@link ChannelInboundHandlerAdapter}. */
H
He Wang 已提交
39 40 41 42
public class ClientHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(ClientHandler.class);

43 44
    /** Magic string used to request log proxy. */
    private static final byte[] MAGIC_STRING = new byte[] {'x', 'i', '5', '3', 'g', ']', 'q'};
45

46
    /** Client ip address. */
H
He Wang 已提交
47 48
    private static final String CLIENT_IP = NetworkUtil.getLocalIp();

49
    /** Length of packet header. */
50 51
    private static final int HEAD_LENGTH = 7;

52
    /** A client stream. */
H
He Wang 已提交
53
    private ClientStream stream;
54

55
    /** Connection params. */
H
He Wang 已提交
56
    private ConnectionParams params;
57 58 59 60

    /**
     * Record queue, it's a {@link BlockingQueue} for storing {@link StreamContext.TransferPacket}.
     */
H
He Wang 已提交
61 62
    private BlockingQueue<StreamContext.TransferPacket> recordQueue;

63
    /** Handshake type enumeration. */
H
He Wang 已提交
64
    enum HandshakeStateV1 {
65
        /** State of parsing the packet header. */
H
He Wang 已提交
66
        PB_HEAD,
67
        /** State of handling handshake response. */
H
He Wang 已提交
68
        CLIENT_HANDSHAKE_RESPONSE,
69
        /** State of handling record. */
H
He Wang 已提交
70
        RECORD,
71
        /** State of handling error response. */
H
He Wang 已提交
72
        ERROR_RESPONSE,
73
        /** State of handling runtime status response. */
H
He Wang 已提交
74 75 76
        STATUS
    }

77
    /** Handshake state. */
H
He Wang 已提交
78 79
    private HandshakeStateV1 state = HandshakeStateV1.PB_HEAD;

80
    /** A {@link Cumulator} instance. */
H
He Wang 已提交
81
    private final Cumulator cumulator = ByteToMessageDecoder.MERGE_CUMULATOR;
82

83
    /** A {@link ByteBuf} used for channel reading. */
H
He Wang 已提交
84
    ByteBuf buffer;
85

86
    /** A flag of whether channel is active. */
H
He Wang 已提交
87
    private boolean poolFlag = true;
88

89
    /** A flag of whether it is the first part of {@link ByteBuf}. */
H
He Wang 已提交
90
    private boolean first;
91

92
    /** Number of read attempts. */
H
He Wang 已提交
93
    private int numReads = 0;
94

95
    /** A flag of whether the message is not readable. */
H
He Wang 已提交
96
    private boolean dataNotEnough = false;
97

98
    /** The length of message body. */
H
He Wang 已提交
99 100
    private int dataLength = 0;

101
    /** A {@link LZ4Factory} instance. */
H
He Wang 已提交
102
    LZ4Factory factory = LZ4Factory.fastestInstance();
103

104
    /** A {@link LZ4FastDecompressor} instance. */
H
He Wang 已提交
105 106
    LZ4FastDecompressor fastDecompressor = factory.fastDecompressor();

107 108
    /** Constructor with empty arguments. */
    public ClientHandler() {}
H
He Wang 已提交
109

110
    /** Reset {@link #state} to {@link HandshakeStateV1#PB_HEAD}. */
H
He Wang 已提交
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
    protected void resetState() {
        state = HandshakeStateV1.PB_HEAD;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf) {
            dataNotEnough = false;
            ByteBuf data = (ByteBuf) msg;
            first = buffer == null;
            if (first) {
                buffer = data;
            } else {
                buffer = cumulator.cumulate(ctx.alloc(), buffer, data);
            }
        } else if (msg instanceof IdleStateEvent) {
            if (stream != null) {
                stream.triggerReconnect();
            }
            return;
        } else {
            return;
        }

        while (poolFlag && buffer.isReadable() && !dataNotEnough) {
            switch (state) {
                case PB_HEAD:
                    handleHeader();
                    break;
                case CLIENT_HANDSHAKE_RESPONSE:
                    handleHandshakeResponse();
                    break;
                case ERROR_RESPONSE:
                    handleErrorResponse();
                    break;
                case STATUS:
                    handleServerStatus();
                    break;
                case RECORD:
                    handleRecord();
                    break;
            }
        }

        if (buffer != null && !buffer.isReadable()) {
            numReads = 0;
            buffer.release();
            buffer = null;
        } else if (++numReads >= ClientConf.NETTY_DISCARD_AFTER_READS) {
            numReads = 0;
            discardSomeReadBytes();
        }
    }

165
    /** Handle header response. */
H
He Wang 已提交
166 167 168 169 170 171 172 173
    private void handleHeader() {
        if (buffer.readableBytes() >= HEAD_LENGTH) {
            int version = buffer.readShort();
            int type = buffer.readByte();
            dataLength = buffer.readInt();
            checkHeader(version, type, dataLength);

            HeaderType headerType = HeaderType.codeOf(type);
174
            if (headerType == HeaderType.HANDSHAKE_RESPONSE_CLIENT) {
H
He Wang 已提交
175
                state = HandshakeStateV1.CLIENT_HANDSHAKE_RESPONSE;
176
            } else if (headerType == HeaderType.ERROR_RESPONSE) {
H
He Wang 已提交
177
                state = HandshakeStateV1.ERROR_RESPONSE;
178
            } else if (headerType == HeaderType.DATA_CLIENT) {
H
He Wang 已提交
179
                state = HandshakeStateV1.RECORD;
180
            } else if (headerType == HeaderType.STATUS) {
H
He Wang 已提交
181 182 183 184 185 186 187
                state = HandshakeStateV1.STATUS;
            }
        } else {
            dataNotEnough = true;
        }
    }

188
    /** Handle handshake response. */
H
He Wang 已提交
189
    private void handleHandshakeResponse() throws InvalidProtocolBufferException {
190
        if (buffer.readableBytes() >= dataLength) {
H
He Wang 已提交
191 192
            byte[] bytes = new byte[dataLength];
            buffer.readBytes(bytes);
193 194 195 196 197 198
            LogProxyProto.ClientHandshakeResponse response =
                    LogProxyProto.ClientHandshakeResponse.parseFrom(bytes);
            logger.info(
                    "Connected to LogProxyServer, ip:{}, version:{}",
                    response.getIp(),
                    response.getVersion());
H
He Wang 已提交
199 200 201 202 203 204
            state = HandshakeStateV1.PB_HEAD;
        } else {
            dataNotEnough = true;
        }
    }

205
    /** Handle error response. */
H
He Wang 已提交
206
    private void handleErrorResponse() throws InvalidProtocolBufferException {
207
        if (buffer.readableBytes() >= dataLength) {
H
He Wang 已提交
208 209 210 211
            byte[] bytes = new byte[dataLength];
            buffer.readBytes(bytes);
            LogProxyProto.ErrorResponse response = LogProxyProto.ErrorResponse.parseFrom(bytes);
            logger.error("LogProxy refused handshake request: {}", response.toString());
212 213 214
            throw new LogProxyClientException(
                    ErrorCode.NO_AUTH,
                    "LogProxy refused handshake request: " + response.toString());
H
He Wang 已提交
215 216 217 218 219
        } else {
            dataNotEnough = true;
        }
    }

220
    /** Handle server status response. */
H
He Wang 已提交
221
    private void handleServerStatus() throws InvalidProtocolBufferException {
222
        if (buffer.readableBytes() >= dataLength) {
H
He Wang 已提交
223 224 225 226 227 228 229 230 231 232
            byte[] bytes = new byte[dataLength];
            buffer.readBytes(bytes);
            LogProxyProto.RuntimeStatus response = LogProxyProto.RuntimeStatus.parseFrom(bytes);
            logger.debug("server status: {}", response.toString());
            state = HandshakeStateV1.PB_HEAD;
        } else {
            dataNotEnough = true;
        }
    }

233
    /** Handle record data response. */
H
He Wang 已提交
234
    private void handleRecord() {
235
        if (buffer.readableBytes() >= dataLength) {
H
He Wang 已提交
236 237 238 239 240 241 242
            parseDataNew();
            state = HandshakeStateV1.PB_HEAD;
        } else {
            dataNotEnough = true;
        }
    }

243 244 245 246
    /**
     * Check if the header is valid.
     *
     * @param version Protocol version.
247 248
     * @param type Header type.
     * @param length Data length.
249
     */
H
He Wang 已提交
250 251 252
    private void checkHeader(int version, int type, int length) {
        if (ProtocolVersion.codeOf(version) == null) {
            logger.error("unsupported protocol version: {}", version);
253 254
            throw new LogProxyClientException(
                    ErrorCode.E_PROTOCOL, "unsupported protocol version: " + version);
H
He Wang 已提交
255 256 257
        }
        if (HeaderType.codeOf(type) == null) {
            logger.error("unsupported header type: {}", type);
258 259
            throw new LogProxyClientException(
                    ErrorCode.E_HEADER_TYPE, "unsupported header type: " + type);
H
He Wang 已提交
260 261 262 263 264 265 266
        }
        if (length <= 0) {
            logger.error("data length equals 0");
            throw new LogProxyClientException(ErrorCode.E_LEN, "data length equals 0");
        }
    }

267
    /** Do parse record data from buffer. It will firstly decompress the raw data if necessary. */
H
He Wang 已提交
268 269 270 271 272 273 274 275 276 277
    private void parseDataNew() {
        try {
            byte[] buff = new byte[dataLength];
            buffer.readBytes(buff, 0, dataLength);
            LogProxyProto.RecordData recordData = LogProxyProto.RecordData.parseFrom(buff);
            int compressType = recordData.getCompressType();
            int compressedLen = recordData.getCompressedLen();
            int rawLen = recordData.getRawLen();
            byte[] rawData = recordData.getRecords().toByteArray();
            if (compressType == CompressType.LZ4.code()) {
F
Fankux 已提交
278 279 280
                byte[] bytes = new byte[rawLen];
                int decompress = fastDecompressor.decompress(rawData, 0, bytes, 0, rawLen);
                if (decompress != compressedLen) {
281 282 283 284 285 286 287
                    throw new LogProxyClientException(
                            ErrorCode.E_LEN,
                            "decompressed length ["
                                    + decompress
                                    + "] is not expected ["
                                    + rawLen
                                    + "]");
H
He Wang 已提交
288 289 290 291 292 293 294 295 296 297
                }
                parseRecord(bytes);
            } else {
                parseRecord(rawData);
            }
        } catch (InvalidProtocolBufferException e) {
            throw new LogProxyClientException(ErrorCode.E_PARSE, "Failed to read PB packet", e);
        }
    }

298
    /**
299 300
     * Do parse record data from an array of bytes to a {@link LogMessage} and add it into {@link
     * #recordQueue}.
301 302 303 304
     *
     * @param bytes An array of bytes of record data.
     * @throws LogProxyClientException If exception occurs.
     */
H
He Wang 已提交
305 306 307 308
    private void parseRecord(byte[] bytes) throws LogProxyClientException {
        int offset = 0;
        while (offset < bytes.length) {
            int dataLength = Conversion.byteArrayToInt(bytes, offset + 4, 0, 0, 4);
309
            LogMessage logMessage;
H
He Wang 已提交
310 311 312 313
            try {
                /*
                 * We must copy a byte array and call parse after then,
                 * or got a !!!RIDICULOUS EXCEPTION!!!,
314
                 * if we wrap an unpooled buffer with offset and call setByteBuf just as same as `parse` function do.
H
He Wang 已提交
315
                 */
316
                logMessage = new LogMessage(false);
H
He Wang 已提交
317 318
                byte[] data = new byte[dataLength + 8];
                System.arraycopy(bytes, offset, data, 0, data.length);
319
                logMessage.parse(data);
H
He Wang 已提交
320 321
                if (ClientConf.IGNORE_UNKNOWN_RECORD_TYPE) {
                    // unsupported type, ignore
322
                    logger.debug("Unsupported record type: {}", logMessage);
H
He Wang 已提交
323 324 325 326 327 328 329 330 331 332
                    offset += (8 + dataLength);
                    continue;
                }

            } catch (Exception e) {
                throw new LogProxyClientException(ErrorCode.E_PARSE, e);
            }

            while (true) {
                try {
333
                    recordQueue.put(new StreamContext.TransferPacket(logMessage));
H
He Wang 已提交
334 335 336 337 338 339 340 341 342 343
                    break;
                } catch (InterruptedException e) {
                    // do nothing
                }
            }

            offset += (8 + dataLength);
        }
    }

344
    /** Discard the bytes in buffer. */
H
He Wang 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    protected final void discardSomeReadBytes() {
        if (buffer != null && !first && buffer.refCnt() == 1) {
            // discard some bytes if possible to make more room in the
            // buffer but only if the refCnt == 1  as otherwise the user may have
            // used slice().retain() or duplicate().retain().
            //
            // See:
            // - https://github.com/netty/netty/issues/2327
            // - https://github.com/netty/netty/issues/1764
            buffer.discardSomeReadBytes();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        poolFlag = true;

        StreamContext context = ctx.channel().attr(ConnectionFactory.CONTEXT_KEY).get();
        stream = context.stream();
        params = context.getParams();
        recordQueue = context.recordQueue();

367 368 369 370
        logger.info(
                "ClientId: {} connecting LogProxy: {}",
                params.info(),
                NetworkUtil.parseRemoteAddress(ctx.channel()));
H
He Wang 已提交
371 372 373
        ctx.channel().writeAndFlush(generateConnectRequest(params.getProtocolVersion()));
    }

374 375 376 377 378
    /**
     * Generate the request body for protocol v2.
     *
     * @return Request body.
     */
H
He Wang 已提交
379
    public ByteBuf generateConnectRequestV2() {
380 381 382 383 384 385 386 387 388
        LogProxyProto.ClientHandshakeRequest handShake =
                LogProxyProto.ClientHandshakeRequest.newBuilder()
                        .setLogType(params.getLogType().code())
                        .setIp(CLIENT_IP)
                        .setId(params.getClientId())
                        .setVersion(ClientConf.VERSION)
                        .setEnableMonitor(params.isEnableMonitor())
                        .setConfiguration(params.getConfigurationString())
                        .build();
H
He Wang 已提交
389 390

        byte[] packetBytes = handShake.toByteArray();
391 392 393
        ByteBuf byteBuf =
                ByteBufAllocator.DEFAULT.buffer(
                        MAGIC_STRING.length + 2 + 1 + 4 + packetBytes.length);
H
He Wang 已提交
394 395 396 397 398 399 400 401
        byteBuf.writeBytes(MAGIC_STRING);
        byteBuf.writeShort(ProtocolVersion.V2.code());
        byteBuf.writeByte(HeaderType.HANDSHAKE_REQUEST_CLIENT.code());
        byteBuf.writeInt(packetBytes.length);
        byteBuf.writeBytes(packetBytes);
        return byteBuf;
    }

402 403 404 405 406 407
    /**
     * Generate the request body.
     *
     * @param version Protocol version.
     * @return Request body.
     */
H
He Wang 已提交
408 409 410 411 412 413 414 415 416 417 418 419
    public ByteBuf generateConnectRequest(ProtocolVersion version) {
        if (version == ProtocolVersion.V2) {
            return generateConnectRequestV2();
        }

        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(MAGIC_STRING.length);
        byteBuf.writeBytes(MAGIC_STRING);

        // header
        byteBuf.capacity(byteBuf.capacity() + 2 + 4 + 1);
        byteBuf.writeShort(ProtocolVersion.V0.code());
        byteBuf.writeInt(HeaderType.HANDSHAKE_REQUEST_CLIENT.code());
420
        byteBuf.writeByte(params.getLogType().code());
H
He Wang 已提交
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

        // body
        int length = CLIENT_IP.length();
        byteBuf.capacity(byteBuf.capacity() + length + 4);
        byteBuf.writeInt(length);
        byteBuf.writeBytes(CLIENT_IP.getBytes());

        length = params.getClientId().length();
        byteBuf.capacity(byteBuf.capacity() + length + 4);
        byteBuf.writeInt(length);
        byteBuf.writeBytes(params.getClientId().getBytes());

        length = ClientConf.VERSION.length();
        byteBuf.capacity(byteBuf.capacity() + length + 4);
        byteBuf.writeInt(length);
        byteBuf.writeBytes(ClientConf.VERSION.getBytes());

        length = params.getConfigurationString().length();
        byteBuf.capacity(byteBuf.capacity() + length + 4);
        byteBuf.writeInt(length);
        byteBuf.writeBytes(params.getConfigurationString().getBytes());

        return byteBuf;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        poolFlag = false;

450 451 452 453
        logger.info(
                "Connect broken of ClientId: {} with LogProxy: {}",
                params.info(),
                NetworkUtil.parseRemoteAddress(ctx.channel()));
H
He Wang 已提交
454 455 456 457 458 459 460 461 462 463 464 465 466
        ctx.channel().disconnect();
        ctx.close();

        if (stream != null) {
            stream.triggerReconnect();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        poolFlag = false;
        resetState();

467 468 469 470 471
        logger.error(
                "Exception occurred ClientId: {}, with LogProxy: {}",
                params.info(),
                NetworkUtil.parseRemoteAddress(ctx.channel()),
                cause);
H
He Wang 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
        ctx.channel().disconnect();
        ctx.close();

        if (stream != null) {
            if (cause instanceof LogProxyClientException) {
                if (((LogProxyClientException) cause).needStop()) {
                    stream.stop();
                    stream.triggerException((LogProxyClientException) cause);
                }

            } else {
                stream.triggerReconnect();
            }
        }
    }
}