Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SCB-611]Provide a default Dispatcher to make user using edge service easier #726

Merged
merged 2 commits into from May 25, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -78,8 +78,8 @@ public Consumer() {
request.setLanguage("zh_CN");
}

public void run() {
prepareEdge();
public void run(String prefix) {
prepareEdge(prefix);

testRecursiveSelf();
testDependType();
Expand Down Expand Up @@ -204,12 +204,12 @@ protected void invoke(String appendUrl, int x, int y, List<ResultWithInstance> r
results.add(result);
}

private URIEndpointObject prepareEdge() {
private URIEndpointObject prepareEdge(String prefix) {
Microservice microservice = RegistryUtils.getMicroservice();
EndpointsCache endpointsCache = new EndpointsCache(microservice.getAppId(), "edge", "latest", "");
Endpoint ep = endpointsCache.getLatestEndpoints().get(0);
URIEndpointObject edgeAddress = (URIEndpointObject) ep.getAddress();
edgePrefix = String.format("http://%s:%d/api/business", edgeAddress.getHostOrIp(), edgeAddress.getPort());
edgePrefix = String.format("http://%s:%d/" + prefix + "/business", edgeAddress.getHostOrIp(), edgeAddress.getPort());
return edgeAddress;
}

Expand Down
Expand Up @@ -25,6 +25,10 @@ public static void main(String[] args) throws Exception {
Log4jUtils.init();
BeanUtils.init();

new Consumer().run();
System.out.println("Running api dispater.");
new Consumer().run("api");
System.out.println("Running rest dispater.");
new Consumer().run("rest");

}
}
Expand Up @@ -15,4 +15,4 @@
# limitations under the License.
#

log4j.rootLogger=DEBUG,stdout
log4j.rootLogger=INFO,stdout
Expand Up @@ -37,3 +37,11 @@ servicecomb:
auth: loadbalance
executors:
default: cse.executor.groupThreadPool
http:
dispatcher:
edge:
default:
enabled: true
prefix: rest
withVersion: true
pathIndex: 2
@@ -0,0 +1,102 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.servicecomb.edge.core;

import java.util.Map;

import com.netflix.config.DynamicPropertyFactory;

import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.CookieHandler;

/**
* Provide an easy mapping dispatcher. User can configure prefix to easily using edge service.
*/
public class DefaultEdgeDispatcher extends AbstractEdgeDispatcher {
private static final String KEY_ENABLED = "servicecomb.http.dispatcher.edge.default.enabled";

private static final String KEY_PREFIX = "servicecomb.http.dispatcher.edge.default.prefix";

private static final String KEY_WITH_VERSION = "servicecomb.http.dispatcher.edge.default.withVersion";

private static final String KEY_PATH_INDEX = "servicecomb.http.dispatcher.edge.default.pathIndex";

private CompatiblePathVersionMapper versionMapper = new CompatiblePathVersionMapper();

private String prefix;

private boolean withVersion;

private int pathIndex;

@Override
public int getOrder() {
return 20000;
}

@Override
public boolean enabled() {
return DynamicPropertyFactory.getInstance().getBooleanProperty(KEY_ENABLED, false).get();
}

@Override
public void init(Router router) {
prefix = DynamicPropertyFactory.getInstance().getStringProperty(KEY_PREFIX, "api").get();
withVersion = DynamicPropertyFactory.getInstance().getBooleanProperty(KEY_WITH_VERSION, true).get();
pathIndex = DynamicPropertyFactory.getInstance().getIntProperty(KEY_PATH_INDEX, 2).get();
String regex;
if (withVersion) {
regex = "/" + prefix + "/([^\\\\/]+)/([^\\\\/]+)/(.*)";
} else {
regex = "/" + prefix + "/([^\\\\/]+)/(.*)";
}
router.routeWithRegex(regex).handler(CookieHandler.create());
router.routeWithRegex(regex).handler(createBodyHandler());
router.routeWithRegex(regex).failureHandler(this::onFailure).handler(this::onRequest);
}

protected void onRequest(RoutingContext context) {
Map<String, String> pathParams = context.pathParams();
String microserviceName = pathParams.get("param0");
String path = findActualPath(context.request().path());

EdgeInvocation edgeInvocation = new EdgeInvocation();
if (withVersion) {
String pathVersion = pathParams.get("param1");
edgeInvocation.setVersionRule(versionMapper.getOrCreate(pathVersion).getVersionRule());
}
edgeInvocation.init(microserviceName, context, path, httpServerFilters);
edgeInvocation.edgeInvoke();
}

protected String findActualPath(String path) {
int fromIndex = 0;
int counter = pathIndex;
char[] chars = path.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '/') {
if (--counter <= 0) {
fromIndex = i;
break;
}
}
}
return path.substring(fromIndex > 0 ? fromIndex : 0);
}
}
@@ -0,0 +1,18 @@
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

org.apache.servicecomb.edge.core.DefaultEdgeDispatcher
@@ -0,0 +1,88 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.servicecomb.edge.core;

import java.util.HashMap;
import java.util.Map;

import org.apache.servicecomb.foundation.test.scaffolding.config.ArchaiusUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import io.vertx.core.Handler;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import mockit.Deencapsulation;
import mockit.Expectations;
import mockit.Mocked;

public class TestServiceAndVersionDispatcher {
@Before
public void setUp() {

}

@After
public void tearDown() {
ArchaiusUtils.resetConfig();
}

@Test
@SuppressWarnings("unchecked")
public void testOnRequest(@Mocked Router router, @Mocked Route route
, @Mocked RoutingContext context
, @Mocked HttpServerRequest requst
, @Mocked EdgeInvocation invocation) {
DefaultEdgeDispatcher dispatcher = new DefaultEdgeDispatcher();
Map<String, String> pathParams = new HashMap<>();
pathParams.put("param0", "testService");
pathParams.put("param1", "v1");

new Expectations() {
{
router.routeWithRegex("/api/([^\\\\/]+)/([^\\\\/]+)/(.*)");
result = route;
route.handler((Handler<RoutingContext>) any);
result = route;
route.failureHandler((Handler<RoutingContext>) any);
result = route;
context.pathParams();
result = pathParams;
context.request();
result = requst;
requst.path();
result = "/api/testService/v1/hello";
invocation.setVersionRule("1.0.0-2.0.0");
invocation.init("testService", context, "/testService/v1/hello",
Deencapsulation.getField(dispatcher, "httpServerFilters"));
invocation.edgeInvoke();
}
};
dispatcher.init(router);
Assert.assertEquals(dispatcher.enabled(), false);
Assert.assertEquals(dispatcher.findActualPath("/api/test"), "/test");
Assert.assertEquals(dispatcher.getOrder(), 20000);

dispatcher.onRequest(context);
// assert done in expectations.
}
}
Expand Up @@ -100,7 +100,9 @@ private void mountAccessLogHandler(Router mainRouter) {
private void initDispatcher(Router mainRouter) {
List<VertxHttpDispatcher> dispatchers = SPIServiceUtils.getSortedService(VertxHttpDispatcher.class);
for (VertxHttpDispatcher dispatcher : dispatchers) {
dispatcher.init(mainRouter);
if(dispatcher.enabled()) {
dispatcher.init(mainRouter);
}
}
}

Expand Down
Expand Up @@ -22,5 +22,9 @@
public interface VertxHttpDispatcher {
int getOrder();

default boolean enabled() {
return true;
}

void init(Router router);
}
Expand Up @@ -36,6 +36,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netflix.config.DynamicPropertyFactory;

import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.ErrorDataDecoderException;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
Expand All @@ -45,13 +47,20 @@
public class VertxRestDispatcher extends AbstractVertxHttpDispatcher {
private static final Logger LOGGER = LoggerFactory.getLogger(VertxRestDispatcher.class);

private static final String KEY_ENABLED = "servicecomb.http.dispatcher.rest.enabled";

private Transport transport;

@Override
public int getOrder() {
return Integer.MAX_VALUE;
}

@Override
public boolean enabled() {
return DynamicPropertyFactory.getInstance().getBooleanProperty(KEY_ENABLED, true).get();
}

@Override
public void init(Router router) {
router.route().handler(CookieHandler.create());
Expand Down