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

The following examples show how to use org.apache.servicecomb.core.Invocation#next() . 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: LoadbalanceHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private boolean defineEndpointAndHandle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
  Object endpoint = invocation.getLocalContext(SERVICECOMB_SERVER_ENDPOINT);
  if (endpoint == null) {
    return false;
  }
  if (endpoint instanceof String) {
    // compatible to old usage
    endpoint = parseEndpoint((String) endpoint);
  }

  invocation.setEndpoint((Endpoint) endpoint);
  invocation.next(resp -> {
    asyncResp.handle(resp);
  });
  return true;
}
 
Example 2
Source File: PackProviderHandler.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResponse) throws Exception {
  if (omegaContext != null) {
    String globalTxId = invocation.getContext().get(GLOBAL_TX_ID_KEY);
    if (globalTxId == null) {
      LOG.debug("Cannot inject transaction ID, no such header: {}", GLOBAL_TX_ID_KEY);
    } else {
      omegaContext.setGlobalTxId(globalTxId);
      omegaContext.setLocalTxId(invocation.getContext().get(LOCAL_TX_ID_KEY));
    }
  } else {
    LOG.debug("Cannot inject transaction ID, as the OmegaContext is null.");
  }
  try {
    invocation.next(asyncResponse);
  } finally {
    // Clean up the OmegaContext
    if(omegaContext != null) {
      omegaContext.clear();
    }
  }
}
 
Example 3
Source File: LoadbalanceHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void send(Invocation invocation, AsyncResponse asyncResp, LoadBalancer chosenLB) throws Exception {
  long time = System.currentTimeMillis();
  ServiceCombServer server = chosenLB.chooseServer(invocation);
  if (null == server) {
    asyncResp.consumerFail(new InvocationException(Status.INTERNAL_SERVER_ERROR, "No available address found."));
    return;
  }
  chosenLB.getLoadBalancerStats().incrementNumRequests(server);
  invocation.setEndpoint(server.getEndpoint());
  invocation.next(resp -> {
    // this stats is for WeightedResponseTimeRule
    chosenLB.getLoadBalancerStats().noteResponseTime(server, (System.currentTimeMillis() - time));
    if (isFailedResponse(resp)) {
      chosenLB.getLoadBalancerStats().incrementSuccessiveConnectionFailureCount(server);
      ServiceCombLoadBalancerStats.INSTANCE.markFailure(server);
    } else {
      chosenLB.getLoadBalancerStats().incrementActiveRequestsCount(server);
      ServiceCombLoadBalancerStats.INSTANCE.markSuccess(server);
    }
    asyncResp.handle(resp);
  });
}
 
Example 4
Source File: SagaProviderHandler.java    From txle with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResponse) throws Exception {
  if (omegaContext != null) {
    String globalTxId = invocation.getContext().get(GLOBAL_TX_ID_KEY);
    if (globalTxId == null) {
      LOG.debug("no such header: {}", GLOBAL_TX_ID_KEY);
    } else {

      omegaContext.setGlobalTxId(globalTxId);
      omegaContext.setLocalTxId(invocation.getContext().get(LOCAL_TX_ID_KEY));
    }
  } else {
    LOG.info("Cannot inject transaction ID, as the OmegaContext is null or cannot get the globalTxId.");
  }

  invocation.next(asyncResponse);
}
 
Example 5
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 6
Source File: ConsumerQpsFlowControlHandler.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 (!Config.INSTANCE.isConsumerEnabled()) {
    invocation.next(asyncResp);
    return;
  }

  QpsController qpsController = qpsControllerMgr.getOrCreate(invocation.getMicroserviceName(), invocation);
  if (qpsController.isLimitNewRequest()) {
    // return http status 429
    CommonExceptionData errorData = new CommonExceptionData("rejected by qps flowcontrol");
    asyncResp.consumerFail(
        new InvocationException(QpsConst.TOO_MANY_REQUESTS_STATUS, errorData));
    return;
  }

  invocation.next(asyncResp);
}
 
Example 7
Source File: AuthHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
protected void doHandle(Invocation invocation, AsyncResponse asyncResp, Boolean authSucc, Throwable authException) {
  if (authException != null) {
    asyncResp.consumerFail(new InvocationException(Status.UNAUTHORIZED, (Object) authException.getMessage()));
    return;
  }

  if (!authSucc) {
    asyncResp.consumerFail(new InvocationException(Status.UNAUTHORIZED, (Object) "auth failed"));
  }

  LOGGER.debug("auth success.");
  try {
    invocation.next(asyncResp);
  } catch (Throwable e) {
    asyncResp.consumerFail(e);
  }
}
 
Example 8
Source File: AuthHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
protected void doHandle(Invocation invocation, AsyncResponse asyncResp, Boolean authSucc, Throwable authException) {
  if (authException != null) {
    asyncResp.consumerFail(new InvocationException(Status.UNAUTHORIZED, (Object) authException.getMessage()));
    return;
  }

  if (!authSucc) {
    asyncResp.consumerFail(new InvocationException(Status.UNAUTHORIZED, (Object) "auth failed"));
  }

  LOGGER.debug("auth success.");
  try {
    invocation.next(asyncResp);
  } catch (Throwable e) {
    asyncResp.consumerFail(e);
  }
}
 
Example 9
Source File: AccessLogHandler.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 {
  invocation.getTraceIdLogger().info(LOGGER, "request for operation {} begin", invocation.getInvocationQualifiedName());
   invocation.next((resp) -> {
     invocation.getTraceIdLogger().info(LOGGER, "request for operation {} end", invocation.getInvocationQualifiedName());
     asyncResp.complete(resp);
   });
}
 
Example 10
Source File: ProviderAuthHanlder.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 {

  String token = invocation.getContext(Const.AUTH_TOKEN);
  if (null != token && authenticationTokenManager.valid(token)) {
    invocation.next(asyncResp);
  } else {
    asyncResp.producerFail(new InvocationException(new HttpStatus(401, "UNAUTHORIZED"), "UNAUTHORIZED"));
  }
}
 
Example 11
Source File: ConsumerAuthHandler.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 {

  Optional<String> token = Optional.ofNullable(athenticationTokenManager.getToken());
  if (!token.isPresent()) {
    asyncResp.consumerFail(
        new IllegalStateException("rejected by consumer authentication handler"));
    return;
  }
  invocation.addContext(Const.AUTH_TOKEN, token.get());
  invocation.next(asyncResp);
}
 
Example 12
Source File: MyHandler.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 {
  LOGGER.info("If you see this log, that means this demo project has been converted to ServiceComb framework.");

  invocation.next(response -> {
    if (invocation.getOperationMeta().getSchemaQualifiedName().equals("server.splitParam")) {
      User user = response.getResult();
      user.setName(user.getName() + SPLITPARAM_RESPONSE_USER_SUFFIX);
      asyncResp.handle(response);
    } else {
      asyncResp.handle(response);
    }
  });
}
 
Example 13
Source File: InvokerUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
/**
 * This is an internal API, caller make sure already invoked SCBEngine.ensureStatusUp
 * @param invocation
 * @param asyncResp
 */
public static void reactiveInvoke(Invocation invocation, AsyncResponse asyncResp) {
  try {
    invocation.onStart(null, System.nanoTime());
    invocation.setSync(false);

    ReactiveResponseExecutor respExecutor = new ReactiveResponseExecutor();
    invocation.setResponseExecutor(respExecutor);

    invocation.getInvocationStageTrace().startHandlersRequest();
    invocation.next(ar -> {
      ContextUtils.setInvocationContext(invocation.getParentContext());
      try {
        invocation.getInvocationStageTrace().finishHandlersResponse();
        invocation.onFinish(ar);
        asyncResp.handle(ar);
      } finally {
        ContextUtils.removeInvocationContext();
      }
    });
  } catch (Throwable e) {
    invocation.getInvocationStageTrace().finishHandlersResponse();
    //if throw exception,we can use 500 for status code ?
    Response response = Response.createConsumerFail(e);
    invocation.onFinish(response);
    LOGGER.error("invoke failed, {}", invocation.getOperationMeta().getMicroserviceQualifiedName());
    asyncResp.handle(response);
  }
}
 
Example 14
Source File: MyHandler.java    From servicecomb-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResponse) throws Exception {
  //code before

  LOGGER.info("It's my handler! \r\n");

  invocation.next(response -> {
    // code after
    asyncResponse.handle(response);
  });
}
 
Example 15
Source File: AuthHandler.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.getHandlerContext().get(EdgeConst.ENCRYPT_CONTEXT) != null) {
    invocation.next(asyncResp);
    return;
  }

  auth.auth("").whenComplete((succ, e) -> doHandle(invocation, asyncResp, succ, e));
}
 
Example 16
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 17
Source File: InternalAccessHandler.java    From servicecomb-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncReponse) throws Exception {
  if (invocation.getOperationMeta().getSwaggerOperation().getTags() != null
      && invocation.getOperationMeta().getSwaggerOperation().getTags().contains("INTERNAL")) {
    asyncReponse.consumerFail(new InvocationException(403, "", "not allowed"));
    return;
  }
  invocation.next(asyncReponse);
}
 
Example 18
Source File: InternalAccessHandler.java    From servicecomb-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncReponse) throws Exception {
  if (invocation.getOperationMeta().getSwaggerOperation().getTags() != null
      && invocation.getOperationMeta().getSwaggerOperation().getTags().contains("INTERNAL")) {
    asyncReponse.consumerFail(new InvocationException(403, "", "not allowed"));
    return;
  }
  invocation.next(asyncReponse);
}
 
Example 19
Source File: AuthHandler.java    From servicecomb-samples with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResponse) throws Exception {
  if (invocation.getMicroserviceName().equals("user-service")
      && (invocation.getOperationName().equals("login")
          || (invocation.getOperationName().equals("getSession")))) {
    // login:return session id, set cookie by javascript
    invocation.next(asyncResponse);
  } else {
    // check session
    String sessionId = invocation.getContext("session-id");
    if (sessionId == null) {
      throw new InvocationException(403, "", "session is not valid.");
    }

    String sessionInfo = sessionCache.getIfPresent(sessionId);
    if (sessionInfo != null) {
      try {
        // session info stored in InvocationContext. Microservices can get it. 
        invocation.addContext("session-id", sessionId);
        invocation.addContext("session-info", sessionInfo);
        invocation.next(asyncResponse);
      } catch (Exception e) {
        asyncResponse.complete(Response.failResp(new InvocationException(500, "", e.getMessage())));
      }
      return;
    }

    // In edge, handler is executed in reactively. Must have no blocking logic.
    CompletableFuture<SessionInfo> result = userServiceClient.getGetSessionOperation().getSession(sessionId);
    result.whenComplete((info, e) -> {
      if (result.isCompletedExceptionally()) {
        asyncResponse.complete(Response.failResp(new InvocationException(403, "", "session is not valid.")));
      } else {
        if (info == null) {
          asyncResponse.complete(Response.failResp(new InvocationException(403, "", "session is not valid.")));
          return;
        }
        try {
          // session info stored in InvocationContext. Microservices can get it. 
          invocation.addContext("session-id", sessionId);
          String sessionInfoStr = JsonUtils.writeValueAsString(info);
          invocation.addContext("session-info", sessionInfoStr);
          invocation.next(asyncResponse);
          sessionCache.put(sessionId, sessionInfoStr);
        } catch (Exception ee) {
          asyncResponse.complete(Response.failResp(new InvocationException(500, "", ee.getMessage())));
        }
      }
    });
  }
}
 
Example 20
Source File: AuthHandler.java    From servicecomb-samples with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResponse) throws Exception {
  if (invocation.getMicroserviceName().equals("user-service")
      && (invocation.getOperationName().equals("login")
          || (invocation.getOperationName().equals("getSession")))) {
    // login:return session id, set cookie by javascript
    invocation.next(asyncResponse);
  } else {
    // check session
    String sessionId = invocation.getContext("session-id");
    if (sessionId == null) {
      throw new InvocationException(403, "", "session is not valid.");
    }

    String sessionInfo = sessionCache.getIfPresent(sessionId);
    if (sessionInfo != null) {
      try {
        // session info stored in InvocationContext. Microservices can get it. 
        invocation.addContext("session-id", sessionId);
        invocation.addContext("session-info", sessionInfo);
        invocation.next(asyncResponse);
      } catch (Exception e) {
        asyncResponse.complete(Response.failResp(new InvocationException(500, "", e.getMessage())));
      }
      return;
    }

    // In edge, handler is executed in reactively. Must have no blocking logic.
    CompletableFuture<SessionInfo> result = userServiceClient.getGetSessionOperation().getSession(sessionId);
    result.whenComplete((info, e) -> {
      if (result.isCompletedExceptionally()) {
        asyncResponse.complete(Response.failResp(new InvocationException(403, "", "session is not valid.")));
      } else {
        if (info == null) {
          asyncResponse.complete(Response.failResp(new InvocationException(403, "", "session is not valid.")));
          return;
        }
        try {
          // session info stored in InvocationContext. Microservices can get it. 
          invocation.addContext("session-id", sessionId);
          String sessionInfoStr = JsonUtils.writeValueAsString(info);
          invocation.addContext("session-info", sessionInfoStr);
          invocation.next(asyncResponse);
          sessionCache.put(sessionId, sessionInfoStr);
        } catch (Exception ee) {
          asyncResponse.complete(Response.failResp(new InvocationException(500, "", ee.getMessage())));
        }
      }
    });
  }
}