Search in sources :

Example 51 with IpPort

use of org.apache.servicecomb.foundation.common.net.IpPort in project incubator-servicecomb-java-chassis by apache.

the class ConfigCenterClient method refreshMembers.

private void refreshMembers(MemberDiscovery memberDiscovery) {
    if (CONFIG_CENTER_CONFIG.getAutoDiscoveryEnabled()) {
        String configCenter = memberDiscovery.getConfigServer();
        IpPort ipPort = NetUtils.parseIpPortFromURI(configCenter);
        clientMgr.findThreadBindClientPool().runOnContext(client -> {
            HttpClientRequest request = client.get(ipPort.getPort(), ipPort.getHostOrIp(), URIConst.MEMBERS, rsp -> {
                if (rsp.statusCode() == HttpResponseStatus.OK.code()) {
                    rsp.bodyHandler(buf -> {
                        memberDiscovery.refreshMembers(buf.toJsonObject());
                    });
                }
            });
            SignRequest signReq = createSignRequest(request.method().toString(), configCenter + URIConst.MEMBERS, new HashMap<>(), null);
            if (ConfigCenterConfig.INSTANCE.getToken() != null) {
                request.headers().add("X-Auth-Token", ConfigCenterConfig.INSTANCE.getToken());
            }
            authHeaderProviders.forEach(provider -> request.headers().addAll(provider.getSignAuthHeaders(signReq)));
            request.end();
        });
    }
}
Also used : HttpClientRequest(io.vertx.core.http.HttpClientRequest) SignRequest(org.apache.servicecomb.foundation.auth.SignRequest) IpPort(org.apache.servicecomb.foundation.common.net.IpPort)

Example 52 with IpPort

use of org.apache.servicecomb.foundation.common.net.IpPort in project incubator-servicecomb-java-chassis by apache.

the class TestRestServletInitializer method setUp.

@Before
public void setUp() throws Exception {
    Configuration configuration = (Configuration) DynamicPropertyFactory.getBackingConfigurationSource();
    configuration.clearProperty(ServletConfig.KEY_SERVLET_URL_PATTERN);
    configuration.setProperty(ServletConfig.KEY_CSE_REST_ADDRESS, LISTEN_ADDRESS);
    PowerMockito.mockStatic(NetUtils.class);
    PowerMockito.when(NetUtils.parseIpPortFromURI(anyString())).thenReturn(new IpPort(LISTEN_ADDRESS, TEST_PORT));
    PowerMockito.when(NetUtils.canTcpListen(anyObject(), anyInt())).thenReturn(false);
}
Also used : Configuration(org.apache.commons.configuration.Configuration) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) Before(org.junit.Before)

Example 53 with IpPort

use of org.apache.servicecomb.foundation.common.net.IpPort in project java-chassis by ServiceComb.

the class TestServiceRegistryClientImpl method undateMicroserviceInstanceStatus_response_failure.

@SuppressWarnings("deprecation")
@Test
public void undateMicroserviceInstanceStatus_response_failure() {
    HttpClientResponse httpClientResponse = new MockUp<HttpClientResponse>() {

        @Mock
        int statusCode() {
            return 400;
        }
    }.getMockInstance();
    new MockUp<RestClientUtil>() {

        @Mock
        void put(IpPort ipPort, String uri, RequestParam requestParam, Handler<RestResponse> responseHandler) {
            Holder<HttpClientResponse> holder = Deencapsulation.getField(responseHandler, "arg$4");
            holder.value = httpClientResponse;
        }
    };
    boolean result = oClient.undateMicroserviceInstanceStatus("svcId", "instanceId", "UP");
    Assert.assertFalse(result);
}
Also used : HttpClientResponse(io.vertx.core.http.HttpClientResponse) Handler(io.vertx.core.Handler) MockUp(mockit.MockUp) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) Mock(mockit.Mock) Test(org.junit.Test)

Example 54 with IpPort

use of org.apache.servicecomb.foundation.common.net.IpPort in project java-chassis by ServiceComb.

the class RestClientInvocation method invoke.

public void invoke(Invocation invocation, AsyncResponse asyncResp) throws Exception {
    this.invocation = invocation;
    this.asyncResp = asyncResp;
    OperationMeta operationMeta = invocation.getOperationMeta();
    restOperationMeta = operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION);
    String path = this.createRequestPath(restOperationMeta);
    IpPort ipPort = (IpPort) invocation.getEndpoint().getAddress();
    Future<HttpClientRequest> requestFuture = createRequest(ipPort, path);
    invocation.getInvocationStageTrace().startGetConnection();
    requestFuture.compose(clientRequest -> {
        invocation.getInvocationStageTrace().finishGetConnection();
        this.clientRequest = clientRequest;
        clientRequest.putHeader(org.apache.servicecomb.core.Const.TARGET_MICROSERVICE, invocation.getMicroserviceName());
        RestClientRequestImpl restClientRequest = new RestClientRequestImpl(clientRequest, httpClientWithContext.context(), asyncResp, throwableHandler);
        invocation.getHandlerContext().put(RestConst.INVOCATION_HANDLER_REQUESTCLIENT, restClientRequest);
        Buffer requestBodyBuffer;
        try {
            requestBodyBuffer = restClientRequest.getBodyBuffer();
        } catch (Exception e) {
            return Future.failedFuture(e);
        }
        HttpServletRequestEx requestEx = new VertxClientRequestToHttpServletRequest(clientRequest, requestBodyBuffer);
        invocation.getInvocationStageTrace().startClientFiltersRequest();
        for (HttpClientFilter filter : httpClientFilters) {
            if (filter.enabled()) {
                filter.beforeSendRequest(invocation, requestEx);
            }
        }
        // 从业务线程转移到网络线程中去发送
        invocation.onStartSendRequest();
        httpClientWithContext.runOnContext(httpClient -> {
            clientRequest.setTimeout(operationMeta.getConfig().getMsRequestTimeout());
            clientRequest.response().onComplete(asyncResult -> {
                if (asyncResult.failed()) {
                    fail(asyncResult.cause());
                    return;
                }
                handleResponse(asyncResult.result());
            });
            processServiceCombHeaders(invocation, operationMeta);
            restClientRequest.end().onComplete((t) -> invocation.getInvocationStageTrace().finishWriteToBuffer(System.nanoTime()));
        });
        return Future.succeededFuture();
    }).onFailure(failure -> {
        invocation.getTraceIdLogger().error(LOGGER, "Failed to send request, alreadyFailed:{}, local:{}, remote:{}, message={}.", alreadyFailed, getLocalAddress(), ipPort.getSocketAddress(), ExceptionUtils.getExceptionMessageWithoutTrace(failure));
        throwableHandler.handle(failure);
    });
}
Also used : CommonExceptionData(org.apache.servicecomb.swagger.invocation.exception.CommonExceptionData) InvocationException(org.apache.servicecomb.swagger.invocation.exception.InvocationException) RestClientRequestImpl(org.apache.servicecomb.common.rest.codec.param.RestClientRequestImpl) OperationConfig(org.apache.servicecomb.core.definition.OperationConfig) VertxClientRequestToHttpServletRequest(org.apache.servicecomb.foundation.vertx.http.VertxClientRequestToHttpServletRequest) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) RequestOptions(io.vertx.core.http.RequestOptions) DefinitionConst(org.apache.servicecomb.registry.definition.DefinitionConst) AsyncResponse(org.apache.servicecomb.swagger.invocation.AsyncResponse) StringUtils(org.apache.commons.lang3.StringUtils) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) ExceptionUtils(org.apache.servicecomb.foundation.common.utils.ExceptionUtils) JsonUtils(org.apache.servicecomb.foundation.common.utils.JsonUtils) ReadStreamPart(org.apache.servicecomb.foundation.vertx.http.ReadStreamPart) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) RestConst(org.apache.servicecomb.common.rest.RestConst) HttpClientFilter(org.apache.servicecomb.common.rest.filter.HttpClientFilter) Status(javax.ws.rs.core.Response.Status) Response(org.apache.servicecomb.swagger.invocation.Response) OperationMeta(org.apache.servicecomb.core.definition.OperationMeta) HttpServletResponseEx(org.apache.servicecomb.foundation.vertx.http.HttpServletResponseEx) RestOperationMeta(org.apache.servicecomb.common.rest.definition.RestOperationMeta) InvocationStageTrace(org.apache.servicecomb.core.invocation.InvocationStageTrace) HttpStatus(org.apache.servicecomb.foundation.common.http.HttpStatus) Logger(org.slf4j.Logger) HttpClientWithContext(org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext) VertxClientResponseToHttpServletResponse(org.apache.servicecomb.foundation.vertx.http.VertxClientResponseToHttpServletResponse) Const(org.apache.servicecomb.core.Const) Future(io.vertx.core.Future) Invocation(org.apache.servicecomb.core.Invocation) HttpServletRequestEx(org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) HttpMethod(io.vertx.core.http.HttpMethod) URIEndpointObject(org.apache.servicecomb.foundation.common.net.URIEndpointObject) Handler(io.vertx.core.Handler) Buffer(io.vertx.core.buffer.Buffer) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientFilter(org.apache.servicecomb.common.rest.filter.HttpClientFilter) RestClientRequestImpl(org.apache.servicecomb.common.rest.codec.param.RestClientRequestImpl) VertxClientRequestToHttpServletRequest(org.apache.servicecomb.foundation.vertx.http.VertxClientRequestToHttpServletRequest) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) OperationMeta(org.apache.servicecomb.core.definition.OperationMeta) RestOperationMeta(org.apache.servicecomb.common.rest.definition.RestOperationMeta) InvocationException(org.apache.servicecomb.swagger.invocation.exception.InvocationException) TimeoutException(java.util.concurrent.TimeoutException) HttpServletRequestEx(org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx)

Example 55 with IpPort

use of org.apache.servicecomb.foundation.common.net.IpPort in project java-chassis by ServiceComb.

the class RegistrationManager method genPublishIpPort.

private static IpPort genPublishIpPort(String schema, IpPort ipPort) {
    String publicAddressSetting = DynamicPropertyFactory.getInstance().getStringProperty(PUBLISH_ADDRESS, "").get();
    publicAddressSetting = publicAddressSetting.trim();
    String publishPortKey = PUBLISH_PORT.replace("{transport_name}", schema);
    int publishPortSetting = DynamicPropertyFactory.getInstance().getIntProperty(publishPortKey, 0).get();
    int publishPort = publishPortSetting == 0 ? ipPort.getPort() : publishPortSetting;
    if (publicAddressSetting.isEmpty()) {
        InetSocketAddress socketAddress = ipPort.getSocketAddress();
        if (socketAddress.getAddress().isAnyLocalAddress()) {
            String host = NetUtils.getHostAddress();
            if (Inet6Address.class.isInstance(socketAddress.getAddress())) {
                host = NetUtils.getIpv6HostAddress();
            }
            LOGGER.warn("address {}, auto select a host address to publish {}:{}, maybe not the correct one", socketAddress, host, publishPort);
            return new IpPort(host, publishPort);
        }
        return ipPort;
    }
    if (publicAddressSetting.startsWith("{") && publicAddressSetting.endsWith("}")) {
        publicAddressSetting = NetUtils.ensureGetInterfaceAddress(publicAddressSetting.substring(1, publicAddressSetting.length() - 1)).getHostAddress();
    }
    return new IpPort(publicAddressSetting, publishPort);
}
Also used : InetSocketAddress(java.net.InetSocketAddress) IpPort(org.apache.servicecomb.foundation.common.net.IpPort)

Aggregations

IpPort (org.apache.servicecomb.foundation.common.net.IpPort)69 ClientException (org.apache.servicecomb.serviceregistry.client.ClientException)36 CountDownLatch (java.util.concurrent.CountDownLatch)35 IOException (java.io.IOException)19 ExecutionException (java.util.concurrent.ExecutionException)19 Holder (javax.xml.ws.Holder)15 Test (org.junit.Test)14 HttpClientResponse (io.vertx.core.http.HttpClientResponse)12 ArrayList (java.util.ArrayList)10 Handler (io.vertx.core.Handler)6 URI (java.net.URI)6 HashMap (java.util.HashMap)6 List (java.util.List)6 Expectations (mockit.Expectations)6 MockUp (mockit.MockUp)6 Future (io.vertx.core.Future)5 HttpClientRequest (io.vertx.core.http.HttpClientRequest)5 HttpMethod (io.vertx.core.http.HttpMethod)5 SignRequest (org.apache.servicecomb.foundation.auth.SignRequest)4 HttpClientWithContext (org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext)4