Java Code Examples for org.apache.servicecomb.core.Invocation#addLocalContext()

The following examples show how to use org.apache.servicecomb.core.Invocation#addLocalContext() . 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: CseClientHttpRequest.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
protected Invocation prepareInvocation(Map<String, Object> swaggerArguments) {
  Invocation invocation =
      InvocationFactory.forConsumer(requestMeta.getReferenceConfig(),
          requestMeta.getOperationMeta(),
          requestMeta.getOperationMeta().buildBaseConsumerRuntimeType(),
          swaggerArguments);

  invocation.getHandlerContext().put(RestConst.REST_CLIENT_REQUEST_PATH,
      path + (this.uri.getRawQuery() == null ? "" : "?" + this.uri.getRawQuery()));

  if (context != null) {
    invocation.addContext(context.getContext());
    invocation.addLocalContext(context.getLocalContext());
  }

  if (responseType != null &&
      !(responseType instanceof Class && Part.class.isAssignableFrom((Class<?>) responseType))) {
    invocation.setSuccessResponseType(TypeFactory.defaultInstance().constructType(responseType));
  }

  invocation.getHandlerContext().put(RestConst.CONSUMER_HEADER, httpHeaders);
  return invocation;
}
 
Example 2
Source File: RestProducerInvocationCreator.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public Invocation create() {
  initRestOperation();

  Invocation invocation = InvocationFactory.forProvider(endpoint,
      restOperationMeta.getOperationMeta(),
      null);
  initInvocationContext(invocation);

  initProduceProcessor();
  initTransportContext(invocation);

  invocation.addLocalContext(RestConst.REST_REQUEST, requestEx);

  return invocation;
}
 
Example 3
Source File: CommonHttpEdgeDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
protected LoadBalancer getOrCreateLoadBalancer(Invocation invocation, String microserviceName, String versionRule) {
  DiscoveryContext context = new DiscoveryContext();
  context.setInputParameters(invocation);
  VersionedCache serversVersionedCache = discoveryTree.discovery(context,
      RegistrationManager.INSTANCE.getMicroservice().getAppId(),
      microserviceName,
      versionRule);
  invocation.addLocalContext(LoadbalanceHandler.CONTEXT_KEY_SERVER_LIST, serversVersionedCache.data());
  return loadBalancerMap
      .computeIfAbsent(microserviceName, name -> createLoadBalancer(microserviceName));
}
 
Example 4
Source File: LoadbalanceHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
protected LoadBalancer getOrCreateLoadBalancer(Invocation invocation) {
  DiscoveryContext context = new DiscoveryContext();
  context.setInputParameters(invocation);
  VersionedCache serversVersionedCache = discoveryTree.discovery(context,
      invocation.getAppId(),
      invocation.getMicroserviceName(),
      invocation.getMicroserviceVersionRule());
  invocation.addLocalContext(CONTEXT_KEY_SERVER_LIST, serversVersionedCache.data());

  return loadBalancerMap
      .computeIfAbsent(serversVersionedCache.name(), name -> createLoadBalancer(invocation.getMicroserviceName()));
}
 
Example 5
Source File: TestLoadBalanceHandler2.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void trying_chance_should_be_released() {
  List<ServiceCombServer> servers = new ArrayList<>();
  ServiceCombServer serviceCombServer = createMockedServer("instanceId", "rest://127.0.0.1:8080");
  servers.add(serviceCombServer);

  DiscoveryTree discoveryTree = createMockedDiscoveryTree(servers);
  LoadbalanceHandler handler = new LoadbalanceHandler(discoveryTree);

  // mock the process of the isolated server selected and changed to TRYING status
  ServiceCombServerStats serviceCombServerStats =
      mockServiceCombServerStats(serviceCombServer, 5, true);

  Invocation invocation = new NonSwaggerInvocation("testApp", "testMicroserviceName", "0.0.0+",
      (inv, aysnc) -> {
        Assert.assertEquals("rest://127.0.0.1:8080", inv.getEndpoint().getEndpoint());
        Assert.assertTrue(serviceCombServerStats.isIsolated());
        Assert.assertEquals(5, serviceCombServerStats.getCountinuousFailureCount());
        Assert.assertFalse(ServiceCombServerStats.isolatedServerCanTry());
        aysnc.success("OK");
      });

  Assert.assertTrue(ServiceCombServerStats.applyForTryingChance());
  invocation.addLocalContext(IsolationDiscoveryFilter.TRYING_INSTANCES_EXISTING, true);
  try {
    handler.handle(invocation, (response) -> Assert.assertEquals("OK", response.getResult()));
  } catch (Exception e) {
    Assert.fail("unexpected exception " + e.getMessage());
  }
  Assert.assertEquals("rest://127.0.0.1:8080", invocation.getEndpoint().getEndpoint());
  Assert.assertTrue(serviceCombServerStats.isIsolated());
  Assert.assertEquals(0, serviceCombServerStats.getCountinuousFailureCount());
  Assert.assertTrue(ServiceCombServerStats.isolatedServerCanTry());
}
 
Example 6
Source File: IsolationDiscoveryFilter.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
private boolean allowVisit(Invocation invocation, MicroserviceInstance instance) {
  ServiceCombServer server = ServiceCombLoadBalancerStats.INSTANCE.getServiceCombServer(instance);
  if (server == null) {
    // first time accessed.
    return true;
  }
  ServiceCombServerStats serverStats = ServiceCombLoadBalancerStats.INSTANCE.getServiceCombServerStats(server);
  Settings settings = createSettings(invocation);
  if (!checkThresholdAllowed(settings, serverStats)) {
    if (serverStats.isIsolated()
        && (System.currentTimeMillis() - serverStats.getLastVisitTime()) > settings.singleTestTime) {
      if (!ServiceCombServerStats.applyForTryingChance()) {
        // this server hasn't been isolated for enough long time, or there is no trying chance
        return false;
      }
      // [1]we can implement better recovery based on several attempts, but here we do not know if this attempt is success
      invocation.addLocalContext(TRYING_INSTANCES_EXISTING, Boolean.TRUE);
      return true;
    }
    if (!serverStats.isIsolated()) {
      serverStats.markIsolated(true);
      eventBus.post(
          new IsolationServerEvent(invocation, instance, serverStats,
              settings, Type.OPEN, server.getEndpoint()));
      LOGGER.warn("Isolate service {}'s instance {}.", invocation.getMicroserviceName(),
          instance.getInstanceId());
    }
    return false;
  }
  if (serverStats.isIsolated()) {
    // [2] so that we add a feature to isolate for at least a minimal time, and we can avoid
    // high volume of concurrent requests with a percentage of error(e.g. 50%) scenario with no isolation
    if ((System.currentTimeMillis() - serverStats.getLastVisitTime()) <= settings.minIsolationTime) {
      return false;
    }
    serverStats.markIsolated(false);
    eventBus.post(new IsolationServerEvent(invocation, instance, serverStats,
        settings, Type.CLOSE, server.getEndpoint()));
    LOGGER.warn("Recover service {}'s instance {} from isolation.", invocation.getMicroserviceName(),
        instance.getInstanceId());
  }
  return true;
}
 
Example 7
Source File: TestLoadBalanceHandler2.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
/**
 * Two available instances, first time the normal instance is selected and failed. Then retry to the TRYING status
 * instance. In the whole procedure, the TRYING status instance should keep the TRYING status.
 */
@Test
public void first_normal_instance_then_trying_instance() {
  ExtensionsManager.addExtentionsFactory(new DefaultRetryExtensionsFactory());
  ArchaiusUtils.setProperty("servicecomb.loadbalance.retryEnabled", true);
  ArchaiusUtils.setProperty("servicecomb.loadbalance.retryOnNext", 1);

  ArrayList<ServiceCombServer> servers = new ArrayList<>();
  ServiceCombServer server0 = createMockedServer("instanceId0", "rest://127.0.0.1:8080");
  ServiceCombServer server1 = createMockedServer("instanceId1", "rest://127.0.0.1:8081");
  servers.add(server0);
  servers.add(server1);

  ServiceCombServerStats stats0 = mockServiceCombServerStats(server0, 0, false);
  ServiceCombServerStats stats1 = mockServiceCombServerStats(server1, 5, true);

  DiscoveryTree discoveryTree = createMockedDiscoveryTree(servers);
  LoadbalanceHandler handler = new LoadbalanceHandler(discoveryTree);

  Holder<Integer> counter = new Holder<>(0);
  Invocation invocation = new NonSwaggerInvocation("testApp", "testMicroserviceName", "0.0.0+",
      (inv, aysnc) -> {
        Assert.assertFalse(stats0.isIsolated());
        Assert.assertTrue(stats1.isIsolated());
        Assert.assertEquals(5, stats1.getCountinuousFailureCount());
        Assert.assertFalse(ServiceCombServerStats.isolatedServerCanTry());
        if (counter.value == 0) {
          Assert.assertEquals("rest://127.0.0.1:8080", inv.getEndpoint().getEndpoint());
          Assert.assertEquals(0, stats0.getCountinuousFailureCount());
          counter.value++;
          aysnc.producerFail(new InvocationException(503, "RETRY", "retry to next instance"));
        } else if (counter.value == 1) {
          Assert.assertEquals("rest://127.0.0.1:8081", inv.getEndpoint().getEndpoint());
          Assert.assertEquals(1, stats0.getCountinuousFailureCount());
          counter.value++;
          aysnc.success("OK");
        } else {
          aysnc.producerFail(new InvocationException(400, "UNEXPECTED", "Unexpected Counter Value"));
        }
      });

  Assert.assertTrue(ServiceCombServerStats.applyForTryingChance());
  invocation.addLocalContext(IsolationDiscoveryFilter.TRYING_INSTANCES_EXISTING, true);
  try {
    handler.handle(invocation, (response) -> Assert.assertEquals("OK", response.getResult()));
  } catch (Exception e) {
    Assert.fail("unexpected exception " + e.getMessage());
  }
  Assert.assertEquals("rest://127.0.0.1:8081", invocation.getEndpoint().getEndpoint());
  Assert.assertFalse(stats0.isIsolated());
  Assert.assertEquals(1, stats0.getCountinuousFailureCount());
  Assert.assertTrue(stats1.isIsolated());
  Assert.assertEquals(0, stats1.getCountinuousFailureCount());
  Assert.assertTrue(ServiceCombServerStats.isolatedServerCanTry());
}