Search in sources :

Example 11 with ClientException

use of com.netflix.client.ClientException in project ribbon by Netflix.

the class NettyClientTest method testUnexpectedResponse.

@Test
public void testUnexpectedResponse() throws Exception {
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(SERVICE_URI + "testAsync/throttle");
    LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient();
    Observable<HttpClientResponse<ByteBuf>> responseObservable = client.submit(new Server(host, port), request);
    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);
    responseObservable.subscribe(new Action1<HttpClientResponse<ByteBuf>>() {

        @Override
        public void call(HttpClientResponse<ByteBuf> t1) {
            latch.countDown();
        }
    }, new Action1<Throwable>() {

        @Override
        public void call(Throwable t1) {
            error.set(t1);
            latch.countDown();
        }
    });
    latch.await();
    assertTrue(error.get() instanceof ClientException);
    ClientException ce = (ClientException) error.get();
    assertTrue(ce.getErrorType() == ClientException.ErrorType.SERVER_THROTTLED);
}
Also used : HttpServer(com.sun.net.httpserver.HttpServer) Server(com.netflix.loadbalancer.Server) MockWebServer(com.google.mockwebserver.MockWebServer) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuf(io.netty.buffer.ByteBuf) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientResponse(io.reactivex.netty.protocol.http.client.HttpClientResponse) ClientException(com.netflix.client.ClientException) Test(org.junit.Test)

Example 12 with ClientException

use of com.netflix.client.ClientException in project ribbon by Netflix.

the class NettyClientTest method testObservableWithMultipleServersFailed.

@Test
public void testObservableWithMultipleServersFailed() throws Exception {
    IClientConfig config = IClientConfig.Builder.newBuilder().withDefaultValues().withRetryOnAllOperations(true).withMaxAutoRetries(1).withMaxAutoRetriesNextServer(3).withConnectTimeout(100).build();
    HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person");
    BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule());
    LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config);
    Server badServer = new Server("localhost:12345");
    Server badServer1 = new Server("localhost:12346");
    Server badServer2 = new Server("localhost:12347");
    List<Server> servers = Lists.newArrayList(badServer, badServer1, badServer2);
    lb.setServersList(servers);
    Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request));
    ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>();
    observableWithRetries.subscribe(observer);
    observer.await();
    assertNull(observer.obj);
    observer.error.printStackTrace();
    assertTrue(observer.error instanceof ClientException);
    ServerStats stats = lbObservables.getServerStats(badServer);
    // two requests to bad server because retry same server is set to 1
    assertEquals(2, stats.getTotalRequestsCount());
    assertEquals(0, stats.getActiveRequestsCount());
    assertEquals(2, stats.getSuccessiveConnectionFailureCount());
}
Also used : HttpServer(com.sun.net.httpserver.HttpServer) Server(com.netflix.loadbalancer.Server) MockWebServer(com.google.mockwebserver.MockWebServer) BaseLoadBalancer(com.netflix.loadbalancer.BaseLoadBalancer) ByteBuf(io.netty.buffer.ByteBuf) ServerStats(com.netflix.loadbalancer.ServerStats) DummyPing(com.netflix.loadbalancer.DummyPing) IClientConfig(com.netflix.client.config.IClientConfig) ClientException(com.netflix.client.ClientException) AvailabilityFilteringRule(com.netflix.loadbalancer.AvailabilityFilteringRule) Person(com.netflix.ribbon.test.resources.EmbeddedResources.Person) Test(org.junit.Test)

Example 13 with ClientException

use of com.netflix.client.ClientException in project feign by OpenFeign.

the class PropagateFirstIOExceptionTest method propagatesFirstNestedIOE.

@Test
public void propagatesFirstNestedIOE() throws IOException {
    thrown.expect(IOException.class);
    thrown.expectCause(isA(IOException.class));
    RibbonClient.propagateFirstIOException(new ClientException(new IOException(new IOException())));
}
Also used : IOException(java.io.IOException) ClientException(com.netflix.client.ClientException) Test(org.junit.Test)

Example 14 with ClientException

use of com.netflix.client.ClientException in project ribbon by Netflix.

the class LoadBalancerCommand method submit.

/**
     * Create an {@link Observable} that once subscribed execute network call asynchronously with a server chosen by load balancer.
     * If there are any errors that are indicated as retriable by the {@link RetryHandler}, they will be consumed internally by the
     * function and will not be observed by the {@link Observer} subscribed to the returned {@link Observable}. If number of retries has
     * exceeds the maximal allowed, a final error will be emitted by the returned {@link Observable}. Otherwise, the first successful
     * result during execution and retries will be emitted.
     */
public Observable<T> submit(final ServerOperation<T> operation) {
    final ExecutionInfoContext context = new ExecutionInfoContext();
    if (listenerInvoker != null) {
        try {
            listenerInvoker.onExecutionStart();
        } catch (AbortExecutionException e) {
            return Observable.error(e);
        }
    }
    final int maxRetrysSame = retryHandler.getMaxRetriesOnSameServer();
    final int maxRetrysNext = retryHandler.getMaxRetriesOnNextServer();
    // Use the load balancer
    Observable<T> o = (server == null ? selectServer() : Observable.just(server)).concatMap(new Func1<Server, Observable<T>>() {

        @Override
        public // Called for each server being selected
        Observable<T> call(Server server) {
            context.setServer(server);
            final ServerStats stats = loadBalancerContext.getServerStats(server);
            // Called for each attempt and retry
            Observable<T> o = Observable.just(server).concatMap(new Func1<Server, Observable<T>>() {

                @Override
                public Observable<T> call(final Server server) {
                    context.incAttemptCount();
                    loadBalancerContext.noteOpenConnection(stats);
                    if (listenerInvoker != null) {
                        try {
                            listenerInvoker.onStartWithServer(context.toExecutionInfo());
                        } catch (AbortExecutionException e) {
                            return Observable.error(e);
                        }
                    }
                    final Stopwatch tracer = loadBalancerContext.getExecuteTracer().start();
                    return operation.call(server).doOnEach(new Observer<T>() {

                        private T entity;

                        @Override
                        public void onCompleted() {
                            recordStats(tracer, stats, entity, null);
                        // TODO: What to do if onNext or onError are never called?
                        }

                        @Override
                        public void onError(Throwable e) {
                            recordStats(tracer, stats, null, e);
                            logger.debug("Got error {} when executed on server {}", e, server);
                            if (listenerInvoker != null) {
                                listenerInvoker.onExceptionWithServer(e, context.toExecutionInfo());
                            }
                        }

                        @Override
                        public void onNext(T entity) {
                            this.entity = entity;
                            if (listenerInvoker != null) {
                                listenerInvoker.onExecutionSuccess(entity, context.toExecutionInfo());
                            }
                        }

                        private void recordStats(Stopwatch tracer, ServerStats stats, Object entity, Throwable exception) {
                            tracer.stop();
                            loadBalancerContext.noteRequestCompletion(stats, entity, exception, tracer.getDuration(TimeUnit.MILLISECONDS), retryHandler);
                        }
                    });
                }
            });
            if (maxRetrysSame > 0)
                o = o.retry(retryPolicy(maxRetrysSame, true));
            return o;
        }
    });
    if (maxRetrysNext > 0 && server == null)
        o = o.retry(retryPolicy(maxRetrysNext, false));
    return o.onErrorResumeNext(new Func1<Throwable, Observable<T>>() {

        @Override
        public Observable<T> call(Throwable e) {
            if (context.getAttemptCount() > 0) {
                if (maxRetrysNext > 0 && context.getServerAttemptCount() == (maxRetrysNext + 1)) {
                    e = new ClientException(ClientException.ErrorType.NUMBEROF_RETRIES_NEXTSERVER_EXCEEDED, "Number of retries on next server exceeded max " + maxRetrysNext + " retries, while making a call for: " + context.getServer(), e);
                } else if (maxRetrysSame > 0 && context.getAttemptCount() == (maxRetrysSame + 1)) {
                    e = new ClientException(ClientException.ErrorType.NUMBEROF_RETRIES_EXEEDED, "Number of retries exceeded max " + maxRetrysSame + " retries, while making a call for: " + context.getServer(), e);
                }
            }
            if (listenerInvoker != null) {
                listenerInvoker.onExecutionFailed(e, context.toFinalExecutionInfo());
            }
            return Observable.error(e);
        }
    });
}
Also used : Server(com.netflix.loadbalancer.Server) Stopwatch(com.netflix.servo.monitor.Stopwatch) AbortExecutionException(com.netflix.loadbalancer.reactive.ExecutionListener.AbortExecutionException) Observable(rx.Observable) ServerStats(com.netflix.loadbalancer.ServerStats) ClientException(com.netflix.client.ClientException) Func1(rx.functions.Func1)

Example 15 with ClientException

use of com.netflix.client.ClientException in project ribbon by Netflix.

the class AbstractServerList method getFilterImpl.

/**
     * Get a ServerListFilter instance. It uses {@link ClientFactory#instantiateInstanceWithClientConfig(String, IClientConfig)}
     * which in turn uses reflection to initialize the filter instance. 
     * The filter class name is determined by the value of {@link CommonClientConfigKey#NIWSServerListFilterClassName}
     * in the {@link IClientConfig}. The default implementation is {@link ZoneAffinityServerListFilter}.
     */
public AbstractServerListFilter<T> getFilterImpl(IClientConfig niwsClientConfig) throws ClientException {
    try {
        String niwsServerListFilterClassName = niwsClientConfig.getProperty(CommonClientConfigKey.NIWSServerListFilterClassName, ZoneAffinityServerListFilter.class.getName()).toString();
        AbstractServerListFilter<T> abstractNIWSServerListFilter = (AbstractServerListFilter<T>) ClientFactory.instantiateInstanceWithClientConfig(niwsServerListFilterClassName, niwsClientConfig);
        return abstractNIWSServerListFilter;
    } catch (Throwable e) {
        throw new ClientException(ClientException.ErrorType.CONFIGURATION, "Unable to get an instance of CommonClientConfigKey.NIWSServerListFilterClassName. Configured class:" + niwsClientConfig.getProperty(CommonClientConfigKey.NIWSServerListFilterClassName), e);
    }
}
Also used : ClientException(com.netflix.client.ClientException)

Aggregations

ClientException (com.netflix.client.ClientException)24 Test (org.junit.Test)18 URI (java.net.URI)11 HttpRequest (com.netflix.client.http.HttpRequest)9 Server (com.netflix.loadbalancer.Server)8 ServerStats (com.netflix.loadbalancer.ServerStats)7 MockWebServer (com.google.mockwebserver.MockWebServer)6 ByteBuf (io.netty.buffer.ByteBuf)6 IClientConfig (com.netflix.client.config.IClientConfig)5 AvailabilityFilteringRule (com.netflix.loadbalancer.AvailabilityFilteringRule)5 BaseLoadBalancer (com.netflix.loadbalancer.BaseLoadBalancer)5 DummyPing (com.netflix.loadbalancer.DummyPing)5 HttpServer (com.sun.net.httpserver.HttpServer)4 IOException (java.io.IOException)4 AbortExecutionException (com.netflix.loadbalancer.reactive.ExecutionListener.AbortExecutionException)3 HttpResponse (com.netflix.client.http.HttpResponse)2 ExecutionListener (com.netflix.loadbalancer.reactive.ExecutionListener)2 Person (com.netflix.ribbon.test.resources.EmbeddedResources.Person)2 Pair (com.netflix.util.Pair)2 HttpClientResponse (io.reactivex.netty.protocol.http.client.HttpClientResponse)2