Search in sources :

Example 1 with DefaultServerEndpointMetric

use of org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultServerEndpointMetric in project java-chassis by ServiceComb.

the class RestServerVerticle method start.

@Override
public void start(Promise<Void> startPromise) throws Exception {
    try {
        super.start();
        // 如果本地未配置地址,则表示不必监听,只需要作为客户端使用即可
        if (endpointObject == null) {
            LOGGER.warn("rest listen address is not configured, will not start.");
            startPromise.complete();
            return;
        }
        Router mainRouter = Router.router(vertx);
        mountAccessLogHandler(mainRouter);
        mountCorsHandler(mainRouter);
        initDispatcher(mainRouter);
        mountGlobalRestFailureHandler(mainRouter);
        HttpServer httpServer = createHttpServer();
        httpServer.requestHandler(mainRouter);
        httpServer.connectionHandler(connection -> {
            DefaultHttpServerMetrics serverMetrics = (DefaultHttpServerMetrics) ((ConnectionBase) connection).metrics();
            DefaultServerEndpointMetric endpointMetric = serverMetrics.getEndpointMetric();
            long connectedCount = endpointMetric.getCurrentConnectionCount();
            int connectionLimit = DynamicPropertyFactory.getInstance().getIntProperty("servicecomb.rest.server.connection-limit", Integer.MAX_VALUE).get();
            if (connectedCount > connectionLimit) {
                connection.close();
                endpointMetric.onRejectByConnectionLimit();
            }
        });
        List<HttpServerExceptionHandler> httpServerExceptionHandlers = SPIServiceUtils.getAllService(HttpServerExceptionHandler.class);
        httpServer.exceptionHandler(e -> {
            if (e instanceof ClosedChannelException) {
                // This is quite normal in between browser and ege, so do not print out.
                LOGGER.debug("Unexpected error in server.{}", ExceptionUtils.getExceptionMessageWithoutTrace(e));
            } else {
                LOGGER.error("Unexpected error in server.{}", ExceptionUtils.getExceptionMessageWithoutTrace(e));
            }
            httpServerExceptionHandlers.forEach(httpServerExceptionHandler -> {
                httpServerExceptionHandler.handle(e);
            });
        });
        startListen(httpServer, startPromise);
    } catch (Throwable e) {
        // vert.x got some states that not print error and execute call back in VertexUtils.blockDeploy, we add a log our self.
        LOGGER.error("", e);
        throw e;
    }
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) HttpServer(io.vertx.core.http.HttpServer) Router(io.vertx.ext.web.Router) DefaultHttpServerMetrics(org.apache.servicecomb.foundation.vertx.metrics.DefaultHttpServerMetrics) Endpoint(org.apache.servicecomb.core.Endpoint) DefaultServerEndpointMetric(org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultServerEndpointMetric)

Example 2 with DefaultServerEndpointMetric

use of org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultServerEndpointMetric in project java-chassis by ServiceComb.

the class TcpServer method init.

public void init(Vertx vertx, String sslKey, AsyncResultCallback<InetSocketAddress> callback) {
    NetServer netServer;
    if (endpointObject.isSslEnabled()) {
        SSLOptionFactory factory = SSLOptionFactory.createSSLOptionFactory(sslKey, null);
        SSLOption sslOption;
        if (factory == null) {
            sslOption = SSLOption.buildFromYaml(sslKey);
        } else {
            sslOption = factory.createSSLOption();
        }
        SSLCustom sslCustom = SSLCustom.createSSLCustom(sslOption.getSslCustomClass());
        NetServerOptions serverOptions = new NetServerOptions();
        VertxTLSBuilder.buildNetServerOptions(sslOption, sslCustom, serverOptions);
        netServer = vertx.createNetServer(serverOptions);
    } else {
        netServer = vertx.createNetServer();
    }
    netServer.connectHandler(netSocket -> {
        DefaultTcpServerMetrics serverMetrics = (DefaultTcpServerMetrics) ((NetSocketImpl) netSocket).metrics();
        DefaultServerEndpointMetric endpointMetric = serverMetrics.getEndpointMetric();
        long connectedCount = endpointMetric.getCurrentConnectionCount();
        int connectionLimit = getConnectionLimit();
        if (connectedCount > connectionLimit) {
            netSocket.close();
            endpointMetric.onRejectByConnectionLimit();
            return;
        }
        TcpServerConnection connection = createTcpServerConnection();
        connection.init(netSocket);
    });
    netServer.exceptionHandler(e -> {
        LOGGER.error("Unexpected error in server.{}", ExceptionUtils.getExceptionMessageWithoutTrace(e));
    });
    InetSocketAddress socketAddress = endpointObject.getSocketAddress();
    netServer.listen(socketAddress.getPort(), socketAddress.getHostString(), ar -> {
        if (ar.succeeded()) {
            callback.success(socketAddress);
            return;
        }
        // 监听失败
        String msg = String.format("listen failed, address=%s", socketAddress.toString());
        callback.fail(new Exception(msg, ar.cause()));
    });
}
Also used : InetSocketAddress(java.net.InetSocketAddress) NetServer(io.vertx.core.net.NetServer) DefaultTcpServerMetrics(org.apache.servicecomb.foundation.vertx.metrics.DefaultTcpServerMetrics) DefaultServerEndpointMetric(org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultServerEndpointMetric) SSLOptionFactory(org.apache.servicecomb.foundation.ssl.SSLOptionFactory) NetServerOptions(io.vertx.core.net.NetServerOptions) SSLOption(org.apache.servicecomb.foundation.ssl.SSLOption) SSLCustom(org.apache.servicecomb.foundation.ssl.SSLCustom)

Example 3 with DefaultServerEndpointMetric

use of org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultServerEndpointMetric in project incubator-servicecomb-java-chassis by apache.

the class TestTcpServer method testConnectionLimit.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testConnectionLimit(@Mocked Vertx vertx, @Mocked AsyncResultCallback<InetSocketAddress> callback, @Mocked NetServer netServer, @Mocked NetSocketImpl netSocket) {
    DefaultServerEndpointMetric endpointMetric = new DefaultServerEndpointMetric(null);
    DefaultTcpServerMetrics tcpServerMetrics = new DefaultTcpServerMetrics(endpointMetric);
    new MockUp<NetServer>(netServer) {

        @Mock
        NetServer connectHandler(Handler<NetSocket> handler) {
            connectHandler = handler;
            return netServer;
        }
    };
    new MockUp<NetSocketImpl>(netSocket) {

        @Mock
        void close() {
            netSocketClosed = true;
        }
    };
    new Expectations() {

        {
            vertx.createNetServer((NetServerOptions) any);
            result = netServer;
            netServer.listen(anyInt, anyString, (Handler) any);
            netSocket.metrics();
            result = tcpServerMetrics;
        }
    };
    URIEndpointObject endpointObject = new URIEndpointObject("highway://127.0.0.1:6663?sslEnabled=true");
    TcpServer server = new TcpServerForTest(endpointObject) {

        @Override
        protected int getConnectionLimit() {
            return 2;
        }
    };
    // assert done in Expectations
    server.init(vertx, "", callback);
    // no problem
    endpointMetric.onConnect();
    endpointMetric.onConnect();
    connectHandler.handle(netSocket);
    // reject
    endpointMetric.onConnect();
    connectHandler.handle(netSocket);
    Assert.assertTrue(netSocketClosed);
    Assert.assertEquals(1, endpointMetric.getRejectByConnectionLimitCount());
}
Also used : Expectations(mockit.Expectations) Handler(io.vertx.core.Handler) MockUp(mockit.MockUp) URIEndpointObject(org.apache.servicecomb.foundation.common.net.URIEndpointObject) DefaultServerEndpointMetric(org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultServerEndpointMetric) DefaultTcpServerMetrics(org.apache.servicecomb.foundation.vertx.metrics.DefaultTcpServerMetrics) Test(org.junit.Test)

Example 4 with DefaultServerEndpointMetric

use of org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultServerEndpointMetric in project java-chassis by ServiceComb.

the class TestTcpServer method testConnectionLimit.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testConnectionLimit(@Mocked Vertx vertx, @Mocked AsyncResultCallback<InetSocketAddress> callback, @Mocked NetServer netServer, @Mocked NetSocketImpl netSocket) {
    DefaultServerEndpointMetric endpointMetric = new DefaultServerEndpointMetric(null);
    DefaultTcpServerMetrics tcpServerMetrics = new DefaultTcpServerMetrics(endpointMetric);
    new MockUp<NetServer>(netServer) {

        @Mock
        NetServer connectHandler(Handler<NetSocket> handler) {
            connectHandler = handler;
            return netServer;
        }
    };
    new MockUp<NetSocketImpl>(netSocket) {

        @Mock
        void close() {
            netSocketClosed = true;
        }
    };
    new Expectations() {

        {
            vertx.createNetServer((NetServerOptions) any);
            result = netServer;
            netServer.listen(anyInt, anyString, (Handler) any);
            netSocket.metrics();
            result = tcpServerMetrics;
        }
    };
    URIEndpointObject endpointObject = new URIEndpointObject("highway://127.0.0.1:6663?sslEnabled=true");
    TcpServer server = new TcpServerForTest(endpointObject) {

        @Override
        protected int getConnectionLimit() {
            return 2;
        }
    };
    // assert done in Expectations
    server.init(vertx, "", callback);
    // no problem
    endpointMetric.onConnect();
    endpointMetric.onConnect();
    connectHandler.handle(netSocket);
    // reject
    endpointMetric.onConnect();
    connectHandler.handle(netSocket);
    Assert.assertTrue(netSocketClosed);
    Assert.assertEquals(1, endpointMetric.getRejectByConnectionLimitCount());
}
Also used : Expectations(mockit.Expectations) Handler(io.vertx.core.Handler) MockUp(mockit.MockUp) URIEndpointObject(org.apache.servicecomb.foundation.common.net.URIEndpointObject) DefaultServerEndpointMetric(org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultServerEndpointMetric) DefaultTcpServerMetrics(org.apache.servicecomb.foundation.vertx.metrics.DefaultTcpServerMetrics) Test(org.junit.Test)

Example 5 with DefaultServerEndpointMetric

use of org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultServerEndpointMetric in project incubator-servicecomb-java-chassis by apache.

the class RestServerVerticle method start.

@Override
public void start(Promise<Void> startPromise) throws Exception {
    try {
        super.start();
        // 如果本地未配置地址,则表示不必监听,只需要作为客户端使用即可
        if (endpointObject == null) {
            LOGGER.warn("rest listen address is not configured, will not start.");
            startPromise.complete();
            return;
        }
        Router mainRouter = Router.router(vertx);
        mountAccessLogHandler(mainRouter);
        mountCorsHandler(mainRouter);
        initDispatcher(mainRouter);
        mountGlobalRestFailureHandler(mainRouter);
        HttpServer httpServer = createHttpServer();
        httpServer.requestHandler(mainRouter);
        httpServer.connectionHandler(connection -> {
            DefaultHttpServerMetrics serverMetrics = (DefaultHttpServerMetrics) ((ConnectionBase) connection).metrics();
            DefaultServerEndpointMetric endpointMetric = serverMetrics.getEndpointMetric();
            long connectedCount = endpointMetric.getCurrentConnectionCount();
            int connectionLimit = DynamicPropertyFactory.getInstance().getIntProperty("servicecomb.rest.server.connection-limit", Integer.MAX_VALUE).get();
            if (connectedCount > connectionLimit) {
                connection.close();
                endpointMetric.onRejectByConnectionLimit();
            }
        });
        List<HttpServerExceptionHandler> httpServerExceptionHandlers = SPIServiceUtils.getAllService(HttpServerExceptionHandler.class);
        httpServer.exceptionHandler(e -> {
            if (e instanceof ClosedChannelException) {
                // This is quite normal in between browser and ege, so do not print out.
                LOGGER.debug("Unexpected error in server.{}", ExceptionUtils.getExceptionMessageWithoutTrace(e));
            } else {
                LOGGER.error("Unexpected error in server.{}", ExceptionUtils.getExceptionMessageWithoutTrace(e));
            }
            httpServerExceptionHandlers.forEach(httpServerExceptionHandler -> {
                httpServerExceptionHandler.handle(e);
            });
        });
        startListen(httpServer, startPromise);
    } catch (Throwable e) {
        // vert.x got some states that not print error and execute call back in VertexUtils.blockDeploy, we add a log our self.
        LOGGER.error("", e);
        throw e;
    }
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) HttpServer(io.vertx.core.http.HttpServer) Router(io.vertx.ext.web.Router) DefaultHttpServerMetrics(org.apache.servicecomb.foundation.vertx.metrics.DefaultHttpServerMetrics) Endpoint(org.apache.servicecomb.core.Endpoint) DefaultServerEndpointMetric(org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultServerEndpointMetric)

Aggregations

DefaultServerEndpointMetric (org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultServerEndpointMetric)6 DefaultTcpServerMetrics (org.apache.servicecomb.foundation.vertx.metrics.DefaultTcpServerMetrics)4 Handler (io.vertx.core.Handler)2 HttpServer (io.vertx.core.http.HttpServer)2 NetServer (io.vertx.core.net.NetServer)2 NetServerOptions (io.vertx.core.net.NetServerOptions)2 Router (io.vertx.ext.web.Router)2 InetSocketAddress (java.net.InetSocketAddress)2 ClosedChannelException (java.nio.channels.ClosedChannelException)2 Expectations (mockit.Expectations)2 MockUp (mockit.MockUp)2 Endpoint (org.apache.servicecomb.core.Endpoint)2 URIEndpointObject (org.apache.servicecomb.foundation.common.net.URIEndpointObject)2 SSLCustom (org.apache.servicecomb.foundation.ssl.SSLCustom)2 SSLOption (org.apache.servicecomb.foundation.ssl.SSLOption)2 SSLOptionFactory (org.apache.servicecomb.foundation.ssl.SSLOptionFactory)2 DefaultHttpServerMetrics (org.apache.servicecomb.foundation.vertx.metrics.DefaultHttpServerMetrics)2 Test (org.junit.Test)2