Search in sources :

Example 6 with EndpointStrategy

use of co.cask.cdap.common.discovery.EndpointStrategy in project cdap by caskdata.

the class FlowTest method testFlow.

@Test
public void testFlow() throws Exception {
    final ApplicationWithPrograms app = AppFabricTestHelper.deployApplicationWithManager(WordCountApp.class, TEMP_FOLDER_SUPPLIER);
    List<ProgramController> controllers = Lists.newArrayList();
    for (ProgramDescriptor programDescriptor : app.getPrograms()) {
        // running mapreduce is out of scope of this tests (there's separate unit-test for that)
        if (programDescriptor.getProgramId().getType() == ProgramType.MAPREDUCE) {
            continue;
        }
        controllers.add(AppFabricTestHelper.submit(app, programDescriptor.getSpecification().getClassName(), new BasicArguments(), TEMP_FOLDER_SUPPLIER));
    }
    TimeUnit.SECONDS.sleep(1);
    TransactionSystemClient txSystemClient = AppFabricTestHelper.getInjector().getInstance(TransactionSystemClient.class);
    QueueName queueName = QueueName.fromStream(app.getApplicationId().getNamespace(), "text");
    QueueClientFactory queueClientFactory = AppFabricTestHelper.getInjector().getInstance(QueueClientFactory.class);
    QueueProducer producer = queueClientFactory.createProducer(queueName);
    // start tx to write in queue in tx
    Transaction tx = txSystemClient.startShort();
    ((TransactionAware) producer).startTx(tx);
    StreamEventCodec codec = new StreamEventCodec();
    for (int i = 0; i < 10; i++) {
        String msg = "Testing message " + i;
        StreamEvent event = new StreamEvent(ImmutableMap.<String, String>of(), ByteBuffer.wrap(msg.getBytes(Charsets.UTF_8)));
        producer.enqueue(new QueueEntry(codec.encodePayload(event)));
    }
    // commit tx
    ((TransactionAware) producer).commitTx();
    txSystemClient.commit(tx);
    // Query the service for at most 10 seconds for the expected result
    Gson gson = new Gson();
    DiscoveryServiceClient discoveryServiceClient = AppFabricTestHelper.getInjector().getInstance(DiscoveryServiceClient.class);
    ServiceDiscovered serviceDiscovered = discoveryServiceClient.discover(String.format("service.%s.%s.%s", DefaultId.NAMESPACE.getNamespace(), "WordCountApp", "WordFrequencyService"));
    EndpointStrategy endpointStrategy = new RandomEndpointStrategy(serviceDiscovered);
    int trials = 0;
    while (trials++ < 10) {
        Discoverable discoverable = endpointStrategy.pick(2, TimeUnit.SECONDS);
        URL url = new URL(String.format("http://%s:%d/v3/namespaces/default/apps/%s/services/%s/methods/%s/%s", discoverable.getSocketAddress().getHostName(), discoverable.getSocketAddress().getPort(), "WordCountApp", "WordFrequencyService", "wordfreq", "text:Testing"));
        try {
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            Map<String, Long> responseContent = gson.fromJson(new InputStreamReader(urlConn.getInputStream(), Charsets.UTF_8), new TypeToken<Map<String, Long>>() {
            }.getType());
            LOG.info("Service response: " + responseContent);
            if (ImmutableMap.of("text:Testing", 10L).equals(responseContent)) {
                break;
            }
        } catch (Throwable t) {
            LOG.info("Exception when trying to query service.", t);
        }
        TimeUnit.SECONDS.sleep(1);
    }
    Assert.assertTrue(trials < 10);
    for (ProgramController controller : controllers) {
        controller.stop().get();
    }
}
Also used : DiscoveryServiceClient(org.apache.twill.discovery.DiscoveryServiceClient) Gson(com.google.gson.Gson) URL(java.net.URL) TransactionSystemClient(org.apache.tephra.TransactionSystemClient) StreamEventCodec(co.cask.cdap.common.stream.StreamEventCodec) HttpURLConnection(java.net.HttpURLConnection) QueueProducer(co.cask.cdap.data2.queue.QueueProducer) EndpointStrategy(co.cask.cdap.common.discovery.EndpointStrategy) RandomEndpointStrategy(co.cask.cdap.common.discovery.RandomEndpointStrategy) ApplicationWithPrograms(co.cask.cdap.internal.app.deploy.pipeline.ApplicationWithPrograms) ProgramDescriptor(co.cask.cdap.app.program.ProgramDescriptor) BasicArguments(co.cask.cdap.internal.app.runtime.BasicArguments) QueueName(co.cask.cdap.common.queue.QueueName) ProgramController(co.cask.cdap.app.runtime.ProgramController) Discoverable(org.apache.twill.discovery.Discoverable) InputStreamReader(java.io.InputStreamReader) StreamEvent(co.cask.cdap.api.flow.flowlet.StreamEvent) ServiceDiscovered(org.apache.twill.discovery.ServiceDiscovered) QueueEntry(co.cask.cdap.data2.queue.QueueEntry) Transaction(org.apache.tephra.Transaction) TransactionAware(org.apache.tephra.TransactionAware) TypeToken(com.google.common.reflect.TypeToken) QueueClientFactory(co.cask.cdap.data2.queue.QueueClientFactory) RandomEndpointStrategy(co.cask.cdap.common.discovery.RandomEndpointStrategy) Test(org.junit.Test)

Example 7 with EndpointStrategy

use of co.cask.cdap.common.discovery.EndpointStrategy in project cdap by caskdata.

the class ProgramLifecycleHttpHandler method getServiceAvailability.

/**
   * Return the availability (i.e. discoverable registration) status of a service.
   */
@GET
@Path("/apps/{app-name}/versions/{app-version}/services/{service-name}/available")
public void getServiceAvailability(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId, @PathParam("app-name") String appName, @PathParam("app-version") String appVersion, @PathParam("service-name") String serviceName) throws Exception {
    ServiceId serviceId = new ApplicationId(namespaceId, appName, appVersion).service(serviceName);
    ProgramStatus status = lifecycleService.getProgramStatus(serviceId);
    if (status == ProgramStatus.STOPPED) {
        responder.sendString(HttpResponseStatus.SERVICE_UNAVAILABLE, "Service is stopped. Please start it.");
    } else {
        // Construct discoverable name and return 200 OK if discoverable is present. If not return 503.
        String serviceDiscoverableName = ServiceDiscoverable.getName(serviceId);
        EndpointStrategy endpointStrategy = new RandomEndpointStrategy(discoveryServiceClient.discover(serviceDiscoverableName));
        if (endpointStrategy.pick(300L, TimeUnit.MILLISECONDS) == null) {
            LOG.trace("Discoverable endpoint {} not found", serviceDiscoverableName);
            responder.sendString(HttpResponseStatus.SERVICE_UNAVAILABLE, "Service is running but not accepting requests at this time.");
        } else {
            responder.sendString(HttpResponseStatus.OK, "Service is available to accept requests.");
        }
    }
}
Also used : RandomEndpointStrategy(co.cask.cdap.common.discovery.RandomEndpointStrategy) EndpointStrategy(co.cask.cdap.common.discovery.EndpointStrategy) ApplicationId(co.cask.cdap.proto.id.ApplicationId) ServiceId(co.cask.cdap.proto.id.ServiceId) ProgramStatus(co.cask.cdap.proto.ProgramStatus) BatchProgramStatus(co.cask.cdap.proto.BatchProgramStatus) RandomEndpointStrategy(co.cask.cdap.common.discovery.RandomEndpointStrategy) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 8 with EndpointStrategy

use of co.cask.cdap.common.discovery.EndpointStrategy in project cdap by caskdata.

the class RouterServiceLookup method discoverService.

private EndpointStrategy discoverService(CacheKey key) throws UnsupportedEncodingException, ExecutionException {
    // First try with path routing
    String lookupService = genLookupName(key.getRouteDestination().getServiceName(), key.getHost(), key.getFirstPathPart());
    EndpointStrategy endpointStrategy = discover(new RouteDestination(lookupService));
    if (endpointStrategy.pick() == null) {
        // Try without path routing
        lookupService = genLookupName(key.getRouteDestination().getServiceName(), key.getHost());
        endpointStrategy = discover(new RouteDestination(lookupService));
    }
    return endpointStrategy;
}
Also used : UserServiceEndpointStrategy(co.cask.cdap.gateway.discovery.UserServiceEndpointStrategy) EndpointStrategy(co.cask.cdap.common.discovery.EndpointStrategy) RandomEndpointStrategy(co.cask.cdap.common.discovery.RandomEndpointStrategy)

Example 9 with EndpointStrategy

use of co.cask.cdap.common.discovery.EndpointStrategy in project cdap by caskdata.

the class RouterServiceLookup method discover.

private EndpointStrategy discover(RouteDestination routeDestination) throws ExecutionException {
    LOG.debug("Looking up service name {}", routeDestination);
    // If its a user service, then use DistributionEndpoint Strategy
    String serviceName = routeDestination.getServiceName();
    ServiceDiscovered serviceDiscovered = discoveryServiceClient.discover(serviceName);
    EndpointStrategy endpointStrategy = ServiceDiscoverable.isServiceDiscoverable(serviceName) ? new UserServiceEndpointStrategy(serviceDiscovered, routeStore, ServiceDiscoverable.getId(serviceName), fallbackStrategy, routeDestination.getVersion()) : new RandomEndpointStrategy(serviceDiscovered);
    if (endpointStrategy.pick(300L, TimeUnit.MILLISECONDS) == null) {
        LOG.debug("Discoverable endpoint {} not found", routeDestination);
    }
    return endpointStrategy;
}
Also used : UserServiceEndpointStrategy(co.cask.cdap.gateway.discovery.UserServiceEndpointStrategy) UserServiceEndpointStrategy(co.cask.cdap.gateway.discovery.UserServiceEndpointStrategy) EndpointStrategy(co.cask.cdap.common.discovery.EndpointStrategy) RandomEndpointStrategy(co.cask.cdap.common.discovery.RandomEndpointStrategy) ServiceDiscovered(org.apache.twill.discovery.ServiceDiscovered) RandomEndpointStrategy(co.cask.cdap.common.discovery.RandomEndpointStrategy)

Example 10 with EndpointStrategy

use of co.cask.cdap.common.discovery.EndpointStrategy in project cdap by caskdata.

the class HttpRequestHandler method getDiscoverable.

private WrappedDiscoverable getDiscoverable(final HttpRequest httpRequest, final InetSocketAddress address) {
    EndpointStrategy strategy = serviceLookup.getDiscoverable(address.getPort(), httpRequest);
    if (strategy == null) {
        throw new HandlerException(HttpResponseStatus.SERVICE_UNAVAILABLE, String.format("No endpoint strategy found for request : %s", httpRequest.getUri()));
    }
    Discoverable discoverable = strategy.pick();
    if (discoverable == null) {
        throw new HandlerException(HttpResponseStatus.SERVICE_UNAVAILABLE, String.format("No discoverable found for request : %s", httpRequest.getUri()));
    }
    return new WrappedDiscoverable(discoverable);
}
Also used : HandlerException(co.cask.cdap.common.HandlerException) Discoverable(org.apache.twill.discovery.Discoverable) EndpointStrategy(co.cask.cdap.common.discovery.EndpointStrategy)

Aggregations

EndpointStrategy (co.cask.cdap.common.discovery.EndpointStrategy)19 RandomEndpointStrategy (co.cask.cdap.common.discovery.RandomEndpointStrategy)18 DiscoveryServiceClient (org.apache.twill.discovery.DiscoveryServiceClient)8 Discoverable (org.apache.twill.discovery.Discoverable)6 AbstractModule (com.google.inject.AbstractModule)5 MetricsCollectionService (co.cask.cdap.api.metrics.MetricsCollectionService)4 DatasetService (co.cask.cdap.data2.datafabric.dataset.service.DatasetService)4 DatasetOpExecutor (co.cask.cdap.data2.datafabric.dataset.service.executor.DatasetOpExecutor)4 Injector (com.google.inject.Injector)4 ConfigModule (co.cask.cdap.common.guice.ConfigModule)3 DiscoveryRuntimeModule (co.cask.cdap.common.guice.DiscoveryRuntimeModule)3 UserServiceEndpointStrategy (co.cask.cdap.gateway.discovery.UserServiceEndpointStrategy)3 MetricsQueryService (co.cask.cdap.metrics.query.MetricsQueryService)3 AuthorizationEnforcementModule (co.cask.cdap.security.authorization.AuthorizationEnforcementModule)3 TransactionManager (org.apache.tephra.TransactionManager)3 ServiceDiscovered (org.apache.twill.discovery.ServiceDiscovered)3 ConnectionConfig (co.cask.cdap.client.config.ConnectionConfig)2 CConfiguration (co.cask.cdap.common.conf.CConfiguration)2 DataSetServiceModules (co.cask.cdap.data.runtime.DataSetServiceModules)2 DataSetsModules (co.cask.cdap.data.runtime.DataSetsModules)2