Search in sources :

Example 21 with IpPort

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

the class ServiceRegistryClientImpl method doGetMicroservice.

private Microservice doGetMicroservice(String microserviceId, boolean global) {
    Holder<GetServiceResponse> holder = new Holder<>();
    IpPort ipPort = ipPortManager.getAvailableAddress();
    CountDownLatch countDownLatch = new CountDownLatch(1);
    RequestParam param = new RequestParam();
    if (global) {
        param.addQueryParam("global", "true");
    }
    restClientUtil.get(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_OPERATION_ONE, microserviceId), param, syncHandler(countDownLatch, GetServiceResponse.class, holder));
    try {
        countDownLatch.await();
        if (holder.value != null) {
            return holder.value.getService();
        }
    } catch (Exception e) {
        LOGGER.error("query microservice {} failed", microserviceId, e);
    }
    return null;
}
Also used : GetServiceResponse(org.apache.servicecomb.serviceregistry.api.response.GetServiceResponse) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) CountDownLatch(java.util.concurrent.CountDownLatch) ClientException(org.apache.servicecomb.serviceregistry.client.ClientException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Example 22 with IpPort

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

the class ServiceRegistryClientImpl method registerMicroserviceInstance.

@Override
public String registerMicroserviceInstance(MicroserviceInstance instance) {
    Holder<RegisterInstanceResponse> holder = new Holder<>();
    IpPort ipPort = ipPortManager.getAvailableAddress();
    try {
        RegisterInstanceRequest request = new RegisterInstanceRequest();
        request.setInstance(instance);
        byte[] body = JsonUtils.writeValueAsBytes(request);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("register microservice: {}", new String(body, Charset.defaultCharset()));
        }
        CountDownLatch countDownLatch = new CountDownLatch(1);
        restClientUtil.post(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_INSTANCE_OPERATION_ALL, instance.getServiceId()), new RequestParam().setBody(body), syncHandler(countDownLatch, RegisterInstanceResponse.class, holder));
        countDownLatch.await();
        if (holder.value != null) {
            return holder.value.getInstanceId();
        }
    } catch (Exception e) {
        LOGGER.error("register microservice instance {} failed", instance.getServiceId(), e);
    }
    return null;
}
Also used : RegisterInstanceRequest(org.apache.servicecomb.serviceregistry.api.request.RegisterInstanceRequest) RegisterInstanceResponse(org.apache.servicecomb.serviceregistry.api.response.RegisterInstanceResponse) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) CountDownLatch(java.util.concurrent.CountDownLatch) ClientException(org.apache.servicecomb.serviceregistry.client.ClientException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Example 23 with IpPort

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

the class ServiceRegistryClientImpl method findServiceInstances.

@Override
public MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision) {
    MicroserviceInstances microserviceInstances = new MicroserviceInstances();
    IpPort ipPort = ipPortManager.getAvailableAddress();
    CountDownLatch countDownLatch = new CountDownLatch(1);
    RequestParam requestParam = new RequestParam().addQueryParam("appId", appId).addQueryParam("serviceName", serviceName).addQueryParam("global", "true").addQueryParam("version", versionRule);
    if (RegistryUtils.getMicroservice().getEnvironment() != null) {
        requestParam.addQueryParam("env", RegistryUtils.getMicroservice().getEnvironment());
    }
    if (consumerId != null) {
        requestParam.addHeader("X-ConsumerId", consumerId);
    }
    if (revision != null) {
        requestParam.addQueryParam("rev", revision);
    }
    restClientUtil.get(ipPort, Const.REGISTRY_API.MICROSERVICE_INSTANCES, requestParam, syncHandlerForInstances(countDownLatch, microserviceInstances));
    try {
        countDownLatch.await();
        if (!microserviceInstances.isNeedRefresh()) {
            return microserviceInstances;
        }
        if (microserviceInstances.getInstancesResponse() == null) {
            // error
            return null;
        }
        List<MicroserviceInstance> list = microserviceInstances.getInstancesResponse().getInstances();
        if (list == null) {
            microserviceInstances.getInstancesResponse().setInstances(new ArrayList<>());
        }
        return microserviceInstances;
    } catch (Exception e) {
        LOGGER.error("find microservice instance {}/{}/{} failed", appId, serviceName, versionRule, e);
    }
    return null;
}
Also used : MicroserviceInstances(org.apache.servicecomb.registry.api.registry.MicroserviceInstances) MicroserviceInstance(org.apache.servicecomb.registry.api.registry.MicroserviceInstance) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) CountDownLatch(java.util.concurrent.CountDownLatch) ClientException(org.apache.servicecomb.serviceregistry.client.ClientException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Example 24 with IpPort

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

the class MockForRestServerVerticle method mockRestServerVerticle.

public void mockRestServerVerticle() {
    final HttpServer server = Mockito.mock(HttpServer.class);
    new MockUp<RestServerVerticle>() {

        @Mock
        private void startListen(HttpServer server, IpPort ipPort, Future<Void> startFuture) {
        }

        @Mock
        private HttpServer createHttpServer(boolean isHttp_2) {
            return server;
        }
    };
}
Also used : HttpServer(io.vertx.core.http.HttpServer) Future(io.vertx.core.Future) MockUp(mockit.MockUp) IpPort(org.apache.servicecomb.foundation.common.net.IpPort)

Example 25 with IpPort

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

the class RestClientUtil method httpDo.

public void httpDo(long timeout, RequestContext requestContext, Handler<RestResponse> responseHandler) {
    HttpClientWithContext vertxHttpClient = httpClientPool.getClient();
    vertxHttpClient.runOnContext(httpClient -> {
        IpPort ipPort = requestContext.getIpPort();
        HttpMethod httpMethod = requestContext.getMethod();
        RequestParam requestParam = requestContext.getParams();
        if (ipPort == null) {
            LOGGER.error("request address is null");
            responseHandler.handle(new RestResponse(requestContext, null));
            return;
        }
        // query params
        StringBuilder url = new StringBuilder(requestContext.getUri());
        String queryParams = requestParam.getQueryParams();
        if (!queryParams.isEmpty()) {
            url.append(url.lastIndexOf("?") > 0 ? "&" : "?").append(queryParams);
        }
        httpClient.request(httpMethod, ipPort.getPort(), ipPort.getHostOrIp(), url.toString()).compose(httpClientRequest -> {
            httpClientRequest.setTimeout(timeout);
            // headers
            Map<String, String> headers = defaultHeaders();
            httpClientRequest.headers().addAll(headers);
            if (requestParam.getHeaders() != null && requestParam.getHeaders().size() > 0) {
                headers.putAll(requestParam.getHeaders());
                for (Map.Entry<String, String> header : requestParam.getHeaders().entrySet()) {
                    httpClientRequest.putHeader(header.getKey(), header.getValue());
                }
            }
            // cookies header
            if (requestParam.getCookies() != null && requestParam.getCookies().size() > 0) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Map.Entry<String, String> cookie : requestParam.getCookies().entrySet()) {
                    stringBuilder.append(cookie.getKey()).append("=").append(cookie.getValue()).append("; ");
                }
                httpClientRequest.putHeader("Cookie", stringBuilder.toString());
                headers.put("Cookie", stringBuilder.toString());
            }
            // SignAuth
            SignRequest signReq = createSignRequest(requestContext.getMethod().toString(), requestContext.getIpPort(), requestContext.getParams(), url.toString(), headers);
            httpClientRequest.headers().addAll(getSignAuthHeaders(signReq));
            // body
            if (httpMethod != HttpMethod.GET && requestParam.getBody() != null && requestParam.getBody().length > 0) {
                return httpClientRequest.send(Buffer.buffer(requestParam.getBody())).compose(response -> {
                    responseHandler.handle(new RestResponse(requestContext, response));
                    return Future.succeededFuture();
                });
            } else {
                return httpClientRequest.send().compose(response -> {
                    responseHandler.handle(new RestResponse(requestContext, response));
                    return Future.succeededFuture();
                });
            }
        }).onFailure(failure -> {
            LOGGER.error("{} {} fail, endpoint is {}:{}, message: {}", httpMethod, url.toString(), ipPort.getHostOrIp(), ipPort.getPort(), failure.getMessage());
            if (failure instanceof UnknownHostException) {
                // help analyses DNS problem
                LOGGER.error("DNS resolve failed!", failure);
            }
            responseHandler.handle(new RestResponse(requestContext, null));
        });
    });
}
Also used : AuthHeaderProvider(org.apache.servicecomb.foundation.auth.AuthHeaderProvider) SignRequest(org.apache.servicecomb.foundation.auth.SignRequest) Logger(org.slf4j.Logger) HttpClientWithContext(org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext) ServiceRegistryConfig(org.apache.servicecomb.serviceregistry.config.ServiceRegistryConfig) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) UnknownHostException(java.net.UnknownHostException) Future(io.vertx.core.Future) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) List(java.util.List) ByteArrayInputStream(java.io.ByteArrayInputStream) Buffer(io.vertx.core.buffer.Buffer) HttpMethod(io.vertx.core.http.HttpMethod) Map(java.util.Map) URI(java.net.URI) Handler(io.vertx.core.Handler) SignRequest(org.apache.servicecomb.foundation.auth.SignRequest) UnknownHostException(java.net.UnknownHostException) HttpClientWithContext(org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) HashMap(java.util.HashMap) Map(java.util.Map) HttpMethod(io.vertx.core.http.HttpMethod)

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