You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@servicecomb.apache.org by GitBox <gi...@apache.org> on 2018/10/23 08:40:53 UTC

[GitHub] liubao68 closed pull request #960: [SCB-967] Support configed IP send request

liubao68 closed pull request #960: [SCB-967] Support configed IP send request
URL: https://github.com/apache/incubator-servicecomb-java-chassis/pull/960
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git a/handlers/handler-loadbalance/src/main/java/org/apache/servicecomb/loadbalance/LoadbalanceHandler.java b/handlers/handler-loadbalance/src/main/java/org/apache/servicecomb/loadbalance/LoadbalanceHandler.java
index 95db713fd..eab708cc6 100644
--- a/handlers/handler-loadbalance/src/main/java/org/apache/servicecomb/loadbalance/LoadbalanceHandler.java
+++ b/handlers/handler-loadbalance/src/main/java/org/apache/servicecomb/loadbalance/LoadbalanceHandler.java
@@ -17,6 +17,7 @@
 
 package org.apache.servicecomb.loadbalance;
 
+import java.net.URI;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
@@ -26,9 +27,14 @@
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.atomic.AtomicInteger;
 
+import javax.ws.rs.core.Response.Status;
+
 import org.apache.commons.lang3.StringUtils;
+import org.apache.servicecomb.core.Endpoint;
 import org.apache.servicecomb.core.Handler;
 import org.apache.servicecomb.core.Invocation;
+import org.apache.servicecomb.core.SCBEngine;
+import org.apache.servicecomb.core.Transport;
 import org.apache.servicecomb.core.exception.ExceptionUtils;
 import org.apache.servicecomb.core.provider.consumer.SyncResponseExecutor;
 import org.apache.servicecomb.foundation.common.cache.VersionedCache;
@@ -61,6 +67,11 @@
 public class LoadbalanceHandler implements Handler {
   public static final String CONTEXT_KEY_SERVER_LIST = "x-context-server-list";
 
+  public static final String SERVICECOMB_SERVER_ENDPOINT = "scb-endpoint";
+
+  public static final boolean supportDefinedEndpoint =
+      DynamicPropertyFactory.getInstance().getBooleanProperty("servicecomb.loadbalance.userDefinedEndpoint.enabled", false).get();
+
   // just a wrapper to make sure in retry mode to choose a different server.
   class RetryLoadBalancer implements ILoadBalancer {
     // Enough times to make sure to choose a different server in high volume.
@@ -150,7 +161,8 @@ private void preCheck() {
     // Old configurations check.Just print an error, because configurations may given in dynamic and fail on runtime.
 
     String policyName = DynamicPropertyFactory.getInstance()
-        .getStringProperty("servicecomb.loadbalance.NFLoadBalancerRuleClassName", null).get();
+        .getStringProperty("servicecomb.loadbalance.NFLoadBalancerRuleClassName", null)
+        .get();
     if (!StringUtils.isEmpty(policyName)) {
       LOGGER.error("[servicecomb.loadbalance.NFLoadBalancerRuleClassName] is not supported anymore." +
           "use [servicecomb.loadbalance.strategy.name] instead.");
@@ -167,6 +179,12 @@ private void preCheck() {
 
   @Override
   public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
+    if (supportDefinedEndpoint) {
+      if (defineEndpointAndHandle(invocation, asyncResp)) {
+        return;
+      }
+    }
+
     String strategy = Configuration.INSTANCE.getRuleStrategyName(invocation.getMicroserviceName());
     if (!isEqual(strategy, this.strategy)) {
       //配置变化,需要重新生成所有的lb实例
@@ -185,6 +203,26 @@ public void handle(Invocation invocation, AsyncResponse asyncResp) throws Except
     }
   }
 
+  private boolean defineEndpointAndHandle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
+    String endpointUri = invocation.getLocalContext(SERVICECOMB_SERVER_ENDPOINT);
+    if (endpointUri == null) {
+      return false;
+    }
+    URI formatUri = new URI(endpointUri);
+    Transport transport = SCBEngine.getInstance().getTransportManager().findTransport(formatUri.getScheme());
+    if (transport == null) {
+      LOGGER.error("not deployed transport {}, ignore {}.", formatUri.getScheme(), endpointUri);
+      throw new InvocationException(Status.BAD_REQUEST,
+          "the endpoint's transport is not found.");
+    }
+    Endpoint endpoint = new Endpoint(transport, endpointUri);
+    invocation.setEndpoint(endpoint);
+    invocation.next(resp -> {
+      asyncResp.handle(resp);
+    });
+    return true;
+  }
+
   private void clearLoadBalancer() {
     loadBalancerMap.clear();
   }
diff --git a/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/TestLoadBalanceHandler2.java b/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/TestLoadBalanceHandler2.java
index 276e45412..5c52f164e 100644
--- a/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/TestLoadBalanceHandler2.java
+++ b/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/TestLoadBalanceHandler2.java
@@ -26,6 +26,7 @@
 
 import org.apache.servicecomb.core.CseContext;
 import org.apache.servicecomb.core.Invocation;
+import org.apache.servicecomb.core.SCBEngine;
 import org.apache.servicecomb.core.Transport;
 import org.apache.servicecomb.core.definition.MicroserviceMeta;
 import org.apache.servicecomb.core.definition.OperationMeta;
@@ -39,6 +40,7 @@
 import org.apache.servicecomb.serviceregistry.api.registry.MicroserviceInstance;
 import org.apache.servicecomb.serviceregistry.cache.InstanceCacheManager;
 import org.apache.servicecomb.serviceregistry.discovery.DiscoveryTreeNode;
+import org.apache.servicecomb.swagger.invocation.AsyncResponse;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.BeforeClass;
@@ -52,6 +54,8 @@
 public class TestLoadBalanceHandler2 {
   @BeforeClass
   public static void beforeClass() {
+    //prepare for defineEndpointAndHandle
+    ArchaiusUtils.setProperty("servicecomb.loadbalance.userDefinedEndpoint.enabled", "true");
     // avoid mock
     ServiceCombLoadBalancerStats.INSTANCE.init();
   }
@@ -191,4 +195,89 @@ public void testZoneAwareAndIsolationFilterWorks() {
     server = (ServiceCombServer) loadBalancer.chooseServer(invocation);
     Assert.assertEquals(server.getEndpoint().getEndpoint(), "rest://localhost:9091");
   }
+
+  @Test
+  public void testConfigEndpoint() {
+    ReferenceConfig referenceConfig = Mockito.mock(ReferenceConfig.class);
+    OperationMeta operationMeta = Mockito.mock(OperationMeta.class);
+    SchemaMeta schemaMeta = Mockito.mock(SchemaMeta.class);
+    when(operationMeta.getSchemaMeta()).thenReturn(schemaMeta);
+    MicroserviceMeta microserviceMeta = Mockito.mock(MicroserviceMeta.class);
+    when(schemaMeta.getMicroserviceMeta()).thenReturn(microserviceMeta);
+    when(schemaMeta.getMicroserviceName()).thenReturn("testMicroserviceName");
+    when(microserviceMeta.getAppId()).thenReturn("testApp");
+    when(referenceConfig.getVersionRule()).thenReturn("0.0.0+");
+    when(referenceConfig.getTransport()).thenReturn("rest");
+    Invocation invocation = new Invocation(referenceConfig, operationMeta, new Object[0]);
+    AsyncResponse asyncResp = Mockito.mock(AsyncResponse.class);
+
+    InstanceCacheManager instanceCacheManager = Mockito.mock(InstanceCacheManager.class);
+    ServiceRegistry serviceRegistry = Mockito.mock(ServiceRegistry.class);
+    TransportManager transportManager = Mockito.mock(TransportManager.class);
+    Transport transport = Mockito.mock(Transport.class);
+    ArchaiusUtils.setProperty("servicecomb.loadbalance.filter.operation.enabled", "false");
+
+    // set up data
+    MicroserviceInstance myself = new MicroserviceInstance();
+
+    MicroserviceInstance findInstance = new MicroserviceInstance();
+    List<String> findEndpoint = new ArrayList<>();
+    findEndpoint.add("rest://localhost:9092");
+    findInstance.setEndpoints(findEndpoint);
+    findInstance.setInstanceId("findInstance");
+
+    Map<String, MicroserviceInstance> data = new HashMap<>();
+    DiscoveryTreeNode parent = new DiscoveryTreeNode().name("parent").data(data);
+    CseContext.getInstance().setTransportManager(transportManager);
+    SCBEngine.getInstance().setTransportManager(transportManager);
+
+    RegistryUtils.setServiceRegistry(serviceRegistry);
+
+    when(serviceRegistry.getMicroserviceInstance()).thenReturn(myself);
+    when(serviceRegistry.getInstanceCacheManager()).thenReturn(instanceCacheManager);
+    when(instanceCacheManager.getOrCreateVersionedCache("testApp", "testMicroserviceName", "0.0.0+"))
+        .thenReturn(parent);
+    when(transportManager.findTransport("rest")).thenReturn(transport);
+
+    LoadbalanceHandler handler = null;
+
+    handler = new LoadbalanceHandler();
+    data.put("findInstance", findInstance);
+    parent.cacheVersion(1);
+    handler = new LoadbalanceHandler();
+    try {
+      handler.handle(invocation, asyncResp);
+    } catch (Exception e) {
+
+    }
+    Assert.assertEquals("rest://localhost:9092", invocation.getEndpoint().getEndpoint());
+
+    //success
+    invocation.addLocalContext("scb-endpoint", "rest://127.0.0.1:8080?sslEnabled=true&protocol=http2");
+    try {
+      handler.handle(invocation, asyncResp);
+    } catch (Exception e) {
+
+    }
+    Assert.assertEquals("rest://127.0.0.1:8080?sslEnabled=true&protocol=http2", invocation.getEndpoint().getEndpoint());
+
+    //endpoint format is not correct
+    invocation.addLocalContext("scb-endpoint", "127.0.0.1:8080");
+    try {
+      handler.handle(invocation, asyncResp);
+      Assert.assertEquals("endpoint's format is not correct, throw exception", " but not throw exception");
+    } catch (Exception e) {
+      Assert.assertTrue(e.getMessage()
+          .contains("Illegal character in scheme name"));
+    }
+
+    //transport is not find
+    invocation.addLocalContext("scb-endpoint", "my://127.0.0.1:8080?sslEnabled=true&protocol=http2");
+    try {
+      handler.handle(invocation, asyncResp);
+      Assert.assertEquals("endpoint's transport not found, throw exception", "but not throw exception");
+    } catch (Exception e) {
+      Assert.assertTrue(e.getMessage().contains("the endpoint's transport is not found."));
+    }
+  }
 }


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services