Java Code Examples for com.linecorp.armeria.client.Endpoint#of()

The following examples show how to use com.linecorp.armeria.client.Endpoint#of() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HealthCheckedEndpointGroupLongPollingPingTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void noPingAtAll() throws Exception {
    final BlockingQueue<RequestLogAccess> healthCheckRequestLogs = new LinkedTransferQueue<>();
    this.healthCheckRequestLogs = healthCheckRequestLogs;

    final Endpoint endpoint = Endpoint.of("127.0.0.1", server.httpPort());
    try (HealthCheckedEndpointGroup endpointGroup = build(
            HealthCheckedEndpointGroup.builder(endpoint, "/no_ping_at_all"))) {

        Thread.sleep(3000);

        assertFirstRequest(healthCheckRequestLogs);

        // The second request must time out while long-polling.
        final RequestLog longPollingRequestLog = healthCheckRequestLogs.take().whenComplete().join();
        assertThat(longPollingRequestLog.responseCause()).isInstanceOf(ResponseTimeoutException.class);

        // There must be no '102 Processing' headers received.
        final BlockingQueue<ResponseHeaders> receivedInformationals =
                longPollingRequestLog.context().attr(RECEIVED_INFORMATIONALS);
        assertThat(receivedInformationals).isEmpty();

        // Eventually, the endpoint must stay healthy.
        assertThat(endpointGroup.endpoints()).isEmpty();
    }
}
 
Example 2
Source File: CuratorDiscoverySpecBuilder.java    From armeria with Apache License 2.0 6 votes vote down vote up
private Function<? super ServiceInstance<?>, Endpoint> converter() {
    if (converter != null) {
        return converter;
    }
    return instance -> {
        if (!instance.isEnabled()) {
            return null;
        }
        if (instanceId != null && !instanceId.equals(instance.getId())) {
            return null;
        }
        if (useSsl != null && useSsl && instance.getSslPort() != null) {
            return Endpoint.of(instance.getAddress(), instance.getSslPort());
        }

        if (instance.getPort() != null) {
            return Endpoint.of(instance.getAddress(), instance.getPort());
        }
        return Endpoint.of(instance.getAddress());
    };
}
 
Example 3
Source File: PartialHealthCheckStrategyTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void updateHealthByDisappearedCandidate() {
    final Endpoint disappearedCandidate = Endpoint.of("disappeared");
    final List<Endpoint> candidates = createCandidates(3);

    maxCountStrategy.updateCandidates(candidates);
    assertThat(maxCountStrategy.getSelectedEndpoints()).hasSize(3);

    boolean updateRes = maxCountStrategy.updateHealth(disappearedCandidate, HEALTHY);
    assertThat(updateRes).isTrue();

    List<Endpoint> selectedCandidates = maxCountStrategy.getSelectedEndpoints();
    assertThat(selectedCandidates).hasSize(3)
                                  .doesNotContain(disappearedCandidate);

    updateRes = maxCountStrategy.updateHealth(disappearedCandidate, UNHEALTHY);
    assertThat(updateRes).isTrue();

    selectedCandidates = maxCountStrategy.getSelectedEndpoints();
    assertThat(selectedCandidates).hasSize(3)
                                  .doesNotContain(disappearedCandidate);
}
 
Example 4
Source File: HealthCheckedEndpointGroupLongPollingTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void periodicCheckWhenConnectionRefused() throws Exception {
    final BlockingQueue<RequestLog> healthCheckRequestLogs = new LinkedTransferQueue<>();
    this.healthCheckRequestLogs = healthCheckRequestLogs;
    final Endpoint endpoint = Endpoint.of("127.0.0.1", 1);
    try (HealthCheckedEndpointGroup endpointGroup = build(
            HealthCheckedEndpointGroup.builder(endpoint, HEALTH_CHECK_PATH))) {

        // Check the initial state (unhealthy).
        assertThat(endpointGroup.endpoints()).isEmpty();

        // Drop the first request.
        healthCheckRequestLogs.take();

        final Stopwatch stopwatch = Stopwatch.createUnstarted();
        for (int i = 0; i < 2; i++) {
            stopwatch.reset().start();
            healthCheckRequestLogs.take();
            assertThat(stopwatch.elapsed(TimeUnit.MILLISECONDS))
                    .isGreaterThan(RETRY_INTERVAL.toMillis() * 4 / 5);
        }
    } finally {
        this.healthCheckRequestLogs = null;
    }
}
 
Example 5
Source File: HealthCheckedEndpointGroupLongPollingTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void immediateNotification() throws Exception {
    final Endpoint endpoint = Endpoint.of("127.0.0.1", server.httpPort());
    try (HealthCheckedEndpointGroup endpointGroup = build(
            HealthCheckedEndpointGroup.builder(endpoint, HEALTH_CHECK_PATH))) {

        // Check the initial state (healthy).
        assertThat(endpointGroup.endpoints()).containsExactly(endpoint);

        // Make the server unhealthy.
        health.setHealthy(false);
        waitForGroup(endpointGroup, null);

        // Make the server healthy again.
        health.setHealthy(true);
        waitForGroup(endpointGroup, endpoint);

        // Stop the server.
        server.stop();
        waitForGroup(endpointGroup, null);
    }
}
 
Example 6
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void endpointRemapper() {
    final EndpointGroup group = Endpoint.of("127.0.0.1", server.httpPort());
    final TestServiceBlockingStub stub =
            Clients.builder("gproto+http://my-group")
                   .endpointRemapper(endpoint -> {
                       if ("my-group".equals(endpoint.host())) {
                           return group;
                       } else {
                           return endpoint;
                       }
                   })
                   .build(TestServiceBlockingStub.class);

    assertThat(stub.emptyCall(Empty.newBuilder().build())).isNotNull();
}
 
Example 7
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void endpointMapping(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {

    final Endpoint group = Endpoint.of("127.0.0.1", protocol.isTls() ? server.httpsPort()
                                                                     : server.httpPort());
    final HelloService.Iface client =
            Clients.builder(format.uriText() + '+' + protocol.uriText() +
                            "://my-group/" + Handlers.HELLO.path(format))
                   .options(clientOptions)
                   .endpointRemapper(endpoint -> {
                       if ("my-group".equals(endpoint.host())) {
                           return group;
                       } else {
                           return endpoint;
                       }
                   })
                   .build(Handlers.HELLO.iface());

    assertThat(client.hello("trustin")).isEqualTo("Hello, trustin!");
}
 
Example 8
Source File: ArmeriaCallFactory.java    From armeria with Apache License 2.0 5 votes vote down vote up
WebClient getWebClient(HttpUrl url) {
    if (baseWebClient.scheme().sessionProtocol().isTls() == url.isHttps() &&
        baseWebClientHost.equals(url.host()) &&
        baseWebClientPort == url.port()) {

        return baseWebClient;
    }

    final SessionProtocol protocol = url.isHttps() ? SessionProtocol.HTTPS : SessionProtocol.HTTP;
    final Endpoint endpoint = Endpoint.of(url.host(), url.port());
    return nonBaseWebClientFactory.apply(protocol, endpoint);
}
 
Example 9
Source File: HealthCheckedEndpointGroupLongPollingPingTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void noPingAfterInitialPing() throws Exception {
    final BlockingQueue<RequestLogAccess> healthCheckRequestLogs = new LinkedTransferQueue<>();
    this.healthCheckRequestLogs = healthCheckRequestLogs;

    final Endpoint endpoint = Endpoint.of("127.0.0.1", server.httpPort());
    try (HealthCheckedEndpointGroup endpointGroup = build(
            HealthCheckedEndpointGroup.builder(endpoint, "/no_ping_after_initial_ping"))) {

        Thread.sleep(3000);

        assertFirstRequest(healthCheckRequestLogs);

        // The second request must time out while long-polling.
        final RequestLog longPollingRequestLog = healthCheckRequestLogs.take().whenComplete().join();
        assertThat(longPollingRequestLog.responseCause()).isInstanceOf(ResponseTimeoutException.class);

        // There must be only one '102 Processing' header received.
        final BlockingQueue<ResponseHeaders> receivedInformationals =
                longPollingRequestLog.context().attr(RECEIVED_INFORMATIONALS);
        assertThat(receivedInformationals).isNotNull();
        for (ResponseHeaders headers : receivedInformationals) {
            assertThat(headers.status()).isEqualTo(HttpStatus.PROCESSING);
        }
        assertThat(receivedInformationals).hasSize(1);

        // Eventually, the endpoint must stay healthy.
        assertThat(endpointGroup.endpoints()).isEmpty();
    }
}
 
Example 10
Source File: HealthCheckedEndpointGroupLongPollingTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void keepEndpointHealthinessWhenLongPollingTimeout() throws Exception {
    final BlockingQueue<RequestLog> healthCheckRequestLogs = new LinkedTransferQueue<>();
    this.healthCheckRequestLogs = healthCheckRequestLogs;
    final Endpoint endpoint = Endpoint.of("127.0.0.1", server.httpPort());
    try (HealthCheckedEndpointGroup endpointGroup = build(
            HealthCheckedEndpointGroup.builder(endpoint, HEALTH_CHECK_PATH))) {

        // Check the initial state (healthy).
        assertThat(endpointGroup.endpoints()).containsExactly(endpoint);

        // Drop the first request.
        healthCheckRequestLogs.take();

        // Check the endpoint is populated even after long polling timeout.
        Thread.sleep(LONG_POLLING_TIMEOUT.toMillis());
        assertThat(endpointGroup.endpoints()).containsExactly(endpoint);

        // Must receive the '304 Not Modified' response with long polling.
        final ResponseHeaders notModifiedResponseHeaders = healthCheckRequestLogs.take().responseHeaders();
        assertThat(notModifiedResponseHeaders.status()).isEqualTo(HttpStatus.NOT_MODIFIED);
        assertThat(notModifiedResponseHeaders.getLong("armeria-lphc", 1))
                .isEqualTo(LONG_POLLING_TIMEOUT.getSeconds());

        final Stopwatch stopwatch = Stopwatch.createStarted();
        healthCheckRequestLogs.take();
        assertThat(stopwatch.elapsed(TimeUnit.MILLISECONDS))
                .isLessThanOrEqualTo((long) (LONG_POLLING_TIMEOUT.toMillis() * 1.1)); // buffer 10 percent.
    }
}
 
Example 11
Source File: ArmeriaRetrofitBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void build_armeriaGroupAuthority() {
    final Endpoint endpoint = Endpoint.of("127.0.0.1", 8080);
    final EndpointGroup group = EndpointGroup.of(endpoint, endpoint);

    assertThat(ArmeriaRetrofit.of(SessionProtocol.H2C, endpoint).baseUrl().toString())
            .isEqualTo("http://127.0.0.1:8080/");

    assertThat(ArmeriaRetrofit.of(SessionProtocol.H2, group).baseUrl().toString())
            .startsWith("https://armeria-group-");
}
 
Example 12
Source File: HealthCheckedEndpointGroupTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void updatesSelectedCandidatesNoStackOverflowEvenUpdatesOnEqualThread() {
    final AtomicReference<HealthCheckerContext> firstSelectedCandidates = new AtomicReference<>();
    final Function<? super HealthCheckerContext, ? extends AsyncCloseable> checkFactory = ctx -> {
        if (firstSelectedCandidates.get() == null) {
            firstSelectedCandidates.set(ctx);
        }

        ctx.updateHealth(HEALTHY);
        return AsyncCloseableSupport.of();
    };

    final Endpoint candidate1 = Endpoint.of("candidate1");
    final Endpoint candidate2 = Endpoint.of("candidate2");

    final MockEndpointGroup delegate = new MockEndpointGroup();
    delegate.set(candidate1, candidate2);

    try (HealthCheckedEndpointGroup group =
                 new HealthCheckedEndpointGroup(delegate, SessionProtocol.HTTP, 80,
                                                DEFAULT_HEALTH_CHECK_RETRY_BACKOFF,
                                                ClientOptions.of(), checkFactory,
                                                new InfinityUpdateHealthCheckStrategy())) {

        assertThat(group.healthyEndpoints).containsOnly(candidate1, candidate2);

        firstSelectedCandidates.get().updateHealth(UNHEALTHY);
        assertThat(group.healthyEndpoints).containsOnly(candidate2);
    }
}
 
Example 13
Source File: AbstractEndpointSelectorTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void immediateSelection() {
    final Endpoint endpoint = Endpoint.of("foo");
    final ClientRequestContext ctx = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    assertThat(newSelector(endpoint).select(ctx, ctx.eventLoop(), Long.MAX_VALUE))
            .isCompletedWithValue(endpoint);
}
 
Example 14
Source File: AbstractEndpointSelectorTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void delayedSelection() {
    final DynamicEndpointGroup group = new DynamicEndpointGroup();
    final ClientRequestContext ctx = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    final CompletableFuture<Endpoint> future = newSelector(group).select(ctx, ctx.eventLoop(),
                                                                         Long.MAX_VALUE);
    assertThat(future).isNotDone();

    final Endpoint endpoint = Endpoint.of("foo");
    group.addEndpoint(endpoint);
    assertThat(future.join()).isSameAs(endpoint);
}
 
Example 15
Source File: DnsServiceEndpointGroup.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
ImmutableSortedSet<Endpoint> onDnsRecords(List<DnsRecord> records, int ttl) throws Exception {
    final ImmutableSortedSet.Builder<Endpoint> builder = ImmutableSortedSet.naturalOrder();
    for (DnsRecord r : records) {
        if (!(r instanceof DnsRawRecord) || r.type() != DnsRecordType.SRV) {
            continue;
        }

        final ByteBuf content = ((ByteBufHolder) r).content();
        if (content.readableBytes() <= 6) { // Too few bytes
            warnInvalidRecord(DnsRecordType.SRV, content);
            continue;
        }

        content.markReaderIndex();
        content.skipBytes(2);  // priority unused
        final int weight = content.readUnsignedShort();
        final int port = content.readUnsignedShort();

        final Endpoint endpoint;
        try {
            final String target = stripTrailingDot(DefaultDnsRecordDecoder.decodeName(content));
            endpoint = port > 0 ? Endpoint.of(target, port) : Endpoint.of(target);
        } catch (Exception e) {
            content.resetReaderIndex();
            warnInvalidRecord(DnsRecordType.SRV, content);
            continue;
        }

        builder.add(endpoint.withWeight(weight));
    }

    final ImmutableSortedSet<Endpoint> endpoints = builder.build();
    if (logger().isDebugEnabled()) {
        logger().debug("{} Resolved: {} (TTL: {})",
                       logPrefix(),
                       endpoints.stream()
                                .map(e -> e.authority() + '/' + e.weight())
                                .collect(Collectors.joining(", ")),
                       ttl);
    }

    return endpoints;
}
 
Example 16
Source File: NettyServerExtension.java    From armeria with Apache License 2.0 4 votes vote down vote up
public final Endpoint endpoint() {
    return Endpoint.of(address().getHostString(), address().getPort());
}
 
Example 17
Source File: HealthCheckedEndpointGroupLongPollingTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void longPollingDisabledOnStop() throws Exception {
    final BlockingQueue<RequestLog> healthCheckRequestLogs = new LinkedTransferQueue<>();
    this.healthCheckRequestLogs = healthCheckRequestLogs;
    final Endpoint endpoint = Endpoint.of("127.0.0.1", server.httpPort());
    try (HealthCheckedEndpointGroup endpointGroup = build(
            HealthCheckedEndpointGroup.builder(endpoint, HEALTH_CHECK_PATH))) {

        // Check the initial state (healthy).
        assertThat(endpointGroup.endpoints()).containsExactly(endpoint);

        // Drop the first request.
        healthCheckRequestLogs.take();

        // Stop the server.
        server.stop();
        waitForGroup(endpointGroup, null);

        // Must receive the '503 Service Unavailable' response with long polling disabled,
        // so that the next health check respects the backoff.
        for (;;) {
            final ResponseHeaders stoppingResponseHeaders = healthCheckRequestLogs.take().responseHeaders();
            if (stoppingResponseHeaders.status() == HttpStatus.OK) {
                // It is possible to get '200 OK' if the server sent a response before the shutdown.
                // Just try again so that another health check request is sent.
                continue;
            }

            assertThat(stoppingResponseHeaders.status()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
            assertThat(stoppingResponseHeaders.getLong("armeria-lphc")).isNull();
            break;
        }

        // Check the next check respected backoff, because there's no point of
        // sending a request immediately only to get a 'connection refused' error.
        final Stopwatch stopwatch = Stopwatch.createStarted();
        healthCheckRequestLogs.take();
        assertThat(stopwatch.elapsed(TimeUnit.MILLISECONDS))
                .isGreaterThan(RETRY_INTERVAL.toMillis() * 4 / 5);
    }
}
 
Example 18
Source File: ServerSetRegistrationTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void serverSetImplCompatible() throws Throwable {
    final List<Endpoint> endpoints = ZooKeeperTestUtil.sampleEndpoints(2);
    final ZooKeeperClient zooKeeperClient =
            new ZooKeeperClient(Duration.fromSeconds(20),
                                InetSocketAddress.createUnresolved("127.0.0.1", zkInstance.port()));
    final ServerSetImpl serverSet = new ServerSetImpl(zooKeeperClient, Z_NODE);
    final Map<String, InetSocketAddress> additionals = ImmutableMap.of(
            "foo", InetSocketAddress.createUnresolved("127.0.0.1", endpoints.get(1).port()));
    final EndpointStatus endpointStatus =
            serverSet.join(InetSocketAddress.createUnresolved("127.0.0.1", 1),
                           additionals, -100, ImmutableMap.of("bar", "baz"));

    final byte[] serverSetImplBytes;
    try (CloseableZooKeeper zk = zkInstance.connection()) {
        serverSetImplBytes = zk.getData(Z_NODE + "/member_0000000000").get();
    }

    endpointStatus.leave();
    await().untilAsserted(() -> zkInstance.assertNotExists(Z_NODE + "/member_0000000000"));

    final ServerSetsRegistrationSpecBuilder specBuilder =
            ZooKeeperRegistrationSpec.builderForServerSets();
    final ZooKeeperRegistrationSpec spec =
            specBuilder.serviceEndpoint(Endpoint.of("127.0.0.1", 1))
                       .additionalEndpoint("foo", Endpoint.of("127.0.0.1", endpoints.get(1).port()))
                       .shardId(-100)
                       .metadata(ImmutableMap.of("bar", "baz"))
                       .build();

    final ZooKeeperUpdatingListener listener =
            ZooKeeperUpdatingListener.builder(zkInstance.connectString(), Z_NODE, spec).build();
    final Server server = Server.builder()
                                .serverListener(listener)
                                .tlsSelfSigned()
                                .http(endpoints.get(0).port())
                                .https(endpoints.get(1).port())
                                .service("/", (ctx, req) -> HttpResponse.of(200))
                                .build();
    server.start().join();

    final byte[] updatingListenerBytes;
    try (CloseableZooKeeper zk = zkInstance.connection()) {
        updatingListenerBytes = zk.getData(Z_NODE + "/member_0000000001").get();
    }
    assertThat(updatingListenerBytes).isEqualTo(serverSetImplBytes);
    final ServerSetsInstance decoded = ServerSetsNodeValueCodec.INSTANCE.decode(
            updatingListenerBytes);
    final ServerSetsInstance expected = new ServerSetsInstance(
            // The specified port number is used although the port is not actually used.
            Endpoint.of("127.0.0.1", 1),
            ImmutableMap.of("foo", Endpoint.of("127.0.0.1", endpoints.get(1).port())),
            -100,
            ImmutableMap.of("bar", "baz"));
    assertThat(decoded).isEqualTo(expected);

    server.stop().join();
    await().untilAsserted(() -> zkInstance.assertNotExists(Z_NODE + "/member_0000000001"));
}
 
Example 19
Source File: ServerSetsInstanceConverter.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static Endpoint endpoint(JsonNode serviceEndpointNode) {
    return Endpoint.of(serviceEndpointNode.get(HOST).asText(),
                       serviceEndpointNode.get(PORT).asInt());
}
 
Example 20
Source File: ElasticsearchDomainEndpointTest.java    From zipkin-aws with Apache License 2.0 4 votes vote down vote up
@Before public void setUp() {
  client = new ElasticsearchDomainEndpoint((endpoint) -> WebClient.of(HTTP, endpoint),
      Endpoint.of("localhost", server.httpPort()), "ap-southeast-1", "zipkin53");
}