org.apache.servicecomb.core.Invocation Java Examples

The following examples show how to use org.apache.servicecomb.core.Invocation. 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: AuthenticationFilter.java    From scaffold with Apache License 2.0 7 votes vote down vote up
@Override
public Response afterReceiveRequest(Invocation invocation, HttpServletRequestEx httpServletRequestEx) {
  if (isInvocationNeedValidate(invocation.getMicroserviceName(), invocation.getOperationName())) {
    String token = httpServletRequestEx.getHeader(AUTHORIZATION);
    if (StringUtils.isNotEmpty(token)) {
      String userName = template
          .getForObject("cse://" + USER_SERVICE_NAME + "/validate?token={token}", String.class, token);
      if (StringUtils.isNotEmpty(userName)) {
        //Add header
        invocation.getContext().put(EDGE_AUTHENTICATION_NAME, userName);
      } else {
        return Response
            .failResp(new InvocationException(Status.UNAUTHORIZED, "authentication failed, invalid token"));
      }
    } else {
      return Response.failResp(
          new InvocationException(Status.UNAUTHORIZED, "authentication failed, missing AUTHORIZATION header"));
    }
  }
  return null;
}
 
Example #2
Source File: LocalHostItemTest.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Before
public void initStrBuilder() {
  accessLogEvent = new ServerAccessLogEvent();
  routingContext = Mockito.mock(RoutingContext.class);
  finishEvent = Mockito.mock(InvocationFinishEvent.class);
  serverRequest = Mockito.mock(HttpServerRequest.class);
  socketAddress = Mockito.mock(SocketAddress.class);
  invocation = Mockito.mock(Invocation.class);
  restClientRequest = Mockito.mock(RestClientRequestImpl.class);
  clientRequest = Mockito.mock(HttpClientRequest.class);
  connection = Mockito.mock(HttpConnection.class);
  Map<String, Object> handlerMap = new HashMap<>();
  handlerMap.put(RestConst.INVOCATION_HANDLER_REQUESTCLIENT, restClientRequest);
  when(finishEvent.getInvocation()).thenReturn(invocation);
  when(invocation.getHandlerContext()).thenReturn(handlerMap);
  accessLogEvent.setRoutingContext(routingContext);
  strBuilder = new StringBuilder();
}
 
Example #3
Source File: LocalPortItemTest.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Before
public void initStrBuilder() {
  accessLogEvent = new ServerAccessLogEvent();
  routingContext = Mockito.mock(RoutingContext.class);
  finishEvent = Mockito.mock(InvocationFinishEvent.class);
  serverRequest = Mockito.mock(HttpServerRequest.class);
  socketAddress = Mockito.mock(SocketAddress.class);
  invocation = Mockito.mock(Invocation.class);
  restClientRequest = Mockito.mock(RestClientRequestImpl.class);
  clientRequest = Mockito.mock(HttpClientRequest.class);
  connection = Mockito.mock(HttpConnection.class);
  Map<String, Object> handlerMap = new HashMap<>();
  handlerMap.put(RestConst.INVOCATION_HANDLER_REQUESTCLIENT, restClientRequest);
  when(finishEvent.getInvocation()).thenReturn(invocation);
  when(invocation.getHandlerContext()).thenReturn(handlerMap);
  accessLogEvent.setRoutingContext(routingContext);
  strBuilder = new StringBuilder();
}
 
Example #4
Source File: ProviderQpsFlowControlHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
  if (invocation.getHandlerIndex() > 0) {
    // handlerIndex > 0, which means this handler is executed in handler chain.
    // As this flow control logic has been executed in advance, this time it should be ignored.
    invocation.next(asyncResp);
    return;
  }

  // The real executing position of this handler is no longer in handler chain, but in AbstractRestInvocation.
  // Therefore, the Invocation#next() method should not be called below.
  if (!Config.INSTANCE.isProviderEnabled()) {
    return;
  }

  String microserviceName = invocation.getContext(Const.SRC_MICROSERVICE);
  QpsController qpsController =
      StringUtils.isEmpty(microserviceName)
          ? qpsControllerMgr.getGlobalQpsController()
          : qpsControllerMgr.getOrCreate(microserviceName, invocation);
  isLimitNewRequest(qpsController, asyncResp);
}
 
Example #5
Source File: RouterInvokeFilter.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
/**
 * pass through headers
 *
 * @param invocation
 * @param httpServletRequestEx
 * @return
 */
@Override
public Response afterReceiveRequest(Invocation invocation,
    HttpServletRequestEx httpServletRequestEx) {
  if (!isHaveHeadersRule()) {
    return null;
  }
  if (!RouterRuleCache.isServerContainRule(invocation.getMicroserviceName())) {
    return null;
  }
  if (loadHeaders()) {
    Map<String, String> headerMap = getHeaderMap(httpServletRequestEx);
    try {
      invocation.addContext(ROUTER_HEADER, JsonUtils.OBJ_MAPPER.writeValueAsString(headerMap));
    } catch (JsonProcessingException e) {
      LOGGER.error("canary context serialization failed");
    }
  }
  return null;
}
 
Example #6
Source File: LoadBalancer.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public ServiceCombServer chooseServer(Invocation invocation) {
  List<ServiceCombServer> servers = invocation.getLocalContext(LoadbalanceHandler.CONTEXT_KEY_SERVER_LIST);
  int serversCount = servers.size();
  for (ServerListFilterExt filterExt : filters) {
    if(!filterExt.enabled()) {
      continue;
    }
    servers = filterExt.getFilteredListOfServers(servers, invocation);
    if (servers.isEmpty() && serversCount > 0) {
      LOGGER.warn("There are not servers exist after filtered by {}.", filterExt.getClass());
      break;
    }
  }
  ServiceCombServer server = rule.choose(servers, invocation);
  if (null == server) {
    return null;
  }
  ServiceCombServerStats serverStats = ServiceCombLoadBalancerStats.INSTANCE.getServiceCombServerStats(server);
  if (serverStats.isIsolated()) {
    LOGGER.info("The Service {}'s instance {} has been isolated for a while, give a single test opportunity.",
        invocation.getMicroserviceName(),
        server.getInstance().getInstanceId());
  }
  return server;
}
 
Example #7
Source File: ProducerOperationHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public Response doInvoke(Invocation invocation, SwaggerProducerOperation producerOperation) {
  Response response;
  try {
    invocation.onBusinessMethodStart();

    Object[] args = invocation.toProducerArguments();
    for (ProducerInvokeExtension producerInvokeExtension : producerOperation.getProducerInvokeExtenstionList()) {
      producerInvokeExtension.beforeMethodInvoke(invocation, producerOperation, args);
    }

    Object result = producerOperation.getProducerMethod().invoke(producerOperation.getProducerInstance(), args);
    response = producerOperation.getResponseMapper().mapResponse(invocation.getStatus(), result);

    invocation.onBusinessMethodFinish();
    invocation.onBusinessFinish();
  } catch (Throwable e) {
    if (shouldPrintErrorLog(e)) {
      invocation.getTraceIdLogger().error(LOGGER, "unexpected error {},",
          invocation.getInvocationQualifiedName(), e);
    }
    invocation.onBusinessMethodFinish();
    invocation.onBusinessFinish();
    response = processException(invocation, e);
  }
  return response;
}
 
Example #8
Source File: ZipkinTracingHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"try", "unused"})
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
  Span span = tracingDelegate.createSpan(invocation);
  try (SpanInScope scope = tracer.tracer().withSpanInScope(span)) {
    LOGGER.debug("{}: Generated tracing span for {}",
        tracingDelegate.name(),
        invocation.getOperationName());

    invocation.next(onResponse(invocation, asyncResp, span));
  } catch (Exception e) {
    LOGGER.debug("{}: Failed invocation on {}",
        tracingDelegate.name(),
        invocation.getOperationName(),
        e);

    tracingDelegate.onResponse(span, null, e);
    throw e;
  }
}
 
Example #9
Source File: DelayFault.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void injectFault(Invocation invocation, FaultParam faultParam, AsyncResponse asynResponse) {
  if (!shouldDelay(invocation, faultParam, asynResponse)) {
    asynResponse.success(SUCCESS_RESPONSE);
    return;
  }

  LOGGER.debug("Fault injection: delay is added for the request by fault inject handler");
  long delay = FaultInjectionUtil.getFaultInjectionConfig(invocation,
      "delay.fixedDelay");
  if (delay == FaultInjectionConst.FAULT_INJECTION_DEFAULT_VALUE) {
    LOGGER.debug("Fault injection: delay is not configured");
    asynResponse.success(SUCCESS_RESPONSE);
    return;
  }

  executeDelay(faultParam, asynResponse, delay);
}
 
Example #10
Source File: TestBizkeeperCommand.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructProvider() {

  Invocation invocation = Mockito.mock(Invocation.class);
  Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class));
  Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1");
  HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
      .withRequestCacheEnabled(true)
      .withRequestLogEnabled(false);

  BizkeeperCommand bizkeeperCommand = new ProviderBizkeeperCommand("groupname", invocation,
      HystrixObservableCommand.Setter
          .withGroupKey(CommandKey.toHystrixCommandGroupKey("groupname", invocation))
          .andCommandKey(CommandKey.toHystrixCommandKey("groupname", invocation))
          .andCommandPropertiesDefaults(setter));

  Observable<Response> response = bizkeeperCommand.construct();
  Assert.assertNotNull(response);
}
 
Example #11
Source File: EdgeSignatureRequestFilter.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public Response afterReceiveRequest(Invocation invocation, HttpServletRequestEx requestEx) {
  EncryptContext encryptContext = (EncryptContext) invocation.getHandlerContext().get(EdgeConst.ENCRYPT_CONTEXT);
  if (encryptContext == null) {
    return null;
  }
  Hcr hcr = encryptContext.getHcr();

  // signature for query and form
  List<String> names = Collections.list(requestEx.getParameterNames());
  names.sort(Comparator.naturalOrder());

  Hasher hasher = Hashing.sha256().newHasher();
  hasher.putString(hcr.getSignatureKey(), StandardCharsets.UTF_8);
  for (String name : names) {
    hasher.putString(name, StandardCharsets.UTF_8);
    hasher.putString(requestEx.getParameter(name), StandardCharsets.UTF_8);
  }
  LOGGER.info("afterReceiveRequest signature: {}", hasher.hash().toString());

  return null;
}
 
Example #12
Source File: TestLoadBalancer.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadBalancerFullOperationWithoutException() {
  List<ServiceCombServer> newServers = new ArrayList<>();
  ServiceCombServer server = Mockito.mock(ServiceCombServer.class);
  Invocation invocation = Mockito.mock(Invocation.class);
  MicroserviceInstance microserviceInstance = Mockito.mock(MicroserviceInstance.class);
  newServers.add(server);
  when(invocation.getLocalContext(LoadbalanceHandler.CONTEXT_KEY_SERVER_LIST)).thenReturn(newServers);
  when(server.getInstance()).thenReturn(microserviceInstance);
  when(microserviceInstance.getInstanceId()).thenReturn("123456");
  LoadBalancer loadBalancer = new LoadBalancer(rule, "test");
  loadBalancer.chooseServer(invocation);

  when(rule.choose(newServers, invocation)).thenReturn(server);

  Assert.assertEquals(server, loadBalancer.chooseServer(invocation));
  Assert.assertNotNull(loadBalancer.getLoadBalancerStats());
  Assert.assertEquals("test", loadBalancer.getMicroServiceName());
}
 
Example #13
Source File: DecodeBodyFilter.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public Response afterReceiveRequest(Invocation invocation, HttpServletRequestEx requestEx) {
  EncryptContext encryptContext = (EncryptContext) invocation.getHandlerContext().get(EdgeConst.ENCRYPT_CONTEXT);
  if (encryptContext == null) {
    return null;
  }
  Hcr hcr = encryptContext.getHcr();

  String encodedBody = requestEx.getParameter("body");
  if (encodedBody == null) {
    return null;
  }

  encodedBody = encodedBody.substring(hcr.getBodyKey().length());

  try {
    Map<String, String[]> decodedBody = RestObjectMapperFactory.getRestObjectMapper()
        .readValue(encodedBody, bodyType);
    requestEx.getParameterMap().putAll(decodedBody);
  } catch (Throwable e) {
    // should be a meaning exception response
    return Response.producerFailResp(e);
  }
  return null;
}
 
Example #14
Source File: TestRoundRobinRuleExt.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testBenchmarkRobin() {
  // less than 0.001ms
  RoundRobinRuleExt rule = new RoundRobinRuleExt();
  LoadBalancer loadBalancer = new LoadBalancer(rule, "testService");
  List<ServiceCombServer> servers = new ArrayList<>();
  Invocation invocation = Mockito.mock(Invocation.class);
  for (int i = 0; i < 100; i++) {
    ServiceCombServer server = Mockito.mock(ServiceCombServer.class);
    Mockito.when(server.toString()).thenReturn("server " + i);
    servers.add(server);
    loadBalancer.getLoadBalancerStats().noteResponseTime(server, 2);
  }
  long begin = System.currentTimeMillis();
  for (int i = 0; i < 10000; i++) {
    rule.choose(servers, invocation);
  }
  long taken = System.currentTimeMillis() - begin;
  System.out.println("taken " + taken);
  Assert.assertEquals("actual token " + taken, taken < 10 * 5, true);  // 5 * times make slow machine happy
}
 
Example #15
Source File: TestHystrixPropertiesStrategyExt.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCommandPropertiesCacheKey() {

  assertNotNull(HystrixPropertiesStrategyExt.getInstance());

  HystrixPropertiesStrategyExt hps = HystrixPropertiesStrategyExt.getInstance();
  HystrixCommandKey commandKey = Mockito.mock(HystrixCommandKey.class);

  Invocation invocation = Mockito.mock(Invocation.class);
  Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class));
  Mockito.when(invocation.getOperationMeta().getMicroserviceName()).thenReturn("testqualify");

  HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
      .withRequestCacheEnabled(true)
      .withRequestLogEnabled(false)
      .withFallbackIsolationSemaphoreMaxConcurrentRequests(
          Configuration.INSTANCE.getFallbackMaxConcurrentRequests("groupname",
              "testing",
              invocation.getOperationMeta().getMicroserviceQualifiedName()));

  String str1 = hps.getCommandPropertiesCacheKey(commandKey, setter);
  Assert.assertNull(str1);
}
 
Example #16
Source File: OperationProtobuf.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void initConsumerRequestCodec(Invocation invocation, Message requestMessage, ProtoMapper mapper) {
  if (ProtoUtils.isWrapArguments(requestMessage)) {
    requestRootSerializer = new RequestRootSerializer(
        mapper.createRootSerializer(requestMessage, Object.class), true, false);
  } else {
    if (invocation.getOperationMeta().getSwaggerOperation().getParameters().isEmpty()) {
      requestRootSerializer = new RequestRootSerializer(mapper.createRootSerializer(requestMessage, Object.class),
          false, false);
    } else if (invocation.getOperationMeta().getSwaggerOperation().getParameters().size() == 1) {
      requestRootSerializer = new RequestRootSerializer(mapper.createRootSerializer(requestMessage,
          Object.class), false, true);
    } else {
      throw new IllegalStateException(
          "unexpected operation definition " + invocation.getOperationMeta().getMicroserviceQualifiedName());
    }
  }
}
 
Example #17
Source File: DefaultHttpClientFilter.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public Response afterReceiveResponse(Invocation invocation, HttpServletResponseEx responseEx) {
  Response response = extractResponse(invocation, responseEx);

  for (String headerName : responseEx.getHeaderNames()) {
    if (headerName.equals(":status")) {
      continue;
    }
    Collection<String> headerValues = responseEx.getHeaders(headerName);
    for (String headerValue : headerValues) {
      response.getHeaders().addHeader(headerName, headerValue);
    }
  }

  return response;
}
 
Example #18
Source File: ProducerOperationHandlerInterceptorTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    ServiceManager.INSTANCE.boot();
    invocationInterceptor = new ProducerOperationHandlerInterceptor();
    PowerMockito.mock(Invocation.class);
    when(operationMeta.getSchemaMeta()).thenReturn(schemaMeta);
    when(endpoint.getAddress()).thenReturn("0.0.0.0:7777");
    when(invocation.getEndpoint()).thenReturn(endpoint);
    when(invocation.getMicroserviceQualifiedName()).thenReturn("productorTest");
    when(operationMeta.getOperationPath()).thenReturn("/bmi");
    when(invocation.getOperationMeta()).thenReturn(operationMeta);
    when(invocation.getStatus()).thenReturn(statusType);
    when(statusType.getStatusCode()).thenReturn(200);
    when(method.getName()).thenReturn("producer");
    when(invocation.getInvocationType()).thenReturn(InvocationType.PRODUCER);
    Config.Agent.SERVICE_NAME = "serviceComnTestCases-APP";

    allArguments = new Object[] {invocation};
    argumentsType = new Class[] {};
    swaggerArguments = new Class[] {};

}
 
Example #19
Source File: RestProducerInvocationCreatorTest.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void should_merge_invocation_context_from_request() {
  mockGetServicePathManager();
  new Expectations() {
    {
      requestEx.getHeader(Const.CSE_CONTEXT);
      result = "{\"k\":\"v\"}";
    }
  };

  Invocation invocation = creator.create();

  assertThat(invocation.getContext("k")).isEqualTo("v");
}
 
Example #20
Source File: ProducerOperationHandlerInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    Object ret) throws Throwable {
    Invocation invocation = (Invocation) allArguments[0];
    AbstractSpan span = ContextManager.activeSpan();
    int statusCode = invocation.getStatus().getStatusCode();
    if (statusCode >= 400) {
        span.errorOccurred();
        Tags.STATUS_CODE.set(span, Integer.toString(statusCode));
    }
    ContextManager.stopSpan();
    return ret;
}
 
Example #21
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 #22
Source File: TestSessionSticknessRule.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testLastServerNotExist() {
  SessionStickinessRule rule = new SessionStickinessRule();

  Transport transport = mock(Transport.class);
  Invocation invocation = mock(Invocation.class);
  MicroserviceInstance instance1 = new MicroserviceInstance();
  instance1.setInstanceId("1234");
  ServiceCombServer mockedServer =
      new ServiceCombServer(transport, new CacheEndpoint("rest:127.0.0.1:8890", instance1));
  mockedServer.setAlive(true);
  mockedServer.setReadyToServe(true);
  mockedServer.setId("mockedServer");
  List<ServiceCombServer> allServers = Arrays.asList(mockedServer);
  LoadBalancer lb = new LoadBalancer(rule, "mockedServer");
  when(invocation.getLocalContext(LoadbalanceHandler.CONTEXT_KEY_SERVER_LIST)).thenReturn(allServers);
  rule.setLoadBalancer(lb);
  ServiceCombServer server = new ServiceCombServer(transport, new CacheEndpoint("rest:127.0.0.1:8890", instance1));
  Deencapsulation.setField(rule, "lastServer", server);

  new MockUp<SessionStickinessRule>(rule) {
    @Mock
    private boolean isTimeOut() {
      return false;
    }

    @Mock
    private boolean isErrorThresholdMet() {
      return false;
    }
  };
  Server s = rule.choose(allServers, invocation);
  Assert.assertEquals(mockedServer, s);
}
 
Example #23
Source File: SimpleLoadBalanceHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
  if (invocation.getEndpoint() != null) {
    invocation.next(asyncResp);
    return;
  }

  DiscoveryContext context = new DiscoveryContext();
  context.setInputParameters(invocation);
  VersionedCache endpointsVersionedCache = discoveryTree.discovery(context,
      invocation.getAppId(),
      invocation.getMicroserviceName(),
      invocation.getMicroserviceVersionRule());
  if (endpointsVersionedCache.isEmpty()) {
    asyncResp.consumerFail(ExceptionUtils.lbAddressNotFound(invocation.getMicroserviceName(),
        invocation.getMicroserviceVersionRule(),
        endpointsVersionedCache.name()));
    return;
  }

  List<Endpoint> endpoints = endpointsVersionedCache.data();
  AtomicInteger index = indexMap.computeIfAbsent(endpointsVersionedCache.name(), name -> {
    LOGGER.info("Create loadBalancer for {}.", name);
    return new AtomicInteger();
  });
  LOGGER.debug("invocation {} use discoveryGroup {}.",
      invocation.getMicroserviceQualifiedName(),
      endpointsVersionedCache.name());

  int idx = Math.abs(index.getAndIncrement());
  idx = idx % endpoints.size();
  Endpoint endpoint = endpoints.get(idx);

  invocation.setEndpoint(endpoint);

  invocation.next(asyncResp);
}
 
Example #24
Source File: TestCommandKey.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testToHystrixCommandKey() {

  Invocation invocation = Mockito.mock(Invocation.class);

  Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class));
  Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName()).thenReturn("test1");
  Assert.assertNotNull(invocation);
  HystrixCommandKey hystrixCommandGroupKey = CommandKey.toHystrixCommandKey("groupname", invocation);
  Assert.assertNotNull(hystrixCommandGroupKey);
}
 
Example #25
Source File: FaultInjectionHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {

  // prepare the key and lookup for request count.
  String key = invocation.getTransport().getName() + invocation.getMicroserviceQualifiedName();
  AtomicLong reqCount = FaultInjectionUtil.getOperMetTotalReq(key);
  // increment the request count here after checking the delay/abort condition.
  long reqCountCurrent = reqCount.getAndIncrement();

  FaultParam param = new FaultParam(reqCountCurrent);
  Context currentContext = Vertx.currentContext();
  if (currentContext != null && currentContext.isEventLoopContext()) {
    param.setVertx(currentContext.owner());
  }

  FaultExecutor executor = new FaultExecutor(faultInjectionFeatureList, invocation, param);
  executor.execute(response -> {
    try {
      if (response.isFailed()) {
        asyncResp.complete(response);
      } else {
        invocation.next(asyncResp);
      }
    } catch (Exception e) {
      asyncResp.consumerFail(e);
    }
  });
}
 
Example #26
Source File: TestDefaultHttpClientFilter.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testAfterReceiveResponseNullProduceProcessor(@Mocked Invocation invocation,
    @Mocked HttpServletResponseEx responseEx,
    @Mocked OperationMeta operationMeta,
    @Mocked RestOperationMeta swaggerRestOperation) throws Exception {
  CommonExceptionData data = new CommonExceptionData("abcd");
  new Expectations() {
    {
      invocation.getOperationMeta();
      result = operationMeta;
      operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION);
      result = swaggerRestOperation;
      invocation.findResponseType(403);
      result = SimpleType.constructUnsafe(CommonExceptionData.class);
      responseEx.getStatus();
      result = 403;
      responseEx.getStatusType();
      result = Status.FORBIDDEN;
      responseEx.getBodyBuffer();
      result = Buffer.buffer(JsonUtils.writeValueAsString(data).getBytes());
    }
  };

  Response response = filter.afterReceiveResponse(invocation, responseEx);
  Assert.assertEquals(403, response.getStatusCode());
  Assert.assertEquals("Forbidden", response.getReasonPhrase());
  Assert.assertEquals(InvocationException.class, response.<InvocationException>getResult().getClass());
  InvocationException invocationException = response.getResult();
  Assert.assertEquals(
      403,
      invocationException.getStatusCode());
  Assert.assertEquals(
      "CommonExceptionData [message=abcd]",
      invocationException.getErrorData().toString());
}
 
Example #27
Source File: UrlPathWithQueryAccessItem.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void appendClientFormattedItem(InvocationFinishEvent finishEvent, StringBuilder builder) {
  Invocation invocation = finishEvent.getInvocation();
  if (null == invocation || null == invocation.getLocalContext(REST_CLIENT_REQUEST_PATH)
      || StringUtils.isEmpty(invocation.getLocalContext(REST_CLIENT_REQUEST_PATH).toString())) {
    builder.append(EMPTY_RESULT);
    return;
  }
  builder.append(invocation.getLocalContext(REST_CLIENT_REQUEST_PATH).toString());
}
 
Example #28
Source File: RestTransportClient.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public void send(Invocation invocation, AsyncResponse asyncResp) {

    HttpClientWithContext httpClientWithContext = findHttpClientPool(invocation);

    RestClientInvocation restClientInvocation = new RestClientInvocation(httpClientWithContext, httpClientFilters);

    try {
      restClientInvocation.invoke(invocation, asyncResp);
    } catch (Throwable e) {
      asyncResp.fail(invocation.getInvocationType(), e);
      LOGGER.error("vertx rest transport send error.", e);
    }
  }
 
Example #29
Source File: InvocationFactory.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static Invocation forProvider(Endpoint endpoint,
    OperationMeta operationMeta,
    Map<String, Object> swaggerArguments) {
  SCBEngine.getInstance().ensureStatusUp();
  return new Invocation(endpoint,
      operationMeta,
      swaggerArguments);
}
 
Example #30
Source File: InvocationMetersInitializer.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
protected AbstractInvocationMeters findInvocationMeters(Invocation invocation) {
  if (invocation.isConsumer()) {
    if (invocation.isEdge()) {
      return edgeMeters.getInvocationMeters();
    } else {
      return consumerMeters.getInvocationMeters();
    }
  }
  return producerMeters.getInvocationMeters();
}