Search in sources :

Example 1 with Packet

use of com.alibaba.otter.canal.protocol.AdminPacket.Packet in project canal by alibaba.

the class ClientAuthenticationHandler method messageReceived.

public void messageReceived(final ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
    final Packet packet = Packet.parseFrom(buffer.readBytes(buffer.readableBytes()).array());
    switch(packet.getVersion()) {
        case SUPPORTED_VERSION:
        default:
            final ClientAuth clientAuth = ClientAuth.parseFrom(packet.getBody());
            if (seed == null) {
                byte[] errorBytes = AdminNettyUtils.errorPacket(300, MessageFormatter.format("auth failed for seed is null", clientAuth.getUsername()).getMessage());
                AdminNettyUtils.write(ctx.getChannel(), errorBytes);
            }
            if (!canalAdmin.auth(clientAuth.getUsername(), clientAuth.getPassword().toStringUtf8(), seed)) {
                byte[] errorBytes = AdminNettyUtils.errorPacket(300, MessageFormatter.format("auth failed for user:{}", clientAuth.getUsername()).getMessage());
                AdminNettyUtils.write(ctx.getChannel(), errorBytes);
            }
            byte[] ackBytes = AdminNettyUtils.ackPacket();
            AdminNettyUtils.write(ctx.getChannel(), ackBytes, future -> {
                logger.info("remove unused channel handlers after authentication is done successfully.");
                ctx.getPipeline().remove(HandshakeInitializationHandler.class.getName());
                ctx.getPipeline().remove(ClientAuthenticationHandler.class.getName());
                int readTimeout = defaultSubscriptorDisconnectIdleTimeout;
                int writeTimeout = defaultSubscriptorDisconnectIdleTimeout;
                if (clientAuth.getNetReadTimeout() > 0) {
                    readTimeout = clientAuth.getNetReadTimeout();
                }
                if (clientAuth.getNetWriteTimeout() > 0) {
                    writeTimeout = clientAuth.getNetWriteTimeout();
                }
                // fix bug: soTimeout parameter's unit from connector is
                // millseconds.
                IdleStateHandler idleStateHandler = new IdleStateHandler(NettyUtils.hashedWheelTimer, readTimeout, writeTimeout, 0, TimeUnit.MILLISECONDS);
                ctx.getPipeline().addBefore(SessionHandler.class.getName(), IdleStateHandler.class.getName(), idleStateHandler);
                IdleStateAwareChannelHandler idleStateAwareChannelHandler = new IdleStateAwareChannelHandler() {

                    public void channelIdle(ChannelHandlerContext ctx1, IdleStateEvent e1) throws Exception {
                        logger.warn("channel:{} idle timeout exceeds, close channel to save server resources...", ctx1.getChannel());
                        ctx1.getChannel().close();
                    }
                };
                ctx.getPipeline().addBefore(SessionHandler.class.getName(), IdleStateAwareChannelHandler.class.getName(), idleStateAwareChannelHandler);
            });
            break;
    }
}
Also used : IdleStateEvent(org.jboss.netty.handler.timeout.IdleStateEvent) Packet(com.alibaba.otter.canal.protocol.AdminPacket.Packet) IdleStateHandler(org.jboss.netty.handler.timeout.IdleStateHandler) ChannelHandlerContext(org.jboss.netty.channel.ChannelHandlerContext) ClientAuth(com.alibaba.otter.canal.protocol.AdminPacket.ClientAuth) IdleStateAwareChannelHandler(org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 2 with Packet

use of com.alibaba.otter.canal.protocol.AdminPacket.Packet in project canal by alibaba.

the class SessionHandler method messageReceived.

public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    logger.info("message receives in session handler...");
    ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
    Packet packet = Packet.parseFrom(buffer.readBytes(buffer.readableBytes()).array());
    try {
        String action = null;
        String message = null;
        String destination = null;
        switch(packet.getType()) {
            case SERVER:
                ServerAdmin serverAdmin = ServerAdmin.parseFrom(packet.getBody());
                action = serverAdmin.getAction();
                switch(action) {
                    case "check":
                        message = canalAdmin.check() ? "1" : "0";
                        break;
                    case "start":
                        message = canalAdmin.start() ? "1" : "0";
                        break;
                    case "stop":
                        message = canalAdmin.stop() ? "1" : "0";
                        break;
                    case "restart":
                        message = canalAdmin.restart() ? "1" : "0";
                        break;
                    case "list":
                        message = canalAdmin.getRunningInstances();
                        break;
                    default:
                        byte[] errorBytes = AdminNettyUtils.errorPacket(301, MessageFormatter.format("ServerAdmin action={} is unknown", action).getMessage());
                        AdminNettyUtils.write(ctx.getChannel(), errorBytes);
                        break;
                }
                AdminNettyUtils.write(ctx.getChannel(), AdminNettyUtils.ackPacket(message));
                break;
            case INSTANCE:
                InstanceAdmin instanceAdmin = InstanceAdmin.parseFrom(packet.getBody());
                destination = instanceAdmin.getDestination();
                action = instanceAdmin.getAction();
                switch(action) {
                    case "check":
                        message = canalAdmin.checkInstance(destination) ? "1" : "0";
                        break;
                    case "start":
                        message = canalAdmin.startInstance(destination) ? "1" : "0";
                        break;
                    case "stop":
                        message = canalAdmin.stopInstance(destination) ? "1" : "0";
                        break;
                    case "release":
                        message = canalAdmin.releaseInstance(destination) ? "1" : "0";
                        break;
                    case "restart":
                        message = canalAdmin.restartInstance(destination) ? "1" : "0";
                        break;
                    default:
                        byte[] errorBytes = AdminNettyUtils.errorPacket(301, MessageFormatter.format("InstanceAdmin action={} is unknown", action).getMessage());
                        AdminNettyUtils.write(ctx.getChannel(), errorBytes);
                        break;
                }
                AdminNettyUtils.write(ctx.getChannel(), AdminNettyUtils.ackPacket(message));
                break;
            case LOG:
                LogAdmin logAdmin = LogAdmin.parseFrom(packet.getBody());
                action = logAdmin.getAction();
                destination = logAdmin.getDestination();
                String type = logAdmin.getType();
                String file = logAdmin.getFile();
                int count = logAdmin.getCount();
                switch(type) {
                    case "server":
                        if ("list".equalsIgnoreCase(action)) {
                            message = canalAdmin.listCanalLog();
                        } else {
                            message = canalAdmin.canalLog(count);
                        }
                        break;
                    case "instance":
                        if ("list".equalsIgnoreCase(action)) {
                            message = canalAdmin.listInstanceLog(destination);
                        } else {
                            message = canalAdmin.instanceLog(destination, file, count);
                        }
                        break;
                    default:
                        byte[] errorBytes = AdminNettyUtils.errorPacket(301, MessageFormatter.format("LogAdmin type={} is unknown", type).getMessage());
                        AdminNettyUtils.write(ctx.getChannel(), errorBytes);
                        break;
                }
                AdminNettyUtils.write(ctx.getChannel(), AdminNettyUtils.ackPacket(message));
                break;
            default:
                byte[] errorBytes = AdminNettyUtils.errorPacket(300, MessageFormatter.format("packet type={} is NOT supported!", packet.getType()).getMessage());
                AdminNettyUtils.write(ctx.getChannel(), errorBytes);
                break;
        }
    } catch (Throwable exception) {
        byte[] errorBytes = AdminNettyUtils.errorPacket(400, MessageFormatter.format("something goes wrong with channel:{}, exception={}", ctx.getChannel(), ExceptionUtils.getStackTrace(exception)).getMessage());
        AdminNettyUtils.write(ctx.getChannel(), errorBytes);
    }
}
Also used : InstanceAdmin(com.alibaba.otter.canal.protocol.AdminPacket.InstanceAdmin) Packet(com.alibaba.otter.canal.protocol.AdminPacket.Packet) ServerAdmin(com.alibaba.otter.canal.protocol.AdminPacket.ServerAdmin) LogAdmin(com.alibaba.otter.canal.protocol.AdminPacket.LogAdmin) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 3 with Packet

use of com.alibaba.otter.canal.protocol.AdminPacket.Packet in project canal by alibaba.

the class SimpleAdminConnector method doServerAdmin.

// ==================== helper method ====================
private String doServerAdmin(String action) {
    try {
        writeWithHeader(Packet.newBuilder().setType(PacketType.SERVER).setBody(ServerAdmin.newBuilder().setAction(action).build().toByteString()).build().toByteArray());
        Packet p = Packet.parseFrom(readNextPacket());
        Ack ack = Ack.parseFrom(p.getBody());
        if (ack.getCode() > 0) {
            throw new ServiceException("failed to subscribe with reason: " + ack.getMessage());
        }
        return ack.getMessage();
    } catch (IOException e) {
        throw new ServiceException(e);
    }
}
Also used : Packet(com.alibaba.otter.canal.protocol.AdminPacket.Packet) ServiceException(com.alibaba.otter.canal.admin.common.exception.ServiceException) Ack(com.alibaba.otter.canal.protocol.AdminPacket.Ack) IOException(java.io.IOException)

Example 4 with Packet

use of com.alibaba.otter.canal.protocol.AdminPacket.Packet in project canal by alibaba.

the class SimpleAdminConnector method connect.

@Override
public void connect() throws ServiceException {
    try {
        if (connected) {
            return;
        }
        channel = SocketChannel.open();
        channel.socket().setSoTimeout(soTimeout);
        channel.connect(address);
        readableChannel = Channels.newChannel(channel.socket().getInputStream());
        writableChannel = Channels.newChannel(channel.socket().getOutputStream());
        Packet p = Packet.parseFrom(readNextPacket());
        if (p.getVersion() != 1) {
            throw new CanalClientException("unsupported version at this client.");
        }
        if (p.getType() != PacketType.HANDSHAKE) {
            throw new CanalClientException("expect handshake but found other type.");
        }
        Handshake handshake = Handshake.parseFrom(p.getBody());
        // seed for auth
        ByteString seed = handshake.getSeeds();
        String newPasswd = passwd;
        if (passwd != null) {
            // encode passwd
            newPasswd = SecurityUtil.byte2HexStr(SecurityUtil.scramble411(passwd.getBytes(), seed.toByteArray()));
        }
        ClientAuth ca = ClientAuth.newBuilder().setUsername(user != null ? user : "").setPassword(ByteString.copyFromUtf8(newPasswd != null ? newPasswd : "")).setNetReadTimeout(idleTimeout).setNetWriteTimeout(idleTimeout).build();
        writeWithHeader(Packet.newBuilder().setType(PacketType.CLIENTAUTHENTICATION).setBody(ca.toByteString()).build().toByteArray());
        // 
        Packet ack = Packet.parseFrom(readNextPacket());
        if (ack.getType() != PacketType.ACK) {
            throw new CanalClientException("unexpected packet type when ack is expected");
        }
        Ack ackBody = Ack.parseFrom(ack.getBody());
        if (ackBody.getCode() > 0) {
            throw new ServiceException("something goes wrong when doing authentication: " + ackBody.getMessage());
        }
        connected = true;
    } catch (IOException | NoSuchAlgorithmException e) {
        throw new ServiceException(e);
    }
}
Also used : Packet(com.alibaba.otter.canal.protocol.AdminPacket.Packet) ServiceException(com.alibaba.otter.canal.admin.common.exception.ServiceException) CanalClientException(com.alibaba.otter.canal.protocol.exception.CanalClientException) ByteString(com.google.protobuf.ByteString) Ack(com.alibaba.otter.canal.protocol.AdminPacket.Ack) ByteString(com.google.protobuf.ByteString) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ClientAuth(com.alibaba.otter.canal.protocol.AdminPacket.ClientAuth) Handshake(com.alibaba.otter.canal.protocol.AdminPacket.Handshake)

Example 5 with Packet

use of com.alibaba.otter.canal.protocol.AdminPacket.Packet in project canal by alibaba.

the class SimpleAdminConnector method doLogAdmin.

private String doLogAdmin(String type, String action, String destination, String file, int count) {
    try {
        writeWithHeader(Packet.newBuilder().setType(PacketType.LOG).setBody(LogAdmin.newBuilder().setType(type).setAction(action).setDestination(destination == null ? "" : destination).setFile(file == null ? "" : file).setCount(count).build().toByteString()).build().toByteArray());
        Packet p = Packet.parseFrom(readNextPacket());
        Ack ack = Ack.parseFrom(p.getBody());
        if (ack.getCode() > 0) {
            throw new ServiceException("failed to subscribe with reason: " + ack.getMessage());
        }
        return ack.getMessage();
    } catch (IOException e) {
        throw new ServiceException(e);
    }
}
Also used : Packet(com.alibaba.otter.canal.protocol.AdminPacket.Packet) ServiceException(com.alibaba.otter.canal.admin.common.exception.ServiceException) Ack(com.alibaba.otter.canal.protocol.AdminPacket.Ack) IOException(java.io.IOException)

Aggregations

Packet (com.alibaba.otter.canal.protocol.AdminPacket.Packet)6 ServiceException (com.alibaba.otter.canal.admin.common.exception.ServiceException)4 Ack (com.alibaba.otter.canal.protocol.AdminPacket.Ack)4 IOException (java.io.IOException)4 ClientAuth (com.alibaba.otter.canal.protocol.AdminPacket.ClientAuth)2 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)2 Handshake (com.alibaba.otter.canal.protocol.AdminPacket.Handshake)1 InstanceAdmin (com.alibaba.otter.canal.protocol.AdminPacket.InstanceAdmin)1 LogAdmin (com.alibaba.otter.canal.protocol.AdminPacket.LogAdmin)1 ServerAdmin (com.alibaba.otter.canal.protocol.AdminPacket.ServerAdmin)1 CanalClientException (com.alibaba.otter.canal.protocol.exception.CanalClientException)1 ByteString (com.google.protobuf.ByteString)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 ChannelHandlerContext (org.jboss.netty.channel.ChannelHandlerContext)1 IdleStateAwareChannelHandler (org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler)1 IdleStateEvent (org.jboss.netty.handler.timeout.IdleStateEvent)1 IdleStateHandler (org.jboss.netty.handler.timeout.IdleStateHandler)1