Search in sources :

Example 36 with IpPort

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

the class TestRemoteServiceRegistry method testLifeCycle.

@Test
public void testLifeCycle(@Injectable ServiceRegistryConfig config, @Injectable ServiceRegistry registry) throws InterruptedException {
    ArrayList<IpPort> ipPortList = new ArrayList<>();
    ipPortList.add(new IpPort("127.0.0.1", 9980));
    ipPortList.add(new IpPort("127.0.0.1", 9981));
    CountDownLatch latch = new CountDownLatch(1);
    ServiceRegistryTaskInitializer initializer = new MockUp<ServiceRegistryTaskInitializer>() {

        @Mock
        void init(RemoteServiceRegistry remoteServiceRegistry) {
            latch.countDown();
        }
    }.getMockInstance();
    new Expectations(SPIServiceUtils.class) {

        {
            config.getHeartbeatInterval();
            result = 30;
            config.getInstancePullInterval();
            result = 30;
            config.getRegistryName();
            result = "TestRegistry";
            SPIServiceUtils.getOrLoadSortedService(ServiceRegistryTaskInitializer.class);
            result = Arrays.asList(initializer);
        }
    };
    ServiceRegistry oldRegistry = RegistryUtils.getServiceRegistry();
    RegistryUtils.setServiceRegistry(registry);
    EventBus bus = new EventBus();
    RemoteServiceRegistry remote = new TestingRemoteServiceRegistry(bus, config, ConfigUtil.createLocalConfig());
    remote.init();
    remote.run();
    // should not block
    latch.await();
    // includes complete tasks
    Assert.assertTrue(2 <= remote.getTaskPool().getTaskCount());
    bus.post(new ShutdownEvent());
    remote.getTaskPool().schedule(() -> {
    }, 0, TimeUnit.SECONDS);
    Assert.assertTrue(remote.getTaskPool().isShutdown());
    RegistryUtils.setServiceRegistry(oldRegistry);
}
Also used : Expectations(mockit.Expectations) ArrayList(java.util.ArrayList) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) EventBus(com.google.common.eventbus.EventBus) ShutdownEvent(org.apache.servicecomb.serviceregistry.event.ShutdownEvent) CountDownLatch(java.util.concurrent.CountDownLatch) Mock(mockit.Mock) ServiceRegistry(org.apache.servicecomb.serviceregistry.ServiceRegistry) Test(org.junit.Test)

Example 37 with IpPort

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

the class TestClientHttp method testServiceRegistryClientImpl.

@SuppressWarnings("unchecked")
@Test
public void testServiceRegistryClientImpl(@Mocked IpPortManager manager) {
    IpPort ipPort = new IpPort("127.0.0.1", 8853);
    new Expectations() {

        {
            manager.getAvailableAddress();
            result = ipPort;
        }
    };
    new MockUp<CountDownLatch>() {

        @Mock
        public void await() throws InterruptedException {
        }
    };
    new MockUp<RestUtils>() {

        @Mock
        void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) {
        }
    };
    new MockUp<WebsocketUtils>() {

        @Mock
        void open(IpPort ipPort, String url, Handler<Void> onOpen, Handler<Void> onClose, Handler<Buffer> onMessage, Handler<Throwable> onException, Handler<Throwable> onConnectFailed) {
        }
    };
    MicroserviceFactory microserviceFactory = new MicroserviceFactory();
    Microservice microservice = microserviceFactory.create("app", "ms");
    ServiceRegistryClientImpl oClient = new ServiceRegistryClientImpl(manager);
    oClient.init();
    oClient.registerMicroservice(microservice);
    oClient.registerMicroserviceInstance(microservice.getInstance());
    Assert.assertEquals(null, oClient.getMicroservice(microservice.getServiceId()));
    Assert.assertEquals(null, oClient.getMicroserviceInstance("testConsumerID", "testproviderID"));
    Assert.assertEquals(null, oClient.findServiceInstance(microservice.getServiceId(), microservice.getAppId(), microservice.getServiceName(), microservice.getVersion()));
    Assert.assertEquals(null, oClient.findServiceInstances(microservice.getServiceId(), microservice.getAppId(), microservice.getServiceName(), microservice.getVersion(), "0"));
    Assert.assertEquals(null, oClient.getMicroserviceId(microservice.getAppId(), microservice.getServiceName(), microservice.getVersion()));
    Assert.assertEquals(null, oClient.heartbeat(microservice.getServiceId(), microservice.getInstance().getInstanceId()));
    oClient.watch("", Mockito.mock(AsyncResultCallback.class));
    Assert.assertEquals(false, oClient.unregisterMicroserviceInstance(microservice.getServiceId(), microservice.getInstance().getInstanceId()));
}
Also used : Expectations(mockit.Expectations) Microservice(org.apache.servicecomb.serviceregistry.api.registry.Microservice) Handler(io.vertx.core.Handler) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) MockUp(mockit.MockUp) MicroserviceFactory(org.apache.servicecomb.serviceregistry.api.registry.MicroserviceFactory) AsyncResultCallback(org.apache.servicecomb.foundation.vertx.AsyncResultCallback) Test(org.junit.Test)

Example 38 with IpPort

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

the class TestIpPortManager method testGetAvailableAddress.

@Test
public void testGetAvailableAddress(@Injectable ServiceRegistryConfig config, @Injectable InstanceCacheManager cacheManager, @Injectable InstanceCache cache) {
    ArrayList<IpPort> ipPortList = new ArrayList<>();
    ipPortList.add(new IpPort("127.0.0.1", 9980));
    ipPortList.add(new IpPort("127.0.0.1", 9981));
    new Expectations() {

        {
            config.getIpPort();
            result = ipPortList;
            config.getTransport();
            result = "rest";
            config.isRegistryAutoDiscovery();
            result = true;
        }
    };
    IpPortManager manager = new IpPortManager(config, cacheManager);
    IpPort address1 = manager.getAvailableAddress();
    if (address1.getPort() == 9980) {
        Assert.assertEquals("127.0.0.1", address1.getHostOrIp());
        Assert.assertEquals(9980, address1.getPort());
    } else {
        Assert.assertEquals("127.0.0.1", address1.getHostOrIp());
        Assert.assertEquals(9981, address1.getPort());
    }
    IpPort address2 = manager.getNextAvailableAddress(address1);
    if (address1.getPort() == 9980) {
        Assert.assertEquals("127.0.0.1", address2.getHostOrIp());
        Assert.assertEquals(9981, address2.getPort());
    } else {
        Assert.assertEquals("127.0.0.1", address2.getHostOrIp());
        Assert.assertEquals(9980, address2.getPort());
    }
    IpPort address3 = manager.getAvailableAddress();
    if (address1.getPort() == 9980) {
        Assert.assertEquals("127.0.0.1", address3.getHostOrIp());
        Assert.assertEquals(9981, address3.getPort());
    } else {
        Assert.assertEquals("127.0.0.1", address3.getHostOrIp());
        Assert.assertEquals(9980, address3.getPort());
    }
    Map<String, List<CacheEndpoint>> addresses = new HashMap<>();
    List<CacheEndpoint> instances = new ArrayList<>();
    instances.add(new CacheEndpoint("http://127.0.0.1:9982", null));
    addresses.put("rest", instances);
    new Expectations() {

        {
            cacheManager.getOrCreate("default", "SERVICECENTER", "latest");
            result = cache;
            cache.getOrCreateTransportMap();
            result = addresses;
        }
    };
    manager.initAutoDiscovery();
    IpPort address4 = manager.getNextAvailableAddress(address3);
    if (address1.getPort() == 9980) {
        Assert.assertEquals("127.0.0.1", address4.getHostOrIp());
        Assert.assertEquals(9982, address4.getPort());
    } else {
        address4 = manager.getNextAvailableAddress(address1);
        Assert.assertEquals("127.0.0.1", address4.getHostOrIp());
        Assert.assertEquals(9982, address4.getPort());
    }
    IpPort address5 = manager.getNextAvailableAddress(address4);
    Assert.assertEquals("127.0.0.1", address5.getHostOrIp());
    Assert.assertEquals(9980, address5.getPort());
}
Also used : Expectations(mockit.Expectations) HashMap(java.util.HashMap) CacheEndpoint(org.apache.servicecomb.serviceregistry.cache.CacheEndpoint) ArrayList(java.util.ArrayList) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.Test)

Example 39 with IpPort

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

the class RestUtils method httpDo.

public static void httpDo(long timeout, RequestContext requestContext, Handler<RestResponse> responseHandler) {
    HttpClientWithContext vertxHttpClient = HttpClientPool.INSTANCE.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);
        }
        HttpClientRequest httpClientRequest = httpClient.request(httpMethod, ipPort.getPort(), ipPort.getHostOrIp(), url.toString(), response -> {
            responseHandler.handle(new RestResponse(requestContext, response));
        });
        httpClientRequest.setTimeout(timeout).exceptionHandler(e -> {
            LOGGER.error("{} {} fail, endpoint is {}:{}, message: {}", httpMethod, url.toString(), ipPort.getHostOrIp(), ipPort.getPort(), e.getMessage());
            responseHandler.handle(new RestResponse(requestContext, null));
        });
        // 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) {
            httpClientRequest.end(Buffer.buffer(requestParam.getBody()));
        } else {
            httpClientRequest.end();
        }
    });
}
Also used : HttpClientRequest(io.vertx.core.http.HttpClientRequest) SignRequest(org.apache.servicecomb.foundation.auth.SignRequest) HttpClientWithContext(org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) MultiMap(io.vertx.core.MultiMap) HashMap(java.util.HashMap) Map(java.util.Map) HttpMethod(io.vertx.core.http.HttpMethod)

Example 40 with IpPort

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

the class ServiceRegistryClientImpl method isSchemaExist.

@Override
public boolean isSchemaExist(String microserviceId, String schemaId) {
    Holder<GetExistenceResponse> holder = new Holder<>();
    IpPort ipPort = ipPortManager.getAvailableAddress();
    CountDownLatch countDownLatch = new CountDownLatch(1);
    RestUtils.get(ipPort, Const.REGISTRY_API.MICROSERVICE_EXISTENCE, new RequestParam().addQueryParam("type", "schema").addQueryParam("serviceId", microserviceId).addQueryParam("schemaId", schemaId), syncHandler(countDownLatch, GetExistenceResponse.class, holder));
    try {
        countDownLatch.await();
    } catch (Exception e) {
        LOGGER.error("query schema exist {}/{} fail", microserviceId, schemaId, e);
    }
    return holder.value != null && schemaId.equals(holder.value.getSchemaId());
}
Also used : Holder(javax.xml.ws.Holder) IpPort(org.apache.servicecomb.foundation.common.net.IpPort) CountDownLatch(java.util.concurrent.CountDownLatch) GetExistenceResponse(org.apache.servicecomb.serviceregistry.api.response.GetExistenceResponse) ClientException(org.apache.servicecomb.serviceregistry.client.ClientException)

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